JavaTM EE Patterns SL-314 JavaTM EE Patterns EE Patterns Java™ EE Patterns Java SL-314 TM EE...

655
Java TM EE Patterns SL-500-EE5

Transcript of JavaTM EE Patterns SL-314 JavaTM EE Patterns EE Patterns Java™ EE Patterns Java SL-314 TM EE...

Page 1: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

SS

Java™ EE Patterns

Java™ EE Patterns

SL-314JavaTM EE Patterns

L-314-EE5

JavaTM EE Patterns

L-500-EE5

Page 2: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Copyrig

This pro lation. No part of this product or document maybe repro

Third-p

Sun, Sun Java Server Pages, JDBC, JDK, Java Naming andDirector countries.

All SPA . and other countries. Products bearing SPARCtradema

UNIX is

The OPE es the pioneering efforts of Xerox in researchingand dev ox to the Xerox Graphical User Interface, whichlicense a

U.S. Gov

RESTRI nd FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95

DOCUM IES, INCLUDING ANY IMPLIED WARRANTYOF MER HE EXTENT THAT SUCH DISCLAIMERS AREHELD T

ht 2008 Sun Microsystems, In. 4150 Network Circle, Santa Clary, California 95054, U.S.A. All rights reserved.

duct or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompiduced in any form by any means without prior written authorization of Sun and its licensors, if any.

arty software, including font technology, is copyrighted and licensed from Sun supplier.

Microsystems, the Sun logo, EJB, Enterprise Javanese, J2EE, J2ME, Java, Java Center, Javanese, Juvenal, Java Script, Java Server,y Interface, JSP, Sailors, J2SE, JVM, and are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other

RC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.Srks are based upon an architecture developed by Sun Microsystems, Inc.

a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd.

N LOOK and Sun Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledgeloping the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerlso covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements.

ernment approval might be required when exporting the product.

CTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) a) and DFAR 227.7202-3(a).

ENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO TO BE LEGALLY INVALID.

Page 3: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Copyrig

Ce prod ution, et la décompilation. Aucune partie de ceproduit e Sun et de ses bailleurs de licence, s’il y en a.

Le logic é par des fournisseurs de Sun.

Sun, Sun ver, JavaServer Pages, JDBC, JDK, Java Namingand Dir U.S. and other countries.

Toutes l l, Inc. aux Etats-Unis et dans d’autres pays. Lesproduits

UNIX es

L’interfa . Sun reconnaît les efforts de pionniers de Xeroxpour lar n détient une licence non exclusive de Xerox surl’interfa tion graphique OPEN LOOK et qui en outre seconform

L’accord

LA DOC ESSES OU TACITES SONT FORMELLEMENTEXCLU RELATIVE A LA QUALITE MARCHANDE, AL’APTIT

ht 2008 Sun Microsystems Inc. 4150 Network Circle, Santa Clara, California 95054, Etats-Unis. Tous droits réservés.

uit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite d

iel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licenci

Microsystems, le logo Sun, EJB, Enterprise JavaBeans, J2EE, J2ME, Java, Java Center, JavaBeans, JavaMail, JavaScript, JavaSerectory Interface, JSP, Solaris, J2SE, JVM, and SunTone are trademarks or registered trademarks of Sun Microsystems, Inc. in the

es marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARC Internationa portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.

t une marques déposée aux Etats-Unis et dans d’autres pays et licenciée exclusivement par X/Open Company, Ltd.

ces d’utilisation graphique OPEN LOOKet Sun™ a été développée par Sun Microsystems, Inc. pour ses utilisateurs et licenciésecherche et le développement du concept des interfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Suce d’utilisation graphique Xerox, cette licence couvrant également les licenciés de Sun qui mettent en place l’interface d’utilisaent aux licences écrites de Sun.

du gouvernement américain est requis avant l’exportation du produit.

UMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITEUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

Page 4: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ EE Pattern 12008 Sun Microsystem

...................................Preface-i...................................... Preface-ii.....................................Preface- iii......................................Preface-iv.......................................Preface-v.....................................Preface-vii................................... Preface-viii..................................... Preface-ix....................................... Preface-x

..................................... 1-1

.................................................. 1-2

................................................. 1-3

.................................................. 1-4

.................................................. 1-5

.................................................. 1-6

.................................................. 1-7

.................................................. 1-8

.................................................. 1-9

................................................ 1-11

............................................... 1-12

............................................... 1-13

............................................... 1-14

................................................ 1-15

................................................ 1-16

ss, Inc. All Rights Reserved. Sun Services, Revision C.1

Table of Contents

About This Course .........................................................................Course Goals...........................................................................................Course Map.............................................................................................Topics Not Covered ..............................................................................How Prepared Are You?.......................................................................Introductions ..........................................................................................Icons ........................................................................................................Typographical Conventions .................................................................Additional Conventions........................................................................

Developing a View Component ..........................................Objectives ...............................................................................................Reviewing Design Goals .......................................................................Course Flow............................................................................................Exploring Object-Oriented Design Concepts.....................................Cohesion..................................................................................................Low and High Cohesion Examples.....................................................Encapsulation .........................................................................................Encapsulation Example.........................................................................Coupling .................................................................................................Four Levels of Coupling .......................................................................Implementation Inheritance .................................................................Implementation Inheritance Example.................................................Composition............................................................................................Interface Inheritance .............................................................................

Page 5: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 2Copyrig

................................................ 1-17

................................................ 1-18

................................................ 1-19

................................................ 1-21

............................................... 1-23

............................................... 1-25

................................................ 1-26

............................................... 1-27

................................................ 1-28

............................................... 1-29

............................................... 1-30

............................................... 1-31

................................................ 1-32

............................................... 1-33

............................................... 1-34

............................................... 1-36

.................................... 2-1

................................................. 2-2

................................................. 2-3

................................................. 2-4

................................................. 2-5

................................................. 2-6

................................................. 2-7

................................................. 2-8

............................................... 2-11

............................................... 2-13

............................................... 2-14

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Interface Inheritance Example .............................................................Polymorphism .......................................................................................Polymorphism Example .......................................................................Favoring Composition ..........................................................................Programming to an Interface ...............................................................Designing for Change............................................................................Introducing Design Patterns ...............................................................Origin of the Pattern Concept ..............................................................Design Pattern Catalogs .......................................................................Gang of Four (GoF) Patterns ................................................................Gang of Four (GoF) Patterns: Description..........................................Gang of Four (GoF) Patterns: Groups .................................................Design Pattern Selection ......................................................................Design Pattern Elements .......................................................................Design Pattern Notation .......................................................................When and How to Apply Patterns ......................................................

Using Gang of Four Behavioral Patterns...........................Objectives ................................................................................................Introducing Behavioral Patterns .........................................................Strategy Pattern Example Problem .....................................................Applying the Strategy Pattern: Problem Forces ...............................Applying the Strategy Pattern: Solution.............................................Strategy Pattern Structure.....................................................................Strategy Pattern Example Solution......................................................Applying the Strategy Pattern ............................................................Command Pattern Example Problem .................................................Applying the Command Pattern:

Problem Forces ...................................................................................

Page 6: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 3Copyrig

............................................... 2-16

............................................... 2-17

............................................... 2-19 Language............................ 2-20............................................... 2-21............................................... 2-22............................................... 2-24............................................... 2-25............................................... 2-26............................................... 2-27............................................... 2-28uage ..................................... 2-29............................................... 2-31............................................... 2-33............................................... 2-34............................................... 2-35............................................... 2-36............................................... 2-37nguage .................................. 2-42............................................... 2-43............................................... 2-45

.................................... 3-1

................................................. 3-4

................................................. 3-5

................................................. 3-6

................................................. 3-7

................................................. 3-8

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command Pattern: Solution .......................................Command Pattern Structure ................................................................Command Pattern Example Solution ................................................Applying the Command Pattern: Use in the Java™ ProgrammingEJB Command Pattern Dynamic Structure .......................................Applying the Command Pattern: Consequences .............................Applying the Iterator Pattern: Example Problem ............................Applying the Iterator Pattern: Problem Forces .................................Applying the Iterator Pattern: Solution ..............................................Iterator Pattern Structure .....................................................................Iterator Pattern Example Solution ......................................................Applying the Iterator Pattern: Use in the Java Programming LangApplying the Iterator Pattern: Consequences ...................................Applying the Observer Pattern: Example Problem .........................Applying the Observer Pattern: Problem Forces ..............................Applying the Observer Pattern: Solution...........................................Observer Pattern Structure ..................................................................Observer Pattern Example Solution ...................................................Applying the Observer Pattern: Use in the Java Programming LaApplying the Observer Pattern: Consequences ................................Summary ................................................................................................

Using Gang of Four Creational Patterns............................Objectives 2Factory Method Pattern Example Problem........................................Applying the Factory Method Pattern: Problem Forces ..................Applying the Factory Method Pattern: Solution ...............................Factory Method Pattern Structure ......................................................Factory Method Pattern Example Solution ........................................

Page 7: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 4Copyrig

................................................. 3-9

............................................... 3-10

............................................... 3-11

............................................... 3-12

............................................... 3-13

............................................... 3-14

............................................... 3-15

............................................... 3-16

............................................... 3-17

............................................... 3-18

............................................... 3-19

............................................... 3-21

............................................... 3-22

............................................... 3-23

.................................... 4-1

.................................................. 4-2

.................................................. 4-4

.................................................. 4-5

................................................. 4-6

.................................................. 4-7

................................................. 4-8

.................................................. 4-9

............................................... 4-10

............................................... 4-11

................................................ 4-12

............................................... 4-13

................................................ 4-14

................................................ 4-15

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC API Factory Method Scheme Class Diagram ..........................Applying the Factory Method Pattern: Consequences ....................Abstract Factory Pattern Example Problem.......................................Applying the Abstract Factory Pattern: Problem Forces .................Applying the Abstract Factory Pattern: Solution .............................Abstract Factory Pattern Structure ......................................................Abstract Factory Pattern Example Solution .......................................Applying the Abstract Factory Pattern: Consequences....................Applying the Singleton Pattern: Example Problem .........................Applying the Singleton Pattern: Problem Forces .............................Singleton Pattern Structure ..................................................................Singleton Pattern Example Solution....................................................Applying the Singleton Pattern: Consequences ................................Summary .................................................................................................

Using Gang of Four Structural Patterns ............................Objectives ................................................................................................Façade Pattern Example Problem .......................................................Applying the Façade Pattern: Problem Forces .................................Applying the Façade Pattern: Solution...............................................Façade Pattern Structure ......................................................................Façade Pattern Example Solution........................................................Façade Pattern Example Sequence ......................................................Applying the Façade Pattern: Consequences ....................................Proxy Pattern Example Problem..........................................................Applying the Proxy Pattern: Problem Forces ...................................Applying the Proxy Pattern: Solution.................................................Proxy Pattern Structure ........................................................................Applying the Proxy Pattern: Solution ................................................

Page 8: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 5Copyrig

................................................ 4-16age ........................................ 4-17............................................... 4-18............................................... 4-19............................................... 4-20................................................ 4-21................................................ 4-22............................................... 4-23............................................... 4-24................................................ 4-26................................................ 4-28................................................ 4-29............................................... 4-30............................................... 4-31............................................... 4-32anguage ............................... 4-35................................................ 4-36................................................ 4-37................................................ 4-38............................................... 4-39................................................ 4-40............................................... 4-41............................................... 4-43nguage................................. 4-44............................................... 4-45

..................................... 5-1

.................................................. 5-2

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Proxy Pattern Example Solution .........................................................Applying the Proxy Pattern: Use in the Java Programming LanguApplying the Proxy Pattern: Consequences ......................................Adapter Pattern Example Problem .....................................................Applying the Adapter Pattern: Problem Forces ................................Applying the Adapter Pattern: Solution ...........................................Object Adapter Strategy Structure ......................................................Class Adapter Strategy Structure ........................................................Object Adapter Strategy Example Solution .......................................Applying the Adapter Pattern: Consequences .................................Composite Pattern Example Problem ................................................Applying the Composite Pattern: Problem Forces ..........................Applying the Composite Pattern: Solution ........................................Composite Pattern Structure ................................................................Composite Pattern Example Solution .................................................Applying the Composite Pattern: Use in the Java Programming LApplying the Composite Pattern: Consequences .............................Decorator Pattern Example Problem ..................................................Applying the Decorator Pattern: Problem Forces ............................Applying the Decorator Pattern: Solution..........................................Decorator Pattern Structure .................................................................Decorator Pattern Example Solution...................................................Decorator Pattern Example Sequence.................................................Applying the Decorator Pattern: Use in the Java Programming LaApplying the Decorator Pattern: Consequences ...............................Summary 46

Using Architectural Building Blocks .................................Objectives ...............................................................................................

Page 9: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 6Copyrig

.................................................. 5-3

................................................. 5-4

................................................. 5-5

................................................. 5-6

................................................. 5-7

.................................................. 5-8

................................................ 5-10

................................................ 5-11

................................................ 5-12

............................................... 5-13

................................................ 5-14

................................................ 5-15

................................................ 5-16

................................................ 5-17lications ................................ 5-18................................................ 5-19................................................ 5-21................................................ 5-23................................................ 5-24................................................ 5-25

.................................... 6-1

................................................. 6-2

................................................. 6-3

................................................. 6-4

................................................. 6-5

................................................. 6-6

................................................. 6-7

................................................. 6-8

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Comparing Architectural Patterns to Design Patterns ....................Applying the Model View Controller (MVC) Pattern......................Applying the MVC Pattern: Example Problem .................................Applying the MVC Pattern: Problem Forces .....................................Applying the MVC Pattern: Solution..................................................Model View Controller Pattern Structure .........................................Model View Controller Pattern Example Solution ..........................Applying the MVC Pattern: Consequences .......................................Applying the Layers Pattern ...............................................................Applying the Layers Pattern: Example Problem...............................Applying the Layers Pattern: Problem Forces ..................................Applying the Layers Pattern: Solution ..............................................Layers Pattern: Example Solution ......................................................Applying the Layers Pattern: Consequences ....................................Applying Layers and Tiers in Java™ EE Platform Enterprise AppSunToneTM Architecture Methodology Layers ................................SunTone Architecture Methodology Tiers ........................................Java EE Technologies in Each Tier ......................................................Java EE Platform Example – Layers and Tiers ..................................Summary ................................................................................................

Introducing Java EE™ Patterns..........................................Objectives ................................................................................................Purpose of the Java EE Patterns ..........................................................Benefits ....................................................................................................Relation to the Java EE BluePrints Design Guidelines ....................Gang of Four and Java EE Patterns .....................................................Describing the Patterns and Tiers of the Java EE Pattern Catalog..Integration Tier Patterns .......................................................................

Page 10: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 7Copyrig

................................................. 6-9

............................................... 6-11

............................................... 6-13

..................................... 7-1

.................................................. 7-2

.................................................. 7-3

.................................................. 7-4

................................................. 7-5

.................................................. 7-6

.................................................. 7-7

................................................. 7-8

.................................................. 7-9

............................................... 7-10

............................................... 7-12

............................................... 7-13

................................................ 7-14

............................................... 7-15

............................................... 7-16

............................................... 7-17

............................................... 7-18

................................................ 7-19

................................................ 7-20

................................................ 7-21

................................................ 7-26

............................................... 7-27

................................................ 7-28

................................................ 7-29

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Tier Patterns ...........................................................................Presentation Tier Patterns ....................................................................Java EE Pattern Relationships ..............................................................Summary 14

Using Integration Tier Patterns ..........................................Objectives ...............................................................................................Introducing Integration Tier Patterns .................................................Integration Tier Java EE Patterns Overview .....................................Applying the Service Activator Pattern: Problem Forces ................Applying the Service Activator: Solution ..........................................Service Activator Pattern Structure ....................................................Service Activator Pattern Sequence.....................................................Applying the Service Activator Pattern: Strategies ..........................Service Activator Pattern Example......................................................Service Activator Pattern Example......................................................Service Activator Pattern Example......................................................Applying the Service Activator: Consequences ...............................Applying the DAO Pattern: Problem Forces .....................................Applying the DAO Pattern: Solution..................................................DAO Pattern Structure..........................................................................DAO Pattern Sequence..........................................................................Applying the DAO Pattern: Strategies ...............................................DAO Abstract Factory Strategy Structure .........................................DAO Pattern Example...........................................................................DAO Pattern Example ..........................................................................Applying the DAO Pattern: Consequences .......................................Applying the Domain Store Pattern: Problem Forces .....................Applying the Domain Store Pattern: Solution ..................................

Page 11: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 8Copyrig

............................................... 7-30

............................................... 7-31

............................................... 7-32

................................................7-33

............................................... 7-35

................................................ 7-39

................................................ 7-40

............................................... 7-42

................................................ 7-43

................................................ 7-44

................................................ 7-45

............................................... 7-46

................................................ 7-47

............................................... 7-51

..................................... 8-1

.................................................. 8-2

.................................................. 8-3

.................................................. 8-4

.................................................. 8-5

.................................................. 8-6

.................................................. 8-7

................................................. 8-8

.................................................. 8-9

................................................ 8-10

................................................ 8-13

................................................ 8-15

............................................... 8-16

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Domain Store Pattern Structure...........................................................Domain Store Persistence Sequence....................................................Domain Store Query Sequence ............................................................Applying the Domain Store: Example ................................................Applying the Domain Store Pattern: Example ..................................Applying the Domain Store Pattern: Strategies ...............................Applying the Domain Store Pattern: Consequences .......................Applying the Web Service Broker Pattern: Problem Forces ............Applying the Web Service Broker Pattern: Solution .......................Web Service Broker Pattern Structure.................................................Web Service Broker Pattern Sequence ...............................................Applying the Web Service Broker Pattern: Strategies ......................Web Service Broker Pattern Example ................................................Applying the Web Service Broker Pattern: Consequences 50Summary .................................................................................................

Using Presentation-to-Business Tier Patterns .................Objectives ...............................................................................................Introducing Business Tier Patterns ....................................................Java EE Platform Business Tier Patterns ............................................Applying the Service Locator Pattern: Problem Forces ...................Applying the Service Locator Pattern: Solution ...............................Service Locator Pattern Structure .......................................................Service Locator Pattern Sequence........................................................Applying the Service Locator Pattern: Strategies .............................Service Locator Pattern Example ........................................................Applying the Service Locator Pattern: Consequences .....................Applying the Session Façade Pattern: Problem Forces ...................Applying the Session Façade Pattern: Solution.................................

Page 12: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 9Copyrig

................................................ 8-17

............................................... 8-18

................................................ 8-19

............................................... 8-20

............................................... 8-23

............................................... 8-25

................................................ 8-26

............................................... 8-27

............................................... 8-28

............................................... 8-29

................................................ 8-30

................................................ 8-33

................................................ 8-35

................................................ 8-36

................................................ 8-37

............................................... 8-38

................................................ 8-39

................................................ 8-40

................................................ 8-41

................................................ 8-43

............................................... 8-44

.................................... 9-1

................................................. 9-2

.................................................. 9-4

................................................. 9-5

................................................. 9-6

................................................. 9-7

.................................................. 9-8

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern Structure.........................................................Session Façade Pattern Sequence.........................................................Applying the Session Façade Pattern: Strategies .............................Session Façade Pattern Example..........................................................Applying the Session Façade Pattern: Consequences ......................Applying the Business Delegate Pattern: Problem Forces...............Applying the Business Delegate Pattern: Solution ..........................Business Delegate Pattern Structure ...................................................Business Delegate Pattern Sequence ...................................................Applying the Business Delegate Pattern: Strategies .........................Business Delegate Pattern Example ...................................................Applying the Business Delegate Pattern: Consequences .................Applying the Transfer Object Pattern: Problem Forces ...................Applying the Transfer Object Pattern: Solution ...............................Transfer Object Pattern Structure ........................................................Transfer Object Pattern Sequence........................................................Applying the Transfer Object Pattern: Strategies .............................Updatable Transfer Objects Sequence ...............................................Transfer Object Pattern Example ........................................................Applying the Transfer Object Pattern: Consequences .....................Summary .................................................................................................

Using Intra-Business Tier Patterns ....................................Objectives ................................................................................................Applying the Application Service Pattern: Problem Forces ............Applying the Application Service Pattern: Solution.........................Application Service Pattern Structure.................................................Application Service Pattern Sequence ................................................Applying the Application Service Pattern: Strategies .....................

Page 13: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 10Copyrig

.................................................. 9-9

................................................ 9-12

................................................ 9-13

............................................... 9-14

................................................ 9-15

............................................... 9-16

................................................ 9-17

................................................ 9-18

................................................ 9-19

............................................... 9-21

................................................ 9-22

................................................ 9-24

............................................... 9-25

................................................ 9-26

................................................ 9-27

............................................... 9-29

............................................... 9-31

................................................ 9-33

............................................... 9-34

................................................ 9-35

................................................ 9-36

............................................... 9-37

................................................ 9-38

................................................ 9-45

................................................ 9-47

............................................... 9-48

................................................ 9-50

............................................... 9-51

................................................ 9-52

............................................... 9-53

............................................... 9-58

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern Example ................................................Applying the Application Service Pattern: Consequences .............Applying the Business Object Pattern: Problem Forces ..................Applying the Business Object Pattern: Solution................................Business Object Pattern Structure .......................................................Business Object Pattern Sequence .......................................................Applying the Business Object Pattern: Strategies ............................Business Object Pattern Example .......................................................Applying the Business Object Pattern: Consequences ....................Applying the Transfer Object Assembler Pattern: Problem ForcesApplying the Transfer Object Assembler Pattern: Solution ............Transfer Object Assembler Pattern Structure ...................................Transfer Object Assembler Pattern Sequence ....................................Applying the Transfer Object Assembler Pattern: Strategies..........Transfer Object Assembler Pattern Example ....................................Applying the Transfer Object Assembler Pattern: Consequences..Applying the Composite Entity Pattern: Problem Forces................Comparing BMP and CMP ..................................................................Applying the Composite Entity Pattern: Solution ............................Composite Entity Pattern Structure ...................................................Composite Entity Pattern Sequence ...................................................Applying the Composite Entity Pattern: Strategies..........................Composite Entity Pattern Example ....................................................Applying the Composite Entity Pattern: Consequences..................Applying the Value List Handler Pattern: Problem Forces ............Applying the Value List Handler Pattern: Solution .........................Value List Handler Pattern Structure .................................................Value List Handler Pattern Sequence .................................................Applying the Value List Handler Pattern: Strategies ......................Value List Handler Pattern Example ..................................................Applying the Value List Handler Pattern: Consequences ...............

Page 14: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 11Copyrig

............................................... 9- 60

................................... 10-1

............................................... 10-2

............................................... 10-3

................................................ 10-4

................................................ 10-5

................................................ 10-6

................................................ 10-7

................................................ 10-8

.............................................. 10-10

.............................................. 10-11

.............................................. 10-12

.............................................. 10-13

............................................. 10-14

............................................. 10-15

.............................................. 10-17

.............................................. 10-19

.............................................. 10-20

.............................................. 10-21

.............................................. 10-22

.............................................. 10-23

.............................................. 10-25

.............................................. 10-26

.............................................. 10-27

.............................................. 10-29

.............................................. 10-30

.............................................. 10-31

............................................. 10-32

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary .................................................................................................

Using Presentation Tier Patterns ......................................Objectives ................................................................................................Introducing the Presentation Tier Patterns ........................................Presentation Tier Patterns ....................................................................Traditional Model View Controller Architecture .............................Model 2 Architecture ............................................................................Apache Struts Framework ....................................................................Applying the Intercepting Filter Pattern: Problem Forces ..............Applying the Intercepting Filter Pattern: Solution ..........................Intercepting Filter Pattern Structure ..................................................Intercepting Filter Pattern Sequence ..................................................Applying the Intercepting Filter Pattern: Strategies ........................Applying the Intercepting Filter Pattern: Example...........................Applying the Intercepting Filter Pattern: Example...........................Applying the Intercepting Filter Pattern: Consequences ................Applying the Front Controller Pattern: Problem Forces .................Applying the Front Controller Pattern: Solution .............................Front Controller Pattern Structure .....................................................Front Controller Pattern Sequence .....................................................Applying the Front Controller Pattern: Strategies ...........................Front Controller Pattern Example ......................................................Applying the Front Controller Pattern: Consequences ...................Applying the Application Controller Pattern: Problem Forces ......Applying the Application Controller Pattern: Solution ..................Application Controller Pattern Structure ...........................................Application Controller Pattern Sequence ..........................................Applying the Application Controller Pattern: Strategies.................

Page 15: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 12Copyrig

.............................................. 10-35

............................................. 10-38

............................................. 10-39

.............................................. 10-40

.............................................. 10-41

.............................................. 10-42

.............................................. 10-43

.............................................. 10-46

.............................................. 10-49

.................................. 11-1

............................................... 11-2

............................................... 11-3

............................................... 11-4

............................................... 11-5

............................................... 11-6

............................................... 11-7

............................................... 11-8

............................................... 11-9

............................................. 11-11

............................................. 11-12

............................................. 11-13

............................................. 11-14

............................................. 11-15

............................................. 11-16

............................................. 11-17

............................................. 11-19

............................................. 11-21

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern Example ...........................................Applying the Application Controller Pattern: Consequences.........Applying the Context Object Pattern: Problem Forces ....................Applying the Context Object Pattern: Solution ................................Context Object Pattern Structure ........................................................Context Object Pattern Sequence ........................................................Applying the Context Object Pattern: Strategies ..............................Context Object Pattern Example .........................................................Applying the Context Object Pattern: Consequences ......................

More Presentation Tier Patterns.........................................Objectives ................................................................................................More Presentation Tier Patterns ..........................................................Applying the View Helper Pattern:

Problem Forces ...................................................................................Applying the View Helper Pattern: Solution.....................................View Helper Pattern Structure.............................................................View Helper Pattern Sequence ............................................................Applying the View Helper Pattern: Strategies .................................View Helper Pattern Example..............................................................Applying the View Helper Pattern: Consequences .........................Applying the Composite View Pattern: Problem Forces .................Applying the Composite View Pattern: Solution .............................Composite View Pattern Structure .....................................................Composite View Pattern Sequence .....................................................Applying the Composite View Pattern: Strategies ..........................Composite View Pattern Example ......................................................Applying the Composite View Pattern: Consequences ...................Applying the Dispatcher View Pattern ..............................................

Page 16: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 13Copyrig

............................................. 11-22

............................................. 11-23

............................................. 11-24

............................................. 11-25

............................................. 11-26

............................................. 11-30

............................................. 11-32

............................................. 11-33

............................................. 11-34

............................................. 11-35

............................................. 11-36

............................................. 11-37

............................................. 11-40

............................................. 11-41

.................................. 12-1

................................................ 12-2

................................................ 12-3

................................................ 12-4

................................................ 12-5

................................................ 12-7

................................................ 12-9

............................................. 12-11

............................................. 12-14

.............................................. 12-15

.............................................. 12-18

.............................................. 12-20

.............................................. 12-22

.............................................. 12-24

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View Pattern: Problem Forces ................Applying the Dispatcher View Pattern: Solution..............................Dispatcher View Pattern Structure .....................................................Dispatcher View Pattern Sequence ....................................................Dispatcher View Pattern Example ......................................................Applying the Dispatcher View Pattern: Consequences ..................Applying the Service to Worker Pattern ...........................................Applying the Service to Worker Pattern: Problem Forces ...............Applying the Service to Worker Pattern: Solution ...........................Service to Worker Pattern Structure ...................................................Service to Worker Pattern Sequence ...................................................Service to Worker Pattern Example ....................................................Applying the Service to Worker Pattern: Consequences .................Service to Worker Pattern In Struts ....................................................

Exploring AntiPatterns ........................................................Objectives ...............................................................................................Introducing AntiPatterns .....................................................................Describing Integration Tier AntiPatterns ..........................................Not Pooling Connections AntiPattern ................................................Monolithic Consumer AntiPattern .....................................................Fat Message AntiPattern ......................................................................Hot Potato AntiPattern..........................................................................Describing Business Tier AntiPatterns ...............................................Sledgehammer for a Fly AntiPattern .................................................Local and Remote Interfaces Simultaneously AntiPattern ..............Accesses Entities Directly AntiPattern ...............................................Mirage AntiPattern ...............................................................................Cacheless Cow AntiPattern ..................................................................

Page 17: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 14Copyrig

............................................. 12-27

............................................. 12-29

.............................................. 12-31

.............................................. 12-32

............................................. 12-34

.............................................. 12-36

.............................................. 12-38

.................................. 13-1

............................................... 13-2

................................................ 13-3

................................................ 13-4

............................................... 13-5

............................................... 13-6

............................................... 13-7

............................................... 13-9

.............................................. 13-10

............................................. 13-11

.............................................. 13-12

............................................. 13-13

............................................. 13-14

.............................................. 13-15

.............................................. 13-16

............................................. 13-18

.............................................. 13-20

.............................................. 13-21

............................................. 13-22

............................................. 13-23

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Conversational Baggage AntiPattern..................................................Golden Hammers of Session State AntiPattern.................................Describing Presentation Tier AntiPatterns ........................................Including Common Functionality in Every Servlet AntiPattern ...Embedded Navigational Information AntiPattern ...........................Ad Lib TagLibs AntiPattern ................................................................Summary ................................................................................................

Applying Java EE BluePrints Design Guidelines..............Objectives ................................................................................................Describing the Java EE BluePrints Design Guidelines ....................Object-Oriented Guidelines..................................................................Client Tier Guidelines ...........................................................................Web Tier Guidelines ..............................................................................Business Tier Guidelines.......................................................................Integration Tier Guidelines ..................................................................Describing the Java Pet Store Demo Software ..................................Analyzing Java EE Patterns in the Java Pet Store Demo SoftwareWeb Application Framework...............................................................Java Pet Store Demo Software Web Application Framework .........Java EE Patterns in the Web Application Framework......................The SignOnFilter Class Mapping in the web.xml File..................The SignOnFilter Class .....................................................................The SignOnFilter Class .....................................................................The SignOnFilter Class ......................................................................Front Controller Servlet Mapping in the web.xml File ...................The mapping.xml Class Mapping ......................................................The MainServlet Class ........................................................................The MainServlet Class ........................................................................

Page 18: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 15Copyrig

............................................. 13-25

.............................................. 13-26

.............................................. 13-27

.............................................. 13-28

.............................................. 13-29

............................................. 13-30

.............................................. 13-31

.............................................. 13-32

.............................................. 13-33

.............................................. 13-34

............................................. 13-35

............................................. 13-36

.............................................. 13-37

............................................. 13-38

.............................................. 13-39

............................................. 13-40are Administrative............................................. 13-42ctionality ............................. 13-43.............................................. 13-44.............................................. 13-45.............................................. 13-46............................................. 13-47.............................................. 13-49............................................. 13-50.............................................. 13-51.............................................. 13-52............................................. 13-54.............................................. 13-55

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The RequestProcessor Class processRequest Method ..............The RequestProcessor Class processRequest Method .............The DefaultWebController Class ..................................................The EJBControllerLocalEJB Class .................................................The EJBControllerLocalEJB Class .................................................The StateMachine Class ......................................................................The StateMachine Class .....................................................................The ScreenFlowManager Class ..........................................................The ScreenFlowManager Class ...........................................................The screendefinitions_en_US.xml File .......................................The screendefinitions_en_US.xml File ........................................The TemplateServlet Class ...............................................................The TemplateServlet Class ..............................................................The Template.jsp Page.......................................................................The Template.jsp Page ......................................................................The InsertTag Custom Tag ................................................................Analyzing the Java EE Patterns in the Java Pet Store Demo SoftwClasses .....................................................................................................Design Pattern Implementation in the Administrative Client FunThe AdminRequestBD Class..................................................................The AdminRequestBD Class .................................................................The ServiceLocator Class .................................................................The ServiceLocator Class..................................................................The ServiceLocator Class .................................................................The MutableOrderTO Class..................................................................The OPCAdminFacadeEJB Class ...........................................................The OPCAdminFacadeEJB Class ..........................................................The OPCAdminFacadeEJB Class ...........................................................Summary ................................................................................................

Page 19: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ EE Pattern 162008 Sun Microsystem

.....................................A-1

.....................................B-1

..................................................B-2

..................................................B-3

................................................. B-6

................................................. B-7

................................................B-15

................................................B-17) API .....................................B-24............................................... B-25............................................... B-27................................................B-28................................................B-32................................................B-33................................................B-34................................................B-35................................................B-38................................................B-39................................................B-40................................................B-41............................................... B-48................................................B-49onent .....................................B-50................................................B-54

ss, Inc. All Rights Reserved. Sun Services, Revision C.1

Table of Contents

Quick Reference for UML ...................................................

J2EE Technology Review ...................................................Objectives ................................................................................................Reviewing the J2EE Platform ..............................................................Multi-Tier J2EE Architecture Basics ....................................................Understanding Java Remote Method Invocation..............................Understanding the Java IDL API ........................................................Understanding the JAX-RPC API .......................................................Understanding the Java Naming and Directory Interface™ (JNDIJNDI API Class .......................................................................................Understanding Servlets.........................................................................Servlet Class ...........................................................................................Understanding JavaServer Pages™ Technology ..............................JSP Page Flow ........................................................................................HTML Form Processed by a JSP Page ................................................JSP Page ..................................................................................................Understanding the Java Message Service (JMS) API .......................Understanding the JMS API ................................................................Understanding the JMS API ................................................................Understanding the JMS API ................................................................Understanding Enterprise JavaBeans™ Technology ComponentsOverall Enterprise JavaBeans Architecture........................................Overall Enterprise JavaBeans Architecture: Parts of an EJB CompThree Types of EJB Components ........................................................

Page 20: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java™ 17Copyrig

................................................B-55

................................................B-56

................................................B-57

................................................B-58

............................................... B-62

................................................B-63

................................................B-64

............................................... B-65

................................................B-74

................................................B-75

................................................B-76

................................................B-79

................................................B-80

................................................B-83

................................................B-84

............................................... B-85

................................................B-87

............................................... B-88

............................................... B-91

EE Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Beans ..........................................................................................Session Bean Home Interface ..............................................................Session Bean Component Interface ....................................................Session Bean Class ................................................................................Entity Beans ............................................................................................BMP Entity Bean Home Interface .......................................................BMP Entity Bean Component Interface .............................................BMP Entity Bean Class ..........................................................................CMP Entity Bean Home Interface .......................................................CMP Entity Bean Component Interface .............................................CMP Entity Bean Class .........................................................................Message-Driven Beans .........................................................................Message-Driven Bean Class .................................................................Understanding JDBC™ Technology ..................................................JDBC Technology Class Interactions on the J2EE Platform ............JDBC Technology Using the DataSource Class .................................JDBC Technology Using the DataSource Class ................................Understanding J2EE Connector Architecture....................................Summary .................................................................................................

Page 21: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

P

A

Java EE™ Patterns

Preface

About This Coursereface

bout The Course

Preface

About The Course

Page 22: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 2 of 10

e able to:

tterns,

(Integration, 2 Platform,) applicationa Java EE

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Course Goals

Upon completion of this course, you should b

• Describe the fundamentals of design paincluding key Gang of Four patterns

• Apply appropriate patterns in the tiersBusiness, and Presentation) of a Java™Enterprise Edition (Java EE™ platform

• Use patterns to apply best practices in platform environment

Page 23: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java

EE

™ P

atte

rns

Pre

face

, slid

e3

of 1

0C

opyr

ight

200

8 S

un M

icro

syst

ems,

Inc.

All

Rig

hts

Res

erve

d. S

un S

ervi

ces,

Rev

isio

n C

.1

Ap

plic

atio

no

fBes

tPra

ctic

esIn

Java

EE

Env

iro

nm

ent

Exp

lorin

gA

ntiP

atte

rns

App

lyin

gJa

vaE

EB

lueP

rints

Des

ign

Gui

delin

es

Cou

rse

Map

Pat

tern

Fu

nd

amen

tals

Usi

ngG

ang

ofF

our

Beh

avio

ralP

atte

rns

Exp

lorin

gO

bjec

t-O

rient

edD

esig

nP

rinci

ples

and

Des

ign

Pat

tern

s

Usi

ngG

ang

ofF

our

Str

uctu

ralP

atte

rns

Usi

ngG

ang

ofF

our

Cre

atio

nalP

atte

rns

Usi

ngP

rese

ntat

ion-

to-B

usin

ess

Tie

rPat

tern

s

Usi

ngIn

tegr

atio

nT

ierP

atte

rns

Usi

ngIn

tra-

Bus

ines

sT

ierP

atte

rns

Pat

tern

sIn

Java

EE

Ap

plic

atio

nT

iers

Usi

ngA

rchi

tect

ural

Bui

ldin

gB

lock

sIn

trod

ucin

gJa

vaE

E™

Pat

tern

s

Usi

ngP

rese

ntat

ion

Tie

rPat

tern

s

Mor

eP

rese

ntat

ion

Tie

rPat

tern

s

Page 24: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 4 of 10

. Many of these Sun Services:

overed insign Using UMLent – CoveredApplicationsin SL-425:cations

nformation

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Topics Not Covered

This course does not cover the following topicstopics are covered in other courses offered by

• Object-oriented analysis and design – COO-226: Object-Oriented Analysis and De

• Java EE platform application developmin FJ-310: Developing Java EE Compliant

• Java EE system architecture – Covered Architecting and Designing Java EE Appli

Refer to the Sun Services catalog for specific iand registration.

Page 25: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 5 of 10

e, can you

g the Java

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

How Prepared Are You?

To be sure you are prepared to take this coursanswer yes to the following questions?

• Have you designed systems usingobject-oriented techniques?

• Have you developed applications usinprogramming language?

Page 26: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 6 of 10

nologies, such JavaBeans™let technologyeology?uage (UML)gram?

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

How Prepared Are You?

• Can you describe Java EE platform techas components based on the Enterprisespecification (EJB™ components), servcomponents, and pages created with thJavaServer Pages™ (JSP™ pages) techn

• Can you read a Unified Modeling Langclass diagram and a UML sequence dia

Page 27: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 7 of 10

in this course

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introductions

• Name• Company affiliation• Title, function, and job responsibility• Experience related to topics presented • Reasons for enrolling in this course• Expectations for this course

Page 28: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 8 of 10

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Icons

Additional resources

Demonstration

Discussion

Note

123

?!

Page 29: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 9 of 10

ns

ands, files,mmingtput.and numbersramming coden.es andplaced with a

epresentby the student

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Typographical Conventio

• Courier is used for the names of commdirectories, programming code, prograconstructs, and on-screen computer ou

• Courier bold is used for characters that you type, and for each line of progthat is referenced in a textual descriptio

• Courier italics is used for variablcommand-line placeholders that are rereal name or value.

• Courier italics bold is used to rvariables whose values are to be enteredas part of an activity.

Page 30: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Preface, slide 10 of 10

e following

ethods,

es unless an.rations,e.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Additional Conventions

Java programming language examples use thadditional conventions:

• Courier is used for the class names, mand keywords.

• Methods are not followed by parenthesformal or actual parameter list is show

• Line breaks occur where there are sepaconjunctions, or white space in the cod

Page 31: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

onentM

EODD

Java EE™ Patterns

Module 1

Developing a View Compodule 1

xploringbject-Orientedesign Principles andesign Patterns

Module 1

ExploringObject OrientedDesign Principles AndDesign Patterns

Page 32: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 2 of 38

ed

ed

atterns

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the fundamental object-orientdesign concepts

• Describe the fundamental object-orientdesign principles

• Describe the characteristics of design p

Page 33: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 3 of 38

tterns forals:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Reviewing Design Goals

This course presents design principles and pareaching the following Java EE™ platform go

• Adaptability• Extensibility• Maintainability• Reusability• Performance• Scalability• Reliability• Development efficiency

Page 34: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 4 of 38

ach these goals:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Course Flow

The course presents the following topics to reObject-Oriented Design Principles

Architectural Patterns

Anti-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Page 35: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 5 of 38

sign

re the buildingerns:

ition inheritancephism

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Exploring Object-Oriented DeConcepts

These fundamental object-oriented concepts ablocks of the object-oriented and Java EE patt

• Cohesion• Encapsulation• Coupling• Implementation

inheritance

• Compos• Interface• Polymor

Page 36: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 6 of 38

thods andurpose

nrelated code

e class’ roleble components

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Cohesion

• Cohesion is the degree to which the meattributes of a class focus on only one pin the system

• Advantages of high cohesion:• Avoids the side affects of changing u

within the same class• Improves readability by clarifying th• Facilitates the creation of small reusa

Page 37: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 7 of 38

ples

vice

ee()()yName()

rvice

ment()nt()ByID()

ice

sion

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Low and High Cohesion Exam

SystemServices

+deleteDepartment()+deleteEmployee()+login()+logout()+makeDepartment()+makeEmployee()+retrieveDeptByID()+retrieveEmpByName()

EmployeeSer

+deleteEmploy+makeEmployee+retrieveEmpB

DepartmentSe

+deleteDepart+makeDepartme+retrieveDept

LoginServ

+login()+logout()

High CoheLow Cohesion

Page 38: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 8 of 38

n object should

apsulation:

ld provide an

ithout

t knowing all of

s are prevented

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Encapsulation

• The internal structure and behavior of anot be exposed

• Information hiding is key to proper enc• Data should be kept private• Accessor and mutator methods shou

abstract interface to the data• Advantages:

• Implementation of a class can vary wchanging its interface

• Developers can use the class withouits implementation details

• Inappropriate attribute modification

Page 39: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 9 of 38

Name();

amantha");

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Encapsulation Example

ObjectsClasses

Stack

main employee

department

:Engineer

fname="Fred"lname="Cartz"salary=US$47,000

Engineer

-fname:String-lname:String-salary:Money

+getFirstName():String+getLastName():String+setFirstName(:String)+increaseSalary(amt)+analyzeReq()+designSoftware()+implementCode()

name = employee.fname; name = employee.getFirst

employee.fname = "Samantha"; employee.setFirstName("S

Page 40: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 10 of 38

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Encapsulation Example

1 class Engineer {2 private String fname;3 private String lname;4 private Money salary;56 public String getFirstName() {7 return fname;8 }910 public String getLastName() {11 return lname;12 }1314 public void setFirstName(String fn) {15 fname = fn;16 }17 ...18 }

Page 41: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 11 of 38

t classes are on

sesclasse interface

tem rather than

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Coupling

• Coupling is a measure of how dependanother classes

• To reduce coupling:• Hide the implementation of the clas• Couple to the abstract interface of a • Reduce the number of methods in th

of the class• Consider the coupling of the entire sys

just between individual classes

Page 42: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 12 of 38

Service

Coupling

upling

Service

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Four Levels of Coupling

<<interface>>

Service

ServiceClient

Looser Abstract Coupling

Looser Tight Coupling

Client

Client

No Co

Client

ServiceImpl

Page 43: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 13 of 38

e

ed attributes

on to subtypesnce

om

the subclass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Implementation Inheritanc

Implementation inheritance is inheriting sharand methods from a superclass

Advantages:

• Avoids duplication of code that is comm• Organizes classes according to inherita

Disadvantages:

• Forces subclass to inherit everything frits superclass

• Changes to the superclass might affect

Page 44: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 14 of 38

mple

oyee

ggy

StringString Moneyy( : int )me : String )me : String )lary : Money )

Engineer

-education : String-hardware : String

+analyzeReq()+designSoftware()+getEducation()+getHardware()+implementCode()

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Implementation Inheritance Exa

1 class Employee2 {3 . . .4 }56 class Manager extends Employee7 {8 . . .9 }1011 class Engineer extends Employee12 {13 . . .14 }

Empl

-fname : Strin-lname : Strin-salary : Mone

+getFname() : +getLname() : +getSalary() :+increaseSalar+setFname( fna+setLname( lna+setSalary( sa

Manager

-quarterlyBonus : Money

+increaseBonus()+playGolfWithClient()

Page 45: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 15 of 38

jects

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composition

• Builds complex objects from simpler ob• Forms a looser coupling than

implementation inheritance

1 class Department {2 private Employee worker;3 .. .4 }

Department Employee

Page 46: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 16 of 38

terface

ment a

ing modifiedinterfaces)tract classes

ossible andhether anpriate for them

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Interface Inheritance

Interface inheritance is the separation of an indefinition from its implementation:

• Similar to hardware devices that implecommon interface

• Can make a class extensible without be• Java technology-based interfaces (Java

provide pure interface inheritance; absallow a mixture of implementation andinterface inheritance

• This course uses interfaces whenever pleaves it to the attendee to determine wabstract class or interface is more appro

Page 47: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 17 of 38

le

ation}ementation}

renceRoom

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Interface Inheritance Examp

1 interface Schedulable {2 public void cancelActivity();3 public void notifyAboutActivity();4 }5 class Equipment implements Scheduable {6 public void cancelActivity() {//implement7 public void notifyAboutActivity() {//impl8 }

<<interface>>Schedulable

+cancelActivity()+notifyAboutActivity()

ConfeEquipment

Schedule

Employee

Page 48: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 18 of 38

erations ofces

ypes at runtimeed by the object

oes not depend

use a supertype

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Polymorphism

• Polymorphism allows invocation of opspecific objects through generic referen

• Aspects of polymorphism:• A variable can be assigned different t• Method implementation is determin

type, not the reference type

Advantages:

• Enables you to write generic code that dupon a specific subclass

• Allows you to code fewer methods becacan be specified as the parameter type

Page 49: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 19 of 38

:List

er

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Polymorphism Example

List list = getProjectTeam();for ( int i=0; i<list.size(); i++ ) { Employee employee = (Employee) list.get(i); employee.increaseSalary(0.10); //10%}

ObjectsClasses

Stack

main employee

list

Employee Kathy:Manag

Fred:Engineer

Samantha:EngineerManager Engineer

Page 50: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 20 of 38

sign

riented

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Exploring Object-Oriented DePrinciples

The Gang of Four book outlines three object-odesign principles:

• Favoring composition• Programming to an interface• Designing for change

Page 51: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 21 of 38

ementation], and Vlissides,bject-Oriented

ead of

x reuse

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Favoring Composition

“Favor object composition over [implinheritance.” (Gamma, Helm, JohnsonDesign Patterns: Elements of Reusable OSoftware)

Reuse functionality through composition instimplementation inheritance:

• Implementation inheritance is white-bo• Composition is black-box reuse

Page 52: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 22 of 38

ArrayList

lementData : Objectize : int.

dd( o : Object ) : booleanrrayList( initialCapacity : int )lear()et( index : int ) : Objectemove( index : int )ize() : int.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Favoring Composition

ArrayList

-elementData : Object-size : int...

+add( o : Object ) : boolean+ArrayList( initialCapacity : int )+clear()+get( index : int ) : Object+remove( index : int )+size() : int...

DepartmentEmployeeList

-departmentName : String

+getDepartmentName() : String+setDeptName( deptName ) : String

Implementation Inheritance

DepartmentEmployeeList

-departmentName : String

+addEmployee( e : Employee ) : boolean+fireEmployee( e : Employee )+getDepartmentName() : String+getEmployee( ssn : String ) : Employee+getNumEmployees() : int+setDeptName( deptName : String )...

-e-s..

+a+A+c+g+r+s..

Composition

-employees

Page 53: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 23 of 38

e

ion.” (Gamma,: Elements of

ooleanacity : int )

Object

>>n

: boolean

ooleanlean

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Programming to an Interfac

“Program to an interface, not an implementatHelm, Johnson, and Vlissides, Design PatternsReusable Object-Oriented Software)

DepartmentEmployeeList

-departmentName : String

+addEmployee( e : Employee ) : boolean+fireEmployee( e : Employee )+getDepartmentName() : String+getEmployee( ssn : String ) : Employee+getNumEmployees() : int+setDepartmentName( departmentName ) : String...

ArrayList

-elementData-size : int...

+add( o : Object ) : b+ArrayList( initialCap

+clear()+get( index : int ) : +remove( index : int )+size() : int...

<<interfaceCollectio

+add( o : Object )+clear()+contains( o ) : b+remove( o ) : boo+size() : int

-employees

Page 54: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 24 of 38

e

ion:

st();

ist();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Programming to an Interfac

Programming to the ArrayList Implementat

1 public class DepartmentEmployeeList {2 private ArrayList employees = new ArrayLi3 . . .4 }

Programming to the Collection Interface:

1 public class DepartmentEmployeeList {2 private Collection employees = new ArrayL3 . . .4 }

Page 55: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 25 of 38

ing for change:

designing for

n-Closedsses, should befication

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Designing for Change

The previous two principles are about design

• Requirements do change, which makeschange very important

• This is more formally stated in the Opeprinciple: Software entities, such as claopen for extension but closed for modi

Page 56: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 26 of 38

s

experiencerade-offs to

gn

turessign decisions

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Design Pattern

Design patterns:

• Identify and document proven design • Capture recurring solutions and their t

similar problems in a given context• Provide a common vocabulary for desi

and architecture• Clarify and document existing architec• Move design forward and influence de

Page 57: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 27 of 38

pt

concept. They

t occurs overnd thenat problem, in

tion a millionsame

guage: Towns,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Origin of the Pattern Conce

Building architects first developed the patternstated that:

“Each pattern describes a problem thaand over again in our environment, adescribes the core of the solution to thsuch a way that you can use this solutimes over, without ever doing it theway twice.”(Christopher Alexander, A Pattern LanBuildings, Construction)

Page 58: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 28 of 38

are catalogs ofure, building

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern Catalogs

Pattern catalogs are groups of patterns. Theredesign patterns for analysis, design, architectarchitecture, and other topics.

This course focuses on two pattern catalogs:

• Gang of Four Design Pattern catalog• Java EE Pattern catalog

Page 59: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 29 of 38

s

Object-Orientedh Johnson, and

eral design

booktions toms

ere built upon

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Gang of Four (GoF) Pattern

The book Design Patterns: Elements of ReusableSoftware by Erich Gamma, Richard Helm, RalpJohn Vlissides:

• Represented the first publication of sevpatterns organized together

• Is often called the Gang of Four or GoF• Provided common object-oriented solu

common object-oriented design proble• Includes 23 design patterns• Influenced many Java EE patterns that w

the GoF patterns

Page 60: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 30 of 38

cription

ifies the keyke it useful fordesign patternes, their rolesponsibilities.ject-oriented

pplies, whethertraints, and the

n Patterns)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Gang of Four (GoF) Patterns: Des

“A design pattern names, abstracts, and identaspects of a common design structure that macreating a reusable object-oriented design. Theidentifies the participating classes and instancand collaborations, and the distribution of resEach design pattern focuses on a particular obdesign problem or issue. It describes when it ait can be applied in view of other design consconsequences and trade-offs of its use.”(Gamma, Helm, Johnson, and Vlissides, Desig

Page 61: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 31 of 38

roups

ups:

jects interact

ust ways to

cts are

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Gang of Four (GoF) Patterns: G

The GoF patterns are organized into three gro

• Behavioral patterns – Describe how oband distribute responsibility

• Creational patterns – Provide more robcreate objects

• Structural patterns – Discuss how objewired together

Page 62: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 32 of 38

pecific patterns

milaritieshe forces of the

e a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern Selection

There is no one best pattern, rather there are sthat apply to particular problems:

• Pattern selection should be based on sibetween the context, the problem, and tpattern and a design problem

• Multiple patterns might be used to solvparticular problem

Page 63: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 33 of 38

ts:

m being

addresses must satisfye problemvantages of

ilar or are used

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern Elements

Design patterns include the following elemen

• Context – Situation in which the probleaddressed occurs

• Problem – Design issue that the pattern• Forces – Requirements that the solution• Solution and Structure – Solution to th• Consequences – Advantages and disad

using the pattern• Related Patterns – Patterns that are sim

to build this pattern

Page 64: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 34 of 38

grams.

nt s;

t void y(int i);

tFname)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern Notation

This course uses UML class and sequence dia

Employee{abstract}

-fname : String-lname : String-numEmployees : int-salary : Money

+getFname() : String+increaseSalary( : int )+setFname( fname : String )...

Manager

-quarterlyBonus : Money

+increaseBonus()+increaseSalary( : int )+playGolfWithClient()

Engineer

-education : String-hardware : String

+analyzeReq()+designSoftware()+increaseSalary( : int )...

<<interface>>Schedulable

+cancelActivity()+notifyAboutActivity()

ConferenceRoomEquipment

Interface

creates

0..* -scheduleItems

+addActivity( : Schedulable )

Scheduler

Dependency

Multiplicity

Association

Role names

Realization (implements)

Abstract class

private Stringfname;

private static inumEmployee

public String getFname()

public abstracincreaseSalar

public void se(String fname

Generalization (extends)

Schedule

Page 65: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 35 of 38

loor: ConferenceRoom

5.1.1:notifyObservers

notifyAboutActivity method calls

otifyObservers method in the same class

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern Notation

fifthF

projector : Equipment

: Scheduler

: Schedule

Creation of object Objects

5.1:notifyAboutActivity

4:create()

3.1: notifyAboutActivity3.1.1: notifyObservers

5: addActivity( fifthFloor )

1: create()

2: create()

3: addActivity( projector )

n

Method call orsome form of

communication

Activation barshows when theobject is actively

working or waitingfor a response

Page 66: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 36 of 38

rns

e proactively

tterns and only

n balance of

u might be with a

er to solve

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

When and How to Apply Patte

• Some literature suggests that patterns bapplied to designs

• Some literature suggests using fewer parefactoring them into a design

• Either way, you should look for a desigflexibility and simplicity

• After taking a design pattern course, yoinclined to try and solve every problemdesign pattern

• Design patterns are not a golden hammevery problem

Page 67: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 37 of 38

Object-Oriented Design Principles

Architectural Patterns

-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

The following object-oriented conceptscan help you focus on improvingJava EE designs:

• Cohesion• Encapsulation• Implementation inheritance• Interface inheritance• Polymorphism• Coupling• Composition

Anti

Page 68: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 1, slide 38 of 38

hieve the Java

ience of otheroftware

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

The following GoF principles can help you acEE platform design goals:

• Favoring composition• Programming to an interface• Designing for change

Design patterns will help you reuse the experdesigners to improve your Java EE platform s

Page 69: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

l PatternsM

UB

Java EE™ Patterns

Module 2

Using Gang of Four Behavioraodule 2

sing Gang of Fourehavioral Patterns

Module 2

Using Gang Of FourBehavioral Patterns

Page 70: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 2 of 45

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the basic characteristics of theBehavioral patterns

• Apply the Strategy pattern• Apply the Command pattern• Apply the Iterator pattern• Apply the Observer pattern

Page 71: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 3 of 45

erns

he distribution

rithms for

cts for execution

loosely coupled

ts without

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Behavioral Patt

Behavioral patterns focus on algorithms and tof responsibility between classes

Pattern Primary FunctionStrategy Encapsulates a family of algo

interchangeable useCommand Encapsulates requests in obje

by another objectIterator Traverses any collection in a

wayObserver Provides notification of even

polling

Page 72: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 4 of 45

oblem

uld use

sorting strategy

rt

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Strategy Pattern Example Pr

• The library system’s search method comultiple algorithms to sort the results

• You need a way to easily exchange the

CatalogSearchEngine

+search() : ArrayList

//perform search//perform merge soreturn list;

Page 73: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 5 of 45

rn:

iple algorithms from

s of conditional

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Strategy PatteProblem Forces

• Classes often need to choose from mult• Details of algorithms should be hidden

client classes• Algorithms implemented in large serie

statements are difficult to maintain

Page 74: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 6 of 45

Solution

arate class that

trategy objectked, it forwards

btype of the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Strategy Pattern:

• Each algorithm is implemented in a sepimplements the Strategy interface

• The Clientobject has a reference to a S• When aClientobject operation is invo

the request to that strategy• The Client object can specify which su

Strategy interface should be used

Page 75: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 7 of 45

re

rategy3

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Strategy Pattern Structu

ConcreteSt

doTask()doTask()

<<interface>>Strategy

doTask()

strategy.doTask();

Client

+task()

-strategy

ConcreteStrategy2

doTask()

ConcreteStrategy1

Page 76: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 8 of 45

lution

rgeSort

: ArrayList )

)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Strategy Pattern Example So

QuickSort

+sort( : ArrayList )

Me

+sort(

CatalogSearchEngine

+search() : ArrayList

<<interface>>SortStrategy

+sort( : ArrayList

//perform searchsorter.sort(list);return list;

-sorter

Page 77: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 9 of 45

lution

s) {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Strategy Pattern Example So

Strategy pattern client:

1 public class CatalogSearchEngine {23 private SortStrategy sorter;45 public CatalogSearchEngine(SortStrategy s6 sorter = ss;7 }8 public ArrayList search() {9 ArrayList list = //perform search10 sorter.sort(list);11 return list;12 }13 }

Page 78: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 10 of 45

lution

egy {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Strategy Pattern Example So

Strategy pattern interface:

1 public interface SortStrategy {2 public void sort(ArrayList al);3 }

First strategy implementation:

1 public class QuickSort implements SortStrat2 public void sort(ArrayList al) {3 //implement Quick sort code4 }5 }

Page 79: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 11 of 45

ern

gorithms

gorithmstementss or changes to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Strategy Patt

Advantages:

• Allows multiple implementations of alwithout subclassing the client class

• Allows multiple implementations of alwithout placing them in conditional sta

• Allows easy additions of new algorithmexisting algorithms

Page 80: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 12 of 45

ern

are

ad

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Strategy Patt

Disadvantages:

• To select a strategy, clients must be awof the strategies

• There can be a slight increase in overhe

Page 81: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 13 of 45

roblem

can be executedabilities

ions and

rce )urce )ource )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Command Pattern Example P

• A library system has many actions that• The system requires undo and redo cap• You need a simple way to structure act

their invocationsLibraryActions

+checkIn( p : Patron, r : Resou+checkOut( p : Patron, r : Reso+putOnHold( p : Patron, r : Res

Client

Page 82: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 14 of 45

tern:

ated from how

ically add new

mechanics of

ld be simple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command PatProblem Forces

Useful when the client class needs to be separthat request is executed:

• There needs to be an easy way to dynamactions and modify existing actions

• The client should be simple• The client should not need to know the

handling a specific requests• The interface to carry out requests shou

Page 83: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 15 of 45

tern:

tionsmotely, or in a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command PatProblem Forces

• Undo and redo previously executed ac• Execute commands asynchronously, re

different thread

Page 84: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 16 of 45

: Solution

ute method ofand interfaceicCommandctof whatkes the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command Pattern

• Each action is implemented in the execits own class that implements the Comm

• The client creates the necessary Specifobject and passes it to an Invoker obje

• The Invoker object has no knowledge SpecificCommand does, it simply invoexecute method

Page 85: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 17 of 45

re

f action

ificCommand2

cute()

>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Command Pattern Structu

Invoker

+doCommand( c : Command )

implementation o

SpecificCommand1

+execute()

Spec

+exe

<<interface>Command

+execute()

c.execute();

create

create

Client

Page 86: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 18 of 45

: Solution

state data

ment the actionk an

d, process, or

execute

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command Pattern

Implementation strategies include:

• The SpecificCommand can also containrelating to the command

• TheSpecificCommandcan either impleitself or call other objects to do the wor

• The Command interface can also includeundo method

• The Invoker can be in a separate threaserver from the Client

• The Invoker can queue the actions andthem asynchronously

Page 87: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 19 of 45

olution

Command

esource, p : Patron )

)

and

rce, p : Patron )

te())

erface>>mmand

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Command Pattern Example S

PutOnHold

-item : Resource-thePatron : Patron

+execute()+PutOnHoldCommand( r : R+undo()

CheckOutCommand

-item : Resource-thePatron : Patron

+CheckOutCommand( p : Patron, r : Resource+execute()+undo()

CheckInComm

-item : Resource-thePatron : Patron

+CheckInCommand( r : Resou+execute()+undo()

LibraryCommandInvoker

-lastCommand : int

+executeCommand( lc : Command )+redoNextCommand()+undoLastCommand()

lastCommand++;if (lastCommand < history.size() history.get(lastCommand).execute();

history.get(lastCommand).undo();lastCommand--;

lc.execute();history.add(lc);lastCommand = history.size()-1;

check out the resource

+execu+undo(

undo the check out of the resource

item = r;thePatron = p;

Client

create

create

create

0..*

history

<<intCo

Page 88: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 20 of 45

Use in theage

us enterprise

documents the

lient from thee business logicCommand and is a stateless

ern

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command Pattern:Java™ Programming Langu

• GoF Command pattern is used in varioframeworks, such as Struts

• EJB Design Patterns, by Floyd MarinescuEJB Command pattern

• EJB Command pattern decouples the cbusiness tier and simplifies changing th

• The major distinction between the GoFEJB Command patterns is that Invokersession bean in the EJB Command patt

Page 89: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 21 of 45

StructureBusiness Objectsmand

1.1.1: doWork

return

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

EJB Command Pattern Dynamic<<SessionBean>>

Invokerremote:Com

local : Command

RoutingLogicClient

2.

2.1: doCommand( remote:Command )

return

2.1.1: execute

3: getResults

1: Command( InitialState )

2: doCommand( local:Command )

return

return

return

Page 90: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 22 of 45

tern:

seueads or remotely

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command PatConsequences

Advantages:

• Reduces complexity of decision logic• Provides easy extensibility• Can readily provide for undo operation• Can place multiple commands on a qu• Can execute commands in separate thre

Page 91: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 23 of 45

tern:

on, destruction,

ore complex

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Command PatConsequences

Disadvantages:

• Might increase overhead in object creatiand use

• Makes the structure of an application m

Page 92: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 24 of 45

rn:

g data fromnal database, aof test datas various

source classesions of the data

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator PatteExample Problem

• The library system needs to read cataloseveral data sources including a relatioproprietary legacy database, and a file

• Each of the data source classes providemethods for traversing the data

• The traversal logic complicates the dataand exposes clients to the implementatsource classes

Page 93: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java E Module 2, slide 25 of 45Copyrig

:

Pla data source isno

ightly custom

ithout a time-

d support the

E™ Patternsht 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator PatternProblem Forces

cing traversal logic directly in a collection ort always desirable:

• Callers become needlessly complex and tcoupled to the collection if they must usetraversal logic to access that collection

• Accessing the elements should be easy wconsuming lookup

• Multiple traversals should be supported• For uniformity, different collections shoul

same model for traversal

Page 94: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 26 of 45

olution

e in an

r subtype fromvance through

l collections ofan be an

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator Pattern: S

• Place the Aggregate object’s access codIterator object

• The Client object requests an Iteratothe Aggregate and uses Iterator to adthe elements of Aggregate

• Iterators do not need to iterate over reaobjects (for example, an input stream citerator source)

Page 95: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 27 of 45

e

ce>>or

booleanect

erator

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Iterator Pattern Structur

<<interface>>Aggregate

+createIterator() : Iterator

<<interfaIterat

+hasNext() : +next() : Obj

Client

-data

createConcreteAggregate ConcreteIt

Page 96: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 28 of 45

lution

)

)

or

leIterator

erator

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Iterator Pattern Example So

ResultSetWrapper

+getIterator() : CatalogIterator

TestIFileSource

+getIterator() : CatalogIterator

LegacyDataSource

+getIterator() : CatalogIterator

<<interface>>CatalogDataSource

+getIterator() : CatalogIterator

return new ResultSetIterator();

return new TestFileIterator();

return new LegacyIterator();

<<interface>>CatalogIterator

+currentElement()+hasMoreElements(+nextElement()+previousElement(

ResultSetIterat

TestFi

LegacyIt

Client

creates

creates

creates

Page 97: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 29 of 45

in the Java

e>>tor

lean boolean

nt

: int

e>>r

oolean

id

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator Pattern: UseProgramming Language

<<interface>>List

+listIterator() : ListIterator...

<<interfacListItera

+add( o ) : void+hasNext() : boo+hasPrevious() :+next()+nextIndex() : i+previous()+previousIndex()+remove() : void+set( o ) : void

<<interface>>Collection

+iterator() : Iterator...

<<interfacIterato

+hasNext() : b+next()+remove() : vo

LinkedList ArrayListHashSet Vector

Set

Page 98: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 30 of 45

in the Java

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator Pattern: UseProgramming Language

Collection subtype:

1 public void printData(Collection data) {2 Iterator dataI = data.iterator();3 while (dataI.hasNext()) {4 System.out.println(dataI.next());5 }6 }

Page 99: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 31 of 45

sequences

g out traversal-

t collections on the

sals

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator Pattern: Con

Advantages:

• Simplifies the collection interface, liftinrelated methods

• Supports uniform traversal on differen• Supports different traversal algorithms

same collection• Supports simultaneous multiple traver

Page 100: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 32 of 45

sequences

e

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Iterator Pattern: Con

Disadvantages:

• Introduces additional objects at runtim• Not inherently thread-safe

Page 101: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 33 of 45

ern:

application, thend sendEMail

ult handlers

ultMsg : String )

Msg : String )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer PattExample Problem

• When a serious fault occurs in the hotelfaultOccurred method calls the log amethods in the FaultLogger andFaultEMailer classes

• You need a way to flexibly add more fa

FaultMessageGenerator

+faultOccurred( faultType : int, faultMsg : String )

FaultEMailer

+sendEMail( faultTyoe : int, fa

FaultLogger

+log( faultType : int, fault

logger.log(faultType, faultMsg);eMailer.sendEMail(faultType, faultMsg);

-eMailer

-logger

Page 102: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 34 of 45

ern:

f changes in

essive memoryesource usaget can lead to

the observablebject must be

upled to the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer PattProblem Forces

Sometimes several classes need to be aware oanother class:

• Polling an object for its state leads to excand the central processing unit (CPU) r

• Multiple object queries of a single objecsynchronization problems

• The observer objects must be aware of object; for notification, the observable oaware of its observers

• The observable object should not be cotypes of observer objects

Page 103: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 35 of 45

Solution

observers canclass typesserverobjects

ferencellow aner with

lls a method in collection

hein a superclassd to be coupled

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer Pattern:

• An interface is provided through whichbe called, irrespective of their concrete

• TheSubjectobject has a collection ofObreferenced by an Observer interface re

• The Subject object has methods that aObserver object to register or de-registthe Subject

• When the Subject object changes, it caeach Observer object in the observers

• The Observer pattern functionality of tConcreteSubject class can be placed so that Observer objects might not neeto the ConcreteSubject

Page 104: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 36 of 45

re

Observer

)

face>>rver

)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Structu

Subject{abstract}

+attach( o : Observer )+detach( o : Observer )+notify()

for (each observer o) o.update();

Concrete

+update(

ConcreteSubject

<<interObse

+update(

add o to observers

-subject

1

-observes

0..*

Page 105: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 37 of 45

olution

ger

nt, faultMsg : String )

ault(faultType, faultMsg);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Example S

FaultListener

FaultEMailer

FaultMessageGenerator

+addFaultListener( listener : FaultListener )+faultOccurred( faultType : int, faultMsg : String )+removeFaultListener( listener : FaultListener )

FaultLogger

+handleFault( faultType : int, faultMsg : String )

FaultPa

+handleFault( faultType : i

+handleFault( faultType : int, faultMsg : String )

+handleFault( faultType : int, faultMsg : String )

while (listener.hasNext()) listeners.next().handleF

-listeners 0..*

Page 106: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 38 of 45

olution

st();

r listener) {

String faultMsg) {r();

stenersI.next();

ener listener) {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Example S

Observable class:

1 import java.util.*;2 public class FaultMessageGenerator {3 private ArrayList listeners = new ArrayLi45 public void addFaultListener(FaultListene6 listeners.add(listener);7 }8 public void faultOccurred(int faultType, 9 Iterator listenersI = listeners.iterato10 while(listenersI.hasNext()) {11 FaultListener fl = (FaultListener) li12 fl.handleFault(faultType,faultMsg);13 } }14 public void removeFaultListener(FaultList15 listeners.remove(listener);16 }17 }

Page 107: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 39 of 45

olution

ring faultMsg);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Example S

Observer interface:

1 public interface FaultListener {2 public void handleFault(int faultType, St3 }

Page 108: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 40 of 45

olution

stener{Logger("");

fmg) {

ring faultMsg) {

faultMsg);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Example S

Logging observer:

1 import java.util.logging.*;23 public class FaultLogger implements FaultLi4 private static Logger logger = Logger.get56 public FaultLogger(FaultMessageGenerator 7 fmg.addFaultListener(this);8 }9 public void handleFault(int faultType, St10 logger.log(Level.WARNING,11 "A " + faultType + " occurred: " + 12 }13 }

Page 109: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 41 of 45

olution

ssageGenerator();

a: Peters, V.");

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Observer Pattern Example S

Simple test class:

1 public class FaultTester {2 public static void main(String args[]) {3 FaultMessageGenerator fmg = new FaultMe4 new FaultLogger(fmg);5 new FaultPager(fmg);6 new FaultEMailer(fmg);7 fmg.faultOccurred(72,"Lost customer dat8 }9 }

Page 110: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 42 of 45

se in thege

etHandler

cord : LogRecord )

g the record to a socket

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer Pattern: UJava Programming Langua

Logger

+addHandler( handler : Handler )+log( record : LogRecord )+removeHandler( handler : Handler )

ConsoleHandler

+publish( record : LogRecord )...

Sock

+publish( re...

Handler{abstract}

+publish( record : LogRecord )...

FileHandler

+publish( record : LogRecord )...

if (handlers != null) { for (int i = 0; i < handlers.length; i++) handlers[i].publish(record);

Log the record to the console

handlers.remove(handler);

Lo

handlers.add(handler);

Log the record to a file

-handlers

Page 111: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 43 of 45

ern:

dependentlyinterfaces) and

hanging

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer PattConsequences

Advantages:

• Subjects and observers can be reused in• Coupling is between abstract classes (or

not between concrete classes• Observers are easily changed without c

the subject

Page 112: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 44 of 45

ern:

d with updatesject when itate a bottleneck

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Observer PattConsequences

Disadvantages:

• An observer system can become floode• The observer often calls back to the sub

receives a notification, which might cre

Page 113: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 2, slide 45 of 45

nts

Object-Oriented Design Principles

Architectural Patterns

atterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

Behavioral patterns focus on algorithmsand the distribution of responsibilitiesbetween classes:

• Strategy – Encapsulates a family ofalgorithms for interchangeable use

• Command – Encapsulates requestsin objects for execution byother objects

• Iterator – Traverses any collectionin a loosely coupled way

• Observer – Provides notification of evewithout polling

Anti-P

Page 114: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

l Patterns

Java EE™ Patterns

Module 3

Using Gang of Four CreationaModule 3

Using Gang of FourCreational Patterns

Module 3

Using Gang Of FourCreational Patterns

Page 115: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 2 of 23

the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the basic characteristics of Creational patterns

• Apply the Factory Method pattern• Apply the Abstract Factory pattern• Apply the Singleton pattern

Page 116: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 3 of 23

erns

reation.

class or itsa method call

objectsterfaceone globally

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Creational Patt

Creational patterns hide the details of object c

Pattern Primary FunctionFactory Method Creates objects of a

subclasses throughAbstract Factory Creates a family of

through a single inSingleton Restricts a class to

accessible instance

Page 117: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 4 of 23

Problem

which

RoomList

ist

ist

ist

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Factory Method Pattern Example

• Three hotel systems have been merged• The Client class must directly decide

HotelRoomList object to create• The Client is tightly coupled to Hotel

classes due to the creation process

HotelBRoomL

HotelARoomL

HotelCRoomL

Client

uses

uses

create

create

create

uses

Page 118: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 5 of 23

rn: Problem

tightly coupledf the client codeo add new

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Factory Method PatteForces

• Clients that call target constructors areto the constructors, limiting flexibility o

• Reusable frameworks must allow you tconcrete subclasses

Page 119: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 6 of 23

rn: Solution

tory reference

actory method

reference to a

ifferenterent

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Factory Method Patte

• The Client class obtains a generic Facto a ConcreteFactory object

• The Client calls the createProduct fon the ConcreteFactory

• The factory method returns a Product new ConcreteProduct

• If the Client obtains a reference to a dConcreteFactory, it will receive a diffConcreteProduct

Page 120: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 7 of 23

cture

rn new ConcreteProduct1();

rn new ConcreteProduct2();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Factory Method Pattern Stru

The client code might look like:

Factory f = new ConcreteFactory1();Product p = f.createProduct();

<<interface>>Factory

+createProduct() : Product

ConcreteFactory1

+createProduct() : Product

ConcreteFactory2

+createProduct() : Product

retu

retu

<<interface>>Product

ConcreteProduct2

ConcreteProduct1

Clientrequests

create

create

uses

Page 121: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 8 of 23

Solution

turn new HotelCRoomList();

turn new HotelARoomList();

turn new HotelBRoomList();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Factory Method Pattern Example

<<interface>>RoomFinder

+createList() : RoomList

HotelCRoomFinder

+createList() : RoomList

HotelARoomFinder

+createList() : RoomList

HotelBRoomFinder

+createList() : RoomList

re

re

re

<<interface>>RoomList

moreRooms()nextRoom()

HotelBRoomList

HotelCRoomList

HotelARoomList

Client-finder

create

create

create

-rooms

Page 122: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 9 of 23

me Class

reation of

OracleResultSet

SybaseResultSet

interface>>ResultSet

create

create

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC API Factory Method ScheDiagram

The JDBC API uses two factory methods for cStatement and ResultSet objects

<<interface>>Connection

+createStatement() : Statement...

SybaseConnection

+createStatement() : Statement...

OracleConnection

+createStatement() : Statement...

<<interface>>Statement

+executeQuery() : ResultSet...

SybaseStatement

+executeQuery() : ResultSet...

OracleStatement

+executeQuery() : ResultSet...

<<

create

create

Page 123: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 10 of 23

attern:

ation to thes

withoutn details

ace to create

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Factory Method PConsequences

Advantages:

• Factories restore control of object cresystem; clients merely request object

• Client code works with any subclassknowing the name or implementatio

Disadvantage:

You have to subtype the factory interfnew product types

Page 124: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 11 of 23

e Problem

l objects

RoomB

Description()Rate()

RoomA

Description()Rate()

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Abstract Factory Pattern Exampl

The Client class must create a family of hoteCustomerA

+getPreferences()

+get+get

+get+get

CustomerB

+getPreferences()

ReservationB

+calculateBill()+confirm()

ReservationA

+calculateBill()+confirm()

HotelChainB

HotelChainA

Client

create

create

create

create

createcreate

create create

Page 125: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 12 of 23

attern:

to

objectscts from

n you expose

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Abstract Factory PProblem Forces

• The client does not need to know how instantiate products

• A client needs to use a family of related• You might not want a client to mix obje

different families• Client maintainability is sacrificed whe

details of the related objects to a client

Page 126: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 13 of 23

attern:

y reference to a

iple factorywithin a family

ory, theClientucts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Abstract Factory PSolution

• The client obtains an AbstractFactorConcreteFactory object

• The ConcreteFactory object has multmethods that produce different objectsof products

• By obtaining a differentConcreteFactis switched to a different family of prod

Page 127: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 14 of 23

cture

e>>

oductA2

e>>

oductB2

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Abstract Factory Pattern Stru

ConcreteFactory1

+createProductA()+createProductB()

ConcreteFactory2

+createProductA()+createProductB()

<<interface>>Factory

+createProductA()+createProductB()

<<interfacProductA

PrProductA1

<<interfacProductB

PrProductB1

Client uses

create

uses

create

create

create

requests

Page 128: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 15 of 23

e Solution

ionB

ill()

rB

nces()

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Abstract Factory Pattern Exampl

<<interface>>HotelChain

+createCustomer() : Customer+createReservation() : Reservation+createRoom() : Room

HotelChainA

+createCustomer() : Customer+createReservation() : Reservation+createRoom() : Room

HotelChainB

+createCustomer() : Customer+createReservation() : Reservation+createRoom() : Room

RoomA

+getDescription()+getRate()

RoomB

+getDescription()+getRate()

<<interface>>Room

+getDescription()+getRate()

ReservationA

+calculateBill()+confirm()

Reservat

+calculateB+confirm()

<<interface>>Reservation

+calculateBill()+confirm()

CustomerA

+getPreferences()

Custome

+getPrefere

<<interface>>Customer

+getPreferences()

Client uses

create

uses

create

create

create

create

create

uses

Page 129: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 16 of 23

attern:

for anothernt viewr

ime consumingeme

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Abstract Factory PConsequences

Advantages:

• Simplifies exchanging one product family • Hides concrete family classes from the clie• Imposes a consistent naming convention fo

family members

Disadvantages:

• Developing new families correctly can be t• Adding family members to an existing sch

can be difficult

Page 130: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 17 of 23

ern:

to

e thread pool soowing threads

le throughout

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Singleton PattExample Problem

• The hotel system uses a pool of threadsinvoke processing

• There should only be one instance of ththat all parts of the application are borrfrom the same pool

• The thread pool must be easily accessibthe application

Page 131: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 18 of 23

ern:

to only have a

to be easilyication to hide it

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Singleton PattProblem Forces

• There are some classes that are intendedsingle instance

• The single instance of a class may needaccessible to different parts of the appl

• The only way to secure a constructor is

Page 132: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 19 of 23

re

class:

rivate or

tic reference to

ic method that

== null) { new Singleton();

nce;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Singleton Pattern Structu

Three steps are needed to create a Singleton

1. The Singleton class’ constructor is pprotected, hiding it from client view

2. The Singleton class has a private stathe only instance of itself

3. The Singleton class has a public statreturns the single instance

if (uniqueInstance uniqueInstance =}return uniqueInsta

Singleton

-uniqueInstance : Singleton

+getInstance() : Singleton-Singleton()

Page 133: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 20 of 23

re

nctionality

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Singleton Pattern Structu

Singleton structure code:

1 public class Singleton {2 private static Singleton uniqueInstance;34 public static Singleton getInstance( ) {5 if (uniqueInstance == null) {6 uniqueInstance = new Singleton();7 }8 return uniqueInstance;9 }10 private Singleton( ) {11 }12 //Add attributes and methods for class fu13 }

Page 134: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 21 of 23

olution

dPool

Pool

d )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Singleton Pattern Example S

ThreadPool

-singleInstance : Threa

+getInstance() : Thread+getThread() : Thread+returnThread( : Threa-ThreadPool()

ClientB

ClientA

uses

uses

Page 135: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 22 of 23

ern:

single objecte class loading

ce, not just one

this hint is

s thread-safe

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Singleton PattConsequences

Advantages:

• A client can easily obtain a reference to the• A singleton can construct the instance at th

time or on-demand• Singleton can guard several instances at on

Disadvantages:

• Singleton can replace global variables, butoften misapplied

• Singleton must make on-demand instance

Page 136: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 3, slide 23 of 23

Object-Oriented Design Principles

Architectural Patterns

Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

Gang of Four creational patterns hide thedetails of object creation:

• Factory Method – Creates objectsof a class or its subclasses througha method call

• Abstract Factory – Creates a familyof objects through a single interface

• Singleton – Restricts objectcreation to a single globallyaccessible instance

Anti-

Page 137: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

l PatternsM

US

Java EE™ Patterns

Module 4

Using Gang of Four Structuraodule 4

sing Gang of Fourtructural Patterns

Module 4

Using Gang Of FourStructural Patterns

Page 138: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 2 of 46

the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the basic characteristics of Structural patterns

• Apply the Façade pattern• Apply the Proxy pattern• Apply the Adapter pattern• Apply the Composite pattern• Apply the Decorator pattern

Page 139: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 3 of 46

rns

face to a

object whichobject.bject that has an

t-whole tree

to an object

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Structural Patte

Pattern Primary FunctionFaçade Provides a simplified inter

subsystem.Proxy Provides an intermediate

controls access to another Adapter Enables a caller to use an o

incompatible interface.Composite Composes objects into par

structures.Decorator Attaches new functionality

dynamically.

Page 140: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 4 of 46

blem

n subsystem.

om

eUpCall()atus()

chService

s()

t

ofile()

on

0..*

0..*

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Façade Pattern Example Pro

Client is coupled to many classes in reservatio

HotelSearchService hss = new HotelSearchService();Room[] rooms = hss.findRooms();Room theRoom = //chosen roomGuest theGuest = new Guest();//set guest informationReservation r = new Reservation(theRoom, theGuest);theRoom.updateStatus();

Ro

+issueWak+updateSt

HotelSear

+findRoomClient

+makeReservation() Gues

+updatePr

Reservati

+cancel()+create()+update()

Page 141: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 5 of 46

rn:

s in any of

the interfaces of

rations in then between

ls to subsystem

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Façade PatteProblem Forces

When clients directly link to many classes:

• Client classes are vulnerable to changethose classes

• The programmer must be familiar withmany classes

• The client must call the subsystem opecorrect order and pass state informatiothe operations

• In a distributed environment, client calobjects can increase network overhead

Page 142: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 6 of 46

olution

-level interface

ommunicatingyfor sequencing,ith each

municater

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Façade Pattern: S

Provide a Facade class that has a simple, highto a subsystem:

• Clients use a Facade object instead of cwith each subsystem object individuall

• The Facade contains the logic requiredmanaging state, and communicating wsubsystem object

• The Client may also be allowed to comdirectly with other subsystem classes foadditional functionality

Page 143: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 7 of 46

e

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Façade Pattern Structur

Facade

+request()

Class1

Class2Client

Class3

Page 144: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 8 of 46

lution

ll())

rvice

()

..*

0..*

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Façade Pattern Example So

The client uses the facade class object. It does not know there are HotelSearchService, Room, Guest, or Reservation objects.

ReservationServiceFacade

+cancelReservation()+confirmReservation()+findRoom()+makeReservation()+modifyReservation()

Room

+issueWakeUpCa+updateStatus(

HotelSearchSe

+findRooms()

Guest

+updateProfile

Reservation

+cancel()+create()+update()

Client

0

Page 145: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 9 of 46

uence

: Reservationt

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Façade Pattern Example Seq

: ReservationServiceFacade : HotelSearchService: Client : Gues: Room

1: makeReservation

1.1: findRooms

1.4: create

1.3: updateProfile

1.2: updateStatus

Page 146: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 10 of 46

sequences

onents, making

subsystems

ght

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Façade Pattern: Con

Advantages:

• Clients are shielded from subsystem compthe clients less brittle

• Network overhead may be decreased in adistributed environment

• Clients are loosely-coupled to subsystems• Clients can still communicate directly with

Disadvantage:

Introduces an extra level of indirection, which miimpact performance.

Page 147: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 11 of 46

blem

bjects thatually neededient class

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Proxy Pattern Example Pro

• RoomTypeImage objects are expensive oshould not be created until they are act

• You might want to avoid having the Cldecide when to create expensiveRoomTypeImage objects

RoomTypeImage

-imageData : byte[][]

+getImage() : byte[][]+getSize() : Dimension+RoomTypeImage()

Client0..*

Page 148: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 12 of 46

em Forces

cess these types

ode in the client

ntensive objects

de in a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Proxy Pattern: Probl

It may be undesirable for a client to directly acof classes:

• Remote objects – Placing networking cand remote class decreases cohesion

• Expensive objects – Creating resource ibefore they are actually needed candecrease performance

• Restricted objects – Placing security corestricted class decreases cohesion

Page 149: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 13 of 46

olution

nds in for the

plement the

t interface type

ealSubject

o RealSubject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Proxy Pattern: S

• The Client uses a Proxy object that staRealSubject object

• The Proxy and RealSubject classes imSubject interface

• The client has a reference of the Subjecwhich only refers to Proxy objects

• The Proxy object keeps a reference to R• The Proxy object propagates requests t

as appropriate

Page 150: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 14 of 46

entation

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Proxy Pattern Structure

Client has a reference variable of type Subject that refers to a Proxy object

actual implem

<<interface>>Subject

+request()

RealSubject

+request()

impl.request()

Proxy

+request()

Client

-impl

Page 151: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 15 of 46

olution

municates to a

tes the resourceakes a request

determinesgated

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Proxy Pattern: S

• Remote proxy – A Proxyobject that comremote RealSubject

• Virtual proxy – AProxyobject that creaintensive RealSubject after a client mon Proxy

• Restricted proxy – A Proxy object thatwhether an invocation should be propato RealSubject

Page 152: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 16 of 46

tion

age();

do the actual work

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Proxy Pattern Example Solu

Client has a reference with type RoomTypeImage that refers to a ProxyRoomTypeImage

if (realImage == null) realImage = new ActualRoomTypeImage();return realImage.getImage();

if (realImage == null) realImage = new ActualRoomTypeImreturn realImage.getSize();

<<interface>>RoomTypeImage

+getImage() : byte[][]+getSize() : Dimension

ProxyRoomTypeImage

+getImage() : byte[][]+getSize() : Dimension

ActualRoomTypeImage

-imageData : byte[][]

+ActualRoomTypeImage()+getImage() : byte[][]+getSize() : Dimension

Client 0..*

-realImage

Page 153: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 17 of 46

n the Java

Impl

entation

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Proxy Pattern: Use iProgramming Language

The Client acquires a RemoteBusiness type reference to a Stub object. It calls the business methods on the Stub.

Networking logic to propogate the request to the RemoteBusinessImpl on the remote machine.

Stub

+doTask()

Client RemoteBusiness

+doTask()

Actual Implem

<<interface>>RemoteBusiness

+doTask()

Page 154: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 18 of 46

equences

ng capabilities the real object

ed that might

s transparent

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Proxy Pattern: Cons

Advantages:

• The proxy is transparent to the client• The proxy simplifies client access• The proxy provides a point for extendi• The proxy can control or limit access to

Disadvantages:

• An extra level of indirection is introducimpact performance

• Interaction with the proxy is not alway

Page 155: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 19 of 46

blem

s to be adapted

modified

rchEngine

: String ) : ArrayList) : ArrayList

tible Interface

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Adapter Pattern Example Pro

• The Library3SearchEngine class needto the Searchable interface

• Library3SearchEngine should not be

Library1SearchEngine

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

Library3Sea

+recall()+searchByCallNumber( callNum +titleSearch( title : char[]

<<interface>>Searchable

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

Library2SearchEngine

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

Incompa

SearchInvoker

Page 156: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 20 of 46

rn:

patible

e functionalityundant code

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Adapter PatteProblem Forces

• Forcing clients to use classes with incominterfaces can complicate code

• Creating different interfaces for the samby copy-and-paste reuse can lead to red

Page 157: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 21 of 46

olution

apterred interface: on Adapter

to theAdaptee

re complex or

has a reference

is a subclass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Adapter Pattern: S

• The solution is similar to a hardware ad• Create an Adapter class with the requi

• The Client object invokes methods• TheAdapterobject forwards calls on

class for some methods• The Adapter object can provide mo

additional methods when required• In the Object Adapter strategy,Adapter

to Adaptee• In the Class Adapter strategy, Adapter

of Adaptee

Page 158: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 22 of 46

cture

Task2()

stTask()

n

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Object Adapter Strategy Stru

return adaptee.do

return adaptee.fir

<<interface>>DesiredInterface

+doTask1()+doTask2()+doTask3()

full implementatio

Adaptee

+doTask2()+firstTask()

Adapter

+doTask1()+doTask2()+doTask3()

Client

-adaptee

Page 159: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 23 of 46

cture

ation

k()

)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Class Adapter Strategy Stru

<<interface>>DesiredInterface

+doTask1()+doTask2()+doTask3()

full implement

return firstTas

Adaptee

+doTask2()+firstTask(

Adapter

+doTask1()+doTask3()

Client

Page 160: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 24 of 46

e Solution

chEngine

: String ) : ArrayList) : ArrayList

rchByCallNumber(callNum);

e.toCharArray();tee.titleSearch(t);

ntation

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Object Adapter Strategy Exampl

Library1SearchEngine

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

Library3Sear

+recall()+searchByCallNumber( callNum +titleSearch( title : char[]

Library3SearchEngineAdapter

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

<<interface>>Searchable

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

Library2SearchEngine

+searchByAuthor( author : String ) : ArrayList+searchByCallNumber( callNum : String ) : ArrayList+searchByTitle( title : String ) : ArrayList

return adaptee.sea

char t[] = titlreturn adap

full impleme

-adaptee

Page 161: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 25 of 46

e Solution

thor) {author

g callNum) {um);

le) {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Object Adapter Strategy Exampl

The library adapter class code:

1 import java.util.ArrayList;2 public class Library3SearchEngineAdapter3 implements Searchable {4 private Library3SearchEngine adaptee =5 new Library3SearchEngine();6 public ArrayList searchByAuthor(String au7 //... full implementation of search by 8 return results;9 }10 public ArrayList searchByCallNumber(Strin11 return adaptee.searchByCallNumber(callN12 }13 public ArrayList searchByTitle(String tit14 char t[] = title.toCharArray();15 return adaptee.titleSearch(t);16 }17 }

Page 162: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 26 of 46

sequences

aving to use a

r without

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Adapter Pattern: Con

Advantages:

• The client class is not complicated by hdifferent interface

• The adaptee class is not modified• Clients can use the adaptee class with o

the adapter

Page 163: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 27 of 46

sequences

t

upports thent is coupled to

e adaptee class

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Adapter Pattern: Con

Object Adapter strategy disadvantages:

• You must create an additional object• Requests are forwarded, causing a sligh

overhead increase

Class Adapter strategy disadvantages:

• The interface of the adapter class also sinterface of the adaptee class, so the cliethe adaptee class

• The single inheritance slot is used by th

Page 164: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 28 of 46

roblem

red

manOperations: Manager

anager

: Concierge

BerlinHotel: Manager

: SalesPerson

: Clerk

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Pattern Example P

A composite-part employee structure is requi

CanadianOperations: Manager FrenchOperations: Manager Ger

MarkhamHotel: Manager

VPOperations: M

OttawaHotel: Manager ParisHotel: Manager

President : Manager

VPSales : Manager

: SalesPerson

: SalesPerson : SalesPerson: SalesPerson

: Concierge

: Concierge

: Concierge : Concierge

: Clerk

: Clerk: Clerk

: Clerk

: Clerk

: Clerk

Page 165: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 29 of 46

: Problem

that can

ted down the

of the parts in

e of the and parts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite PatternForces

Objects exist in a composite-part hierarchy:

• Variable number of levels of objects change dynamically

• Some operations should be propagacomposite hierarchy

• Need to treat the composite and eacha uniform way

• It can be inappropriate to handle somoperations uniformly on composites

Page 166: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 30 of 46

: Solution

individual part

onent, some of which

and Part

n the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite Pattern

Provide a common interface for the classes ofobjects and grouped composite objects:

• The Composite object has a set of Compreferences that refers to its componentsmay be other Composite objects

• The client manipulates both Compositeobjects through a common interface

• Some method calls are propagated dowcomposition hierarchy

Page 167: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 31 of 46

ure

t

i++

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Pattern Struct

Composite

+add( comp : Component )+getChild( index : int ) : Componen+operation()+remove( comp : Component )

for (int i=0; i<children.length; children[i].operation();

<<interface>>Component

+operation()

full implementation

Part

+operation()

-children

0..*

Page 168: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 32 of 46

olution

nager

double

: Employee )) : doubledouble : int ) : Employee( e : Employee )

ulatePay();s.length; i++)ates[i].calculateDeptPay();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Pattern Example S

Ma

-individualBonus :

+addSubordinate( e+calculateDeptPay(+calculatePay() : +getSubordinate( i+removeSubordinate

double totalPay = calcfor (i=0; i<subordinate totalPay += subordinreturn totalPay;

<<interface>>Employee

+calculateDeptPay() : double+calculatePay() : double

Clerk

-basePayRate : double-individualBonus : double-overtimeHours : int

+calculateDeptPay() : double+calculatePay() : double

SalesPerson

-basePayRate : double-comissionRate : double-totalSales : double

+calculateDeptPay() : double+calculatePay() : double

Concierge

-basePayRate : double-individualBonus : double-tips : double

+calculateDeptPay() : double+calculatePay() : double

return calculatePay();

0..*

-subordinates

Page 169: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 33 of 46

olution

l pay

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Pattern Example S

The Clerk class code:

1 public class Clerk implements Employee2 {3 private double basePayRate;4 private double individualBonus;5 private int overtimeHours;67 public double calculateDeptPay() {8 return calculatePay();9 }10 public double calculatePay() {11 double pay = // ... calculate individua12 return pay;13 }14 }

Page 170: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 34 of 46

olution

+) {DeptPay();

l pay return pay;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Pattern Example S

The Manager class code:

1 public class Manager implements Employee {2 private Employee subordinates[];3 public void addSubordinate(Employee e) {4 // ... add e to the subordinates array5 }6 public double calculateDeptPay() {7 double totalPay = calculatePay();8 for (int i=0; i<subordinates.length; i+9 totalPay += subordinates[i].calculate10 }11 return totalPay;12 }13 public double calculatePay() {14 double pay = // ... calculate individua15 }16 . . .17 }

Page 171: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 35 of 46

Use in thege

iner

nent ) int ) : Componentcs )mponent )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite Pattern:Java Programming Langua

Conta

+add( comp : Compo+getComponent( n :+paint( g : Graphi+remove( comp : Co

Component{abstract}

+paint( g : Graphics )

List

+paint( g : Graphics )

Button

+paint( g : Graphics )

0..*

Page 172: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 36 of 46

tern:

rmlypth

le

provides but not

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite PatConsequences

Advantages:

• Composites and parts are treated unifo• Composite hierarchy is an arbitrary de

• Composite hierarchy is highly extensib

Disadvantages:

• The design can become too general

• The component interface might have tomethods that make sense for compositefor parts

Page 173: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 37 of 46

roblem

calculations,ent

lculator

rementFund()entFund()

sePay();lateRetirement(pay);lateTax(pay);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Decorator Pattern Example P

Calculating an employee’s pay involves base various tax calculations, and possibly retiremfund calculations

FrenchPayWithTaxCalculator

+calculatePayWithoutRetirementFund()+calculatePayWithRetirementFund()

CanadianPayWthTaxCa

+calculatePayWithoutReti+calculatePayWithRetirem

GermanPayWithTaxCalculator

+calculatePayWithoutRetirementFund()+calculatePayWithRetirementFund()

<<interface>>PayCalculator

+calculatePayWithoutRetirementFund()+calculatePayWithRetirementFund()

double pay =calculateBapay -= calcupay -= calcu

Page 174: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 38 of 46

tern:

t subclassing

simple mannerdded or removede duplication

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Decorator PatProblem Forces

Adding extended functionality through direcmay lead to:

• An explosion of subclasses• Code duplication in subclasses

A solution is needed that:

• Allows functionalities to be expanded in a• Allows functionalities to be dynamically a• Maintains high cohesion and minimizes th

of code

Page 175: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 39 of 46

Solution

om theorator classes

ality to

t reference toecorates

ir functionalitymponent class

nt to the caller

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Decorator Pattern:

• Additional functionalities are moved frConcreteComponent class into the Dec

• The Decorator class adds one functionanother class

• The Decorator class keeps a Componenthe ConcreteComponent class that it d

• The Decoratormethods implement theand propagate the invocation to the Cothey decorate

• The chain of Decorators are transparewhen dealing with a decorated class

Page 176: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 40 of 46

re

of

on();

eration();

;

ctionality

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Decorator Pattern Structu

ConcreteDecorator

-additionalAttribute

+ConcreteDecorator( d : Component )+operation()

Decorator

+Decorator( d : Component )+operation()

ConcreteComponent

<<interface>>Component

+operation()

1

//implentation

super.operati

implement base functionality

decoratee.op+operation()

decoratee = d

super(d);

-decoratee

decorator fun

Page 177: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 41 of 46

olution

ator

PayCalculator )

e.calculatePay();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Decorator Pattern Example S

PayCalculatorDecorator

+calculatePay()

Implement tax calculationsuper.calculatePay();

BasePayCalculator

+calculatePay()

<<interface>>PayCalculator

+calculatePay()

-decoratee

1

Implement RetirementFund Calculationsuper.calculatePay();

RetirementFundCalcul

+calculatePay()+RetirementFundCalculator( :

CanadianTaxCalculator

+calculatePay()+CanadianTaxCalculator( : PayCalculator )

FrenchTaxCalculator

+calculatePay()+FrenchTaxCalculator( : PayCalculator )

GermanTaxCalculator

+calculatePay()+GermanTaxCalculator( : PayCalculator )

+PayCalculatorDecorator( : PayCalculator ) decorate

Page 178: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 42 of 46

olution

();culator(calc1);ator(calc2);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Decorator Pattern Example S

Pay calculation code:

1 PayCalculator calc1 = new BasePayCalculator2 PayCalculator calc2 = new RetirementFundCal3 PayCalculator calc3 = new CanadianTaxCalcul4 calc3.calculatePay();

Page 179: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 43 of 46

quence

ntFundCalculator

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Decorator Pattern Example Se

calc3: Retireme

calc2: CanadianTaxCalculator

calc1: BasePayCalculator

: Client

4: calculatePay

return

3: create( calc2 )

4.1: calculatePay

return

2: create( calc1 )

4.2: calculatePay

1: create()

return

Page 180: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 44 of 46

Use in thege

FilterInputStream

utStream( is : InputStream )

DataInputStream

tStream( is : InputStream )

() : charle() : double) : int

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Decorator Pattern:Java Programming Langua

BufferedInputStream

+BufferedInputStream( is : InputStream )+close()+read( byte[] )...

+close()+FilterInp+read()...

FileInputStream

+close()+FileInputStream( filename : String )+read()...

ByteArrayInputStream

+ByteArrayInputStream( buf : byte[] )+close()+read()...

+close()+DataInpu+read()+readChar+readDoub+readInt(...

InputStream{abstract}

+close()+read()...

-is

1

Page 181: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 45 of 46

tern:

nd behavior

rchies because of

ehavior

same, so object

lightly decrease

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Decorator PatConsequences

Advantages:

• Can dynamically modify an object’s state a

• Does not modify or break inheritance hieraan addition to a base class

• Can nest decorators to add new state and b

Disadvantages:

• Decorator and decorated object are not theidentity becomes an issue

• Many little objects get created, which can sperformance

Page 182: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 4, slide 46 of 46

to an

Object-Oriented Design Principles

Architectural Patterns

Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

The GoF structural patterns:

• Façade – Provides a simplifiedinterface to a subsystem

• Proxy – Provides an intermediateobject that controls access toanother object

• Adapter – Enables a caller to use anincompatible interface

• Composite – Composes objectsinto part-whole tree structures

• Decorator – Attaches new functionalityobject dynamically

Anti-

Page 183: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

BlocksM

UB

Java EE™ Patterns

Module 5

Using Architectural BuildingModule 5

Using ArchitecturalBuilding Blocks

odule 5

sing Architecturaluilding Blocks

Page 184: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 2 of 25

n patternsrn

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Compare architectural patterns to desig• Apply the Model View Controller patte• Apply the Layers pattern• Explain tiers and layers in Java EE

platform applications

Page 185: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 3 of 25

to Design

e tacticaloblem

mposite

design patterns the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Comparing Architectural PatternsPatterns

• Design patterns concentrate more on thaspects required to solve a low-level pr

• Architectural patterns:• Focus on the strategic, high-level co

structure of a solution• Usually implemented with multiple• Define the role of each subsystem in

overall solution

Page 186: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 4 of 25

ler (MVC)

is an

va Foundation

ent from core

nterface might

ns

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Model View ControlPattern

• Model View Controller (MVC) pattern architectural pattern

• Found in many places, including the JaClasses/Swing (JFC/Swing) API

• MVC separates presentation managemapplication logic

• Useful in applications where the user ifrequently change

• MVC can be adapted to Web applicatio

Page 187: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 5 of 25

n:

r interface tonformation and

to parts so that: interface

thout changing

s non-Web userss logic

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the MVC PatterExample Problem

• The hotel system needs a non-Web useallow hotel clerks to access reservation icheck guests in and out

• You need a way to divide the system in• Programmers can specialize on user

development or business logic• The user interface can be changed wi

the business logic• The Web reservation system and thi

interface can access the same busine

Page 188: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 6 of 25

m Forces

changele user interface

in

eflect changes

tely to changes

from the data

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the MVC Pattern: Proble

User interfaces and business processing oftenindependently and some systems have multipviews:

• You can display the same information different views

• The views might need to immediately rto the model data

• The model data must respond immediainitiated in the views

• The user interface should be decoupledand processing

Page 189: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 7 of 25

lution

e system into

user, invokesnd determineslayedace (GUI)to the user ander componentsocessing, andetails about the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the MVC Pattern: So

The Model View Controller pattern divides ththree sets of components:

• Controller – Accepts requests from theprocessing on the Model components, awhich View component should be disp

• View – Displays a graphical user interfcontaining the Model components datausually passes GUI events to Controll

• Model – Contains the business data, prrules. The Model should not have any duser interface

Page 190: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 8 of 25

tructure

hanges androcessing

statestionality

nd behaviorel updatese

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Model View Controller Pattern S

Controller

Model

View

Select View

Send User Gestures

Notify of Changes

Get Data

Set Data CRequest P

● Renders the models● Requests updates from model● Sends user gestures to controller

● Encapsulates application● Responds to state querie● Exposes application func

● Defines application flow a● Maps user actions to mod● Selects views for respons

Page 191: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 9 of 25

lution

ented usingg:

nts can be

ents can be a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the MVC Pattern: So

The MVC architectural pattern may be implemseveral Gang of Four design patterns includin

• Observer Pattern – The View componeobservers of the Model components

• Composite Pattern – The View componcomposite of other GUI components

Page 192: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 10 of 25

xample

RoomObserver

vailabilityListScreen

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Model View Controller Pattern ESolution

Model

GuestList

ReservationService

RoomList

ReservationList

RoomObservable

ReservationObservable

View

CheckInAndOutScreen

ReservationListScreen

ReservationObserver

RoomA

Controller

CheckOutEventHandler

CheckInEventHandler

set dataset data

set data

notify

notify

get data

get data

get data

get data

invoke

invoke displays

Page 193: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 11 of 25

equences

businessspectivesiew, and the

on the userdel

model

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the MVC Pattern: Cons

Advantages:

• Multiple views can allow access to the processing and data from different per

• It is simpler to modify the model, the vcontroller separately

• It is easier for some developers to focusinterface and others to focus on the mo

Disadvantage:

Dividing the subsystems can increasecommunication overhead between theand the view

Page 194: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 12 of 25

rn

ctureups of subtaskslar level of

, Sommerlad,):

in numerouscethe basis for the EE BluePrintsrns

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Layers Patte

“The Layers architectural pattern helps to struapplications that can be decomposed into groin which each group of subtasks is at a particuabstraction.” (Buschmann, Meunier, Rohmertand Stal. Pattern Oriented Software Architecture

• The Layers architectural pattern is seenand diverse systems in computer scien

• The principles behind this pattern formarchitecture recommended by the Javadesign guidelines and the Java EE Patte

Page 195: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 13 of 25

rn:

send Web

low and high

sending the

g flexiblelopment

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Layers PatteExample Problem

• A communication protocol is needed torequests between services written inheterogeneous environments

• This protocol must address a variety oflevel issues

• The low level issues include physicallyrequest across the network

• The high level issues include structurinmessages between heterogeneous deveenvironments

Page 196: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 14 of 25

rn:

of issues. A

ot ripple

be stable exchanged

subsystems can

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Layers PatteProblem Forces

Complicated systems often have many layerslayering solution must deal with these forces:

• System functionality changes should nthrough the system

• Interfaces between components should• Parts of the system should be able to be

without affecting the rest of the system• Parts of the system should be reusable• Data that is passed frequently between

lead to poor performance

Page 197: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 15 of 25

olution

er below it.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Layers Pattern: S

Each layer can only communicate with the lay

LayerN-1

LayerN

Layer1

Layer2

Page 198: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 16 of 25

lution

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Layers Pattern: Example So

TCP

HTTP

IP

SOAP

Ethernet

Page 199: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 17 of 25

equences

be developed

ting other layers

ery layertion overhead

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Layers Pattern: Cons

Advantages:

• Layers may be reusable• Layers are loosely coupled so that they can

and maintained separately• Layers can be exchangeable without rewri

Disadvantages:

• Adding a new functionality might affect ev• Separating layers can increase communica

Page 200: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 18 of 25

va EE™tions

practicepplications

EE Patternselines arere

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying Layers and Tiers in JaPlatform Enterprise Applica

• Layering is a Java EE architecture best • The size and complexity of enterprise a

makes layering a natural choice• The layering approach used by the Java

and the Java EE BluePrints design guiddescribed in the SunToneSM ArchitectuMethodology

Page 201: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 19 of 25

logy Layers

a more specific

re stack thaters represent(SunTone

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

SunToneTM Architecture Methodo

The SunTone Architecture Methodology usesdefinition of layers than the Layers pattern:

Layers are “The hardware and softwahosts services within a given tier. (laycomponent/container relationships)”Architecture Methodology page 11)

Page 202: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 20 of 25

gy Layers

lementation ofquirementshat application

ucture for the

ng systems that

dware required

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

SunTone Architecture Methodolo

• Application – Provides a concrete impcomponents to satisfy the functional re

• Virtual Platform – Provides the APIs tcomponents implement

• Upper Platform – Provides the infrastrapplication layer components

• Lower Platform – Provides the operatisupport the previous layers

• Hardware Platform – Provides the harto support the previous layers

Page 203: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 21 of 25

ogy Tiers

e Layers

ization ofservicerchitecture

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

SunTone Architecture Methodol

SunTone Architecture Methodology applies thpattern to define tiers

Tiers are “A logical or physical organcomponents into an ordered chain ofproviders and consumers.”(SunTone AMethodology page 10)

Page 204: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 22 of 25

ogy Tiers

the system markupt are sent to therequestsces and entitiesintegrate the

rces, such as a) or Enterprise

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

SunTone Architecture Methodol

• Client – Provides user interaction with• Presentation – Provides the hyper-text

language (HTML) pages and forms thaWeb browser and processes the user’s

• Business – Provides the business servi• Integration – Provides components to

Business tier with the Resource tier• Resource – Contains all backend resou

DataBase Management System (DBMSInformation System (EIS)

Page 205: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 23 of 25

h Tier

ces tiers sinceE platform.

irectory Service

egacy SystemsERP Systems

esource Tier

Database

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Technologies in Eac

There are no patterns for the client and resourthose tiers are implemented outside the Java E

<%

%>

ServletJSP

EJB Container

EJB

Java Beans/Plain Old Java

Objects (POJO)

JDBC

Java EE Connector

JavaMail

JAX-RPC

JavaIDL

JTA/JTS

JMS

D

L

Client Tier

Web Browser

Java SE AWT or SwingApplication or Applet

Non-Java Client

Java SE Client

Presentation Tier

Dependency

Business Tier Integration Tier R

Web Container

Page 206: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 24 of 25

s and Tiers

sent

ation

ueuin

g

uste

ring

nd R

obin

ntal

Scalin

g

ScalingStrategy

cyerm

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Platform Example – Layer

Client

Prese

ntat

ion

PreQ

ClRou

Busine

ss

Inte

grat

ion

Resou

rces

Horizo

Virtual HTML JSP EJB JMS APPO

UpperAny

BrowseriES iAS

MQSeries

CICS

Orderform

Formhandler

Orderservice

Ordersystem

interface

Legaord

syste

LowerAnyOS

Solaris Solaris Solaris MVS

HardwareAnyHW

E450 E5500 ES9000E250

Page 207: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 5, slide 25 of 25

umers

Object-Oriented Design Principles

Architectural Patterns

i-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• Architectural patterns focus on thestrategic, high-level compositestructure of a solution

• The MVC pattern separatespresentation management frombusiness logic

• Layers are the hardware andsoftware stack within a given tier

• Tiers are the logical or physicalorganization of components intoan ordered chain of providers and cons

Ant

Page 208: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

tterns

Java EE™ Patterns

Module 6

Introducing Java EE™ PaModule 6

IntroducingJava EE Patterns

Module 6

IntroducingJava EE Patterns

Page 209: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 2 of 14

y in the Java EE

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the Java EE pattern philosoph• Describe the Java EE patterns and tiers

pattern catalog

Page 210: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 3 of 14

terns

n Professionalfor a wide

r experienceing the Java EE

e familiardocument and

evelop entirely

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Purpose of the Java EE Pat

• The Java CenterSM program, part of SuServices, has built enterprise solutions variety of customers

• The Java EE patterns evolved from thei• The Java EE patterns solve problems us

platform technologies• Some Java EE patterns might already b• The purpose of the Java EE patterns is to

recommend best practices rather than dnew techniques

Page 211: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 4 of 14

de:

ticesy’s primary role

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Benefits

The key benefits of the Java EE patterns inclu

• Using sound design principles• Leveraging documented, accepted prac• Understanding each Java EE technolog• Reducing coupling and dependencies

between components• Minimizing network traffic• Reducing costs of network latency

Page 212: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 5 of 14

ts Design

ing complexscale and

erns thats to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Relation to the Java EE BluePrinGuidelines

The Java EE BluePrints design guidelines:

• Describe standard techniques for buildJava EE platform applications that can change quickly

• Are complemented by the Java EE pattprovide formally documented solutionspecific problems

Page 213: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 6 of 14

tterns

nted in very

tterns

or other

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Gang of Four and Java EE Pa

Gang of Four Patterns:

• Abstract solutions that can be implemediverse ways

• Can be used with any object-orientedprogramming language

• Often build on or expand other GoF pa

Java EE Patterns:

• Designed for the Java EE platform• Often build on or expand GoF patterns

Java EE patterns

Page 214: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 7 of 14

of the Java

hree tiers:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing the Patterns and TiersEE Pattern Catalog

The Java EE patterns catalog is grouped into t

• Integration tier• Business tier• Presentation tier

Page 215: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 8 of 14

platform codestems:

synchronouslyva Message

-specific codented interfacetencesiness objects

services

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Integration Tier Patterns

Concerned with the integration of the Java EEwith other types of applications and legacy sy

• Service Activator – Allows a client to ainvoke an EJB component, using the JaService (JMS) API

• Data Access Object – Isolates databaseinto classes that expose a business-orie

• Domain Store – Creates a robust persismechanism that is transparent to the buwithout using entity beans

• Web Service Broker – Makes business available as web services

Page 216: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 9 of 14

r a Java EENaming and acquiring

tion tier with atierupled access to

of remotees in one object

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Tier Patterns

Concerned with managing persistence andbusiness processing:

• Service Locator – Removes the need foplatform client to be aware of the Java Directory Interface™ (JNDI) API whenbusiness components

• Session Façade – Provides the presentasimple interface to access the business

• Business Delegate – Provides loosely cobusiness tier components

• Transfer Object – Reduces the numbermethod calls by returning multiple valu

Page 217: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 10 of 14

ness logicsiness objectsata from

es transferctsf related, fine- entity,, containing

ent mechanisma large numbersults

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Tier Patterns

• Application Service – Centralizes busibetween the service facades and the bu

• Business Object – Separates business dbusiness logic and workflow logic

• Transfer Object Assembler – Assemblobject data from multiple business obje

• Composite Entity – Wraps a number ograined, persistent objects into a singlerepresenting a structured organizationthose objects

• Value List Handler – Provides an efficifor executing queries that might returnof objects and browsing through the re

Page 218: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 11 of 14

s

essing and post-

sm forts actionatchingcomponenttext specificut of

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Presentation Tier Pattern

Concerned with organizing the application’spresentation components:

• Intercepting Filter – Manages pre-procprocessing of a client request

• Front Controller – Provides a mechanicentralized management of user reques

• Application Controller – Separates theinvocation management and view dispmanagement from the front controller

• Context Object – Passes data from conobjects without passing those objects otheir context

Page 219: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 12 of 14

s

ieval for a view

rom many

Controller and

atcher View takes moresiness

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Presentation Tier Pattern

• View Helper – Factors out content retrfrom the logic needed to build the view

• Composite View – Constructs a view fdifferent sub-views

• Dispatcher View – Combines the FrontView Helper patterns

• Service to Worker – Similar to the Disppattern, except that the front controllerresponsibility for view selection and buprocess invocation

Page 220: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 13 of 14

ips

tes

Might Invoke

sparentlysts

vice Broker

ss Object

vice

licationntroller

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Pattern Relationsh

Business Tier Java EE Patterns

Presentation Tier Java EE Patterns

Integration Tier Java EE Patterns

Behavioral Gang of Four Patterns

Creational Gang of Four Patterns

Structural Gang of Four Patterns

Might Get Data From

Might Create

Might Get Data From

Has Similar Result To

Uses

Based On

Might invoke

Might Invoke

Might Invoke

Might Be A

Might Be A

Might Execute

Might Be Created By

Might Be Created By

Based On

Might InvokeMight Invoke

Uses

Might Be Created By

MightCreate

Uses CreatesCrea

Might Invoke

Uses Functionality Of

Might Create

Contains

Might Be A

Might Invoke

MightInvoke

Might Use

Uses

Might Be A

MightInvoke

Controller Invokes

Creates

Uses

Delegates To

Forward To

Uses

Uses

Invokes

Creates

TranPersi

MightCreate

Might Include

Singleton

Factory Method

Iterator

Composite Entity

Value List Handler

Transfer Object

Dispatcher View Context Object

Decorator

Strategy

Composite

Command

Observer

GoF

GoF

GoF

Proxy

Adapter

Facade

Abstract Factory

View Helper

Composite View

Session Facade

Business Delegate

Data Access Object

Transfer ObjectAssembler

Front Controller

Intercepting Filter

Service To Worker

Service Locator

Web Ser

Busine

Application Ser

Service Activator

Domain Store

AppCo

Could BeImplemented As

Page 221: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 6, slide 14 of 14

Object-Oriented Design Principles

Architectural Patterns

Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

Java EE patterns help to improve theinternal structure of applications by:

• Consolidating common services• Minimizing traffic between tiers• Emphasizing loose coupling

of objects

Anti-

Page 222: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 1 of 51

tterns

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Module 7

Using Integration Tier PaModule 7

Using IntegrationTier Patterns

Module 7

Using IntegrationTier Patterns

Page 223: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 2 of 51

egration

attern

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• List the features and purpose of the IntTier patterns

• Apply the Service Activator pattern• Apply the Data Access Object (DAO) p• Apply the Domain Store pattern• Apply the Web Service Broker pattern

Page 224: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 3 of 51

tterns

AO)

h

ey technologies

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Integration Tier Pa

• Encapsulate access to the data stores (D• Provide messaging to the business tier• Provide integration of web services wit

business components• Rely on the JDBC API and JMS API as k

Page 225: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 4 of 51

Overview

tie together asstudent guide.

ging for businessmponents.

. Simplifies access to

echanism that isjects without using

e business services

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Integration Tier Java EE Patterns

All examples in the next five modulesshown in the reference diagram in the

Pattern Primary FunctionService Activator Provides asynchronous messa

components, including EJB co

Data Access Object(DAO)

Encapsulates data access logicdisparate data sources.

Domain Store Creates a robust persistence mtransparent to the business obentity beans.

Web Service Broker Provides a flexible way to makavailable as web services.

Page 226: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 5 of 51

Pattern:

seful for:gts with

d componentsponents to be

rchitecture (EJBw to mostsing messages

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service ActivatorProblem Forces

• Invocation through messaging is very u• Establishing asynchronous processin• Communicating between componen

different lifetimes• Communicating with loosely couple

• A mechanism is needed for EJB 1.x cominvoked indirectly using messages

• Even with containers based on EJB 2.x a2.x containers), you should consider hoflexibly invoke business components u

Page 227: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 6 of 51

Solution

API

tor is a plain

tor can also be

Messages andthe requestofability

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Activator:

• The ServiceActivator class is a JMS MessageListener implementation

• For EJB 1.x containers, ServiceActivaold Java object (POJO)

• For EJB 2.x containers, ServiceActivaa message-driven bean

• The ServiceActivator class receivesinvokes business components to fulfill

• Keeping substantial business logic out ServiceActivator improves maintainand reusability

Page 228: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 7 of 51

uctureListener>>ctivator

Component

0..*

activates

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Str<<MessageServiceA

Business

<<Message>>Request

Client

receives

creates/sends

Page 229: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 8 of 51

uence<<POJO>>

BusinessComponent2

: Acknowledgement

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Seq

<<Message>>: Request

2. send( : Request )

1. create()

Message ServerMessage Server <<MessageListener>>: ServiceActivator :

<<SessionEJB>>: BusinessComponent

3.1. parseMessage

3.3 process

3.4 create()˚

3.2 process

3: send( :Request )

3.5: sendAcknowledgement

: Client

Page 230: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 9 of 51

Pattern:

r is mostly used

or – This.x container

contain a GOFe activatorponse – Annse to the clientther

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service ActivatorStrategies

• POJO Service Activator – This activatowith EJB 1.x containers or when no EJBcontainers are used

• Message-Driven Bean Service Activatactivator is only available with an EJB 2

• Command Request – The message cancommand that is invoked by the servic

• Database, Email, or JMS Message Resasynchronous process can place a respoin a database, an email message, or anoJMS message

Page 231: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 10 of 51

mple

ceActivator

FactoryName, queueName )

n bean>>onfirmerBean

n( reservationID )

activates

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Exa

<<JMS Listener>>ReservationConfirmationServi

+close()+onMessage( msg )+ReservationConfirmationServiceActivator( conn-startListener()

<<JMS Sender>>ReservationConfirmationClient

+sendReservationConfirmation( reservationID )

<<sessioReservationC

+confirmReservatio

<<JMS Message>>ObjectMessage

+getObject()+setObject( )

recieves

creates/sends

Page 232: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 11 of 51

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Exa

1 import javax.jms.*;2 public class ResConfirmServiceActivator3 implements MessageListener{4 private QueueSession qSession;5 private QueueReceiver qReceiver;6 private String connFactoryName;7 private String queueName;8 private JMSServiceLocator serviceLocator;9 public ResConfirmServiceActivator10 (String cfn, String qn) {11 connFactoryName = cfn;12 this.queueName = qn;13 startListener();14 }15 private void startListener() {16 try {17 serviceLocator =18 new JMSServiceLocator(connFactoryName);19 QueueConnectionFactory qConnFactory =20 serviceLocator.getQueueConnectionFactory();

Page 233: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 12 of 51

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Exa

21 QueueConnection qConn =22 qConnFactory.createQueueConnection();23 qSession = qConn.createQueueSession24 (true,Session.AUTO_ACKNOWLEDGE);25 Queue shipBookQueue =26 serviceLocator.getQueue(queueName);27 qReceiver =28 qSession.createReceiver(shipBookQueue);29 qReceiver.setMessageListener(this);}30 catch (JMSException e) {31 e.printStackTrace();32 }33 }34 public void onMessage(Message msg) {35 try {36 ObjectMessage objMsg = (ObjectMessage) msg;37 String reservationID =38 (String) objMsg.getObject();39 //. . .Lookup and create bean40 ReservationConfirmerLocal resConfirmer =...

Page 234: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 13 of 51

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Activator Pattern Exa

41 resConfirmer.confirmReservation42 (reservationID);43 }44 catch (JMSException e) {45 e.printStackTrace();46 }47 }48 public void close() {49 try {50 qReceiver.setMessageListener(null);51 qSession.close();52 }53 catch(Exception e) {54 e.printStackTrace();55 }56 }57 }

Page 235: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 14 of 51

tor:

nents from a

ions of any type

ssage

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service ActivaConsequences

Advantages:

• Allows the invocation of EJB 1.x compomessaging server

• Provides flexible asynchronous invocatof business component

• Separates business processing from meconsuming and parsing

Page 236: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 15 of 51

m Forces

y requires

ewrites of the

ind and createnot integrated

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the DAO Pattern: Proble

• Accessing different data sources usualldifferent code

• Data source changes should not force rbusiness logic

• Data access objects need to be easy to f• Persistence code is more reusable if it is

with business logic

Page 237: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 16 of 51

lution

usiness objects

ject interfaceg transparency

ess classese classes from

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the DAO Pattern: So

• Data access code is factored out of the binto POJOs called DataAccessObjects

• When product changes take place, newimplementations of the DataAccessObcan be added to the system, maintaininto the BusinessComponent

• DataAccessObjects are usually statel• DataAccessObjects should not expos

packages like java.sql

Page 238: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 17 of 51

DataSourcecapsulates

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern StructureDataAccessObject

+DataAcessObject()+delete( : TransferObject )+find( . . . ) : TransferObject[]+insert( : TransferObject )+update( : TransferObject )

TransferObject

-propertyA-propertyB

+getPropertyA()+getPropertyB()+setPropertyA()+setPropertyB()

BusinessComponent

obtains, modifies

creates, uses

enuses

Page 239: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 18 of 51

ansferObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Sequence

: DataAccessObject

: BusinessComponent

: Tr

: DataSource

2. find( . . . )

4. update

1. Create()

return TransferObject

3. Set Property

4.1 GetProperty

2.2 Create()

2.1 SELECT

4.2 UPDATE

Page 240: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 19 of 51

ategies

er methodssfer objects, for

y and placed in

rning transfert is a wrapperhnology rowsethe GoF Factorycan be a useful

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the DAO Pattern: Str

• Transfer Object Collection – DAO findcreate simple data structures, called traneach row that is returned from the quera collection

• Rowset Wrapper List – Instead of retuobjects, the DAO can return a class thaaround a caching or read-only JDBC tec

• Factory for the Data Access Object – TMethod and Abstract Factory patterns way to create DAO objects

Page 241: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 20 of 51

tructure

Object )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Abstract Factory Strategy S

<<interface>>DAO1

+update( : TransferObject )...

<<interface>>DAO2

+update( : Transfer...

<<interface>>DAOFactory

+createDAO1()+createDAO2()

RdbDAOFactory

+createDAO1()+createDAO2()

XmlDAOFactory

+createDAO1()+createDAO2()

XmlDAO1RdbDAO1 XmlDAO2RdbDAO2

createscreates

Page 242: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 21 of 51

tonTO[]ReservationTO[]ationTO[] int

int

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern ExampleReservationDAO

+deleteReservation( reservationID ) : in+findAvailableReservations() : Reservati+findReservationsByCustomer( custID ) : +findReservationsByDate( date ) : Reserv+insertReservation( : ReservationTO ) :+ReservationDAO()+updateReservation( : ReservationTO ) :...

ReservationTO

-endDate-startDate...

+getCustomer()+getEndDate()+getRoom()+getStartDate()+ReservationTO( . . . )...

BusinessObject

obtains/provides creates/uses

Page 243: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 22 of 51

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Example

1 import java.sql.*;2 import java.util.*;3 import javax.sql.*;4 import javax.naming.*;56 public class ReservationDAO {7 private DataSource ds;89 public ReservationDAO() throws DAOException {10 try {11 InitialContext ic = new InitialContext();12 ds=(DataSource)13 ic.lookup("java:comp/env/jdbc/hotelDS");14 } catch (NamingException e) {15 throw new DAOException16 ("Error obtaining DataSource", e);17 }18 }19 public ArrayList findReservationByDate

Page 244: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 23 of 51

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Example

20 (java.util.Date theDate)21 throws DAOException {22 ArrayList data = new ArrayList();23 Connection conn=null;24 PreparedStatement stmt = null;25 ResultSet results = null;26 try {27 conn = ds.getConnection();28 String query = "SELECT * FROM RESERVATION“ +29 “ WHERE DATE = ?";30 stmt = conn.prepareStatement(query);31 stmt.setDate(1,32 new java.sql.Date(theDate.getTime()));33 results = stmt.executeQuery();3435 java.util.Date startDate, endDate;36 while (results.next()) {37 startDate = results.getDate("startDate");38 endDate = results.getDate("endDate");

Page 245: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 24 of 51

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Example

39 data.add(40 new ReservationTO(startDate, endDate));41 }42 }43 catch (SQLException e) {44 throw new DAOException45 ("Error finding reservation", e);46 }47 finally {48 try {49 if (results != null)50 results.close();51 if (stmt != null)52 stmt.close();53 if (conn != null)54 conn.close();55 } catch (SQLException e) {56 throw new DAOException57 ("Error closing connection", e);

Page 246: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 25 of 51

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Example

58 }59 }60 return data;61 }62 public int deleteReservation63 (String reservationID) throws DAOException{64 Connection conn=null;65 PreparedStatement stmt = null;66 int count=0;67 try {68 conn=ds.getConnection();69 String query= "DELETE FROM Reservation “70 + “WHERE ReservationID = ?";71 stmt=conn.prepareStatement(query);72 stmt.setString(1, reservationID);73 count = stmt.executeUpdate();

Page 247: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 26 of 51

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

DAO Pattern Example

74 }75 //. . .implement exception handling76 }77 //. . .implement other access methods78 }

Page 248: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 27 of 51

equences

ctsre

ctsier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the DAO Pattern: Cons

Advantages:

• Factors data access out of business obje• Creates a more flexible system for futu

migration efforts• Increases cohesiveness in business obje• Isolates data access logic in a separate t

Disadvantages:

• An extra layer of infrastructure to bedeveloped is added

• It is not useful with CMP entity beans

Page 249: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 28 of 51

n: Problem

nce code fromes not make thesophisticated

ution for

re not requiredntainerheritance

table

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store PatterForces

• The DAO pattern separates the persistethe business objects, but the pattern docode transparent to the business object

• Many enterprise applications require spersistence mechanisms

• Entity beans are not an appropriate solsome systems:• If many of the services of entity beans a• If the application does not use an EJB co• If entity beans constraints, such as no in

between business objects, are not accep

Page 250: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 29 of 51

n: Solution

lasses that

toref worktence product) or aroductmplement thisn will help you

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Patter

• A domain store is a set of persistence ctransparently persist business objects

• You can implement a custom domain simplementation, but this is quite a bit o

• More frequently you might use a persisthat is based on Java Data Objects (JDOproprietary object relational mapping p

• Although few developers are likely to ipattern themselves, learning the patterlearn how these products work

Page 251: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 30 of 51

ture

<<interface>>PeristenceCapable

BusinessObject

DataSource

0..*

1..*

UD

1

ata

0..*

ML file>>rsistMap

s

lts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Domain Store Pattern StrucPersistenceManagerFactory

+getPersistenceManager() : PersistenceManager

PersistenceManager

+close()+currentTransaction() : Transaction+deletePersistent( : PersistenceCapable )+makePersistent( : PersistenceCapable )+newQuery( Class, String ) : Query

Query

+declareOperations( )+execute( ) : Collection

ApplicationService

<<DAO>>StoreManager

StateManager

Transaction

+begin()+commit()+rollback()

0..*

executes1..*

<<creates>>

1..*CR

<<creates>>

1

get/set d

1 1<<XPe

CRUDupdates

consult

consu

Page 252: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 31 of 51

quence<<DAO>>toreManager

: DataSource

.1: insert( data )

7.1.1.1.1.1: INSERT

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Domain Store Persistence Se: PersistenceManagerFactory : PersistenceManager: ApplicationService

: BusinessObject

: StateManager

: S

: Transaction

3: getPersistenceManager

6: makePersistent( busObj )

4: currentTransaction

7.1: flushData

2: setData

6.1.1: setStateManager

7.1.1.1: getData

1: create()

6.1: create()

7.1.1: flushData

7.1.1.1

5: begin

7: commit

4.1: create()

7.2: commit

Page 253: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 32 of 51

ncenessObject : DataSource

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Domain Store Query Seque: PersistenceManager: ApplicationService : Busi<<DAO>>

: StoreManager

: StateManager

: Query

1: newQuery( class, queryString )

2.2.1: repeat for each row

2.2: returnRows

2.2.1.2: create

2.2.1.3: setData

3: getData

2.1: getData

2.1.1: SELECT

2.2.1.1: create()

2: execute( queryParameters )

1.1: create()

Page 254: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 33 of 51

xample

{

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store: E

The Payment Business Object:

1 package sl500;2 import java.util.Date;3 public class Payment {4 private double amount;5 private Date datePaid;6 private PaymentMethod payMethod;78 private Payment() {}9 public Payment(double a, Date d, PaymentMethod p)10 amount = a;11 datePaid = d;12 payMethod = p;13 }14 //. . .standard plain get/set methods15 }

Page 255: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 34 of 51

xample

{

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store: E

The PaymentMethod Business Object:

1 package sl500;23 import java.util.Date;45 public class PaymentMethod {6 private String type;7 private String number;8 private Date expiration;910 private PaymentMethod() {}11 public PaymentMethod(String t, String n, Date e) 12 type = t;13 number = n;14 expiration = e;15 }16 //. . .standard plain get/set methods17 }

Page 256: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 35 of 51

n: Example

D Java Data Objectsdtd">

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Patter

JDO Descriptor:

1 <?xml version="1.0" encoding="UTF-8"?>2 <!DOCTYPE jdo PUBLIC "-//Sun Microsystems, Inc.//DT

Metadata 1.0//EN" "http://java.sun.com/dtd/jdo_1_0.3 <jdo>4 <package name="sl500">5 <class name="Payment">6 <field name="payMethod">7 <collection element-type="PaymentMethod"/>8 </field>9 </class>10 <class name="PaymentMethod"/>11 </package>12 </jdo>

Page 257: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 36 of 51

n: Example

ops);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Patter

The PaymentService Application Service:

1 package sl500;2 import javax.jdo.*;3 import java.io.*;4 import java.util.*;56 public class PaymentService {7 private PersistenceManager pm;89 public PaymentService() throws IOException {10 InputStream propertyStream =11 new FileInputStream("jdo.properties");12 Properties jdoProps = new Properties();13 jdoProps.load(propertyStream);14 PersistenceManagerFactory pmf =15 JDOHelper.getPersistenceManagerFactory(jdoPr

Page 258: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 37 of 51

n: Example

e(), method);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Patter

16 pm = pmf.getPersistenceManager();17 }18 public void makePayment(double amount,19 String type, String number, Date expiration){20 Transaction tx = pm.currentTransaction();21 tx.begin();22 PaymentMethod method = new PaymentMethod23 (type, number, expiration);24 Payment thePayment = new Payment(amount, new Dat25 pm.makePersistent(thePayment);26 tx.commit();27 }28 public void queryPayments() {29 Extent e = pm.getExtent(Payment.class, true);30 Iterator i = e.iterator();31 while (i.hasNext())32 {33 Payment p = (Payment) i.next();

Page 259: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 38 of 51

n: Example

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Patter

34 System.out.println(p.getAmount() + " - " +35 p.getPayMethod().getType());36 }37 e.close(i);38 }39 }

Page 260: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 39 of 51

: Strategies

the entire

ess objects, thehe core

he

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store Pattern

• Custom Persistence – You implement domain store pattern from scratch.

• Java Data Objects – You write the businqueries, and the application services. Tpersistence code is provided by the JDOimplementation and is transparent to tdeveloper’s code.

Page 261: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 40 of 51

attern:

ithout the

ersistence

ness objects

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store PConsequences

Advantages:

• Allows many benefits of entity beans woverhead of other entity beans services

• Creates more robust and transparent pcapabilities than the DAO pattern

• Separates the persistence from the busi

Page 262: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 41 of 51

attern:

m scratch onlyle overkill for

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Domain Store PConsequences

Disadvantages:

• You should implement this pattern frowhen all other options seem undesirab

• A full persistence framework might besome applications

Page 263: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 42 of 51

r Pattern:

d as web

sufficientlyices should not be

e adapted to

ing, auditing,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Web Service BrokeProblem Forces

If business service facades are directly exposeservices the following problems can occur:

• They might contain methods that are incoarse grained to be effective web serv

• They might contain some methods thatexposed as web services

• Some of their methods might need to bmake effective web services

• They might require additional monitorlogging, or security code

Page 264: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 43 of 51

r Pattern:

t thatng the web

the invokes the

ght be a EJB 2.1a object

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Web Service BrokeSolution

• Create a WebServiceBroker componenimplements any code specific to handliservice request and then invokes theBusinessService component

• The web services request is received byEndPointProcessor component whichWebServiceBroker

• The WebServiceBroker component mistateless session bean or a plain old Jav

Page 265: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 44 of 51

tructure

BusinessService

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Service Broker Pattern S

<<servlet>>EndpointProcessor

WebServiceBrokerClientsend request

1..*

invoke

1..*

accesses

Page 266: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 45 of 51

quence BusinessService

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Service Broker Pattern Se<<servlet>>

: EndpointProcessor: WebServiceBroker :: Client

1: send request1.1: extract Request

1.1.1: invoke

1.1.1.1: invoke

Page 267: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 46 of 51

r Pattern:

(XML)m

RPC) – Thed by JAX-RPCecture for XMLthe XML andML

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Web Service BrokeStrategies

• Custom Extensible Markup LanguageMessaging – You write your own custoEndPointProcessor component

• Java™ API for XML-based RPC (JAX-EndPointProcessor servlet is provide

• Java Binder Strategy – The Java ArchitBinding (JAXB) can be used to process generate transfer objects based on the X

Page 268: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 47 of 51

xample

session bean>>servationSessionFacade

r( ... )rvation( ... )omer( ... )er( ... )ation( ... )tionData()ation( ... )ationConfirmation( ... )

<session bean>>nMgmtApplicationService

rvation( ... )ation( ... )tionData()ation( ... )ationConfirmation( ... )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Service Broker Pattern E

<<CustomerRe

+addCustome+cancelRese+deleteCust+editCustom+findReserv+getReserva+makeReserv+sendReserv...

<<session bean>>ReservationWebServiceBean

+cancelReservation( ... )+findReservation( ... )+makeReservation( ... )

<<servlet>><<JAX-RPC>>

EndpointProcessor

DotNetClient

send request

accesses

invokes1..*

<Reservatio

+cancelRese+findReserv+getReserva+makeReserv+sendReserv

<<session bean>>CustomerMgmtApplicationService

+addCustomer( ... )+deleteCustomer( ... )+editCustomer( ... )

Page 269: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 48 of 51

xample

te {teException;moteException;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Service Broker Pattern E

The ReservationWebService Interface:

1 package sl500;23 import java.rmi.*;45 public interface ReservationWebService extends Remo6 public boolean makeReservation(. . .) throws Remo7 public boolean cancelReservation(. . .) throws Re8 }

Page 270: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 49 of 51

xample

essionBean {

ean

bean

{}

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Service Broker Pattern E

The ReservationWebServiceBeanClass:

1 package sl500;2 import javax.ejb.*;3 public class ReservationWebServiceBean implements S4 public void ejbCreate() {5 //. . . Obtain session facade bean6 }7 public boolean makeReservation(. . .) {8 //. . .Call makeReservation on session facade b9 }10 public boolean cancelReservation(. . .) {11 //. . .Call cancelReservation on session facade12 }13 public void ejbRemove() {}14 public void ejbActivate() {}15 public void ejbPassivate() {}16 public void setSessionContext(SessionContext sc) 17 }

Page 271: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 50 of 51

r Pattern:

ice specific

head due to the

ly to have antation tier. Athe web service

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Web Service BrokeConsequences

Advantages:

A layer is introduced where web servcode can be added.

Disadvantages:

• Web services can increase network overprotocols used.

• The business service component is likeremote interface for access by the preselocal interface must be added for use bybroker component.

Page 272: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 7, slide 51 of 51

s a flexible wayeb services

Object-Oriented Design Principles

Architectural Patterns

Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• Service Activator pattern –Provides asynchronous messagingfor business components,including EJB components

• Data Access Object pattern –Encapsulates data store details

• Domain Store pattern – Creates arobust persistence mechanism thatis transparent to the businessobjects without using entity beans

• Web Service Broker pattern – Provideto make business services available as w

Anti-

Page 273: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

ess Tier

Java EE™ Patterns

Module 8

Using Presentation-to-BusinPatterns

Module 8

Presentation-to-Business TierPatterns

Module 8

Presentation-To -Business TierPatterns

Page 274: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 2 of 44

iness tier Javaon with the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe basic characteristics of the busEE patterns that facilitate communicatipresentation tier

• Apply the Service Locator pattern• Apply the Session Façade pattern• Apply the Business Delegate pattern• Apply the Transfer Object pattern

Page 275: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 3 of 44

tterns

ing theiness tiers

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing Business Tier Pa

Business Tier patterns:

• Built primarily with EJB components• Organize business logic• Reduce coupling• Reduce network overhead

The patterns in this module focus on structurinteraction between the presentation and bus

Page 276: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 4 of 44

Patterns

r service

ent detail with a

clients and

encapsulatinge object.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Platform Business Tier

Pattern Primary FunctionService Locator Provides one interface fo

lookups.Session Façade Hides business compon

simpler interface.BusinessDelegate

Decouples presentation business services.

Transfer Object Reduces remote calls byreturn value data into on

Page 277: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 5 of 44

rn: Problem

the same JNDI create a beanach client:

to write bean

dg up JMS

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Locator PatteForces

• All session or entity beans clients needAPI code to locate a home object and to

• Disadvantages of putting this code in e• Code is duplicated• Client programmer has to know how

client code• Reusable home objects are not cache

• The same issues apply to clients lookinConnectionFactory objects

Page 278: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 6 of 44

rn: Solution

nted

NDI Context

nt class that uses

eviously found

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Locator Patte

• The ServiceLocator class is implemeas a singleton

• The ServiceLocator object creates a Jobject and does a lookup of theComponentFactory object

• The ServiceLocator can either:• Return ComponentFactory to the Clie

it to create Component instances• Use ComponentFactory to create the

Component instances• The ServiceLocator has a cache of pr

ComponentFactory instances

Page 279: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 7 of 44

cture

ComponentFactory

MS tory y.

Context

uses

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Locator Pattern Stru<<Singleton>>ServiceLocator

+getComponentFactory( jndiName, homeClass ) : +getInstance() : ServiceLocator-ServiceLocator()

An EJB Home object, or JAPI QueueConnectionFacor TopicConnectionFactor

ComponentFactoryComponent

Client

1..*

1..*

uses1..*

1..*

uses (caches)

creates

1..* 1

uses

creates

For EJB components, an entity or session bean. For the JMS API, a QueueConnection or TopicConnection.

Page 280: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 8 of 44

uence

tory

: Component

: Create and Find

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Locator Pattern Seq

: ComponentFac

<<Singleton>>: ServiceLocator

: Context

: Client

2.2: Create and Find Component

2.1.1: Create()

1: Get Instance

2: Get Component

return ComponentFactory

2.2.1

2.1: Lookup

1.1: Create()

return Component

Page 281: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 9 of 44

attern:

r

ation of the

ponent’s JNDId in thes in a parameter

he last strategy,e are specified in

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Locator PStrategies

• EJB Component Service Locator• JMS API Topic and Queue Service Locato• Web Service Locator• Combined Service Locator – Some combin

above three strategies• Type Checked Service Locator – The com

name and the resource class are hard codeServiceLocator class and the client passeto specify which set of values to use

• Service Locator Properties – The same as tbut the JNDI name and resource class nama configuration file

Page 282: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 10 of 44

mple

EJBHome

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Locator Pattern Exa

<<Singleton>>ServiceLocator

+getHomeObject( jndiName, homeClass ) : +getInstance() : ServiceLocator-ServiceLocator()

<<session bean>>CustomerReservationSessionFacadeBean

+cancelReservation( ... ) : boolean+findReservation( ... )+getReservationData()+makeReservation( ... ) : boolean...

CustomerReservationSFHome<<Servlet>>

Client

create

lookup/cache

Page 283: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 11 of 44

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Locator Pattern Exa

1 public class ServiceLocator {2 private HashMap nameHomePairs = null;3 private Context ctx = null;4 private static ServiceLocator singleton = null;56 private ServiceLocator() throws NamingException{7 nameHomePairs = new HashMap();8 ctx = new InitialContext();9 }10 public static ServiceLocator getInstance()11 throws NamingException {12 if (singleton == null) {13 singleton = new ServiceLocator();14 }15 return singleton;16 }

Page 284: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 12 of 44

mple

;

.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service Locator Pattern Exa

17 public EJBHome getHomeObject18 (String jndiName, Class homeClass)19 throws NamingException {20 if (nameHomePairs.containsKey(jndiName)) {21 return (EJBHome) nameHomePairs.get(jndiName)22 }23 Object ejbRef = ctx.lookup(jndiName);24 EJBHome ejbHome = (EJBHome)PortableRemoteObject25 narrow(ejbRef, homeClass);26 nameHomePairs.put(jndiName, ejbHome);27 return ejbHome;28 }29 }

Page 285: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 13 of 44

attern:

is hidden uniform

ded to the

ng previously

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Locator PConsequences

Advantages:

• The complexity of lookup and creation• Access to the service is centralized and

without duplication of the lookup code• New business components are easily ad

lookup service• Performance can be improved by cachi

looked up objects

Page 286: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 14 of 44

attern:

ice Locator

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service Locator PConsequences

Disadvantage:

Even as a Singleton, there is one Servinstance per Java virtual machine

Page 287: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 15 of 44

attern:

e services ofe

tiple businessupledmponents

interactionwork trafficsinessnt and misuse

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Session Façade PProblem Forces

To fulfill a user request, a client might need thmultiple business components. This causes thfollowing problems:

• When clients interact directly with mulcomponents, the tiers become tightly co

• Clients that deal with many business cobecome responsible for managing their

• Fine-grained client access increases net• Lack of a uniform access strategy to bu

components leads to ad hoc developme

Page 288: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 16 of 44

rn: Solution

a session beantsess servicenent

creates, andent instances usually not

de will create

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Session Façade Patte

• You apply the GoF Façade pattern within front of the other business componen

• The client invokes coarse-grained businmethods on the SessionFacade compo

• The SessionFacade component finds,invokes the necessary BusinessCompon

• The SessionFacade component shouldcontain significant business logic

• Mapping each use case to a session facatoo many session facades

Page 289: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 17 of 44

cture

)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern Stru

<<session bean>>SessionFacade

+doService1( ... )+doService2( ... )...

BusinessComponent

+doService3( ... +getData( ... )+setData( ... )...

Client 1..*

accesses

Page 290: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 18 of 44

uencee2 : BusinessComponent

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern SeqappService1 : BusinessComponent appServic<<session bean>>

: SessionFacade: Client

1.1: doPart1( ... )

2.1: doSomething( ... )

1.3: doPart3( ... )

1.2: doPart2( ... )

1: doService1( ... )

2: doService2( ... )

Page 291: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 19 of 44

attern:

thod callsethod calls with

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Session Façade PStrategies

• Stateless Session Bean – For single me• Stateful Session Bean – For multiple m

intermediate state information

Page 292: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 20 of 44

mple

: EJBHome

>onService

ion( ... )

ervice

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern Exa

<<Servlet>>Client

<<Singleton>>ServiceLocator

+getHomeObject( jndiName, homeClass )+getInstance() : ServiceLocator-ServiceLocator()

<<session bean>>CustomerReservationSessionFacade

+addCustomer( ... )+cancelReservation( ... )+deleteCustomer( ... )+editCustomer( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )...

<<session bean>ReservationMgmtApplicati

+cancelReservation( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmat

<<session bean>>CustomerMgmtApplicationS

+addCustomer( ... )+deleteCustomer( ... )+editCustomer( ... )

Page 293: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 21 of 44

mple

e = null;ice = null;

nstance();ect

ject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern Exa

1 public class CustomerReservationSessionFacade2 implements SessionBean {3 private CustMgmtASHome custHome = null;4 private ResMgmtASHome resHome = null;5 private CustomerMgmtApplicationService custServic6 private ReservationMgmtApplicationService resServ78 public void ejbCreate() throws CreateException {9 try {10 ServiceLocator locator = ServiceLocator.getI11 resHome = (ResMgmtASHome) locator.getHomeObj12 ("ejb/ResAS", ResMgmtASHome.class);13 custHome = (CustMgmtASHome) locator.getHomeOb14 ("ejb/custAS", CustMgmtASHome.class);15 resService = resHome.create();16 custService = custHome.create();17 }18 catch (Exception e) {19 System.err.println(e);

Page 294: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 22 of 44

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Façade Pattern Exa

20 throw new CreateException21 ("Unable to initialize facade");22 }23 }24 public boolean makeReservation(. . .)25 throws Exception {26 if (newCustomer==true)27 custService.addCustomer(. . .);28 return resService.makeReservation(. . .);29 }30 . . .31 }

Page 295: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 23 of 44

attern:

ier components on multiple

rvice tiersy managementssion façadeiness tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Session Façade PConsequences

Advantages:

• Simplifies client access to the business t• Eliminates a client’s direct dependency

business objects• Reduces network traffic between the se• Provides a place for centralized securit• Centralizes transaction control in the se• Provides a uniform interface to the bus

Page 296: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 24 of 44

attern:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Session Façade PConsequences

Disadvantage:

Adds an extra layer

Page 297: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 25 of 44

Pattern:

h business

mplementation

ntt make too

of caching or

know how tos

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business DelegateProblem Forces

If presentation tier clients interact directly witservices:

• Clients are exposed to the underlying idetails of the service API

• Business service changes affect the clie• The presentation tier components migh

many remote invocations due to a lackrequest aggregation

• Presentation tier programmers needs toinvoke the business service component

Page 298: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 26 of 44

Pattern:

nessDelegaten an invokes

chnologyxceptionstically retry

sults

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business DelegateSolution

• On behalf of the Client class, the Busiuses a ServiceLocator object to obtaiBusinessService component and thebusiness methods on it

• The BusinessDelegate might catch tespecific exceptions and throw generic e

• The BusinessDelegate might automafailed requests

• The BusinessDelegate might cache re

Page 299: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 27 of 44

ructure

omponent orPI component

essService

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Delegate Pattern St

EJB cJMS A

BusinessDelegate Busin

ServiceLocator

Client

lookup and create

creates and uses

uses

uses

Page 300: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 28 of 44

quenceusinessService

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Delegate Pattern Se

: BusinessDelegate

: B: ServiceLocator: Client

return Service

2: invoke

1: Create()

1.1.1: Lookup

2.1: Invoke

1.1: Get Service

Page 301: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 29 of 44

Pattern:

acts as a proxyinterface as the

can sendate thatquests to Java

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business DelegateStrategies

• Delegate Proxy – The business delegatethat supports approximately the same business component

• Delegate Adapter – Disparate systemsrequests using XML to a business delegtranslates the requests and sends the reEE components

Page 302: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 30 of 44

ample

>>or

eClass ) : EJBHometor

acade

( ... )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Delegate Pattern Ex

<<SingletonServiceLocat

+getHomeObject( jndiName, hom+getInstance() : ServiceLoca-ServiceLocator()

<<session bean>>CustomerReservationSessionF

+addCustomer( ... )+cancelReservation( ... )+deleteCustomer( ... )+editCustomer( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation...

ReservationBusinessDelegate

+cancelReservation( ... )+findReservation( ... )+makeReservation( ... )...

<<Servlet>>Client

invokes

Page 303: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 31 of 44

ample

null;

or.getInstance();e =

ionSF",;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Delegate Pattern Ex

1 public class ReservationBusinessDelegate {2 private ReservationSessionFacade resSF = 3 public ReservationBusinessDelegate()4 throws ReservationException {5 try {6 ServiceLocator locator = ServiceLocat7 ReservationSessionFacadeHome resSFHom8 (ReservationSessionFacadeHome)9 locator.getHomeObject("ejb/Reservat10 ReservationSessionFacadeHome.class)11 resSF = resSFHome.create();12 }13 catch (NamingException e) {14 throw new ReservationException();15 }16 catch (CreateException e) {17 throw new ReservationException();18 }

Page 304: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 32 of 44

ample

Data)

;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Delegate Pattern Ex

19 catch (RemoteException e) {20 throw new ReservationException();21 }22 }23 public boolean makeReservation(String res24 throws ReservationException {25 try {26 return resSF.makeReservation(resData)27 }28 catch (Exception e) {29 throw new ReservationException();30 }31 }32 }

Page 305: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 33 of 44

Pattern:

tation tier and

the clients to

by caching

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business DelegateConsequences

Advantages:

• Reducing coupling between the presenthe business tier

• Adding a simple, uniform interface foruse to access business components

• Improving performance made possiblerequests

Page 306: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 34 of 44

Pattern:

elopers totion

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business DelegateConsequences

Disadvantages:

• Adding an additional layer to manage• Hiding remoteness which can lead dev

ignore the costs of these method invoca

Page 307: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 35 of 44

rn: Problem

een remote tiers getter

one remote

whenever

y data than

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object PatteForces

• Data often needs to be exchanged betw• If components only expose fine grained

methods, the remote client must make method invocation per attribute

• Remote calls should be coarse-grained possible

• Clients typically require more read-onlupdatable data

Page 308: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 36 of 44

rn: Solution

eansvalues and

mponents it, and returns

et the data from

ecause only the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object Patte

• A Transfer Object is a serializable JavaBcomponent that encapsulates attribute provides accessor methods

• The getTransferObject method of Cocreates the TransferObject, populateit to the Client class

• TheClientclass callsgetmethods to gthe TransferObject

• The network overhead should be low bgetTransferObject method is remote

Page 309: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 37 of 44

cture

sfer objectransfer objectsfer object

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Pattern Stru

Component

+getTransferObject() : TransferObject

create tranpopulate treturn tran

<<Serializable>>TransferObject

-attribute1-attribute2-attribute3

+getAttribute1()+getAttribute2()+getAttribute3()

Client

creates

Page 310: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 38 of 44

ence

<<Serializable>>tCopy: TransferObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Pattern Sequ

<<Serializable>>ServerCopy: TransferObject

Clien

: Component: Client

1.1: Create()

2: getAttribute1

3: getAttribute2

1: getTransferObject

return TransferObject

Page 311: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 39 of 44

attern:

onent objectmethods that

ansferObject

ts:odsect method

sed to protectther clients

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object PStrategies

• Multiple Transfer Objects – The Compprovides several getTransferObject return different TransferObject types

• Entity Inherits Transfer Object - TheBusinessObject is a subclass of the Tr

• Updateable (Mutable) Transfer Objec• A TransferObject provides set meth• A Component object’s setTransferObj

updates the Component data• Time stamp or version number can be u

against overwriting changes made by o

Page 312: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 40 of 44

quence

alizable>>: TransferObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Updatable Transfer Objects Se

<<Serializable>>ServerCopy: TransferObject

<<SeriClientCopy

: BusinessObject: Client

3: getAttribute2

2: getAttribute1

4. setAttribute1

5. setAttribute2

1: getTransferObject

6. setTransferObject

return TransferObject

1.1: Create()

Page 313: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 41 of 44

mple

ate, end : Dtae )

servationTO

<<entity bean>>CustomerBean

create

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Pattern Exa

ReservationTO

-endDate : Date-startDate : Date...

+getCustomer()+getEndDate() : Date+getRoom()+getStartDate() : Date+ReservationTO( . . ., start : D...

ReservationDAO

+findReservationByCustomer():Re+findAvailableReservations()+findReservationByDate()...

<<session bean>>ReservationMgmtApplicationService

+cancelReservation( ... )+findReservation( ... ) : ReservationTO+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )

<<session bean>>CustomerReservationSessionFacade

...

ReservationBusinessDelegate

...

<<session bean>>PaymentService

...

<<entity bean>>ReservationBean

...

<<Singleton>>ServiceLocator

...

<<Servlet>>Client

create

Page 314: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 42 of 44

mple

lizable

) {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Pattern Exa

1 public class ReservationTO implements Seria2 {3 private Date startDate;4 private Date endDate;56 public ReservationTO() { }7 public ReservationTO(Date start, Date end8 startDate = start;9 endDate = end;10 }11 public Date getStartDate() {12 return startDate;13 }14 public Date getEndDate() {15 return endDate;16 }17 }

Page 315: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 43 of 44

attern:

terfaces

lee the systemn usingocesses

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object PConsequences

Advantages:

• Simplifies entity bean and remote in• Reduces network traffic

Disadvantages:

• Transfer object data may become sta• Synchronization logic can complicat• The system can be complicated whe

concurrent access and transaction pr

Page 316: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 8, slide 44 of 44

n the tiers

Object-Oriented Design Principles

Architectural Patterns

-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

Presentation to business tier patterns:

• Service Locator – Focuses allservice lookups through oneinterface

• Session Façade – Provides simplerinterfaces to business components

• Business Delegate – Decouplespresentation tier components frombusiness components

• Transfer Object – Improvesefficiency of the transfer of data betwee

Anti

Page 317: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

atternsM

UT

Java EE™ Patterns

Module 9

Using Intra-Business Tier PModule 9

Tier PatternsUsing Intra-Business

odule 9

sing Intra-Businessier Patterns

Page 318: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 2 of 61

Intra-Business

attern

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the basic characteristics of theTier patterns

• Apply the Application Service pattern• Apply the Business Object pattern• Apply the Transfer Object Assembler p• Apply the Composite Entity pattern• Apply the Value List Handler pattern

Page 319: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 3 of 61

ier Patterns

usiness logic betweenness objects

eparate business dataw

jects into a composite

client requirements

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Platform Intra-Business T

Pattern Primary Function

Application Service Provides a central place to put bthe service façades and the busi

Business Object Describes how to organize and sfrom business logic and workflo

Transfer ObjectAssembler

Builds complex transfer objects

Composite Entity Organizes related persistence obstructure

Value List Handler Manages result sets according toand limits

Page 320: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 4 of 61

Pattern:

façades or

tities.t in the business

couplings

ced in the servicewhen the same

c somewhere incts.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ServiceProblem Forces

• Service façade is a generic term for sessionPOJO façades.

• Business objects represent business data en• Business processing logic should not be pu

objects. This can lead to a lot of expensive between the business objects.

• Business processing logic should not be plafaçades. This can lead to code duplication logic is needed for multiple use cases.

• You need to place business processing logibetween service façades and business obje

Page 321: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 5 of 61

Pattern:

e code and

ve the businessjects and

s can also usets, ordinaryts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ServiceSolution

• The ServiceFacade class has very littlprimarily just invokes the appropriateApplicationService methods

• The ApplicationServicemethods halogic that encapsulates the business obcoordinates their invocations

• The ApplicationService componentother ApplicationService componenService objects, and DataAcessObjec

Page 322: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 6 of 61

ructure

ataAccessObject

usinessObject

ervice

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern St

ApplicationService D

B

ServiceFacade

S

uses

uses

uses

Page 323: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 7 of 61

quencenessObject : DataAccessObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern Sesecond : Busifirst : BusinessObject: SecondAppService: FirstAppService: ServiceFacade

3.2: invoke

1.2: invoke

3.1: invoke

2: invoke

2.2: process

2.1: invoke

1: invoke

1.1: process

3: invoke

3.3: process

Page 324: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 8 of 61

Pattern:

pplicationas specified byly, themand.

– If there areve the samemight be

ou can havehat invoke eachent generict client specific.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ServiceStrategies

• Application Service Command – An aservice might be invoked by a commandthe GoF Command pattern. Alternativeapplication service might itself be a com

• GoF Strategy for Application Servicemultiple application services that achieresult using different algorithms, they implemented using a Strategy pattern.

• Application Service Layer Strategy – Ymultiple layers of application services tother. The lower layers are the most clilayers, and the upper layers are the mos

Page 325: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 9 of 61

ample

<<JMS Sender>>ervationConfirmationClient

<entity bean>>RoomBean

tRoomTO() : RoomTO

ession bean>>mentServiceBean

ntity bean>>ervationBean

ntity bean>>stomerBean

ervationDAO

tomerDAO

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern Ex

<<session bean>>CustomerReservationSessionFacadeBean

+addCustomer( ... )+cancelReservation( ... )+deleteCustomer( ... )+editCustomer( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )...

<<session bean>>ReservationMgmtApplicationService

+cancelReservation( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )

<<session bean>>CustomerMgmtApplicationService

+addCustomer( ... )+deleteCustomer( ... )+editCustomer( ... )

Res

...

<

+ge...

<<sPay

...

<<eRes

...

<<eCu

...

Res

...

Cus

...

Page 326: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 10 of 61

ample

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern Ex

1 public class ReservationMgmtAS2 implements SessionBean {3 private ReservationHome resHome = null;4 private PaymentHome payHome = null;5 private PaymentService payService = null;6 public void ejbCreate() throws CreateException {7 try {8 ServiceLocator locator =9 ServiceLocator.getInstance();10 resHome = (ReservationHome) locator.11 getHomeObject("ejb/Reservation",12 ReservationHome.class);13 payHome = (PaymentHome) locator.14 getHomeObject("ejb/Payment",15 PaymentHome.class);16 payService = payHome.create();17 }18 catch (Exception e) {19 throw new CreateException20 ("Unable to initialize AS");

Page 327: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 11 of 61

ample

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Service Pattern Ex

21 }22 }23 public boolean makeReservation(. . .)24 throws Exception {25 Reservation res = resHome.create(. . .);26 double cost = res.getCost();27 return payService.verifyPayment(cost);28 }29 . . .

Page 328: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 12 of 61

Pattern:

kflow logicdes

e unnecessary

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ServiceConsequences

Advantages:

• Encourages reusability of business wor• Avoids duplicating code in service faca

Disadvantage:

Introduces an extra layer that might bfor smaller applications

Page 329: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 13 of 61

attern:

the data store:

are likely to

to be moree with the

tentiallydling, data

ode might needice classes

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business Object PProblem Forces

If business service components directly access

• Changes to the data store or its schemaaffect the business services

• The business service components haveaware of how to properly communicatdata store

• Many applications have to deal with pocomplex issues such as transaction hancaching, and data synchronization

• Much of the data access and handling cto be repeated in multiple business serv

Page 330: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 14 of 61

attern:

to a separate

s logic in them,inimal and not

hould be logicalidation

ed into anothercess Object

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business Object PSolution

• Business entities should be separated inlayer of reusable business objects

• Business objects can have some businesbut the business logic should be fairly muse case specific

• The business logic in business objects sthat is very data oriented such as data vand manipulation

• Data persistence code should be separatlayer such as described by the Data Acpattern or the Domain Store pattern

Page 331: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 15 of 61

cture

ependantBO

0..*

contains

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Object Pattern Stru

ApplicationService D

DataStore

ParentBO

0..*

contains

persisted inpersisted in

accesses

Page 332: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 16 of 61

uencetaStore

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Object Pattern Seq: ApplicationService : DependantBO : Da: ParentBO

2.1: invoke

1.1: persist

2.1.1: persist

1: invoke

2: invoke

Page 333: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 17 of 61

attern:

JO businessit might be thees such as

usiness objects

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business Object PStrategies

• POJO Business Object – Although POobjects might seem faster and simpler, opposite if you need entity bean servictransactional and concurrency control

• Composite Entity Business Object – Bcan be implemented as entity beans

Page 334: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 18 of 61

mple<<entity bean>>

RoomBean

+getRoomTO() : RoomTO...

<<entity bean>>CustomerBean

...

<<entity bean>>ReservationBean

...

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Object Pattern Exa

<<session bean>>CustomerReservationSessionFacadeBean

+addCustomer( ... )+cancelReservation( ... )+deleteCustomer( ... )+editCustomer( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )...

<<session bean>>ReservationMgmtApplicationService

+cancelReservation( ... )+findReservation( ... )+getReservationData()+makeReservation( ... )+sendReservationConfirmation( ... )

<<session bean>>CustomerMgmtApplicationService

+addCustomer( ... )+deleteCustomer( ... )+editCustomer( ... )

Page 335: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 19 of 61

attern:

riented data is centralizedm the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business Object PConsequences

Advantages:

• Business data can be viewed as object-o• Data validation and manipulation code• The business data logic is separated fro

persistence logic• The business service layer is simplified

Page 336: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 20 of 61

attern:

too much

extra layer

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Business Object PConsequences

Disadvantages:

• Business objects can become bloated if business logic is placed in them

• Small applications might not need this

Page 337: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 21 of 61

semblers

ired fromise beans, datat gets themponents:

he

uired obtain and

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Problem Force

Client classes often need data that can be acqunumerous business objects, including enterpraccess objects, and transfer objects. If the clienneeded data directly from several business co

• The client becomes tightly coupled to tbusiness components

• Many remote invocations might be req• Client cohesion decreases by having to

construct the data model

Page 338: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 22 of 61

sembler

that exposesethodsers data from

a compositeclient

ovide the datas, or other

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Solution

• In the business tier, use a session bean coarse-grained getTransferObject m

• This getTransferObject method gathother business tier components, buildsTransferObject, and returns it to the

• The BusinessObject instances that prcan be session beans, entity beans, DAOobject types

Page 339: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 23 of 61

sembler

single object or

mutable

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Solution

• The TransferObject instance can be acan be a composite that contains otherTransferObject instances

• These TransferObject instances are im

Page 340: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 24 of 61

n Structure

ssObject

Object

acade

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Assembler Patter

<<session bean>>TransferObjectAssembler

+getCompositeTransferObject()

TransferObject

Client

0..*

contains

builds

DataAcce

Business

ServiceF

Service

Page 341: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 25 of 61

SequencesObject

: TransferObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Assembler Pattern<<session bean>>

: TransferObjectAssembler: DataAcces<<session bean>>

: BusinessSession<<entity bean>>: BusinessEntity

: Client

1.4: Get Data

1.3: Get Data

1.2: Get Data

1.6: Add Data From BusinessSession

1.5: Add Data From BusinessEntity

1.7: Add Data From DAO

1.1: Create()

return

CompositeTransferObject

1: GetComposoteTransferObject

Page 342: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 26 of 61

sembler

mplemented asusually frontedade componentler – Ifsfer object

bean

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Strategies

• POJO Transfer Object Assembler – If ia POJO, the transfer object assembler isby a session bean such as the session fac

• Session Bean Transfer Object Assembimplemented as a session bean, the tranassembler is usually a stateless session

Page 343: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 27 of 61

n Example

bean>>ean

) : RoomTO

mTO

creates

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Assembler Patter

ReservationTO

-endDate : Date-startDate : Date...

+getCustomer()+getEndDate() : Date+getRoom()+getStartDate() : Date+ReservationTO( , , start : Date, end : Date )...

<<session bean>>ReservationReportTOAssemblerBean

+findReservation( ... )+getReservationAndHotelData( reservationID )+getReservationData()+junk()+makeReservation( ... )

ReservationHotelTO

+getHotel() : HotelTO+getReservation()+ReservationHotelTO( : HotelTO, )

HotelDAO

+getHotelData( . . . ) : HotelTO...

<<entity bean>>CustomerBean

+getCustomerTO() : CustomerTO...

<<entityRoomB

+getRoomTO(...

<<entity bean>>ReservationBean

+create( ... )+getReservationTO()+remove()...

HotelTO

-amenities-location...

+getAmenities()+getLocation()...

CustomerTO

Roo

creates

creates

-room-customer

uses1

-reservation

-hotel

creates

creates

Page 344: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 28 of 61

n Example

otelData

ta();ReservationTO();, resData);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Transfer Object Assembler Patter

Transfer object assembler code:

1 public ReservationHotelTO getReservationH2 (String reservationID) {3 HotelTO hotelData = hotelDAO.getHotelDa4 ReservationTO resData = reservation.get5 return new ReservationHotelTO(hotelData

Page 345: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 29 of 61

sembler

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Consequences

Advantages:

• Removes business logic from client• Reduces coupling• Reduces network traffic• Improves client performance• Improves transaction performance

Page 346: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 30 of 61

sembler

side increases

ly

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Transfer Object AsPattern: Consequences

Disadvantages:

• Object creation overhead on the server• Data in transfer objects might get stale• Update logic must be handled separate

Page 347: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 31 of 61

Pattern:

veral decisions:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntityProblem Forces

When using entity beans you need to make se

• Local or remote interfaces• BMP or CMP• Whether to use CMR

Page 348: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 32 of 61

Pattern:

ntity beansacy persistencen desirable for

from the client

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntityProblem Forces

Consider the following forces:

• Avoid dependencies between remote e• You might need BMP for custom or leg• Entity beans container services are ofte

business objects• The database schema should be hidden

Page 349: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 33 of 61

P

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Comparing BMP and CM

TM

JDBC

Data Access Object

Container

Data

Data

BMP

TM

Container

Deployment Descriptor

EJB QL

CMP

Page 350: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 34 of 61

Pattern:

tly deployable, cycles.cessed only by

t should behe dependantJO.t should be dependant

OJOs or localR can be used.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntitySolution

• Parent objects are reusable, independencomponents that manage their own life

• Dependant objects are managed and actheir parent objects.

• For EJB 1.1 containers, the parent objecimplemented as a remote entity bean. Tobjects should be implemented as a PO

• For EJB 2.0 containers, the parent objecimplemented as a local entity bean. Theobjects can be implemented as either Pentity beans. If you are using CMP, CM

Page 351: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 35 of 61

ucture

ct 0..*

contains

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Str

Local entity bean or plain Java technology object

<<local entity bean>>CompositeEntity

DependentObjeClient 1 0..*

contains

Page 352: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 36 of 61

uencey object>>entObject

: DataStore

.2.1: processRequest

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Seq<<Java technologsecond : Depend

<<local entity bean>>first : DependentObject

<<local entity bean>>: CompositeEntity

: Client

2.2: getData

2

2.1: getData

2: busMethod

1.2: processRequest

1: busMethod

1.1: loadData

3: storeData

Page 353: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 37 of 61

Pattern:

applicationsade can be as an entitypplications.ethod onlyed by business

ith BMP, is marked

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntityStrategies

• Composite Entity Remote Façade – In with trivial business logic, a session façreplaced by a composite entity that actsfaçade. This is dangerous for complex a

• Lazy Loading – With BMP, ejbLoad mloads some data. The other data is loadmethods if and when it is required.

• Store Optimization (Dirty Marker) – WejbStore method only stores data thatas dirty.

Page 354: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 38 of 61

mple

ity bean>>erBean

ity bean>>Bean

Address

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

<<session bean>>ReservationSessionFacade

...

<<local entity bean>>ReservationBean

...

<<local entCustom

...

<<local entRoom

...

uses

accesses

1..*

Page 355: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 39 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

Composite entity code:

1 public abstract class ReservationBean2 implements EntityBean {3 //virtual persistence fields4 public abstract String getReservationID();5 public abstract void6 setReservationID(String resID);7 public abstract Date getStartDate();8 public abstract void setStartDate(Date d);9 public abstract Date getEndDate();10 public abstract void setEndDate(Date d);11 //virtual relationship fields12 public abstract CustomerLocal getCustomer();13 public abstract void14 setCustomer(CustomerLocal c);15 public abstract RoomLocal getRoom();16 public abstract void setRoom(RoomLocal r);17 private EntityContext context;

Page 356: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 40 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

18 public String ejbCreate(String resID,19 Date start, Date end, CustomerLocal cust,20 RoomLocal room) throws CreateException {21 setReservationID(resID);22 setStartDate(start);23 setEndDate(end);24 setCustomer(cust);25 setRoom(room);26 return null;

Page 357: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 41 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

27 }28 public void ejbPostCreate(String resID,29 Date start, Date end, CustomerLocal cust,30 RoomLocal room) throws CreateException {31 setCustomer(cust);32 setRoom(room);33 }34 public void setEntityContext35 (EntityContext ctx){36 context = ctx;37 }38 public void unsetEntityContext() {39 context = null;40 }41 public void ejbRemove() { }42 public void ejbActivate() { }43 public void ejbPassivate() { }44 public void ejbStore() { }45 public void ejbLoad() { }

Page 358: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 42 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

46 public ReservationTO getReservationTO() {47 return new ReservationTO();48 }49 }

Page 359: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 43 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

CMR relationship in deployment descriptor:

1 . . .2 <ejb-relation>3 <ejb-relationship-role>4 <ejb-relationship-role-name>5 ReservationBean6 </ejb-relationshiprole-name>7 <multiplicity>One</multiplicity>8 <relationship-role-source>9 <ejb-name>ReservationBean</ejb-name>10 </relationship-role-source>11 <cmr-field>12 <cmr-field-name>customer</cmr-field-name>13 </cmr-field>14 </ejb-relationship-role>15 <ejb-relationship-role>16 <ejb-relationship-role-name>17 CustomerBean

Page 360: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 44 of 61

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite Entity Pattern Exa

18 </ejb-relationship-rolename>19 <multiplicity>One</multiplicity>20 <relationship-role-source>21 <ejb-name>CustomerBean</ejb-name>22 </relationship-role-source>23 </ejb-relationship-role>24 </ejb-relation>25 . . .

Page 361: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 45 of 61

Pattern:

g entity

less remote

ing a façade

base

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntityConsequences

Advantages:

• Improves maintainability by simplifyinbean interactions

• Decreases network overhead by using entity beans

• Decreases network overhead by providand composite transfer objects

• Shields clients from changes in the data

Page 362: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 46 of 61

Pattern:

CMR, entityell as POJOs

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite EntityConsequences

Disadvantage:

Even with local interfaces, CMP, andbeans might not always perform as w

Page 363: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 47 of 61

Pattern:

ery facility

port result sets

ily read-onlyource-intensive sets

, as well as

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerProblem Forces

• Client applications need an efficient qu

• Clients need server-side caching to supthat are too large for the client

• Large search results are usually primar• EJB componentfindermethods are res

and ill-suited for browsing large result

• Clients might want to scroll backwardsforwards, through the search results

Page 364: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 48 of 61

Pattern:

a search query,to retrieve the

arch methodequest to the

ery and createsct instances

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerSolution

• The ValueListHandler class executesholds the results, and allows the client results they need

• When the client invokes the executeSeon ValueListHandler, it passes that rDataAccessObject

• TheDataAccessObjectexecutes the quthe ValueList object of TransferObje

Page 365: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 49 of 61

Pattern:

ents and results

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerSolution

• The ValueListHandler keeps theValueList reference

• The client can invoke the getNextElemgetPreviousElements methods to get

Page 366: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 50 of 61

ucture

ransferObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Str

<<interface>>ValueListIterator

+getNextElements( count : int )+getPreviousElements( count : int )+getSize() : int+resetIndex()

ValueListHandler

+executeSearch( . . . )

DataAccessObject

+executeSearch( . . . )

<<interface>>List

TValueListClient collects

provides data

iterates

accesses

Page 367: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 51 of 61

uence

: TransferObject

st

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Seq: ValueListHandler : DataAccessObject

: ValueLi

: Client

1: executeSearch( . . . )

2: getNextElements( 10 )

2.1: Create Sub-List from ValueList

3: getPreviousElemenets( 10 )

3.1: Create Sub-List from ValueList

return valueList

1.1: executeSearch( . . . )

1.1.2: create()

1.1.3: add( transferObjects )

1.1.1: create()

return subList

return sublist

Page 368: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 52 of 61

Pattern:

e list handler isd by a stateful

not use EJBe implementedessed by a

urn results in asultSet, a JDBC

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerStrategies

• Stateful Session Bean Handler – A valuusually a stateful session bean or frontesession bean

• POJO Handler – If an application doescomponents, the value list handler can bas a plain Java object that is directly accbusiness delegate

• Value List from DAO – A DAO can retvariety of formats including a JDBC ReRowset, or a collection

Page 369: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 53 of 61

ample

ReservationTO

dDate : DateartDate : Date

tEndDate() : DatetStartDate() : Date

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Ex

ValueListHandler

-endIndex : int-startIndex : int

+findReservationByDate( theDate : Date ) : void+getNextElements( count : int )+getPreviousElements( count : int )+getSize() : int+resetIndex() : void

ReservationDAO

+findAvailableReservations()+findReservationsByCustomer()+findReservationsByDate()+ReservationDAO()...

-en-st...

+ge+ge...

Client

create

iterates

0..*

Page 370: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 54 of 61

ample

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Ex

Value list handler code:

1 public class ValueListHandler {2 private List allResults;3 private int startIndex, endIndex;45 public void findReservationByDate(Date theDate)6 throws Exception {7 ReservationDAO dao = new ReservationDAO();8 allResults =9 dao.findReservationByDate(theDate);10 }11 public ReservationTO[] getNextElements12 (int howMany) {13 if (howMany > allResults.size()-endIndex) {14 howMany = allResults.size() - endIndex;15 }16 ReservationTO[] subset =17 new ReservationTO[howMany];

Page 371: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 55 of 61

ample

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Ex

18 int index;19 for (index=0; index<howMany; index++) {20 subset[index] = (ReservationTO)21 allResults.get(startIndex+index);22 }23 startIndex = endIndex;24 endIndex = startIndex+index;25 return subset;26 }

Page 372: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 56 of 61

ample

any) {

any];

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Ex

27 public ReservationTO[] getPreviousElements(int howM28 if (howMany > startIndex) {29 howMany = startIndex;30 }31 ReservationTO[] subset = new ReservationTO[howM3233 startIndex -= howMany;34 int index;35 for (index=0; index<howMany; index++) {36 subset[index] = (ReservationTO)37 allResults.get(startIndex+index);38 }39 endIndex = startIndex+index;40 return subset;41 }42 public int getSize() {43 return allResults.size();44 }45 public void resetIndex() {

Page 373: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 57 of 61

ample

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Value List Handler Pattern Ex

46 startIndex = endIndex = 0;47 }48 }

Page 374: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 58 of 61

Pattern:

od overheadsng results

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerConsequences

Advantages:

• Avoids EJB component finder meth• Supports server caching of result set• Enables client control over dispatchi• Reduces network overhead

Page 375: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 59 of 61

Pattern:

caching some

sults are

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Value List HandlerConsequences

Disadvantages:

• Performance can be impeded when query patterns

• This pattern is less effective when reupdated frequently

Page 376: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 60 of 61

.mplex business

Object-Oriented Design Principles

Architectural Patterns

-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

Intra-Business Tier patterns help expediteclient access to business objects. Insummary, these patterns contribute asfollows:

• Application Service – Provides acentral place to put business logicbetween the service facades andthe business objects.

• Business Object – Describes howto organize and separate businessdata from business logic and workflow

• Transfer Object Assembler – Builds coobjects from multiple transfer objects.

Anti

Page 377: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 9, slide 61 of 61

persistence

sult sets on

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• Composite Entity – Organizes related objects into a composite structure.

• Value List Handler – Manages large rebehalf of a client.

Page 378: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

atterns

Java EE™ Patterns

Module 10

Using Presentation Tier PModule 10

Tier PatternsUsing Presentation

Module 10

Using PresentationTier Patterns

Page 379: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 2 of 51

sentation Tier

the Apache

rn

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe basic characteristics of the PreJava EE Patterns

• Describe the Model 2 Architecture andStruts Framework

• Apply the Intercepting Filter pattern• Apply the Front Controller pattern• Apply the Application Controller patte• Apply the Context Object pattern

Page 380: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 3 of 51

r Patterns

ual

d-paste reusend

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing the Presentation Tie

Presentation Tier patterns:

• Provide guidance for designing individpresentation tier components by role

• Provide mechanisms to reduce copy-an• Enforce role separation between logic a

presentation components

Page 381: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 4 of 51

s

-processing and post-ponses.

resentation tier. It cancontrol.

gement and viewont controller

objects withouttext.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Presentation Tier Pattern

Pattern Primary FunctionInterceptingFilter

Provides a simple mechanism for preprocessing of HTTP requests and res

Front Controller Provides a single entry point to the phandle security, validation, and flow

ApplicationController

Separates the action invocation manadispatching management from the frcomponent.

Context Object Passes data that is in context-specificpassing those objects out of their con

Page 382: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 5 of 51

rchitecture

dification to be

d behaviorl updates

ate

nality

ng

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Traditional Model View Controller A

The traditional MVC architecture requires mouseful for Web applications

- Defines application flow an- Maps user actions to mode- Selects view for response

- Renders the models- Requests updates from models- Sends user gestures to controller

- Encapsulates application st- Responds to state queries- Exposes application functio

Controller

Send User Gestures

Select View

Notify of Changes

Set Data ChangesRequest Processi

View

Get Data

Model

Page 383: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 6 of 51

apply the MVCpplicationhis architecture

estpdates

ng

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Model 2 Architecture

• Model 2 architecture describes how to architecture to a Java technology web a

• The Presentation Tier patterns fit into t

- Renders the model with an HTML response- Requests updates from models- Creates HTML forms and hyperlinks that can trigger the next request to the Controller

- Verifies data from HTTP requ- Maps user actions to model u- Selects view for response

Select View

Model

<<JSP page>>ViewComponent

Get Data

View

<<servlet>>FrontController

Controller

- Encapsulates application state- Responds to state queries- Exposes application functionality

Set Data ChangesRequest Processi

Page 384: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 7 of 51

rk

l 2 architectureework

popular Model

avaBeanstate theure applicationTier patternstruts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Apache Struts Framewo

• Many development teams create Modeapplications without a pre-written fram

• You might want to use a Model 2architecture framework

• Apache Jakarta Struts is one of the most2 Architecture frameworks

• Struts provides a servlet, custom tags, Jcomponents, and other helpers to faciliimplementation of a Model 2 Architect

• The second edition of the Presentation discuss how they are implemented in S

Page 385: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 8 of 51

Pattern:

nd some

ng Tasks

mization for aclient

ption

ression

lation

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterProblem Forces

Some requests might require pre-processing aresponses may require post-processing.

Pre-Processing Tasks Post-Processi

User authentication Response custocertain type of

Session validate Response encry

Denial of service attack detection Response comp

Request decryption Language trans

Request decompression Debugging

Request auditing

Page 386: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 9 of 51

Pattern:

cessing tasks in

vedesirable copy-

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterProblem Forces

Placing all of the pre-processing and post-proone component can result in:

• Components with poor cohesion• Tasks that are difficult to add and remo• Tasks that are reusable only through un

and-paste techniques

Page 387: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 10 of 51

Pattern:

lared filterach

different the GoF

ativelyide built-in

plement a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterSolution

• Incoming requests go through each dec• Outgoing responses go back through e

declared filter• The pattern can be implemented using

designs, but the result is comparable toDecorator pattern

• Filters can be added or removed declar• Java Servlet 2.3 or later containers prov

support for filters• Pre-2.3 Java Servlet containers must im

custom filter strategy

Page 388: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 11 of 51

ucture

ain : FilterChain )

: ServletResponse )

t, response);

<<Servlet>>Target

-servlet

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Intercepting Filter Pattern Str

<<interface>>Filter

+destroy()+doFilter( request : ServletRequest, response : ServletResponse, ch+init( : FilterConfig )

<<interface>>FilterChain

+doFilter( : ServletRequest,

Filter nextFilter = filtersIterator.next();if (nextFilter != null) nextFilter.doFilter(request, response, this);else servlet.service(request, response);

//pre-processingchain.doFilter(reques//post-processing

FilterB

+destroy()+doFilter( . . . )+init( . . . )

FilterChainImpl

+doFilter( . . . )

FilterA

+destroy()+doFilter( . . . )+init( . . . )

FilterManagerWebClient

-filters0..*

Page 389: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 12 of 51

uence<<Servlet>>: Target

: FilterB

Filter

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Intercepting Filter Pattern Seq: FilterChainImpl: FilterManager: WebClient : FilterA

1.1: doFilter

1.1.1.1: doFilter

1.1.1.1.1.1 do

1: Request

1.1.1.1.1.1.1 service

1.1.1.1.1: doFilter

1.1.1: doFilter

Page 390: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 13 of 51

Pattern:

let containers,ammaticallytainers, filters

superclass for

used with the

e client or

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterStrategies

• Custom Filter – With pre-2.3 Java Servyou must define the filter pattern progr

• Standard Filter – In Java Servlet 2.3 conare added declaratively through thedeployment descriptor

• Base Filter – Base filter class serves as aall other filter classes

• Template Filter – The base filter can beGoF Template Method pattern

• JAX-RPC Filter – The filter is used in thintegration tier in front of a web service

Page 391: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 14 of 51

Pattern:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterExample

The timing filter:

1 package sl500;2 import java.io.*;3 import javax.servlet.*;4 public class TimerFilter implements Filter {5 private FilterConfig filterConfig = null;67 public void init(FilterConfig filterConfig)8 throws ServletException {9 this.filterConfig = filterConfig;10 }1112 public void destroy() { }1314 public void doFilter(ServletRequest request,15 ServletResponse response,16 FilterChain chain)

Page 392: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 15 of 51

Pattern:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterExample

17 throws IOException, ServletException {18 long start = System.currentTimeMillis();1920 chain.doFilter(request, response);2122 long end = System.currentTimeMillis();23 filterConfig.getServletContext().log24 ("Request processed in " + (end - start) +25 " milliseconds");26 }27 }

Page 393: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 16 of 51

Pattern:

lass>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterExample

Part of the web.xml file

1 <filter>2 <filter-name>TimerFilter</filter-name>3 <filter-class>sl500.TimerFilter</filter-c4 </filter>5 <filter-mapping>6 <filter-name>TimerFilter</filter-name>7 <url-pattern>/*</url-pattern>8 </filter-mapping>

Page 394: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 17 of 51

Pattern:

quests without

ationsaratively

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterConsequences

Advantages:

• Filters can be applied to all incoming rehaving to duplicate code

• Filters can easily be combined indifferent combinations

• Filters are easily reusable across applic• Filters can be added and removed decl

Page 395: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 18 of 51

Pattern:

a is shared

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Intercepting FilterConsequences

Disadvantage:

Filters can be inefficient if a lot of datbetween them

Page 396: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 19 of 51

rn: Problem

ng mechanism request. Thisany

and auditing,ponente neededimilar

is easier with a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Front Controller PatteForces

The system lacks a centralized request-handlifor activities needing to be completed for eachleads to these activities being littered across mcomponents

• Common system services, such as securityshould not be duplicated in each view com

• Workflow management and a controller ar• Multiple views can be used to respond to s

business requests• Tracking a user’s progress through the site

centralized point of contact

Page 397: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 20 of 51

rn: Solution

ontact forquest

view

ion strategies

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Front Controller Patte

Use a Front Controller as the initial point of chandling a request. The controller manages reprocessing, including:

• Invoking security services• Delegating business processing• Managing the choice of an appropriate• Handling errors• Managing the selection of content creat

Page 398: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 21 of 51

cture

JSP Page>>View

Action

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Front Controller Pattern Stru

ApplicationController<<Servlet>>

FrontController

<<

Client

forwards

invokesdelegates

Page 399: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 22 of 51

ence>> : Action

.1.1: Process Request

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Front Controller Pattern Sequ: ApplicationController<<Servlet>>

: FrontController<<JSP Page

: View: Client

1.1: Delegate

2.1: Delegate

3.2: Delegate

1: Send Request

3: Send Request

2: Send Request

1.1.1: Forward Request

2.1.1: Forward Request

3.2.2: Forward Request

1.1

3.2.1: Process Request

Page 400: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 23 of 51

attern:

ront Controllerletr functionalitynt controllerr functionalities

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Front Controller PStrategies

• Servlet Front Controller vs. JSP Page F– A FrontController is usually a serv

• Dispatcher in Controller – If dispatcheis minimal, it can be included in the fro

• Filter Controller – Some front controllecan be placed in a filter

Page 401: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 24 of 51

attern:

g – Rather thansuch as http:/.Controller,or the servletical resources *.dowhich isontroller

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Front Controller PStrategies

• Physical vs. Logical Resource Mappinclients requesting actual physical URLs/www.server.com/servlet/packageuse a logical URL mapping as an alias f

• Multiplexed Resource Mapping – Logmapping can include wildcards, such amapped to the Struts ActionServlet c

Page 402: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 25 of 51

mple

ns CancelReservation

+execute()

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Front Controller Pattern Exa

<<JSP Page>>ReservationSearchResults

<<JSP Page>>ReservationConfirmation

RequestContextObjectFactory

AuthenticationBean

SearchReservatio

+execute()

MakeReservation

+execute()

<<Filter>>DebuggingFilter

+doFilter()

<<Servlet>>FrontController

+doPost()

<<interface>>Command

+execute()

<<Filter>>TimingFilter

+doFilter()

<<JSP Page>>ErrorPage

ApplicationController

Client request

forwardforward

forward

forward

forward

Page 403: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 26 of 51

attern:

ication flowand logging of

centrally

hesion

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Front Controller PConsequences

Advantages:

• Avoids duplication of common requestprocessing code

• Allows central control of the Web appl• Allows the tracking of a particular user

related activity• Manages validation and error handling

Disadvantage:

The front controller can have poor co

Page 404: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 27 of 51

er Pattern:

responsibilities:

ecides whaty invokes the

cides which

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllProblem Forces

The controller has two particularly important

• Action Management – The controller daction to invoke, which in turn typicallbusiness processing

• View Management – The controller deview to forward the request to

Page 405: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 28 of 51

er Pattern:

agement in thes:

hesionology, making

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllProblem Forces

Placing the action management and view manfront controller component can cause problem

• The front controller might have poor co• This code is coupled to the servlet techn

the code harder to reuse and test

Page 406: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 29 of 51

er Pattern:

agement are class initial requestonController

uses a Mapperoke and what

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllSolution

• The action management and view manplaced in the ApplicationController

• The FrontController servlet does theprocessing and invokes the Applicati

• The ApplicationController usually class that determines what action to invview to forward to

Page 407: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 30 of 51

tructure

<<JSP Page>>View

Action

okes

vokes

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern S

ApplicationControllerFrontController

Mapper

Map

creates

creates

inv

delegates in

uses

searches

Page 408: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 31 of 51

equence<<JSP Page>>

: View

Action

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern S: ApplicationController<<Servlet>>

: FrontController: Mapper

:

: Map

1: delegate

1.4: forward

1.1: getAction

1.3: getView

1.2: invoke

1.1.2:create()

1.1.1: resolve

Page 409: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 32 of 51

er Pattern:

troller that controllersand pattern and

configuration fileld be invoked

r that performsplication a view handler. used to which view the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllStrategies

• Command Handler – An application conperforms action management. Applicationusually invoke actions using the GoF Commthe mapper component might use an XMLto determine which action command shoubased on the request URL.

• View Handler – An application controlleview management. Most commonly an apcontroller is both a command handler andThe result of the action command might bedetermine from the XML configuration filerequest should be forwarded to.

Page 410: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 33 of 51

er Pattern:

Languaged of JSP pages

ontrollernd invokes

e way, theication flow.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllStrategies

• Transform Handler – XML Stylesheet Transformations (XSLT) are used insteato generate the view. The application cdetermines an XSLT stylesheet to use athat stylesheet.

• Navigation and Flow Control – In somapplication controller controls the appl

Page 411: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 34 of 51

er Pattern:

l (SOAP)a request from

rvices message.ategy is similarstrategy, but it

work.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllStrategies

• Custom Simple Object Access ProtocoMessage Handling – Rather than beinga web user, the request can be a web se

• JAX-RPC Message Handling – This strto the Custom SOAP Message Handlinguses JAX-RPC to automate much of the

Page 412: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 35 of 51

xample

sDelegate

ions CancelReservation

+execute()

>>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern E

ReservationBusines

...

<<JSP Page>>ReservationSearchResults

<<JSP Page>>ReservationConfirmation

ApplicationController

SearchReservat

+execute()

MakeReservation

+execute()

<<Servlet>>FrontController

+doPost()

<<interfaceCommand

+execute()

<<JSP Page>>ErrorPage

Mapper

Map

uses

searches

forwardforward forward

Page 413: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 36 of 51

xample

troller with the

hen a request is(Action) object

susiness logic

guration file, class

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern E

• Struts implements the Application ConRequestProcessor class

• Each action that should be performed wreceived is implemented as a command

• For each type of request that requiresbusiness processing:• Create a subclass of the Action clas• Implement the process and invoke b

from the execute method• Create a mapping in the Struts confi

from the request URI to that Action

Page 414: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 37 of 51

xample

ervation">Confirmation.jsp"/>sp"/>

e methodfying “success”

the request tor

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Application Controller Pattern E

Example Struts Mapping Code:

<action path="/reserveRoom" type="hotel.MakeRes<forward name=”success” path="/Reservation<forward name=”failure” path="/ErrorPage.j

</action>

• The MakeReservation object’s executreturns an ActionForward object specior “failure”

• The RequestProcessor then forwardsthe ReservationConfirmation.jsp oErrorPage.jsp page

Page 415: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 38 of 51

er Pattern:

managementontrollerplicationsable by

ight be

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Application ControllConsequences

Advantages:

• Improves cohesion by separating actionand view management from the front c

• Improves reusability by keeping the apcontroller protocol generic and thus reudifferent client types

Disadvantage:

Introduces an extra component that munnecessary for smaller applications

Page 416: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 39 of 51

n: Problem

rvletRequesthroughout theontexts such as

o classes inbility of those

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PatterForces

• Context specific objects, such as HttpSeobjects often contain data that is used trequest processing, including in other cthe business tier

• If context specific objects are passed intother contexts, the flexibility and reusaclasses is reduced

Page 417: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 40 of 51

rn: Solution

m the context

e get methods,er method to the protocole data from the

ata validation

transfer object,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object Patte

• An object that encapsulates the data frospecific object is created

• The context object can be a set of simplor it can have one HashMap generic gett

• The context object can keep a referencespecific class, or it can keep a copy of thprotocol specific object

• The context object might also contain dand conversion logic

• A context object might seem similar to abut they have different intents

Page 418: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 41 of 51

cture

ContextObject

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Context Object Pattern Stru

ProtocolSpecificObject

ContextFactoryClient

uses

uses

uses creates

Page 419: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 42 of 51

ence

rotocolSpecificObject

t

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Context Object Pattern Sequ

: P

: ContextFactory

: ContextObjec

Container : Client

2.2: getData

1: create()

2: getContextObject( :ProtocolSpecificObject )

2.3: setData

3: getData1

4: getData2

2.1: create( :ProtocolSpecificObject )

Page 420: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 43 of 51

attern:

s:

ext object holds therMap method

OJO contextf data. The populatesletRequest

For either ofe method

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PStrategies

Strategies for ServletRequest context object

• Request Context Map Strategy – Contthe immutable Map object returned byServletRequest object’s getParamete

• Request Context POJO Strategy – A Pobject has a get method for each piece oconstructor takes ServletRequest andinstance variables with the data in Serv

• Request Context Validation Strategy –the above strategies, provide a validat

Page 421: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 44 of 51

attern:

ext object stores

ject stores

Context

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PStrategies

• Configuration Context Strategy – Contconfiguration state, for examplejavax.servlet.jsp.PageContext

• Security Context Strategy – Context obsecurity state, for examplejavax.security.auth.login.Login

Page 422: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 45 of 51

attern:

a factory to

egy – Ratherta from thebject onet automatically

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PStrategies

• Context Object Factory Strategy – Usecreate context objects

• Context Object Auto-Population Stratthan calling the methods to pass the daprotocol-specific object to the context oattribute at a time, you can use code thacopies all data over

Page 423: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 46 of 51

mple

ssDelegate

ations CancelReservation

+execute()

e>>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Context Object Pattern Exa

SearchReservationRequestData

ReservationBusine

...

MakeReservationRequestData

ApplicationController

AuthenticationBean

SearchReserv

+execute()

HttpServletRequest

MakeReservation

+execute()

<<Servlet>>FrontController

+doPost()

<<interfacCommand

+execute()

ContextFactory

creates

uses

uses

creates

Page 424: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 47 of 51

mple

uest{

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Context Object Pattern Exa

1 import javax.servlet.*;23 public class MakeReservationRequestData extends Req4 private String roomType;5 private int numNights;6 //...other fields78 public void initialize(ServletRequest request) {9 setRoomType(request.getParameter("roomType"));10 int numNights = Integer.parseInt11 (request.getParameter("numNights"));12 setNumNights(numNights);13 }14 public boolean validate() {15 //...Validation rules checked here16 return true;17 }

Page 425: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 48 of 51

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Context Object Pattern Exa

18 public void setRoomType(String rt) {19 roomType = rt;20 }21 public void setNumNights(int nn) {22 numNights = nn;23 }24 public String getRoomType() {25 return roomType;26 }27 public int getNumNights() {28 return numNights;29 }30 //...more get/set methods31 }

Page 426: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 49 of 51

attern:

sts can be filled

ific classes thatersions

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PConsequences

Advantages:

• Improves the reusability of component• Improves testability since context objec

with test data• Reduces dependencies on protocol spec

might change in different technology v

Page 427: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 50 of 51

attern:

be developed

ing copies of

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Context Object PConsequences

Disadvantage:

• Increases the amount of code that mustand maintained

• Slightly decreases performance by makdata and adding a layer of indirection

Page 428: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 10, slide 51 of 51

ntrollertext-specific

Object-Oriented Design Principles

Architectural Patterns

atterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• Intercepting Filter – Provides asimple mechanism for pre-processing and post-processingHTTP requests and responses

• Front Controller – Provides asingle entry point to thepresentation tier; may handlesecurity and validation

• Application Controller –Separates the action invocationand view dispatching from the front co

• Context Object – Passes data from conobjects to other scopes

Anti-P

Page 429: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

tterns

Java EE™ Patterns

Module 11

More Presentation Tier PaModule 11

Tier PatternsMore Presentation

Module 11

More PresentationTier Patterns

Page 430: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 2 of 42

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Apply the View Helper pattern• Apply the Composite View pattern• Apply the Dispatcher View pattern• Apply the Service to Worker pattern

Page 431: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 3 of 42

erns

tation tier logic inents, like JSP pages.

s from smaller view

iew Helper patterns.ss processes and thusr responsibility.

iew Helper patterns.esses.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

More Presentation Tier Patt

Pattern Primary Function

View Helper Provides an object to carry out presenorder to remove it from view compon

CompositeView

Provides a simple way to create viewcomponents.

DispatcherView

Combines the Front Controller and VThe view components request businemight have to assume some controlle

Service ToWorker

Combines the Front Controller and VThe controller requests business proc

Page 432: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 4 of 42

ttern:

ogic with view

tent developers

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the View Helper PaProblem Forces

Combining data preparation and formatting lgeneration logic leads to:

• Poor role separation between Web conand programmers

• Brittle view components• Copy-and-paste reuse

Page 433: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 5 of 42

: Solution

c moved to

components,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the View Helper Pattern

• The view focuses on presentation logic• Business logic and data formatting logi

helper classes• Helper classes can be either JavaBeans

custom tags or simple tag files

Page 434: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 6 of 42

ure

iewHelper

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

View Helper Pattern Struct

The View is responsible for dynamically formatting the presentation response. The View requests data from its Helpers.

<<JSP Page>>View

VClient requests

0..*

uses

Page 435: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 7 of 42

nce

: TransferObjectBean

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

View Helper Pattern Seque

: BusinessService: ViewHelper<<JSP Page>>: View

: Client

1.2: Get Property

1.1.1.1: Create()

1.1.1: Get Data

1.1: Get Data

1: Send Request

Page 436: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 8 of 42

Strategies

View

iewHelper

custom tag 2.0 tag filelper is a

mplemented assformer (XSLT)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the View Helper Pattern:

• JSP Page View vs. Servlet View – Thecomponent is usually a JSP page

• JavaBeans Component Helper – The Vcomponent is a JavaBeans component

• Custom Tag Helper – ViewHelper is a• Tag File Helper – ViewHelper is a JSP• Business Delegate as Helper – ViewHe

business delegate• Transformer Helper – ViewHelper is i

an eXtensible Stylesheet Language Tran

Page 437: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 9 of 42

ple

Tag

ag

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

View Helper Pattern Exam

<<JSP Page>>ReservationSearchResults

ReservationTO

...

...

CustomerTO

...

...

Loop

IfT

uses uses

uses

uses

-customer

Page 438: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 10 of 42

: Example

ollection" %>/core" %>

s">

</td>></td>/td>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the View Helper Pattern

1 <%@ attribute name="reservations" type="java.util.C2 <%@ taglib prefix="c" uri="http://java.sun.com/jstl3 <table>4 <c:forEach var="reservation"5 items="${reservations}" varStatus="statu6 <tr>7 <td><c:out value="${status.count}"/></td>8 <td><c:out value="${reservation.roomType}"/>9 <td><c:out value="${reservation.startDate}"/10 <td><c:out value="${reservation.endDate}"/><11 </tr>12 </c:forEach>13 </table>

1 <%@ taglib prefix="tag" tagdir="/WEB-INF/tags" %>2 <tag:buildResTable reservations="${reservations}"/>

Page 439: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 11 of 42

ttern:

in a cleanerata

om the viewmight have on

s more reusable

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the View Helper PaConsequences

Advantages:

• Using ViewHelper components resultsseparation between the view and the dprocessing logic

• Separating the data preparation logic frreduces dependencies that developers the same resources

• Data preparation and formatting logic i

Page 440: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 12 of 42

attern:

es causes

many JSP pages maintaininations

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite View PProblem Forces

Copying and pasting content on multiple pagseveral problems:

• A content change can require changing• A consistent look and feel is difficult to• Many views are needed to create comb

of content

Page 441: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 13 of 42

attern:

desiteView pagesre the layout

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite View PSolution

• Make a CompositeView page that incluViewFragment pages and other Compos

• Use the CompositeView page to structuof a page

Page 442: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 14 of 42

cture

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite View Pattern Stru

<<JSP Page>>CompositeView

<<JSP Page>>View

<<JSP Page>>ViewFragment

0..*

includes

Page 443: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 15 of 42

uence

<<JSP Page>>oter : ViewFragment

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite View Pattern Seq

<<JSP Page>>header : ViewFragment fo

<<JSP Page>>: CompositeView

: ViewManager

2: include

4: include

1: include

3: include

Page 444: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 16 of 42

attern:

es of theude>)s of the

ent – Viewsntss are included

used tosed with Struts.

s are managed

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite View PStrategies

• Early-Binding Resource – Include piectemplate at translation time (<%@ incl

• Late-Binding Resource – Include piecetemplate at runtime (<jsp:include>)

• JavaBeans Component View Managemare included using JavaBeans compone

• Custom Tag View Management – Viewusing custom tags. Apache Tiles can beimplement this pattern. Tiles is often u

• Transformer View Management – Viewusing an XSL Transformer

Page 445: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 17 of 42

mple

P Page>>nSearchResults

>Header

1<<JSP Page>>Advertisement2

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite View Pattern Exa

<<JSReservatio

<<JSP Page>>ReservationConfirmation

<<JSP Page>ReservationList

<<JSP Page>>ReservationData

<<JSP Page>>Advertisement

<<JSP Page>>NavigationBar

<<JSP Page>>Header

Page 446: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 18 of 42

mple

%>

Bar.jsp"/>

nData.jsp"/>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Composite View Pattern Exa

1 <TABLE BORDER='0'>2 <TR>3 <TD>4 <%@ include file="../incl/Header.jsp"5 </TD>6 </TR>7 <TR>8 <TD>9 <jsp:include page="../incl/Navigation10 </TD>11 <TD>12 <jsp:include page="../incl/Reservatio13 </TD>14 </TR>15 </TABLE>

Page 447: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 19 of 42

attern:

viewsgments or

ferent

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite View PConsequences

Advantages:

• Fragments can be reused in numerous • Manageability is improved because fra

templates can be changed in one place• Templates can dynamically include dif

fragments based on the request or user

Page 448: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 20 of 42

attern:

tes and

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Composite View PConsequences

Disadvantages:

• Invalid content can be created if templafragments are not properly configured

• Runtime inclusion of fragments candecrease performance

Page 449: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 21 of 42

Pattern

to combine theplication

rnative to thisate for more

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View

• The Dispatcher View pattern is one wayView Helper, Front Controller, and ApController patterns

• This pattern reduces the role of thecontroller components

• The Service to Worker pattern is an altepattern, and it might be more appropricomplex Web applications

Page 450: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 22 of 42

attern:

ller activities

have large

troller, and theed to decideents should

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View PProblem Forces

• Without controller components, controcan be dispersed throughout the system

• Without view helpers, JSP pages mightquantities of scriptlet code

• If the Front Controller, Application ConView Helper patterns are used, you newhether the controller or view componrequest the business services

Page 451: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 23 of 42

attern:

apt the

in the request

gateents or custom display model

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View PSolution

The controller component:

• Invokes common Service components• Does not invoke business services or ad

display model• Dispatches using information included

state, as opposed to return values fromBusinessService objects

The View component uses the BusinessDelecomponents, which can be JavaBeans compontags to invoke business services and adapt the

Page 452: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 24 of 42

cture

BusinessServicekes

adapts

creates

<<transfer object>>PresentationModel

lper

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Stru

<<servlet>>FrontController

<<JSP page>>View

Service

Client

invokes

invo

forward

1..*

1..*

BusinessDelegate

View He

ApplicationController

Page 453: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 25 of 42

uencegate :TransferObject: View Helper

rocess

1.2.1.5 Adapt

t

nt

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Seq: ApplicationController : BusinessDelesecurity : Service<<servlet>>

: FrontController<<JSP page>>

: View: Client

1.2: Dispatch

1.2.1.1: Request Business P

1.1: Authenticate

1: Request

1.2.1.4: Get Data

return transferObject

1.2.1.2: Select View Conten

1.2.1.3: Display View Conte

1.2.1: Forward

Page 454: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 26 of 42

mple

ce>>d

HttpServletResponse ) : String

rvation SearchReservations

ReservationBusinessDelegate

+findReservation( ... )+makeReservation( ... )...

O

()

recieves/stores

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Exa

View Model

ApplicationController

<<servlet>>FrontController

+doPost()

AuthenticationBean <<interfaComman

+execute( : HttpServletRequest, :

MakeRese

<<JSP page>>ErrorPage

<<JSP page>>ReservationConfirmation

<<JSP page>>ReservationSearchResults

ReservationT

-endDate-startDate...

+getEndDate()+getStartDate...

Client

forwardforward

forward

queries

recieves/stores

Controller

queries

request

Mapper

Map searches

Page 455: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 27 of 42

mple

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Exa

The front controller code:

1 public class ApplicationController {2 //. . .3 public void process(HttpServletRequest request,4 HttpServletResponse response)5 throws IOException, ServletException {6 String action = request.getParameter("action");7 String viewName=mapper.getView(action);8 RequestDispatcher view;9 view = request.getRequestDispatcher(viewName);10 view.forward(request, response);11 }

Page 456: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 28 of 42

mple

{ate");

. . .);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Exa

The command code:

1 public class MakeReservation implements Command {2 public String execute(HttpServletRequest request,3 HttpServletResponse response) 4 String startDate = request.getParameter("startd5 //. . .get other request parameters6 //. . .validate request parameters7 try {8 ReservationBusinessDelegate rbd =9 new ReservationBusinessDelegate();10 ReservationTO resData = rbd.makeReservation(11 if (resData == null) {12 return "failure";13 } else {14 request.setAttribute("resData", resData);15 return "success";16 } . . .

Page 457: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 29 of 42

mple

a.lang.String'/>

'/>,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Dispatcher View Pattern Exa

The pattern view page:

1 <myTag:executeLogic>2 <jsp:useBean id='result' scope='request' class='jav3 <%if (result.equals("failure") {%>4 <jsp:forward page="errorPage.jsp">5 <%}%>67 <jsp:useBean id='resData'8 scope='request' class='ReservationTO'/>9 Your reservation for10 <jsp:getProperty name='resData' property='startDate11 has been confirmed.

Page 458: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 30 of 42

attern:

ont Controller,er patterns

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View PConsequences

Advantage:

Offers most of the advantages of the FrApplication Controller, and View Help

Page 459: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 31 of 42

attern:

amount ofssingtical code to

producew components results

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Dispatcher View PConsequences

Disadvantages:

• The View components can have a largescriptlet code to request business proce

• Many View components can have idenrequest the same business processing

• The View components will likely eitherdifferent views or dispatch to other Vieto react to different business processing

Page 460: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 32 of 42

Pattern

er way tooller, and

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service to Worker

• The Service to Worker pattern is anothcombine the View Helper, Front ContrApplication Controller patterns

• This pattern increases the role of thecontroller components

Page 461: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 33 of 42

Pattern:

ller activitiesmave large

troller, and theed to decideents should

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service to WorkerProblem Forces

• Without controller components, contromay be dispersed throughout the syste

• Without view helpers, JSP pages may hquantities of scriptlet code

• If the Front Controller, Application ConView Helper patterns are used, you newhether the controller or view componrequest the business services

Page 462: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 34 of 42

Pattern:

ppropriate for

nt, based on theness processing

uerying theoller’s businessntent.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service to WorkerSolution

The controller components:

• Invoke common Service components• Invoke the business processing that is a

this request• Dispatch to a particular View compone

request state and the results of the busi

The View component is only responsible for qHelperobjects for data produced by the contrprocessing request and creating the display co

Page 463: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 35 of 42

ucture

BusinessServiceokes

adapts

creates

<<transfer object>>PresentationModel

lper

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern Str

<<servlet>>FrontController

Service

Client <<JSP page>>View

invokes

inv

forward

1..*

1..*

BusinessDelegate

View He

ApplicationController

Page 464: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 36 of 42

uenceate :TransferObject: View Helper

1.2.1.5 Adapt

t

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern Seq: ApplicationController : BusinessDeleg

1.2: Dispatch

1.2.1: Request Business Process

1.1: Authenticate

1: Request

1.2.1.3: Display View Conten

1.2.2: Forward

1.2.1.2: Select View Content

: Client <<servlet>>: FrontController

security : Service <<JSP page>>: View

1.2.1.4: Get Data

Page 465: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 37 of 42

ample

ce>>d

HttpServletResponse ) : String

rvation SearchReservations

ReservationBusinessDelegate

+findReservation( ... )+makeReservation( ... )...

O

()

receives/stores

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern Ex

View Model

<<servlet>>FrontController

+doPost()

AuthenticationBean <<interfaComman

+execute( : HttpServletRequest, :

MakeRese

<<JSP page>>ErrorPage

<<JSP page>>ReservationConfirmation

<<JSP page>>ReservationSearchResults

ReservationT

-endDate-startDate...

+getEndDate()+getStartDate...

Client

forwardforwardforward

queries

receives/stores

Controller

queries1

request

ApplicationController

Mapper

Map searches

Page 466: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 38 of 42

ample

);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern Ex

The controller code:

1 public class ApplicationController {2 //. . .3 public void process(HttpServletRequest request,4 HttpServletResponse response)5 throws IOException, ServletException {6 String action = request.getParameter("action");7 Command cmd = mapper.getCommand(action);8 String result = cmd.execute(request, response);9 String viewName = mapper.getView(action, result10 RequestDispatcher view;11 view = request.getRequestDispatcher(viewName);12 view.forward(request, response);13 }

Page 467: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 39 of 42

ample

'/>,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern Ex

The view page:

1 <jsp:useBean id='resData'2 scope='request' class='ReservationTO'/>3 Your reservation for4 <jsp:getProperty name='resData' property='startDate5 has been confirmed.

Page 468: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 40 of 42

Pattern:

ontroller,er patternsern, Viewe, have lessd maintain

, thee

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Applying the Service to WorkerConsequences

Advantages:

• Offers all the advantages of the Front CApplication Controller, and View Help

• Compared to the Dispatcher View pattcomponents are likely be more cohesivscriptlet code, and be easier to adapt an

Disadvantage:

Depending on how it is implementedFrontController component can havpoor cohesion

Page 469: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 41 of 42

Struts

Actionpache.struts.action}

te( . . . )

tion SearchReservations

ReservationBusinessDelegate

+findReservation( ... )+makeReservation( ... )...

recieves

. . ) +execute( . . . )

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Service to Worker Pattern In

{org.a

+execu

<<servlet>>ActionServlet

{org.apache.struts.action}

View Model

MakeReserva

<<JSP page>>ErrorPage

<<JSP page>>ReservationConfirmation

<<JSP page>>ReservationSearchResults

ReservationTO

-endDate-startDate...

+getEndDate()+getStartDate()...

Client

forwardforwardforward

queries

recieves

Controller

queries

creates

+execute( .

Page 470: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 42 of 42

rry out view

ay to create

he Fronthe viewand thus mightsibility. the Fronthe controller

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• View Helper – Provides an object to capresentation tier logic to remove it fromcomponents, like JSP pages.

• Composite View – Provides a simple wviews from smaller view components.

• Dispatcher View Pattern – Combines tController and View Helper patterns. Tcomponents request business processeshave to assume some controller respon

• Service to Worker Pattern – CombinesController and View Helper patterns. Trequests business processes.

Page 471: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

sM

AE

Java EE™ Patterns

Module 11

Exploring AntiPatternodule 12

ntiPatternsxploring

Module 12

ExploringAntiPatterns

Page 472: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 2 of 38

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Define AntiPatterns• Describe Integration Tier AntiPatterns• Describe Business Tier AntiPatterns• Describe Presentation Tier AntiPattern

Page 473: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 3 of 38

s

ell-known codetive impact on

them and learn

d into three sets

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Introducing AntiPattern

• AntiPatterns identify and document wdevelopment practices that have a negaa software system

• Studying AntiPatterns helps you avoidrefactored solutions

• In this module, AntiPatterns are groupeof patterns:• Integration Tier AntiPatterns• Business Tier AntiPatterns• Presentation Tier AntiPatterns

Page 474: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 4 of 38

Patterns

of the Java EE

n tier Java EE good designs

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing Integration Tier Anti

• These AntiPatterns involve poor usageplatform integration tier technologies

• Work hand in hand with the integratiopatterns to avoid poor designs and findfor the integration tier

Page 475: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 5 of 38

attern

nections every

t be hardcoded

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Not Pooling Connections AntiP

AntiPattern problem:

Creating and destroying database contime a query is run is expensive

Symptoms and consequences:

• Performance is poor• Scalability is poor• Database driver and location data migh

in many parts of the system

Page 476: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 6 of 38

attern

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Not Pooling Connections AntiP

Refactored solution:

• Use a connection pool• Use the DataSource interface

Page 477: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 7 of 38

ttern

ge method of a

by sending a

g business logicnfficult

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Monolithic Consumer AntiPa

AntiPattern problem:

• Business logic is placed in the onMessamessage driven bean

• This business logic can only be invokedJMS message to a messaging server

Symptoms and consequences:

• Clients don’t have the option of invokinusing a synchronous method invocatio

• Testing of the business logic is more di

Page 478: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 8 of 38

ttern

essage or

uest a services objectn be used to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Monolithic Consumer AntiPa

Refactored solution:

• The message driven bean:• Reads and prepares the data in the m• Invokes a method on a regular class

a session bean• Clients that want to synchronously req

can call the logic directly in the busines• Service Activator pattern’s structure ca

achieve the refactored solution

Page 479: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 9 of 38

n

ugh messaging

ht have to

ave to marshall

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Fat Message AntiPatter

AntiPattern problem:

• Asynchronous messages delivered throservers can become too fat

• Fat messages cause:• Network overhead increases• Strain on messaging server that mig

persist the messages• Strain on senders and receivers that h

and unmarshall the data

Page 480: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 10 of 38

n

ses

eters for anr remote

an ID or a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Fat Message AntiPatter

Symptoms and consequences:

• Network overhead increased• Strain on the messaging server increase• Strain on senders and receivers increas

Refactored solution:

• Carefully consider the necessary paramasynchronous service, just as you do fomethod invocations

• Consider the possibility of only passingreference to the data

Page 481: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 11 of 38

g server has tonowledgement: tied to the

ot tied to the

n ongoingntinuously

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Hot Potato AntiPattern

AntiPattern problem:

• With guaranteed delivery, the messaginre-deliver messages until it receives ack• With CMT, the acknowledgement is

transaction outcome• With BMT, the acknowledgment is n

transaction outcome• If the message is not processed due to a

condition, the messaging server will coresend the message

Page 482: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 12 of 38

eiversessages

are burdenedng messages

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Hot Potato AntiPattern

Symptoms and consequences:

• Message driven beans or other JMS reccontinually receive the same invalid mfor processing

• The messaging server and the receiversfrom repeatedly delivering and receivithat can not be processed

Page 483: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 13 of 38

nother bean, the problem email orsagesan rollback theessagessage Queues

n

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Hot Potato AntiPattern

Refactored solution:

• Message that cannot be processed by ashould probably be acknowledged, andshould be announced, perhaps throughthrough another queue of problem mes

• It can be necessary to use BMT so you ctransaction and still acknowledge the m

• Some messaging servers have Dead Mewhere the message is sent after a certainumber of attempts

Page 484: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 14 of 38

atterns

or usage of thegies with thepoor designs tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing Business Tier AntiP

• This group of AntiPatterns involves poJava EE platform business tier technolo

• These AntiPatterns work hand in handbusiness tier Java EE patterns to avoid and find good designs for the business

Page 485: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 15 of 38

attern

s are verye problems:

increasedeased

aintenancen the costs are

en you areare not using

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Sledgehammer for a Fly AntiP

AntiPattern problem:

Like a sledgehammer, EJB componentpowerful tools—too powerful for som• EJB component services can lead to

overhead, increased complexity, incrdevelopment time, and increased m

• If you need many of the services, thegreatly outweighed by the savings

• If you do not need these services, thpaying a price for services that you

Page 486: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 16 of 38

attern

decreased

interfaces than

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Sledgehammer for a Fly AntiP

Symptoms and consequences:

• Increased development complexity anddeveloper efficiency

• More lines of code and more classes andare required for the job

• Slower performance

Page 487: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 17 of 38

attern

going to benefit

ponent

ent descriptorsde ten files and

technologyted transaction,security offer

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Sledgehammer for a Fly AntiP

Refactored solution:

• Consider whether EJB components areyour situation

• Bitter EJB has a simple logging EJB comexample:• The interfaces, classes, and deploym

for the session and entity bean inclu300 lines of code

• For logging functionality, all the EJBservices such as, scalability, distribustate management, persistence, and little value

Page 488: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 18 of 38

ltaneously

clare that theycts

effects,ed

grainede should be

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Local and Remote Interfaces SimuAntiPattern

AntiPattern problem:

• The local interface methods must demight throw RemoteException obje

• The code can have unintended side depending on whether it was invoklocally or remotely

• Remote interfaces should be coarse • The choice between local and remot

carefully made and enforced

Page 489: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 19 of 38

ltaneously

nsideration of

s not properlyation

ent

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Local and Remote Interfaces SimuAntiPattern

Symptoms and consequences:

• Poor performance due to inadequate colocal versus remote invocation issues

• Unexpected side affects because code idesigned for local versus remote invoc

Refactored solution:

• Carefully choose remote boundaries• Use local or remote interfaces to implem

your decisions

Page 490: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 20 of 38

iPattern

ly access

cations to the

ponsible fornating theroper

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Accesses Entities Directly Ant

AntiPattern problem:

If presentation tier components directentity beans:• You can have too many remote invo

entity beans• Presentation tier components are res

finding or creating the beans, coordimethod invocations, and ensuring ptransactional control

Page 491: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 21 of 38

iPattern

emote

dled correctly much more

sentation tiercomponents

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Accesses Entities Directly Ant

Symptoms and consequences:

• Performance suffers due to too many rmethod invocations

• Transactions barriers might not be han• Presentation tier developers must have

intimate knowledge of the business tierimplementation

Refactored solution:

Uses session beans to separate the precomponents from the business entity

Page 492: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 22 of 38

r’s based on EJBitations

loading, and

specific SQLaind

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Mirage AntiPattern

AntiPattern problem:

• Many developers use BMP due to serve1.x architecture (EJB server’s) CMP lim

• CMP offers many benefits over BMP:• CMP can provide data caching, lazy

other server optimizations• CMP code does not contain vendor • CMP is easier to develop and maint• CMP 2.0 provides container manage

relationships (CMR)

Page 493: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 23 of 38

to:

ce

optionrs CMP

rmance tests

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Mirage AntiPattern

Symptoms and consequences:

Using BMP unnecessarily might lead• Needlessly high development and

maintenance effort• Less efficient entity bean performan

Refactored solution:

• Consider using CMP instead of BMP• There are times when BMP is the only • Check into the reputation of your serve

implementation, or do your own perfo

Page 494: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 24 of 38

rn

d if you neverand reuset makes the

could becausethat have

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Cacheless Cow AntiPatte

AntiPattern problem:

Considerable server capacity is wastecache the results of previous requeststhem when the same or different cliensame request

Symptoms and consequences:

The system does not scale as well as itit wastes time recalculating responsesalready been acquired

Page 495: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 25 of 38

rn

onentsnts

or

ns like caching caching in the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Cacheless Cow AntiPatte

Refactored solution:

• Places where cache might be added:• In front of the Web server• In front of the presentation tier comp• In front of the business tier compone• In the integration tier

• Might use vendor provided hardware software caching

• Might use home grown caching solutiocommands in the Command pattern orValue List Handler pattern

Page 496: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 26 of 38

rn

en developing

nt and that

and for

ht become

nt reads whilemodified

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Cacheless Cow AntiPatte

Refactored solution:

There are many issues to consider wha cache:• Ensure the cached results are sufficie

there is no need to rerun the process• Decide what data should be cached

how long• Consider when the cached data mig

out of date• Consider how to allow fast concurre

protecting the data when it is being

Page 497: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 27 of 38

attern

te, Clark, Lee,

tions require do not to an

ase scalability are likely to

session state

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Conversational Baggage AntiP

AntiPattern problem:

This pattern is documented in Bitter EJB by Taand Linskey:

• While many tasks in enterprise applicakeeping session state, many other tasks

• Session state adds substantial overheadapplication and can significantly decre

• If you are not focused on this issue, youcreate stateful tasks that do not require

Page 498: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 28 of 38

attern

ever you

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Conversational Baggage AntiP

Symptoms and consequences:

Performance and scalability degrades

Refactored solution:

Attempt to make tasks stateless whenreasonably can

Page 499: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 29 of 38

State

ate:

lasss

statete the choice

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Golden Hammers of SessionAntiPattern

AntiPattern problem:

• Four common places to store session st• Client tier, perhaps in cookies• Presentation tier in a HttpSession c• Business tier in stateful session bean• Resource tier in a database

• There is no golden hammer for sessionmanagement; the situation should dicta

Page 500: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 30 of 38

State

ement tool canlity

ice, consider:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Golden Hammers of SessionAntiPattern

Symptoms and consequences:

Using an inappropriate session managlead to poor performance and scalabi

Refactored solution:

When making a session state tool cho• The location of the data to be used• The size and type of the data• The implications of losing the data• Types of clients

Page 501: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 31 of 38

tiPatterns

r usage of thenologiesentation Tier and find goo

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing Presentation Tier An

• This group of AntiPatterns involve pooJava EE platform presentation tier tech

• These AntiPatterns work with the PresJava EE patterns to avoid poor designsdesigns for the presentation tier

Page 502: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 32 of 38

in Every

ks are methods

.3 and

and removed

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Including Common FunctionalityServlet AntiPattern

AntiPattern problem:

• Pre-processing and post-processing tasimplemented or invoked in the serviceof each servlet

• An AntiPattern only with Java Servlet 2later containers

Symptoms and consequences:

• Tasks must be programmatically addedfrom multiple servlets

• The servlets have poor cohesion

Page 503: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 33 of 38

in Every

ks are

s as well

factored

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Including Common FunctionalityServlet AntiPattern

Refactored solution:

• Pre-processing and post-processing tasplaced in filters

• These filters can be applied to JSP pageas servlets

• The Intercepting Filter pattern is the resolution for this AntiPattern

Page 504: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 34 of 38

mation

erlinks orincluded in the

ile names or

ify

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Embedded Navigational InforAntiPattern

AntiPattern problem:

• JSP pages usually include URLs for hypbuttons and for fragment files that are JSP page

• The JSP pages must be modified if the fURLs change

Symptoms and consequences:

• Users receive page not found errors• The application flow is difficult to mod

Page 505: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 35 of 38

mation

al resourceuently change.

gments insteadude> directive.ic attributeiguration file tog maps to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Embedded Navigational InforAntiPattern

Refactored solution:

• With Front Controller pattern and logicmapping, the URLs are unlikely to freq

• You can use custom tags to include fraof the jsp:include action or <%@inclAn include custom tag can take a genervalue such as bannerand look in a confsee what specific resource that the strin

Page 506: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 36 of 38

rn

ht be moved

s, it will not be

ntrollerttributesated to create,a

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Ad Lib TagLibs AntiPatte

AntiPattern problem:

Model or controller functionality migfrom JSP pages into custom tags

Symptoms and consequences:

• If business logic is placed in custom tageasily used by rich clients

• Custom tags that are doing model or cofunctionality are likely to need many a

• Custom tags are slightly more complicdebug, and maintain than ordinary Javtechnology classes

Page 507: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 37 of 38

rn

k yourselfvoked by the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Ad Lib TagLibs AntiPatte

Refactored solution:

When you are writing custom tags, aswhether this logic should really be inJSP page

Page 508: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 11, slide 38 of 38

Object-Oriented Design Principles

Architectural Patterns

atterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• AntiPatterns help us focus on thecommon mistakes made indevelopment and providerefactored solutions to avoid orremedy these problems

• Studying patterns andAntiPatterns provide a naturalbenefit of seeing developmentissues from both a positive and anegative perspective

Anti-P

Page 509: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

s DesignM

ABG

Java EE™ Patterns

Module 13

Applying Java EE BluePrintGuidelines

odule 13

pplying Java EEluePrints Designuidelines

Module 13

Applying Java EEBluePrints DesignGuidelines

Page 510: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 2 of 55

guidelinesaree Java Pet Store

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the Java EE BluePrints design• Describe the Java Pet Store demo softw• Describe the Java EE patterns used in th

demo software

Page 511: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 3 of 55

ts Design

pers with theciples needed, and

les to show youcture and

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing the Java EE BluePrinGuidelines

• Provides enterprise application develoconcepts, technologies, and design printo quickly make secure, robust, scalableextensible applications

• Includes guidance and practical examphow to make the best use of the architefeatures of the Java EE platform

Page 512: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 4 of 55

es

ines areelines.

developed

ith as few other

er two modules declarations

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Object-Oriented Guidelin

Many of the Java EE BluePrints design guidelspecializations of general object-oriented guidModules should:

• Be separately compilable so they can beindependently

• Have few interfaces to communicate wmodules as possible

• Use loose coupling to other modules• Have explicit interfaces so that whenev

communicate, it is obvious from public

Page 513: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 5 of 55

s a:

nt

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Client Tier Guidelines

The Java EE Client tier can be implemented a

• Browser client• Java technology-based Application clie• Java technology-based MIDlet client• Non-Java technology-based client

Page 514: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 6 of 55

mmends using

eparation oficzed control andn, data

framework

hly tested, and

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Web Tier Guidelines

The Java EE BluePrints design guidelines recoan existing Web framework, because:

• Most Web frameworks encourage the spresentation, control, and business log

• Most Web frameworks provide centralicustomization of templating, localizatiovalidation, access control, and logging

• Time can be saved by not building the structure from scratch

• A framework should be stable, thoroughave a community support structure

Page 515: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 7 of 55

s

rsistent

ata

mannerinside

conversationalrg services

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Tier Guideline

• Entity beans may be appropriate for pedata when:• Multiple clients need to access the d• The data is not tied to a user session• Data must be available in a portable• The data must be handled properly

of transactions• Use stateful session beans to keep most

state, instead of in the client or Web tie• Use stateless session beans for providin

without maintenance of client state

Page 516: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 8 of 55

s

nous services or other systemshe type of client tierbeans objectsainer managedappropriate

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Business Tier Guideline

• Use message driven beans for asynchroto loosely couple EJB components with

• Keep EJB technology code agnostic of t• Keep the business logic in the business• Use session beans as a façade to entity • Avoid using fine grained remote entity• Use Data Access Objects (DAO), if cont

persistence (CMP) entity beans are not

Page 517: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 9 of 55

s

Information

nctions, and

mponent typesements of the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Integration Tier Guideline

• Uses access objects to access EnterpriseSystems (EIS) functions and data

• Use command beans that invoke EIS fudata access objects to access EIS data

• Access objects guidelines:• Do not make assumptions about the

deployment environment• Ensure they are usable by different co• Use transaction and security manag• Follow the programming restriction

components that might use them• Use connection pooling

Page 518: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 10 of 55

o Software

ood design andng behind the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Describing the Java Pet Store Dem

The Java Pet Store demo software illustrates gconstruction while demonstrating the reasonidesign choices

Page 519: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 11 of 55

e Java Petlication

mer Web siteWAF)re framework,t also quite

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Analyzing Java EE Patterns in thStore Demo Software Web App

Framework

• The Java Pet Store demo software custouses the Web Application Framework (

• This framework is a Model 2 Architectuwhich is somewhat similar to Struts, budifferent in many regards

Page 520: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 12 of 55

e Web

ger

n( . . . )

>t

. )

vlet>>eServlet

... )( ... )s( ... )

page>>ntPages

page>>atePage

rtTag

forward

forward

uses

include

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java Pet Store Demo SoftwarApplication Framework

<<interface>>HTMLAction

+perform( : HttpServletRequest ) : Event...

WebController

+handleEvent( : Event, : HttpSession )...

RequestProcessor

+processRequest( : HttpServletRequest )...

<<interface>>EJBAction

+perform( : Event ) : EventResponse...

<<interface>>Event

+getEJBActionClassName() : String+getEventName()+setEJBActionClassName( : String )

ScreenFlowMana

+forwardToNextScree+init()

StateMachine

+processEvent( : Event )...

<<session bean>>EJBControllerLocalEJB

+processEvent( : Event )...

<<Servlet>MainServle

+doGet( ... )+doPost( ... )+doProcess( .....

<<Filter>>SignOnFilter

+doFilter( ... )...

<<Filter>>EncodingFilter

+doFilter( ... )...

<<SerTemplat

+doGet(+doPost+proces

<<JSPFragme

<<JSP page>>SignOnPage

<<JSPTempl

<<Browser>>Client

Inse

request invoke

invoke

forward

create invoke

create invoke

create

Page 521: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 13 of 55

plication

ation Patterns:

rvlet classingFilterand

se custom tagscriptlet usagecomponents

nclude

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Java EE Patterns in the Web ApFramework

The Java Pet Store demo software Web Applicframework implements the following Java EE

• Front Controller pattern – The MainSe• Intercepting Filter pattern – TheEncod

SignOnFilter classes• View Helper pattern – The JSP pages u

and JavaBeans components to reduce s• Service to Worker pattern – The view

invoke the RequestProcesses class• Composite View Pattern – The views i

fragment views

Page 522: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 14 of 55

ing in the

OnFilter

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClass Mappweb.xmlFile

1 <filter>2 <filter-name>SignOnFilter</filter-name>3 ...4 <filter-class>5 com.sun.j2ee.blueprints.signon.web.Sign6 </filter-class>7 </filter>8 <filter-mapping>9 <filter-name>SignOnFilter</filter-name>10 <url-pattern>/*</url-pattern>11 </filter-mapping>

Page 523: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 15 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClas

1 package com.sun.j2ee.blueprints.signon.web;23 import javax.servlet.*;4 ...5 public class SignOnFilter implements Filter {67 private HashMap protectedResources;8 private FilterConfig config = null;9 ...10 public void init(FilterConfig config)11 throws ServletException {12 this.config = config;13 URL protectedResourcesURL=14 config.getServletContext().getResource15 ("/WEB-INF/signon-config.xml");16 SignOnDAO dao =17 new SignOnDAO(protectedResourcesURL);18 ...19 protectedResources =

Page 524: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 16 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClas

20 dao.getProtectedResources();21 }2223 public void doFilter( ServletRequest request,24 ServletResponse response, FilterChain chain)25 throws IOException, ServletException {26 HttpServletRequest hreq =27 (HttpServletRequest) request;28 String targetURL = hreq.getRequestURI();

Page 525: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 17 of 55

s

L

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClas

29 ...30 // check if the user is signed on31 boolean signedOn = false;32 if (hreq.getSession().getAttribute33 (SIGNED_ON_USER)!= null {34 signedOn = ((Boolean) hreq.getSession().35 getAttribute(SIGNED_ON_USER)).booleanValue();36 } else {37 hreq.getSession().setAttribute38 (SIGNED_ON_USER, new Boolean(false));39 }4041 // jump to the resource if signed on42 if (signedOn) {43 chain.doFilter(request, response);44 return;45 }4647 // find out if the patterns match the target UR

Page 526: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 18 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClas

48 Iterator it =49 protectedResources.keySet().iterator();50 while (it.hasNext()) {51 String protectedName = (String) it.next();52 ProtectedResource resource =53 (ProtectedResource)54 protectedResources.get(protectedName);55 String urlPattern = resource.getURLPattern();56

Page 527: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 19 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The SignOnFilterClas

57 // now check against the targetURL58 if (urlPattern.equals(targetURL)) {59 // put the orginal url in the session60 hreq.getSession().setAttribute61 (ORIGINAL_URL, targetURL);62 config.getServletContext()63 .getRequestDispatcher("/" + signOnPage)64 .forward(request, response);65 return;66 }67 }68 // No matches if we made it to here69 chain.doFilter(request, response);70 }71 ...72 }

Page 528: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 20 of 55

g in the

Pet Store

web.MainServlet

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Front Controller Servlet Mappinweb.xmlFile

1 <servlet>2 <servlet-name>MainServlet</servlet-name>3 <description>The Front Controller for the4 </description>5 <servlet-class>6 com.sun.j2ee.blueprints.waf.controller.7 </servlet-class>8 ...9 </servlet>10 ...11 <servlet-mapping>12 <servlet-name>MainServlet</servlet-name>13 <url-pattern>*.do</url-pattern>14 </servlet-mapping>

Page 529: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 21 of 55

pping

omplete.screen">

tion

wHandler="true" >

Handler"/>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The mapping.xmlClass Ma

1 <url-mapping url="order.do" screen="order_c2 <web-action-class>3 com.sun.j2ee.blueprints.....OrderHTMLAc4 </web-action-class>5 </url-mapping>67 <url-mapping url="createcustomer.do" useFlo8 <web-action-class>9 com.sun.j2ee.....CustomerHTMLAction10 </web-action-class>11 <flow-handler12 class="com.sun.j2ee......CreateUserFlow13 </url-mapping>

Page 530: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 22 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The MainServletClas

1 package com.sun.j2ee.blueprints.waf.controller.web;2 ...3 public class MainServlet extends HttpServlet {4 ...5 private HashMap urlMappings;6 private HashMap eventMappings;78 public void init(ServletConfig config)9 throws ServletException {10 ...11 urlMappings =12 URLMappingsXmlDAO.loadRequestMappings13 (requestMappingsURL);14 context.setAttribute15 (WebKeys.URL_MAPPINGS, urlMappings);16 eventMappings = URLMappingsXmlDAO.17 loadEventMappings(requestMappingsURL);18 context.setAttribute19 (WebKeys.EVENT_MAPPINGS, eventMappings);

Page 531: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 23 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The MainServletClas

20 ...21 }22 public void doGet(...) ... {23 doProcess(request, response);24 }25 public void doPost(...) ... {26 doProcess(request, response);27 }

Page 532: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 24 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The MainServletClas

2829 private void doProcess30 (HttpServletRequest request,31 HttpServletResponse response)32 throws IOException, ServletException {33 ...34 getRequestProcessor().35 processRequest(request);36 getScreenFlowManager().37 forwardToNextScreen(request,response);38 ...39 }40 ...41 }

Page 533: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 25 of 55

lassd

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The RequestProcessorCprocessRequestMetho

1 String actionClassString = //appropriate2 //<web-action-class> for the request3 //URL that came in4 HTMLAction action = (HTMLAction)5 getClass().getClassLoader().

loadClass(actionClassString).newInstance();6 ...7 action.doStart(request);8 Event ev = action.perform(request);9 EventResponse eventResponse = null;10 if (ev != null) {11 // set the ejb action class name on the event12 EventMapping eventMapping= getEventMapping(ev);13 if (eventMapping != null) {14 ev.setEJBActionClassName15 (eventMapping.getEJBActionClassName());16 }17 ComponentManager sl = (ComponentManager)

Page 534: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 26 of 55

lassd

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The RequestProcessorCprocessRequestMetho

18 request.getSession().19 getAttribute(WebKeys.COMPONENT_MANAGER);20 WebController wcc = sl.getWebController21 (request.getSession());22 eventResponse =23 wcc.handleEvent(ev, request.getSession());24 }25 action.doEnd(request, eventResponse);

Page 535: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 27 of 55

Class

.web;

ebController {

t

onentManager)MANAGER);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The DefaultWebController

1 package com.sun.j2ee.blueprints.waf.controller2 ...3 public class DefaultWebController implements W4 ...56 public synchronized EventResponse handleEven7 (Event ev, HttpSession session)8 throws EventException {9 DefaultComponentManager cm = (DefaultComp10 session.getAttribute(WebKeys.COMPONENT_11 EJBControllerLocal controllerEJB12 =cm.getEJBController(session);13 return controllerEJB.processEvent(ev);14 }15 ...16 }

Page 536: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 28 of 55

BClass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The EJBControllerLocalEJ

1 package com.sun.j2ee.blueprints.waf.controller.ejb;2 ...3 public class EJBControllerLocalEJB4 implements SessionBean {56 protected StateMachine sm;7 protected SessionContext sc;89 public void ejbCreate() {10 sm = new StateMachine(this, sc);11 }1213 public EventResponse processEvent(Event ev)14 throws EventException {15 return (sm.processEvent(ev));16 }17 public void setSessionContext18 (SessionContext sc) {19 this.sc = sc;

Page 537: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 29 of 55

BClass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The EJBControllerLocalEJ

20 }21 public void ejbRemove() {22 sm = null;23 }24 public void ejbActivate() {}25 public void ejbPassivate() {}26 }

Page 538: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 30 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The StateMachineClas

1 package com.sun.j2ee.blueprints.waf.controller.ejb;2 ...3 public class StateMachine4 implements java.io.Serializable {5 ...6 public EventResponse processEvent(Event ev)

throws EventException {7 String actionName =8 ev.getEJBActionClassName();9 EventResponse response = null;10 ...11 action = (EJBAction)12 Class.forName(actionName).newInstance();13 ...14 action.init(this);15 action.doStart();16 response = action.perform(ev);17 action.doEnd();18 ...

Page 539: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 31 of 55

s

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The StateMachineClas

19 return response;20 }21 }

Page 540: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 32 of 55

lass

flow;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ScreenFlowManagerC

1 package com.sun.j2ee.blueprints.waf.controller.web.2 ...3 public class ScreenFlowManager4 implements java.io.Serializable {5 ...6 public void forwardToNextScreen7 (HttpServletRequest request,8 HttpServletResponse response)9 throws java.io.IOException,10 FlowHandlerException,11 javax.servlet.ServletException {12 String selectedURL = request.getRequestURI();13 ...14 URLMapping urlMapping =15 getURLMapping(selectedURL);16 if (!urlMapping.useFlowHandler()) {17 currentScreen = urlMapping.getScreen();18 } else {19 FlowHandler handler = null;

Page 541: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 33 of 55

lass

r();

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ScreenFlowManagerC

20 String flowHandlerString = urlMapping.getFlowHandle21 handler = (FlowHandler) getClass().22 getClassLoader().23 loadClass(flowHandlerString).24 newInstance();25 handler.doStart(request);String flowResult =26 handler.processFlow(request);27 handler.doEnd(request);28 currentScreen =29 urlMapping.getResultScreen(flowResult);30 if (currentScreen == null)31 currentScreen = flowResult;32 ...33 }34 ...35 context.getRequestDispatcher("/"36 +currentScreen).forward(request, response);37 }38 }

Page 542: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 34 of 55

s_

e"/>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The screendefinitionen_US.xmlFile

1 <screen-definitions>2 <default-template>/template.jsp3 </default-template>4 <screen name="main">5 <parameter key="title"6 value="Welcome to the BluePrints Petstore"7 direct="true"/>8 <parameter key="banner" value="/banner.jsp" />9 <parameter key="sidebar"10 value="/sidebar.jsp" />11 <parameter key="body" value="/main.jsp" />12 <parameter key="mylist" value="/mylist.jsp" />13 <parameter key="advicebanner"14 value="/advice_banner.jsp" />15 <parameter key="footer" value="/footer.jsp" />16 </screen>17 <screen name="cart">18 <parameter key="title" value="Cart" direct="tru

Page 543: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 35 of 55

s_

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The screendefinitionen_US.xmlFile

19 <parameter key="banner" value="/banner.jsp" />20 <parameter key="sidebar"21 value="/sidebar.jsp" />22 <parameter key="body" value="/cart.jsp" />23 <parameter key="mylist" value="/mylist.jsp" />24 <parameter key="footer" value="/footer.jsp" />25 <parameter key="advicebanner"26 value="/advice_banner.jsp" />27 </screen>

Page 544: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 36 of 55

ass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The TemplateServletCl

1 package com.sun.j2ee.blueprints.waf.view.template;2 ...3 public class TemplateServlet extends HttpServlet {4 ...5 public void process (HttpServletRequest request,6 HttpServletResponse response)7 throws IOException,ServletException {8 String screenName = null;9 String selectedUrl = request.getRequestURI();10 int lastPathSeparator =11 selectedUrl.lastIndexOf("/") + 1;12 int lastDot = selectedUrl.lastIndexOf(".");13 if (lastPathSeparator != -1 && lastDot != -114 && lastDot > lastPathSeparator) {15 screenName = selectedUrl.substring16 (lastPathSeparator, lastDot);17 }18 //code omitted to cache request parameters

//and request attributes

Page 545: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 37 of 55

ass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The TemplateServletCl

19 ...20 String templateName = localeScreens.21 getTemplate(screenName);22 if (templateName != null) {23 ...24 context.getRequestDispatcher(templateName).25 forward(request, response);26 ...

Page 546: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 38 of 55

e

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The Template.jspPag

1 <%@ taglib uri="/WEB-INF/template.tld"2 prefix="template" %>3 <%@ page contentType="text/html;charset=UTF-8" %>4 <html>5 <head>6 ...7 <body bgcolor="#FFFFFF">8 <table width="100%" height="100%" border="0"9 cellpadding="5" cellspacing="0">10 <tr height="100" valign="top">11 <td colspan="3">12 <template:insert parameter="banner" />13 </td>14 </tr>15 <tr valign="top">16 <td width="20%" valign="top">17 <template:insert parameter="sidebar" />18 </td>19 <td width="60%" valign="top">

Page 547: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 39 of 55

e

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The Template.jspPag

20 <template:insert parameter="body" />21 </td>22 <td valign="top">23 <template:insert parameter="mylist" />24 </td>25 </tr>26 ...

Page 548: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 40 of 55

ag

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The InsertTagCustom T

1 public class InsertTag extends TagSupport {2 private boolean directInclude = false;3 private String parameter = null;4 private Parameter parameterRef = null;5 private Screen screen = null;6 public void setParameter(String parameter){7 this.parameter = parameter;8 }9 public int doStartTag() throws JspTagException {10 screen = (Screen)pageContext.getRequest().11 getAttribute(WebKeys.CURRENT_SCREEN);12 if ((screen != null) && (parameter != null))13 parameterRef = (Parameter)14 screen.getParameter(parameter);15 ...16 if (parameterRef != null)17 directInclude = parameterRef.isDirect();18 return SKIP_BODY;19 }

Page 549: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 41 of 55

ag

alue());

r

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The InsertTagCustom T

20 public int doEndTag() throws JspTagException {21 if (directInclude && parameterRef != null) {22 pageContext.getOut().print(parameterRef.getV23 } else if (parameterRef != null) {24 if (parameterRef.getValue() != null)25 pageContext.getRequest().getRequestDispatche26 (parameterRef.getValue()).include27 (pageContext.getRequest(),28 pageContext.getResponse());29 }30 return EVAL_PAGE;31 }32 }

Page 550: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 42 of 55

he Java Petive Classes

ceptioneption

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Analyzing the Java EE Patterns in tStore Demo Software Administrat

<<session bean>>OPCAdminFacadeEJB

getChartInfo(:String, Date, Date, String) throws OPCAdminFacadeExgetOrdersByStatus( : String ) : OrdersTO throws OPCAdminFacadeExc...

AdminRequestBD

AdminRequestDB() throws AdminDBExceptiongetChartInfo(:String, Date, Date, String) throws AdminDBExceptiongetOrdersByStatus( : String ) : OrdersTO throws AdminDBExceptionupdateOrders( OrderApproval ) throws AdminDBException

<<singleton>>ServiceLocator

+getInstance() : ServiceLocator+getLocalHome( : String ) : EJBLocalHome...

<<session bean>>AsynchSenderEJB

+sendAMessage( : String )...

<<Servlet>>ApplRequestProcessor

...

<<session bean>>ProcessManagerEJB

...

<<entity bean>>PurchaseOrderEJB

...

<<entity bean>>ManagerEJB

...

Page 551: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 43 of 55

n in thenality

RequestBD

Locator class

nFacadeEJB unifiedeans class is aack to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Design Pattern ImplementatioAdministrative Client Functio

• Business Delegate pattern – The Adminclass is a business delegate

• Service Locator pattern – The Servicelocates various resources such as EJBtechnology references

• Session Façade pattern – The OPCAdmiclass is a session façade that provides ainterface to several session and entity b

• Transfer Object pattern – The OrderTOtransfer object that returns order data bthe client tier

Page 552: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 44 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The AdminRequestBDCla

1 package com.sun.j2ee.blueprints.admin.web;2 ...3 public class AdminRequestBD {4 private String OPC_ADMIN_NAME =5 "java:comp/env/ejb/remote/OPCAdminFacade";6 private OPCAdminFacade opcAdminEJB = null;7 public AdminRequestBD()8 throws AdminBDException{9 try {10 OPCAdminFacadeHome home =11 (OPCAdminFacadeHome)12 ServiceLocator.getInstance().13 getRemoteHome(OPC_ADMIN_NAME,14 OPCAdminFacadeHome.class);15 opcAdminEJB = home.create();16 } catch (CreateException ce) {17 ce.printStackTrace();18 throw new AdminBDException(ce.getMessage());19 }

Page 553: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 45 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The AdminRequestBDCla

20 ...21 }22 public OrdersTO getOrdersByStatus(String status)23 throws AdminBDException {24 try {25 return26 opcAdminEJB.getOrdersByStatus(status);27 } catch (RemoteException re) {28 re.printStackTrace();29 throw new AdminBDException(re.getMessage());}}}

Page 554: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 46 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ServiceLocatorCla

1 package2 com.sun.j2ee.blueprints.servicelocator.web;3 ...4 public class ServiceLocator {5 private InitialContext ic;6 private Map cache; //holds references to EJBHomes7 private static ServiceLocator me;89 static {10 me = new ServiceLocator();11 ...12 }13 private ServiceLocator()14 throws ServiceLocatorException {15 try {16 ic = new InitialContext();17 cache = Collections.synchronizedMap18 (new HashMap());19 } catch (NamingException ne) {

Page 555: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 47 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ServiceLocatorCla

20 throw new ServiceLocatorException(ne);21 } ...22 }23 static public ServiceLocator getInstance() {24 return me;25 }26 public EJBLocalHome getLocalHome27 (String jndiHomeName)28 throws ServiceLocatorException {

Page 556: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 48 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ServiceLocatorCla

29 EJBLocalHome home = null;30 try {31 if (cache.containsKey(jndiHomeName)) {32 home = (EJBLocalHome)33 cache.get(jndiHomeName);34 } else {35 home = (EJBLocalHome)36 ic.lookup(jndiHomeName);37 cache.put(jndiHomeName, home);38 }39 } catch (NamingException ne) {40 throw new ServiceLocatorException(ne);41 } catch (Exception e) {42 throw new ServiceLocatorException(e);43 }44 return home;45 }46 public EJBHome getRemoteHome(...) ... {...}47 public QueueConnectionFactory

Page 557: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 49 of 55

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The ServiceLocatorCla

48 getQueueConnectionFactory(...) ...{...}49 public Queue getQueue(...) ... {...}50 public TopicConnectionFactory

getTopicConnectionFactory(...) ...{...}51 public Topic getTopic(...) ... {...}52 public DataSource getDataSource(...) ... {...}53 public URL getUrl(...) ... {...}54 public boolean getBoolean(...) ... {...}55 public String getString(...) ... {...}56 }

Page 558: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 50 of 55

ss

{

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The MutableOrderTOCla

1 package com.sun.j2ee.blueprints.opc.admin.ejb;2 ...3 public interface OrdersTO extends Serializable4 public Iterator iterator();5 public int size();6 public boolean contains(Object o);7 public boolean containsAll(Collection c);8 public boolean equals(Object o);9 public int hashCode();10 public boolean isEmpty();11 public Object[] toArray();12 public Object[] toArray(Object[] a);1314 static class MutableOrdersTO15 extends ArrayList implements OrdersTO {16 }17 }

Page 559: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 51 of 55

lass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The OPCAdminFacadeEJBC

1 package com.sun.j2ee.blueprints.opc.admin.ejb;2 ...3 public class OPCAdminFacadeEJB4 implements SessionBean {5 private String PURCHASE_ORDER_EJB =6 "java:comp/env/ejb/local/PurchaseOrder";7 private String PROCMGR_ORDER_EJB =8 "java:comp/env/ejb/local/ProcessManager";9 private SessionContext sc;10 private PurchaseOrderLocalHome poLocalHome;11 private ProcessManagerLocal processManagerLocal;1213 public void ejbCreate() throws CreateException {14 try {15 ServiceLocator serviceLocator =16 new ServiceLocator();17 poLocalHome = (PurchaseOrderLocalHome)18 serviceLocator.getLocalHome19 (PURCHASE_ORDER_EJB);

Page 560: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 52 of 55

lass

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The OPCAdminFacadeEJBC

20 ProcessManagerLocalHome21 processManagerLocalHome =22 (ProcessManagerLocalHome)23 serviceLocator.getLocalHome24 (PROCMGR_ORDER_EJB);25 processManagerLocal =26 processManagerLocalHome.create();27 } catch(ServiceLocatorException se) {28 throw new EJBException(se);29 } catch (CreateException ce) {30 throw new EJBException(ce);31 }32 }33 public OrdersTO getOrdersByStatus(String status)34 throws OPCAdminFacadeException {35 OrdersTO.MutableOrdersTO retVal =36 new OrdersTO.MutableOrdersTO();37 PurchaseOrderLocal po;38 ProcessManagerLocal mgr = processManagerLocal;39 try {40 PurchaseOrderLocalHome pohome = poLocalHome;

Page 561: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 53 of 55

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

41 Collection orders =42 mgr.getOrdersByStatus(status);43 Iterator it = orders.iterator();44 while((it!= null) && (it.hasNext())) {45 ManagerLocal mgrEjb =46 (ManagerLocal) it.next();47 po = pohome.48 findByPrimaryKey(mgrEjb.getOrderId());49 Date gotDate = new Date(po.getPoDate());50 String podate = (gotDate.getMonth()+1) +51 "/" + gotDate.getDate() + "/" +52 (gotDate.getYear()+1900);53 retVal.add(new OrderDetails(po.getPoId(),54 po.getPoUserId(), podate,55 po.getPoValue(), status));56 }57 } catch(FinderException fe) {58 System.err.println59 ("finder Ex while getOrdByStat :"60 + fe.getMessage());

Page 562: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 54 of 55

lass

find "+

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

The OPCAdminFacadeEJBC

61 throw new OPCAdminFacadeException("Unable to62 "PurchaseOrders of given status : " +63 fe.getMessage());64 }65 return(retVal);66 }67 ...68 }

Page 563: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Module 13, slide 55 of 55

e enterprise

Object-Oriented Design Principles

Architectural Patterns

i-Patterns Java EE BluePrints Design Guidelines

Gang of Four Design Patterns

Java EE Design Patterns

Behavioral

Creational

Structural

Presentation Tier

Business Tier

Integration Tier

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• The Java EE BluePrints designguidelines provide best practicesfor designing enterprise systemsusing Java EE platform technology

• The Java Pet Store demo softwareis a sample Web application thatillustrates these best practices

• By studying the Java Pet Storedemo software , you can see anexample of how the Java EEpatterns can be applied to create a largapplication

Ant

Page 564: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Java EE™ Patterns

Appendix A

Quick Reference for UML

There are no overheads associated with this appendix.

Appendix A

Quick Referencefor UML

associated with this appendix

Appendix A

Quick ReferenceFor UML

There are no overheadsassociated with this appendix

Page 565: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

iew

Java EE™ Patterns

Appendix B

J2EE Technology RevAppendix B

ReviewJ2EE Technology

Appendix B

J2EE TechnologyReview

Appendix B

J2EE TechnologyReview

Page 566: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 2 of 91

J2EE platformon (Java RMI)

y Interface API

re

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Objectives

• Describe the major technologies of the • Describe Java Remote Method Invocati• Describe Java IDL API• Describe the JAX-RPC API• Describe the Java Naming and Director• Describe the Java Servlet API• Describe JSP technology• Describe the Java Message Service API• Describe EJB technology• Describe JDBC technology• Describe the J2EE Connector Architectu

Page 567: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 3 of 91

rm

and framework technology

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Reviewing the J2EE Platfo

The J2EE platform is a development platformfor building component based enterprise Javaapplications

J2EE includes:

• Specification• The reference implementation server• J2EE BluePrints design guidelines• The Java Pet Store Demo application

Page 568: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 4 of 91

rm

NDI) API

sare)

SAAJ)ftware

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Reviewing the J2EE Platfo

• Java Remote Method Invocation (RMI)• Java IDL API• Java Naming and Directory Interface (J• Java Servlet API• JavaServer Pages (JSP pages)• Enterprise JavaBeans (EJB) component• Java API for XML Parsing (JAXP) softw• Java API for XML-based RPC (JAX-RPC• SOAP with Attachments API for Java (• Java API for XML Registries (JAXR) so

Page 569: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 5 of 91

rm

Service (JAAS)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Reviewing the J2EE Platfo

• JDBC API• Java Message Service API (JMS)• JavaMail™ API• Java Transaction API (JTA)• Java Authentication and Authorization• J2EE connector architecture• J2EE management model

Page 570: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 6 of 91

Basics

JavaMail

2SE

JND

IJM

S

JDB

C

JTA

JAF

ontainer

EJB

abase

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Multi-Tier J2EE Architecture

J2SE

Web Container

<%

%>

J

JMX

JAX

RJA

CC

AppletServlet

JAX-RPC

SAAJ

JSP

EJB CApplet Container

J2SE

HTTPSSL

HTTPSSL

ApplicationClient Container

ApplicationClient

JAX-RPC

SAAJ JMXJAX

RJM

SJN

DI

JDB

C

DatJ2SE

JavaMail

JND

IJM

S

JMX

JAX

RJA

CC

JDB

C

JTA

JAF

JAX-RPC

SAAJ

Page 571: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 7 of 91

ethod

n

I classes

Skeleton

emoteObject

Remote Java VM

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

• Light-weight distributed communicatio• Uses stubs and skeletons• The java.rmi package contains the AP

R

Network transport layer (JRMP)

Caller Java VM

Caller

Server

bindlookup

StubRMI Registry

java.rmi.Naming

java.rmi.Naming

Functionality supplied by the Java RMI APIFunctionality generated by Java RMI compilerFunctionality written by the developer

Page 572: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 8 of 91

ethod

va RMI

{oteException,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

These are the basic steps to create and run a Jaapplication:

1. Define a remote interface:1 import java.rmi.*;2 public interface Borrowable extends java.rmi.Remote3 public boolean checkOut(String patron) throws Rem4 PatronException;5 public boolean checkIn() throws RemoteException;6 public boolean catalog() throws RemoteException;7 }

Page 573: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 9 of 91

ethod

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

2. Define a remote class:1 import java.rmi.*;2 import java.rmi.server.*;34 public class Book extends UnicastRemoteObject5 implements Borrowable {6 String title;7 String author;8 String publisher;9 String callNo;1011 public Book(String t, String a, String p,12 String c) throws RemoteException {13 title = t;14 author = a;15 publisher = p;16 callNo = c;

Page 574: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 10 of 91

ethod

ronException {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

17 }1819 public boolean checkOut(String patron) throws Pat20 boolean result = false;21 if (checkOut == true)22 result = true;23 return result;24 }25 public boolean checkIn() {26 boolean result = false;27 if (checkIn == true)28 result = true;29 return result;30 }31 public boolean catalog() {32 boolean result = false;33 if (catalogued == true)34 result = true;

Page 575: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 11 of 91

ethod

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

35 return result;36 }37 }

Page 576: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 12 of 91

ethod

p, String c){

nce and a

);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

3. Define a server class:1 public class BookLauncher {2 public boolean createBook(String t, String a, String3 Book bookRef = new Book(t, a, p, c);4 Naming.rebind("//libServer/Book", bookRef);5 // To put it in the RMI Registry, an object refere6 //logical name for use by callers is needed7 }8 public static void main(String args[]) {9 (new BookLauncher()).createBook(10 args[0], args[1], args[2], args[3]11 }12 }

Page 577: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 13 of 91

ethod

p, String c){;

ect

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

4. Define a caller (client):1 import java.rmi.*;2 import library.*;34 public class BookUser {56 Borrowable b;7 public boolean createBook(String t, String a, String8 b = (Borrowable) Naming.lookup(“//libServer/Book”)9 // Need to know the name of the server10 // Need to know the logical name of the remote obj11 }1213 public boolean checkOut(String patron) {14 b.checkOut(patron);15 }16 // Other methods as necessary17 }

Page 578: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 14 of 91

ethod

e stubs andver-side

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Java Remote MInvocation

5. Compile all the code:javac *.java

6. Use the rmic command to generate thskeletons which serve as caller and seproxies for the remote object:rmic Book.class

7. Start the Java RMI registry:rmiregistryRun the server program.java Booklauncher

8. Run the caller program:java BookUser

Page 579: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 15 of 91

API

y

ins CORBAng Java

Java programming

stry

than CORBA

e Java 2 platform,on (Java SE™

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the Java IDL

• The Java IDL API is the Java technologimplementation of CORBA

• The Object Management Group mainta• You can write CORBA applications usi

technology

Characteristic CORBA Java RMI

Programminglanguages

Java, C, C++, COBOL,Smalltalk, LISP, PL/I, andmore

Specific to the language

Naming service COS Naming Service Java RMI Regi

Complexity Quite complex Much simpler

Requiredsoftware

Must obtain an ORB Core API in thStandard Editiplatform)

Page 580: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 16 of 91

API

I

ming service is

t, uses the Javaethod Protocol

one only using Javay

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the Java IDL

Characteristic CORBA Java RM

Additionalservices

Other services often available,such as event processing andtransaction management

Only a naprovided

Networkprotocol

Uses Internet Inter-ORBProtocol (IIOP)

By defaulRemote M(JRMP)

Interfacedefinition

Definition of attributes andbehaviors in the languageneutral Interface DefinitionLanguage

Work is dtechnolog

Page 581: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 17 of 91

API

s toodel,ironment usedk

service

is the most

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

• Web services enable clients and servicecommunicate regardless of the object mprogramming language, or runtime envon either side of the communication lin

• XML based messages• HTTP is the most commonly used web

transport protocol• Simple Object Access Protocol (SOAP)

common format for the messages

Page 582: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 18 of 91

API

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

Web ServiceInfrastructure

ApplicationFunctions

HeterogeneousClient Base

SwingClient

Other ClientTypes

Browser

ApplicationServer

Page 583: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 19 of 91

API

-RPC) is ansed remote

ort HTTP 1.1 asmessagesX-RPC services

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

• The Java API for XML-based RPC (JAXextensible API for performing XML-baprocedure calls

• A JAX-RPC implementation must suppthe transport mechanism for SOAP 1.1

• The JAX-RPC specification describes JAaccording to the WSDL 1.1 specification

Java Objectsand

Data Types

SOAPMessage

JAX-RPC

InternetSOAP

Message

Marshall/Unmarshall

Transmit

Page 584: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 20 of 91

API

l where servicepointervice messagethe method andn the message.lts, and stateless

ervice

gs

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

• JAX-RPC uses a service endpoint moderequests are directed to the service end

• The service endpoint unmarshalls the sand invokes the specified service usingparameter information contained withi

• JAX-RPC supports two endpoint modeimplementation types, as well as servlesession beans

ServiceRequests

ServiceEndpoint

Web Container

JAX-RPC runtime

To ServiceSOAP

RPCRouterServlet Binding

Classes

EJB Container

To SStatelessSession

EJB BindinClasse

Page 585: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 21 of 91

API

ality provided

.rmi.Remote

adata types

stants

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

• A service interface defines the functionby a web service

• A JAX-RPC interface must extend java

• All of the interface methods must throwjava.rmi.RemoteException and use supported by JAX-RPC

• The interface must not declare any con1 import java.rmi.Remote;2 import java.rmi.RemoteException;34 public interface InterfaceName extends Remote {5 // business method6 public ReturnType methodName(paramList)7 throws RemoteException;8 }

Page 586: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 22 of 91

API

Java class thatice interface

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

A JAX-RPC service implementation class is a implements the methods declared on the serv

1 public class ClassName implements InterfaceName {2 // constructor3 public ClassName() {4 // do nothing5 }6 // the actual service7 public ReturnType methodName(paramList) {8 method body;9 }10 }

Page 587: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 23 of 91

API

mplementation necessaryiles:

or deployment

cerovided with

(Java WSDP)nt build scripts

tionality in an

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JAX-RPC

• Having created a service interface and iclass, a service developer generates theserver-side web service infrastructure f• The server tie files• The service properties file required f• Serializer and deserializer files• A WSDL file that describes the servi

• You can do these tasks using the tools pthe Java Web Services Developer Pack and automate them using one or more A

• Alternatively, you can rely on the funcIDE to perform this work for you

Page 588: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 24 of 91

d Directory

ceshanging codek. It looks up

tions

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the Java Naming anInterface™ (JNDI) API

• Allows access to multiple naming servi• Can change naming services without c• The naming service is like a phone boo

names and gets back objects

Java Application

Naming Manager

JNDI API

JNDI SPI

JNDIImplementa

PossibilitieLDAP DNS NIS NDS RMI CORBA

Page 589: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 25 of 91

String jndiname){

teObject.narrowe.class);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JNDI API Class

1 public class CatalogManager {2 public CatalogQueryBeanHome findCatalogQueryBean(3 try {4 InitialContext ctx = new InitialContext();5 Object ref = ctx.lookup(jndiname);6 CatalogQUeryBeanHome home =7 (CatalogQueryBeanHome)javax.rmi.PortableRemo8 ("CatalogQueryBean", CatalogQUeryBeanHom9 }catch(Exception e) {10 e.printStackTrace();11 }12 }13 }

Page 590: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 26 of 91

d Directory

e API classes

t to specify the

bject.narrow

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the Java Naming anInterface™ API

• The javax.naming package contains th• Create an InitialContext object:

• Use a java.util.Properties objecURL and driver classes

• Call the lookup method• Use the javax.rmi.PortableRemoteO

method to narrow the results• Cast the results

Page 591: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 27 of 91

the API classes

ataource

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Servlets

• Server managed Web components• Servlets create dynamic Web content• Replace CGI and similar technologies• The javax.servlet package contains

Query

Result

Client BrowserHTTP(s)

HTML

DS

Servlet

Web Tier

Servlet retrieves user data from the data source.

Using the data, the servlet generates a personalized page.

User requests a Web page from the Web server.

2

3

1

Page 592: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 28 of 91

nHome)

e.class);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Servlet Class

1 import java.io.*;2 import java.util.*;3 import javax.servlet.*;4 import javax.servlet.http.*;5 import libraryApp.*;67 public class CatalogServlet extends HttpServlet {8 private CatalogQueryBeanHome cqbh;9 public void init() throws ServletException {10 try {11 InitialContext ctx = new InitialContext();12 Object ref = ctx.lookup("CatalogQueryBean");13 CatalogQueryBeanHome cqbh = (CatalogQueryBea14 javax.rmi.PortableRemoteObject.narrow15 ("CatalogQueryBean", CatalogQUeryBeanHom16 }catch(Exception e) {17 e.printStackTrace();18 }19 }

Page 593: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 29 of 91

tion {

chType");earchValue");

chValue);

.getMessage());

Writer

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Servlet Class

2021 public void destroy() { }22 public void doGet (HttpServletRequest request,23 HttpServletResponse response)24 throws ServletException, IOExcep25 HttpSession session = request.getSession();26 try {27 String category = request.getParameter("Sear28 String searchValue = request.getParameter("S29 CatalogQueryBean cqb = cqbh.create();30 Collection titles = cqb.query(category, sear31 cqb.remove();32 }catch(CreateException crex) {33 System.out.println34 ("Error creating CatalogQueryBean " + crex35 }36 // Handle other exception types37 // set content-type header before accessing the

Page 594: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 30 of 91

</head>");

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Servlet Class

38 response.setContentType("text/html");39 response.setBufferSize(8192);40 PrintWriter out = response.getWriter();41 // then write the data of the response42 out.println43 ("<html><head><title>Catalog Query Results</title>44 out.println("<body>");45 Iterator iter = titles.getItems();46 while (iter.hasNext()) {47 String title = (Book)iter.next();48 out.println(title);49 }50 out.println("</body>");51 out.println("</html>");52 out.close();53 }54 }

Page 595: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 31 of 91

ET request:eeters for the

to set mime

HTML back to

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Servlets

• Subclass of HttpServlet• doGet – Called when a client sends a G

• HttpServletRequest object; use thgetParameter method to get paramWeb page

• HttpServletResponse object:• Use the setContentType method

type• Use a PrintWriter object to send

the client

Page 596: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 32 of 91

ges™

s

et classes

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding JavaServer PaTechnology

• Server managed Web components• Allows for separation of developer role• Improves application maintainability• Helps prevent cut-and-paste reuse• Automatic recompilation• Contains HTML with special tags• Get translated and compiled into Servl

Page 597: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 33 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JSP Page Flow

Init event

RequestResponse

Destroy event

jspInit()

jspService

jspDestroy

“JSP” Servlet

Page 598: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 34 of 91

P Page

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

HTML Form Processed by a JS

1 <HTML>2 <HEAD>3 <TITLE>KDL University Library System</TITLE>4 </HEAD>5 <BODY>6 <FORM action="/Catalog.jsp" method="get">7 Search Type:8 <INPUT type=”text” name=”type”><BR>9 Search Text:10 <INPUT type=”text” name=”value”><BR>11 <INPUT type="submit" value="Submit">12 </FORM>13 </BODY>14 </HTML>

Page 599: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 35 of 91

n" />>

%>

lt" />

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JSP Page

1 <%@ include file="Header.jsp" %>2 <jsp:useBean id="Catalog" class="libraryApp.CatalogBea3 <% String searchType = request.getParameter("type"); %4 <jsp:setProperty name="Catalog"5 property="type" value="<%= searchType %>" />6 <% String searchValue = request.getParameter("value");7 <jsp:setProperty name="Catalog" property=8 "value" value="<%= searchValue %>" />9 <% try { %>10 <P>Account:11 <jsp:getProperty name="Catalog" property="searchResu12 </P>13 <% } catch (Exception e) { %>14 <P>Error retrieving item from library ctalog:15 <jsp:getProperty name="Catalog" property="value" />16 </P>17 <% } %>18 <%@ include file="Footer.jsp" %>

Page 600: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 36 of 91

Technology

processor

*" %>

variables

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding JavaServer Pages

• Comments – Text ignored by JSP page <!-- This is a comment -->

• Directives – Compile-time instructions<%@ page language = "java" import = "java.util.

• Declarations – Declare Java technology<%! int x = 5 %>

• Expressions – Produce output<%= clock.getYear(); %>

Page 601: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 37 of 91

Technology

ary" %>

xpression

>

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding JavaServer Pages

• Scriptlets<% int x = 5; out.println(x); %>

• JavaBeans components<jsp:useBean id="name" />

• Custom tags<%@ taglib uri="/tlds/library.tld" prefix="libr<P>New books in our collection</P><library:showNewBooks month="January" >

• Java Standard Tag Library (JSTL) and ELanguage (EL)<c:forEach var=”book” items=”${bookList.books}”<li> <c:out value=”book.name”/> </li></c:forEach>

Page 602: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 38 of 91

e Service

rvices without

PI classesssaging

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the Java Messag(JMS) API

• Allows access to multiple messaging serewriting code

• The javax.jms package contains the A• Provides a way to do asynchronous me

JMS Sender JMS ListenerJMS

Queue

JMS Publisher

JMS Subscriber

JMS Subscriber

JMSTopic

Page 603: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 39 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

1. Create a sender:1 import javax.jms.*;2 import javax.naming.*;3 public class PurchaseRequestSender {4 public static void main(String[] args) {5 Context context = null;6 QueueConnectionFactory qcFactory = null;7 QueueConnection queueConnection = null;8 QueueSession queueSession = null;9 Queue queue = null;10 QueueSender queueSender = null;11 TextMessage message = null;12 try {13 context = new InitialContext();14 } catch (NamingException ne) {15 System.out.println("Could not create “ +16 “JNDI context: " + ne.toString());17 System.exit(1);18 }

Page 604: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 40 of 91

PI

e);

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

19 try {20 qcFactory = (QueueConnectionFactory)21 context.lookup("java:comp/env/jms/22 PurchasingQueueConnectionFactory");23 queue = (queue) context.lookup24 ("java:comp/env/jms/PurchaseQueue");25 } catch (NamingException e) {26 System.out.println27 ("JNDI lookup failed: " +e.toString());28 System.exit(1);29 }30 try {31 queueConnection =32 qcFactory.createQueueConnection();33 queueSession =34 queueConnection.createQueueSession(false,35 Session.AUTO_ACKNOWLEDGE);36 queueSender = queueSession.createSender(queu37 message = queueSession.createTextMessage();

Page 605: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 41 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

38 message.setText39 ("// Purchase request data goes here");40 queueSender.send(message);41 } catch (JMSException jmse) {42 System.out.println("Exception occurred: " +43 jmse.toString());44 } finally {45 if (queueConnection != null) {46 try {47 queueConnection.close();48 } catch (JMSException e) {49 System.out.println50 ("JMS error: " +e.getMessage());51 e.printStackTrace();52 }53 }54 }55 }56 }

Page 606: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 42 of 91

PI

gs:

y.

ry.on.nd passing in

.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

This JMS sender code does the following thin

a. Looks up a queue connection factorb. Looks up a queue.c. Creates a connection using the factod. Creates a session using the connectie. Creates a sender using the session a

the queue.f. Creates a message using the senderg. Sends the message.h. Closes the connection.

Page 607: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 43 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

2. Create a message receiver:1 import javax.jms.*;2 import javax.naming.*;3 public class PurchaseOrderReceiver {4 public static void main(String[] args) {5 Context context = null;6 QueueConnectionFactory qcFactory = null;7 QueueConnection queueConnection = null;8 QueueSession queueSession = null;9 Queue queue = null;10 QueueReceiver queueReceiver = null;11 TextMessage message = null;12 try {13 context = new InitialContext();14 } catch (NamingException e) {15 System.out.println("Could not create16 InitiialContext: " + e.toString());17 System.exit(1);

Page 608: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 44 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

18 }19 try {20 qcFactory = (QueueConnectionFactory)21 context.lookup("java:comp/env/jms22 PurchasingQueueConnectionFactory");23 queue = (Queue)context.lookup24 ("java:comp/env/jms/PurchaseQueue");25 } catch (NamingException e) {26 System.out.println27 ("JNDI lookup failed: " + e.toString());28 System.exit(1);

Page 609: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 45 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

29 }30 try {31 queueConnection =32 qcFactory.createQueueConnection();33 queueSession =34 queueConnection.createQueueSession(35 false,Session.AUTO_ACKNOWLEDGE);36 queueReceiver = queueSession37 .createReceiver(queue);38 queueConnection.start();39 while (true) {40 Message m = queueReceiver.receive(1);41 if (m != null) {42 if (m instanceof TextMessage) {43 message = (TextMessage) m;44 System.out.println("Reading “ +45 “message: " + message.getText());46 } else {47 break;

Page 610: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 46 of 91

PI

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

48 }49 }50 }51 } catch (JMSException e) {52 System.out.println("Exception occurred: "53 + e.toString());54 } finally {55 queueConnection.close();56 ...

Page 611: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 47 of 91

PI

ngs:

..d passing in

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding the JMS A

This JMS receiver code does the following thi

1. Looks up a queue connection factory.2. Looks up a queue.3. Creates a connection using the factory4. Creates a session using the connection5. Creates a receiver using the session an

the queue.6. Starts the connection.7. Receives the message.8. Closes the connection.

Page 612: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 48 of 91

Beans™s

nts

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding Enterprise JavaTechnology Component

• Container managed business compone• Components for business logic• Container provides these services:

• Security• Transactions• Concurrency• Resource management• Persistence

Page 613: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 49 of 91

chitecture

rity

es

0

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Overall Enterprise JavaBeans Ar

Secu

Client

Server B

JNDIJNDI

Server A

Container

createfind remove

HomeObject

Services

Naming Transaction Persistence

HomeInterface

EJBObject

RemoteInterface

Bean

Environmental Properti

2

3

4

8

5

91

6

1

Page 614: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 50 of 91

chitecture:nt

stroys beans

nds the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Overall Enterprise JavaBeans ArParts of an EJB Compone

Home Object:

• Is a factory that creates, locates, and de• Provided by the container• Implements the Home interface that exte

javax.ejb.EJBHome interface

Page 615: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 51 of 91

chitecture:nt

the bean

at extends the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Overall Enterprise JavaBeans ArParts of an EJB Compone

EJB Object:

• A proxy that forwards business calls to• Provided by the container• Implements the component interface th

javax.ejb.EJBObject interface

Page 616: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 52 of 91

chitecture:nt

the

r

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Overall Enterprise JavaBeans ArParts of an EJB Compone

Deployment Descriptor:

• Is an XML document• Contains structural information about • EJB component• Is used for deployment by the containe

Page 617: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 53 of 91

chitecture:es

omponent

omponents

EE platform

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Overall Enterprise JavaBeans ArRemote and Local Interfac

• Developer can choose the Home and Cinterfaces to be remote or local

• Remote interfaces allow access to EJB cacross the network

• Local interfaces are more efficient for J2components on the same physical host

Page 618: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 54 of 91

ents

essage-Drivenean

odelingsynchronoususiness logic

essageDrivenBean

tateless. Notccessible by thelient except throughhe JMS API

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Three Types of EJB Compon

Session Bean Entity BeanMB

PrimaryPurpose

Modelingsynchronousbusiness logic

Modeling entities,especially tables inan RDBMS or objectsin an ODBMS

Mab

Interface SessionBean EntityBean M

Client State Can beconversational(stateful or stateless)

Models persistentstate

Sact

Page 619: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 55 of 91

ss Session Bean

s

lly no

accept parametersialization

ng one-shots logic, such asg a catalog or

ing a credit cardr. Sometimes moret than a stateful bean

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Beans

Stateful Session Bean Statele

Conversational State Stateful Stateles

Instance owned byclient?

Generally yes Genera

create methodparameters

Can take parameters forinitialization

Cannotfor init

Use Modeling conversationalbusiness logic, such asneeded for a shopping cart

Modelibusinesqueryinvalidatnumbeefficiensession

Page 620: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 56 of 91

ace

.EJBHome {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Home Interf

1 import javax.ebj.*;2 import java.rmi.*;34 public interface ShoppingCartHome extends javax.ejb5 public ShoppingCart create() throws6 CreateException, RemoteException;7 public ShoppingCart create(String custID) throws8 CreateException, RemoteException;9 }

Page 621: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 57 of 91

erface

Object {xception;

qty)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Component Int

1 import java.rmi.*;2 import javax.ejb.*;3 public interface ShoppingCart extends javax.ejb.EJB4 public Collection getItemsInCart() throws RemoteE5 public boolean addToCart(String itemID, int qty)6 throws RemoteException;7 public boolean removeFromCart(String itemID, int 8 throws RemoteException;9 public checkOut(String custID)10 throws RemoteException, CustomerException;11 }

Page 622: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 58 of 91

SessionBean {

s

r

s{

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Class

1 import javax.ejb.*;2 import java.util.*;34 public class ShoppingCartBean implements javax.ejb.5 private SessionContext context;6 private String customerID;7 private LinkedList items;8 // Initialize the bean instance with no parameter9 public void ejbCreate() {}10 // Initialize the bean instance with one paramete11 public void ejbCreate(String custID) {12 customerID = custID;13 }14 // Save object which provides environmental acces15 public void setSessionContext(SessionContext sc) 16 context = sc;17 }

Page 623: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 59 of 91

{

qty) {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Class

18 // Destroy bean instance19 public void ejbRemove() { }20 // The next two methods are container callbacks21 // for resource management22 public void ejbPassivate() { }23 public void ejbActivate() { }24 // Remote interface methods25 public Collection getItemsInCart() {26 return items;27 }28 public boolean addToCart(String itemID, int qty) 29 // Add item logic30 }31 public boolean removeFromCart(String itemID, int 32 // Remove item logic33 }34 public checkOut(String custID) {35 // Perform order check out operations36 }}

Page 624: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 60 of 91

thod for every

od in then classthods

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Class

Must contain:

• A codeless, no argument constructor• Home related methods; ejbCreate me

create method in the Home interface• Business methods; every business meth

component interface must be in the bea• javax.ejb.SessionBean interface me

Page 625: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 61 of 91

container

the containerary storagethe containercondary storage

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Session Bean Class

Session Bean Methods:

• ejbCreate – Initialization code• ejbRemove – Clean up code before the

destroys the instance• ejbPassivate – Clean up code before

writes a stateful session bean to second• ejbActivate – Regain resources after

rebuilds a stateful session bean from se

Page 626: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 62 of 91

ions (CMT)

P) or container-

code code

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Entity Beans

• Represent a persistent business entity• Persisted in a data store• Must have container-managed transact• Are pooled• Can be bean-managed persistence (BM

managed persistence (CMP):• BMP – Developer writes data access• CMP – Container writes data access

Page 627: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 63 of 91

rface

{,

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Home Inte

1 import javax.ejb.*;2 import java.rmi.*;3 import java.util.*;4 public interface BookHome extends javax.ejb.EJBHome5 public Book create(String anAuthor, String aTitle6 String aCallNo, String aSubject)7 throws CreateException, RemoteException;8 public String findByPrimaryKey(String theCallNo)9 throws FinderException, RemoteException;10 }

Page 628: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 64 of 91

nterface

oteException;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Component I

1 import javax.ejb.*;2 import java.rmi.*;3 import java.util.*;4 public interface Book extends EJBObject {5 public boolean checkOut(String cardID) throws Rem6 public String getAuthor() throws RemoteException;7 public String getTitle() throws RemoteException;8 public String getStatus() throws RemoteException;9 }

Page 629: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 65 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

1 import javax.ejb.*;2 import java.util.*;3 public class BookBean4 implements javax.ejb.EntityBean {5 private String author;6 private String title;7 private String callNo;8 private String subject;9 private String status;10 private EntityContext context;1112 public String ejbCreate(String anAuthor,13 String aTitle, String aCallNo,14 String aSubject) {15 author = anAuthor;16 title = aTitle;17 callNo = aCallNo;18 subject = aSubject;19 // Do an insert into the database

Page 630: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 66 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

20 // Return the primary key21 return aCallNo;22 }23 public String ejbPostCreate(String anAuthor,24 String aTitle, String aCallNo,25 String aSubject) {26 // There must be an ejbPostCreate() method for27 // every ejbCreate() method which uses the28 // same parameters, even if it does nothing.29 }

Page 631: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 67 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

3031 public void setEntityContext(EntityContext ctx)32 {33 context = ctx;34 }35 public void unsetEntityContext() { }36 public void ejbRemove() {37 // Delete the row from the database38 }39 public void ejbActivate() {40 callNo = (String) context.getPrimaryKey();41 }42 public void ejbPassivate() {43 author = null;44 title = null;45 callNo = null;46 subject = null;47 status = null;48 }

Page 632: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 68 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

49 public void ejbLoad() {50 callNo = (String) context.getPrimaryKey();51 // Do a database select and initialize the data52 // members of the bean with the data53 }5455 public void ejbStore() {56 // Do a database update based on the content57 // of the data members58 }

Page 633: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 69 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

59 public String findByPrimaryKey60 (String theCallNo) throws FinderException {61 boolean found = true;62 // Do query using theCallNo.63 // if unsuccessful, set found to false.64 if(found == false)65 throw new FinderException66 (theCallNo + "not found in database");67 else68 return theCallNo;69 }70 public boolean checkOut(String cardID) {71 boolean result = false;72 // Process check out request73 return result;74 }75 public String getAuthor() {76 return author;77 }

Page 634: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 70 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

BMP Entity Bean Class

78 public String getTitle() {79 return title;80 }81 public String getStatus() {82 return status;83 }84 }

Page 635: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 71 of 91

dte method in

ery findXXX in

thod in then class.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Entity Beans

A BMP bean must contain:

• A codeless no argument constructor.• The persistent fields.• Home related methods – ejbCreate an

ejbPostCreate method for every creathe Home interface. ejbFindXXX for evthe Home interface.

• Business methods – Every business mecomponent interface must be in the bea

• One or more javax.ejb.EntityBeaninterface methods.

Page 636: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 72 of 91

containerary storage containercondary storage

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Entity Beans

Entity Bean Methods:

• ejbCreate – Inserts a row• ejbRemove – Deletes a row• ejbPassivate – Clean up code before

writes a stateful session bean to second• ejbActivate – Regain resources after

rebuilds a stateful session bean from se

Page 637: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 73 of 91

efore container

beanatabase

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Entity Beans

Entity Bean Methods:

• setEntityContext – Constructor code• unsetEntityContext– Cleanup code b

destroys instance• ejbLoad – Puts data from database into• ejbStore – Puts data from bean into d

Page 638: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 74 of 91

rface

ring cardID)

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

CMP Entity Bean Home Inte

1 import javax.ejb.*;2 import java.rmi.*;34 public interface PatronHome extends EJBHome {5 public Patron create(String name, String addr, St6 throws RemoteException, CreateException;7 public String findByPrimaryKey(String cardID)8 throws RemoteException, FinderException;9 }

Page 639: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 75 of 91

nterface

ption;

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

CMP Entity Bean Component I

1 import javax.ejb.*;2 import java.util.*;3 import java.rmi.*;45 public interface Patron extends EJBObject {6 public String getName() throws RemoteException;7 public Collection getHoldings() throws RemoteExce8 public float getFines() throws RemoteException;9 }

Page 640: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 76 of 91

ean {

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

CMP Entity Bean Class

1 import javax.ejb.*;2 import java.util.*;3 import java.rmi.*;45 public abstract class PatronBean implements EntityB6 private EntityContext context;7 public String ejbCreate(String name,8 String addr, String cardID) {9 setName(name);10 setAddress(addr);11 setLibCardNo(cardID);12 return getLibCardNo();13 }14 public void ejbPostCreate(String name,15 String addr, String cardID) {16 }17 public void setEntityContext(EntityContext ctx) {18 context = ctx;19 }

Page 641: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 77 of 91

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

CMP Entity Bean Class

20 public void unsetEntityContext() { }21 public void ejbRemove() { }22 public void ejbActivate() {}23 public void ejbPassivate() {}24 public void ejbLoad() {}25 public void ejbStore() {}26 public abstract String getName();27 public abstract void setName(String name);28 public abstract String getLibCardNo();29 public abstract void setLibCardNo(String lcn);30 public abstract String getAddress();31 public abstract void setAddress(String addr);32 }

Page 642: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 78 of 91

persistent fieldsdte method in

thod in then classhods

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Entity Beans

A CMP bean must contain:

• A codeless no argument constructor• Abstract getters and setters in place of • Home related methods – ejbCreate an

ejbPostCreate method for every creathe Home interface.

• Business methods – Every business mecomponent interface must be in the bea

• javax.ejb.EntityBean interface met

Page 643: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 79 of 91

he JMS API

ts

B

B

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Message-Driven Beans

• Are asynchronously invoked through t• Have no home or component interface• Are similar to stateless session beans:

• Hold no conversational state• Pooled• Handle requests from multiple clien

JMS ClientJMS

MessageTopic

MD

MD

Page 644: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 80 of 91

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Message-Driven Bean Cla

1 import java.io.Serializable;2 import java.rmi.*;3 import javax.ejb.*;4 import javax.naming.*;5 import javax.jms.*;6 public class PurchaseOrderMakerBean7 implements MessageDrivenBean, MessageListener {8 private MessageDrivenContext mdContext;9 public void setMessageDrivenContext(10 MessageDrivenContext mdc) {11 mdContext = mdc;12 }13 public void ejbCreate() { }14 public void onMessage(Message inMessage) {15 try {16 if (inMessage instanceof TextMessage) {17 TextMessage msg =(TextMessage) inMessage;18 // Extract data from msg and create order19 } else {

Page 645: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 81 of 91

ss

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Message-Driven Bean Cla

20 System.out.println("Wrong message type “21 + inMessage.getClass().getName());22 }23 } catch (Exception e) {24 e.printStackTrace();25 mdContext.setRollbackOnly();26 }27 }28 public void ejbRemove() { }29 }

Page 646: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 82 of 91

face methods:

nally save a

face method:ss a message

dard JMS client

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Message-Driven Beans

Must contain:

• A codeless no argument constructor• javax.ejb.MessageDrivenBean inter

• ejbCreate – Initialization code• setMessageDrivenContext – Optio

reference to the context• A javax.jms.MessageListener inter

onMessage – Code for how to proce

There are no interfaces, and the client is a stan

Page 647: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 83 of 91

nology

thout rewriting

JNDI.

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding JDBC™ Tech

• Allows access to multiple databases wicode

• Steps for database access:1. Look up the DataSource object using2. Get a connection.3. Create a statement.4. Execute a query.5. Process the results.6. Close the connection.

Page 648: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 84 of 91

ons on the

2ee/jcbs/ds1")

Connection

ce

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC Technology Class InteractiJ2EE Platform

lookup("java:/j2ee/jcbs/ds1") lookup("java:/j

JNDI

DataSource

Connection

StatementStatement Statement

ResultSet ResultSet

Connection

Statement

ResultSet

DataSour

Page 649: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 85 of 91

taSource

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC Technology Using the DaClass

1 import java.sql.*;2 import javax.sql.*;3 import java.util.*;4 import javax.naming.*;56 public class CatalogSearcher {7 DataSource ds;8 Connection conn;9 PreparedStatement stmt;10 ResultSet rs;11 InitialContext context;12 public static void main(String[] args) {13 CatalogSearcher cs = new CatalogSearcher();14 cs.search("Lewis, C. S.");15 }16 public CatalogSearcher() {17 try {18 context = new InitialContext();

Page 650: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 86 of 91

taSource

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC Technology Using the DaClass

19 ds = (DataSource)context.lookup20 ("java:comp/env/jdbc/catalog");21 } catch(NamingException ne) {22 System.out.println23 ("JNDI failure: " + ne.getMessage());24 System.exit(1);25 }26 }27 public Collection search(String authorName) {28 ArrayList al = new ArrayList();29 try {30 conn = ds.getConnection();31 stmt = conn.prepareStatement(32 "select * from Catalog where author = ?");33 stmt.setString(1, authorName);34 ResultSet rs = stmt.executeQuery();35 int x = 0;36 while(rs.next() == true) {

Page 651: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 87 of 91

taSource

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

JDBC Technology Using the DaClass

37 String title = rs.getString("Title");38 String pub = rs.getString("Publisher");39 String date = rs.getString("Date");40 String callNo = rs.getString("CallNo");41 Material m = new Material42 (title, pub, date, callNo);43 al.add(x, m); // Add item from44 }45 stmt.close();46 conn.close();47 } catch(SQLException sqle) {48 System.out.println49 ("SQL Error: " + sqle.getMessage());50 sqle.printStackTrace();51 }52 return al;53 }54 }

Page 652: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 88 of 91

rchitecture

a wide variety

the ability toerver(RAR) package, Architecture

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding J2EE Connector A

• J2EE applications might need to accessof enterprise information systems (EIS)

• EIS integration components might needintegrate with the services of the J2EE s

• The vendor supplies a resource archivewhich conforms to the J2EE Connector(J2EE CA) specification.

• Benefits:• Fewer restrictions on the code• Full integration with the J2EE server• Can support CCI

Page 653: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 89 of 91

rchitecture

y services of the

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding J2EE Connector A

Resource adapters can integrate with these keapplication server:

• Transaction management• Resource pooling• Security

EIS

Enterprise Bean

Managers:TransactionConnectionSecurity

System Contract Resource Adapter

Web Component

Application Contract

Application Contract

J2EE Technology Server

Page 654: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 90 of 91

rchitecture

the JDBC APIis API to

raged to

pplication

ire CCI.

some API calls

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Understanding J2EE Connector A

• CCI is a set of interfaces that resemble interfaces. The J2EE components use thcommunicate with the EIS.

• CCI support is not compulsory:• Resource adapter vendors are encou

implement CCI.• Vendors can provide an alternative a

contract.• Some resource adapters do not requ

The use of CCI does not completely eliminatethat are specific to the legacy system.

Page 655: JavaTM EE Patterns SL-314 JavaTM EE Patterns  EE Patterns Java™ EE Patterns Java SL-314 TM EE Patterns SL-314-EE5 JavaTM EE Patterns SL-500-EE5

Appendix B, slide 91 of 91

ing enterprise

2EE include:

Java EE™ PatternsCopyright 2008 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision C.1

Summary

• J2EE platform is a framework for buildapplications using Java technology

• The major technologies supported by J• Java RMI• Java IDL• JNDI API• Java Servlet API• JavaServer Pages• JMS API• EJB technology• JDBC technology