You are on page 1of 279

Real World Java EE Patterns Rethinking Best Practices

Adam Bien (blog.adam-bien.com)

press.adam-bien.com

Real World Java EE Patterns Rethinking Best Practices by Adam Bien

Copyright @ 2009 press.adam-bien.com All rights reserved. P blished by press.adam-bien.com !or more in"ormation or "eedbac#$ contact% abien@adam-bien.com

Cover Designer% &inga Bien ('''.graphi#erin.com) Editor% (ichael &och ('''.m#p.com)

Printing )istory% * ne 2009 +teration ,ne (!irst -dition)

+.B/ 901-0-220-00132-2

2
Download at WoweBook.Com

Table of Contents
Pre"ace............................................................................................................................................. 42 1. A Brief History of J EE.............................................................................................................49 5he 6ise and !all o" Applets......................................................................................................49 5he 75C Paradigm% (oving Beyond Applets...........................................................................20 -*B% +ntrod cing Consistency....................................................................................................20 *(.% A (essaging .ystem o" +ts ,'n...................................................................................... 24 *2--% A /e' .tandard +s Born.................................................................................................. 22 *avaBlend................................................................................................................................... 28 9oo#ing Beyond *ava --...........................................................................................................22 .erver-side *ava% 5he Core Principles..................................................................................2: 5he Case o" 5ransactions..................................................................................................... 20 5he Conc rrency Problem................................................................................................... 21 9oc#ing "or Consistency...................................................................................................... 30 ;istrib tion$ 9atency$ and the !allacies............................................................................... 32 . mmary.................................................................................................................................... 33 . !nderstanding Java EE Core Conce"ts.................................................................................. 32 Convention over Con<g ration..................................................................................................32 ;ependency +n=ection ............................................................................................................... 30 Aspect-,riented Programming and +nterceptors....................................................................... 84 -*B 3 and *PA . pport.............................................................................................................. 82 5he 5ransaction mode.......................................................................................................... 8: 5he ->tended mode..............................................................................................................81 5he ->tended (ode and Conc rrency.................................................................................20 5he Problem 'ith 9a?y 9oading and 5ransparent Persistence............................................ 24 Accessing -*B........................................................................................................................... 22 . mmary.................................................................................................................................... 28 #. Rethinking the B$siness %ier.................................................................................................... 22 .ervice !a@ade (Application .ervice)........................................................................................2:

3
Download at WoweBook.Com

Problem................................................................................................................................ 2: !orces................................................................................................................................... 2: .ol tion................................................................................................................................ 2: 6ethin#ing...................................................................................................................... 21 Conventions.................................................................................................................... 21 Participants and 6esponsibilities.................................................................................... 29 .trategies........................................................................................................................ 29 C67; !a@ade........................................................................................................... 29 ; al-Aie' !a@ade.....................................................................................................:0 .,A !a@ade.............................................................................................................. :4 9ight'eight Asynchrono s !a@ade...........................................................................:2 ( ltichannel !a@ade................................................................................................. :0 ++,P !a@ade...............................................................................................................:9 5esting.................................................................................................................................. 04 ;oc mentation..................................................................................................................... 02 ConseB ences....................................................................................................................... 08 6elated Patterns....................................................................................................................08 .ervice (.ession !a@ade)........................................................................................................... 02 Problem................................................................................................................................ 02 !orces................................................................................................................................... 0: .ol tion................................................................................................................................ 0: Conventions.................................................................................................................... 00 6ethin#ing...................................................................................................................... 01 Participants and 6esponsibilities.................................................................................... 01 .trategies........................................................................................................................ 01 .tateless .ession Bean .trategy................................................................................01 P,*, .trategy...........................................................................................................09 ;A, )ybrid..............................................................................................................10 5esting.................................................................................................................................. 14 ;oc mentation..................................................................................................................... 14

8
Download at WoweBook.Com

ConseB ences....................................................................................................................... 12 6elated Patterns....................................................................................................................12 Persistent ;omain ,b=ect (B siness ,b=ect)............................................................................. 13 Problem................................................................................................................................ 13 !orces................................................................................................................................... 13 .ol tion................................................................................................................................ 18 Conventions.................................................................................................................... 19 6ethin#ing...................................................................................................................... 19 Participants and 6esponsibilities.................................................................................... 90 .trategies........................................................................................................................ 90 ;.9 C 5est C ;omain ;riven..................................................................................... 90 !at P;,.................................................................................................................... 90 ;ata Bo nd P;, ..................................................................................................... 98 5esting.................................................................................................................................. 9: ;oc mentation..................................................................................................................... 90 ConseB ences....................................................................................................................... 99 6elated Patterns..................................................................................................................400 Date'ay................................................................................................................................... 404 Problem.............................................................................................................................. 404 !orces................................................................................................................................. 404 .ol tion.............................................................................................................................. 402 Conventions.................................................................................................................. 402 6ethin#ing.................................................................................................................... 402 Participants and 6esponsibilities.................................................................................. 40: .trategies...................................................................................................................... 40: .erver-.ide Date'ay...............................................................................................40: 6+A Date'ay...........................................................................................................400 )ybrid Date'ay...................................................................................................... 442 5esting................................................................................................................................ 442 ;oc mentation................................................................................................................... 448

2
Download at WoweBook.Com

ConseB ences..................................................................................................................... 448 6elated Patterns.................................................................................................................. 442 !l id 9ogic............................................................................................................................... 440 Problem...............................................................................................................................440 !orces................................................................................................................................. 440 .ol tion...............................................................................................................................440 Conventions.................................................................................................................. 449 6ethin#ing.....................................................................................................................449 Participants and 6esponsibilities.................................................................................. 449 .trategies...................................................................................................................... 420 5esting................................................................................................................................ 420 ;oc mentation................................................................................................................... 420 ConseB ences..................................................................................................................... 420 6elated Patterns..................................................................................................................424 Paginator and !ast 9ane 6eader.............................................................................................. 423 Problem.............................................................................................................................. 423 !orces................................................................................................................................. 423 .ol tion.............................................................................................................................. 423 Conventions.................................................................................................................. 423 6ethin#ing.................................................................................................................... 423 Participants and 6esponsibilities.................................................................................. 428 .trategies...................................................................................................................... 428 Paginator and Aal e 9ist )andler........................................................................... 428 Page or -verything..................................................................................................420 5able Aie'.............................................................................................................. 420 9ive C rsor and !ast 9ane 6eader..........................................................................421 5esting................................................................................................................................ 429 ;oc mentation................................................................................................................... 430 ConseB ences..................................................................................................................... 430 6elated Patterns..................................................................................................................430

:
Download at WoweBook.Com

6etired Patterns........................................................................................................................ 434 .ervice 9ocator.................................................................................................................. 434 ,riginal +ntention......................................................................................................... 434 6easons "or 6etirement.................................................................................................434 Composite -ntity................................................................................................................434 ,riginal +ntention......................................................................................................... 434 6easons "or 6etirement.................................................................................................432 Aal e ,b=ect Assembler..................................................................................................... 432 ,riginal +ntention......................................................................................................... 432 6easons "or 6etirement.................................................................................................432 B siness ;elegate.............................................................................................................. 432 ,riginal +ntention......................................................................................................... 433 6easons "or 6etirement.................................................................................................433 ;omain .tore......................................................................................................................433 ,riginal +ntention......................................................................................................... 433 6easons "or 6etirement.................................................................................................433 Aal e 9ist )andler..............................................................................................................438 ,riginal +ntention......................................................................................................... 438 6easons "or 6etirement.................................................................................................438 &. Rethinking the 'ntegration %ier............................................................................................. 432 ;ata Access ,b=ect.................................................................................................................. 430 Problem.............................................................................................................................. 430 !orces................................................................................................................................. 430 .ol tion.............................................................................................................................. 431 6ethin#ing.................................................................................................................... 431 Conventions.................................................................................................................. 439 Participants and 6esponsibilities.................................................................................. 480 .trategies...................................................................................................................... 484 Deneric ;A,.......................................................................................................... 484 ;omain-speci<c ;A,.............................................................................................482

0
Download at WoweBook.Com

Attached-res lt ;A,.............................................................................................. 482 ;etached-res lt ;A,..............................................................................................48: Bac#-end +ntegration ;A,..................................................................................... 480 Abstract ;A,......................................................................................................... 480 5esting................................................................................................................................ 480 ;oc mentation................................................................................................................... 424 ConseB ences..................................................................................................................... 424 6elated Patterns..................................................................................................................422 5rans"er ,b=ect and ;ata 5rans"er ,b=ect............................................................................... 423 Problem.............................................................................................................................. 423 !orces................................................................................................................................. 422 .ol tion.............................................................................................................................. 42: 6ethin#ing.................................................................................................................... 420 Conventions.................................................................................................................. 421 Participants and 6esponsibilities.................................................................................. 421 .trategies...................................................................................................................... 421 B ilder-style 5,......................................................................................................421 B ilder-style +mm table 5,................................................................................... 429 Client-speci<c 5,................................................................................................... 4:4 Deneric ;5,...........................................................................................................4:2 5esting................................................................................................................................ 4:0 ;oc mentation................................................................................................................... 4:1 ConseB ences..................................................................................................................... 4:1 6elated Patterns..................................................................................................................4:9 -*B 2 +ntegration and (igration..............................................................................................404 Problem.............................................................................................................................. 404 !orces................................................................................................................................. 404 .ol tion.............................................................................................................................. 404 .trategies...................................................................................................................... 408 .ingle-vendor (igration......................................................................................... 408

1
Download at WoweBook.Com

Cross-vendor (igration.......................................................................................... 408 ConseB ences..................................................................................................................... 408 5esting................................................................................................................................ 408 9egacy P,*, +ntegration.........................................................................................................400 Problem.............................................................................................................................. 400 !orces................................................................................................................................. 400 .ol tion.............................................................................................................................. 400 6ethin#ing.................................................................................................................... 401 Participants and 6esponsibilities.................................................................................. 409 5esting................................................................................................................................ 409 ;oc mentation................................................................................................................... 409 ConseB ences..................................................................................................................... 409 6elated Patterns..................................................................................................................409 Deneric *CA.............................................................................................................................414 Problem.............................................................................................................................. 414 !orces................................................................................................................................. 414 .ol tion.............................................................................................................................. 414 6ethin#ing.................................................................................................................... 493 Conventions.................................................................................................................. 493 Participants and 6esponsibilities.................................................................................. 498 .trategies...................................................................................................................... 498 5esting................................................................................................................................ 498 ;oc mentation................................................................................................................... 492 ConseB ences..................................................................................................................... 492 6elated Patterns..................................................................................................................492 Asynchrono s 6eso rce +ntegrator (.ervice Activator).......................................................... 490 Problem.............................................................................................................................. 490 !orces................................................................................................................................. 490 .ol tion.............................................................................................................................. 490 6ethin#ing.................................................................................................................... 499

9
Download at WoweBook.Com

Conventions.................................................................................................................. 200 Participants and 6esponsibilities.................................................................................. 200 .trategies...................................................................................................................... 204 !ront-end +ntegration.............................................................................................. 204 Bac#-end +ntegration...............................................................................................204 5esting................................................................................................................................ 204 ;oc mentation................................................................................................................... 204 ConseB ences..................................................................................................................... 202 6elated Patterns..................................................................................................................203 (. 'nfrastr$ct$ral Patterns and !tilities.................................................................................... 202 .ervice .tarter.......................................................................................................................... 200 Problem.............................................................................................................................. 200 !orces................................................................................................................................. 200 .ol tion.............................................................................................................................. 200 -*B 3.4.................................................................................................................... 200 Eor#aro nd "or older -*B versions........................................................................209 6ethin#ing.................................................................................................................... 240 Participants and 6esponsibilities.................................................................................. 240 5esting................................................................................................................................ 240 ;oc mentation................................................................................................................... 240 ConseB ences..................................................................................................................... 240 6elated Patterns..................................................................................................................240 .ingleton.................................................................................................................................. 244 Problem...............................................................................................................................244 !orces................................................................................................................................. 244 .ol tion...............................................................................................................................244 6ethin#ing.................................................................................................................... 242 Participants and 6esponsibilities.................................................................................. 242 .trategies...................................................................................................................... 242 Date#eeper.............................................................................................................. 242

40
Download at WoweBook.Com

Caching .ingleton................................................................................................... 243 5esting................................................................................................................................ 248 ;oc mentation................................................................................................................... 248 ConseB ences..................................................................................................................... 248 6elated Patterns..................................................................................................................242 Bean 9ocator............................................................................................................................ 240 Problem.............................................................................................................................. 240 !orces................................................................................................................................. 240 .ol tion.............................................................................................................................. 240 6ethin#ing.................................................................................................................... 224 Participants and 6esponsibilities.................................................................................. 224 .trategies...................................................................................................................... 222 5esting................................................................................................................................ 222 ;oc mentation................................................................................................................... 222 ConseB ences..................................................................................................................... 222 6elated Patterns..................................................................................................................222 5hread 5rac#er......................................................................................................................... 222 Problem.............................................................................................................................. 222 !orces................................................................................................................................. 222 .ol tion.............................................................................................................................. 222 6ethin#ing.................................................................................................................... 22: Participants and 6esponsibilities.................................................................................. 220 5esting................................................................................................................................ 220 ;oc mentation................................................................................................................... 221 ConseB ences..................................................................................................................... 221 6elated Patterns..................................................................................................................229 ;ependency +n=ection ->tender............................................................................................... 234 Problem.............................................................................................................................. 234 !orces................................................................................................................................. 234 .ol tion.............................................................................................................................. 234

44
Download at WoweBook.Com

6ethin#ing.................................................................................................................... 233 Participants and 6esponsibilities.................................................................................. 233 .trategies...................................................................................................................... 238 .tate" l .ession Bean +n=ector................................................................................ 238 .tateless .ession Bean +n=ector...............................................................................238 5ransactional +ntegration........................................................................................ 238 5esting................................................................................................................................ 238 ;oc mentation................................................................................................................... 238 ConseB ences..................................................................................................................... 232 6elated Patterns..................................................................................................................232 Payload ->tractor.....................................................................................................................230 Problem.............................................................................................................................. 230 !orces................................................................................................................................. 230 .ol tion.............................................................................................................................. 230 6ethin#ing.................................................................................................................... 280 Participants and 6esponsibilities.................................................................................. 284 .trategies...................................................................................................................... 284 5esting................................................................................................................................ 284 ;oc mentation................................................................................................................... 284 ConseB ences..................................................................................................................... 282 6elated Patterns..................................................................................................................282 6eso rce Binder.......................................................................................................................283 Problem.............................................................................................................................. 283 !orces................................................................................................................................. 283 .ol tion.............................................................................................................................. 283 6ethin#ing.................................................................................................................... 288 Participants and 6esponsibilities.................................................................................. 282 .trategies...................................................................................................................... 282 5esting................................................................................................................................ 282 ;oc mentation................................................................................................................... 28:

42
Download at WoweBook.Com

ConseB ences..................................................................................................................... 28: 6elated Patterns..................................................................................................................28: Conte>t )older.........................................................................................................................280 Problem.............................................................................................................................. 280 !orces................................................................................................................................. 280 .ol tion.............................................................................................................................. 280 6ethin#ing.................................................................................................................... 281 Participants and 6esponsibilities.................................................................................. 289 .trategies...................................................................................................................... 289 5ransaction.ynchroni?ation6egistry .trategy........................................................289 5hread9ocal .trategy..............................................................................................289 5esting................................................................................................................................ 224 ;oc mentation................................................................................................................... 224 ConseB ences..................................................................................................................... 224 6elated Patterns..................................................................................................................222 ). Prag*atic Java EE Architect$res.......................................................................................... 223 Premat re -ncaps lation +s the 6oot o" All -vil..................................................................... 223 -ntity Control Bo ndary (-CB) F 5he 9ean Eay................................................................... 223 9ean .ervice-,riented Architect res....................................................................................... 222 5he -ssential +ngredients o" .,As.................................................................................... 222 5he -ssential Comple>ity o" .,As................................................................................... 22: .eparation o" Concerns$ or ;ivide and ConB er................................................................221 ;omain ,b=ects or .tr ct resG................................................................................................ 229 5hin#ing Abo t +nternal .tr ct re..................................................................................... 2:0 ;A,s% ;ead or AliveG....................................................................................................... 2:4 A small pattern lang age "or .,A..................................................................................... 2:2 A to ch o" pragmatism....................................................................................................... 2:8 As 9ean as Possible$ b t /ot 9eaner..................................................................................2:2 ,b=ects- or ;omain-;riven ;esign......................................................................................... 2:2 5he -ssential +ngredients o" ;omain-;riven ;esigns.......................................................2:2

43
Download at WoweBook.Com

5he -ssential Comple>ity o" ;omain-;riven ;esigns......................................................2:: (onolithic or 9oosely Co pledG........................................................................................2:0 A .mall Pattern 9ang age "or ;omain-driven Components..............................................2:9

48
Download at WoweBook.Com

0
Preface

(ost o" the *ava -- 2 pro=ects #eep sing the old$ s perH o s *2-- patterns and best practices. *2-'as intr siveIthe separation o" the technical in"rastr ct re and b siness logic reB ired the introd ction o" patterns, 'hich 'ere mostly 'or#aro nds "or the *2-- shortcomings. +Jm "reelance coding architect$ 'or#ing on the architect re$ design$ and implementation o" enterprise applications. Eith the advent o" *ava -- 2$ + 'as able to remove a remar#able amo nt o" patterns$ indirections$ and layersI'itho t sacri<cing the " nctionality. -ven tho gh + mostly deleted only s perH o s code$ my clients 'ere delighted by the res lts. + sometimes give trainings and 'or#shops abo t vario s *ava$ *ava !K$ and *ava -- topics. Ee 'ere able to c t prod ction time in hal" 'ith *ava -- 2 "or comparable tas#s$ 'itho t strange 'or#aro nds and patternsIit is a really good prod ctivity indicator. 5he *ava 7ser Dro p )amb rg invited me in (ay 2001 to tal# abo t a *ava -- 2 topic at 9ehmannJs boo#store in )amb rg Lhttp%CC'''.lob.deM. + s bmitted a tal# 'ith the title% NPragmatic Java EE 5 Hacking: Rethinking Best Practices with code/deployment / demos and few slides O Lhttp%CC'''.adambien.comCrollerCabienCentryC"reeP= gPsessionPpragmaticP=avaM. (ore attendees came$ than + ever e>pected. 5he tal# 'as s pposed to last abo t one ho rI+ 'as done a"ter abo t <ve ho rs$ incl ding an open-ended$ disc ssion.

.omeone mentioned d ring the tal#$ Nyo sho ld 'rite a boo# abo t that.O + 'as able to get ,J6eilly interested in the topic d ring a podcast at the *ava,ne 2001 con"erence$ b t p blication 'o ld have been de"erred to 2040$ so + decided to sel"-p blish the boo#% http%CCpress.adam-bien.com.

Download at WoweBook.Com

5he goal o" this boo# is to B estion already established *2-- best practices and disc ss the alternatives 'ith 'or#ing code. Cha"ter 1$ A Brief History of J EE and Cha"ter +!nderstanding Java EE Core Conce"ts+ introd ce yo to the *ava -- 2 'orld and help dispel some o" the misconceptions aro nd *ava -- 2. Qo 'ill learn abo t common principles s ch con<g ration by e>ception$ ;ependency +n=ection$ interceptors$ *PA and -*B "eat res. + even started 'ith a brie" *ava -- history to e>plain the m lti-vendor *ava -- origins and the reason "or the variety o" available AP+sItopics that have been part o" my past tal#s. +" yo are a *ava -- savvy developer$ yo can s#ip Chapters 4 and 2 and start 'ith Chapter 3. Cha"ter #+ Rethinking the B$siness %ier+ "oc ses on patterns "or the b siness tier. .erviceoriented as 'ell as domain driven patterns and best practices are disc ssed 'ith many aspects$ variants and strategies. Beca se o" Nrethin#ingO + 'ill not only introd ce "resh ideas li#e integration o" scripting " nctionality 'ith *.6-223 into -*Bs or state" l gate'ays 'ith NopenO -ntity(anager$ b t also retire the ma=ority o" the *2-- patterns. Cha"ter &+ Rethinking the 'ntegration %ier+ disc sses some controversial patterns li#e ;ata Access ,b=ect or ;ata 5rans"er ,b=ect $ -*B 2 to -*B 3 migration strategies and even a generic *ava Connector Architect re (*CA) implementation. Cha"ter (+ 'nfrastr$ct$ral Patterns and !tilities+ describes niversal patterns$ that cannot be niB ely associated 'ith a partic lar layer. Qo 'ill <nd crossc tting " nctionality li#e e>tensions o" ;ependency +n=ection (e.g. D ice integration)$ */;+ loo# ps $ singleton implementation$ start p services$ additional monitoring tilities (thread trac#ing$ precondition chec#s) 'hich can be applied to any layer. Cha"ter )+ Prag*atic Java EE Architect$res+ s mmari?es the pattern lang age and combines the patterns into t'o opposite con<g rations$ service-oriented and domaindriven architect re. +n an enterprise conte>t$ ho'ever$ nothing is simple blac# and 'hite. Qo 'ill have to <nd a pragmatic 'ay in bet'een the t'o e>tremes to prod ce e"<cient$ lean$ and clean code.

+Jve sed these patterns in recent pro=ects 'itho t consistent naming. +n the ma=ority o" pro=ects$ disc ssion started 'ith architects$ designers$ and sometimes developers and 'e ended 'ith another name pointing to the same old de<nition. As long as the name o" a pattern in a pro=ect$ or even company is consistentIitJs <ne. 5he patterns "acilitate the comm nication and ma#e the doc mentation leaner. + open so rced all the e>amples at #enai.comIa really interesting collaboration plat"orm% http%CC#enai.comCpro=ectsC=avaee-patterns. 5he main motivation behind this boo# 'as "orcing mysel" to re-implement concepts "rom my pro=ects in a b siness logicne tral 'ay (and 'itho t the /;A restrictions) and learning ne' approaches. + can se them no' in my 'or#shops and training as 'ell. ; ring the process o" 'riting$ + got some better ideas and re"actored some patterns and reintrod ced them bac# into my pro=ects. +Jm al'ays open "or "eedbac# and disc ssionIto learn

4:
Download at WoweBook.Com

"rom yo $ the reader. * st drop me an email (abien@adam-bien.com) and +Jll be s re to incorporate them in a " t re pdate o" the boo#. Also$ #eep an eye on my blog (http%CCblog.adambien.com) 'here + 'ill contin e to cover the topics disc ssed in this boo#. .pecial than#s to my 'i"e &inga "or the great cover (altho gh the colors 'ere my ideaIshe didnJt li#e them)$ my technical revie'er Patric# "or technical revie'$ and -ileen Cohen "or pointing me to my editor$ (ichael &och ('''.m#p b.com)$ 'ho helped me clean p my man script$ c t red ndancies$ and eliminate my NDerman-isms.O Adam Bien

-n ro te "rom ( nich to )amb rg$ * ne 2009

40
Download at WoweBook.Com

Download at WoweBook.Com

1
A Brief History of J2EE

+" yo Rre ne' to *ava Plat"orm$ -nterprise -dition or *ava --$ yo might be 'ondering abo t the plat"ormRs comple>ity and AP+s. 5he *ava -- plat"orm is not the prod ct o" a single companyS it is an abstraction o" many established prod cts$ libraries$ and "rame'or#s. +n "act$ distrib ted comp ting$ not *ava --$ ma#es o r daily 'or# so challenging. !or a better nderstanding o" 'hatRs behind the history o" *ava --$ + 'ill start 'ith its history and e>plain the basics o" synchroni?ation and transactionsthe basics o" o r distrib ted 'orld. +" yo are a *ava -- e>pert and already #no' the advantages o" transaction management$ isolation levels$ and conc rrency control$ yo can sa"ely s#ip this chapter.

%he Rise and ,all of A""lets


5he beginnings o" *ava -- can be traced bac# to the introd ction o" *ava applets in the <rst *ava release in 4992. Ehen /etscape introd ced s pport "or applets in its /etscape /avigator bro'ser in the mid4990s$ *ava B ic#ly gained in pop larity. -verything 'as t rned into applets$ even simple static pages became animated. Altho gh applets B ic#ly gained in si?e and became more sophisticated$most o" their " nctionality 'as handled on the bac# end$ ma#ing client server comm nication essential "or even simple operations. 5he introd ction o" 6emote (ethod +nvocation (6(+) in the *ava ;evelopment &it (*;&) 4.4 at least addressed the need "or a transparent client-server comm nication$ b t it didnRt solve it entirely. *ava ;atabase Connectivity (*;BC)$ also introd ced in *;& 4.4$ "acilitated the implementation o" lo'level access to relational databases and even helped control local transactions. .everal applets shared a single$ remote server instance$ 'hich accessed the database sing *;BC. And thatRs 'hen things became problematic. 6(+ code isnRt thread-sa"e. ,nly one instance o" the UnicastRemoteObject 'as bo nd to a partic lar port$ 'hich 'as shared among di""erent sers or threads. 5his instance 'as act ally a distrib ted singleton and maintained the connections to the database as 'ell. ;atabase transactions co ld only be managed sing the partic lar java.sql.Connection instanceS the *ava 5ransaction AP+ (*5A) had yet to be 'ritten. Access to the shared connection had to be seriali?ed to ens re consistency$ b t demand "or scalability increased signi<cantly at the same time.

Download at WoweBook.Com

By the time the bro'ser 'ars 'ere in " ll s'ing$ it became signi<cantly harder to b ilt crossbro'ser applets. Pro>y servers and <re'alls 'ere not *ava 6emote (ethod Protocol (*6(P) "riendlyIcomm nication problems bet'een applets and the bac# end 'ere common. 5he advent o" a ne' architect ral paradigm$ the ltra!thin client (75C)$ co pled 'ith an increasing n mber o" incompatible *;& versions$ o"ten "rom di""erent vendors$ contrib ted to the demise o" applets.

%he !%C Paradig*- .oving Beyond A""lets


5he basic idea behind the 75C 'as as simple as it 'as radical% movethe entire b siness logic to the server and limit the clientRs responsibilities to presentation logic and ser interaction. 5he introd ction o" the .ervlet AP+ andthe *ava Eeb .erver (*E.)$ the prec rsor o" an application server$ in 4990 'ere intended as the 75C bac#bone. .ervlets$ altho gh not thread-sa"e$ 'ere m ltithreaded and able to dynamically generate )5(9 o tp t. C rio sly$ the ser inter"ace o" the *E. admin console 'as implemented sing applets. ;atabase access 'as still implemented sing plain *;BC. 5he association o" ser reB est and its transaction became important again "or database consistency. (ost applications sed the java.sql.Conneciton#setAutoCommit(true) strategy to start a ne' transaction "or every single statement. A ser reB est initiated a series o" <ne-grained$ independent transactions. 5his approach is comparable to not having transactions at all$ beca se other sers (transactions) 'ere able to see immediately all the changes per"ormed inside a parallel 'eb reB est. As long as the application 'as only seB entially nit tested ('hich 'as not common then neither ) in a single thread$ everything 'or#ed = st <ne. 5ro ble started d ring integration tests i" not in prod ction. .erver crashes o"ten led to inconsistent or corr pted databases. +t 'as hard to provide a reasonable level o" isolation bet'een di""erent transactions. -ven ser actions inter"ered nder load. 5he introd ction o" -nterprise *avaBeans (-*B) technology and the *ava 5ransaction AP+ (*5A) aro nd 4990C91 helped ma#e transactions more logical or b siness-oriented.

EJB- 'ntrod$cing Consistency


5he -*B AP+ is a server-side component model. An -*B 4.02." consists o" a *ava class (the Bean class)$ one "actory inter"ace (the home) and the remote inter"ace (the remote vie'). Clients are able to access the -*B remotely via Common ,b=ect 6eB est Bro#er Architect re (C,6BA). An applet co ld access an -*B instead o" the 6(+ server. 5his o"ten nderestimated "eat re$ ho'ever$ 'as the sol tion "or the conc rrency and consistency problems. Beca se -*Bs are al'ays e>ec ted in a dedicated thread$ they appear as single-threaded to the developer. !or every thread (that is$ ser reB est or transaction) a ne' -*B instance is created (or re sed "rom the pool)Ithere is no shared state bet'een calls. 5he -*B speci<cation even prohibits the se o" the synchroni?ation primitives and threading " nctionality inside session beans. 5he programming model is rather proced ral (sometimes also re"erred to as service oriented). 5he methods o" a stateless session bean (..B) process some inp t data and give it bac# to the caller. -ven state" l session beans (.!.B) do not bra#e the r leIthe container still prohibits conc rrent

20
Download at WoweBook.Com

access to a state" l instance. Beca se an ..B can only be e>ec ted in a single thread$ yo do not have to care abo t thread synchroni?ation either. 5he single-threaded programming model combined 'ith declarative transactions solved the inconsistency problem as 'ellno' the database connection can be accessed only by a single thread at a time. 5he -*B container starts a transaction be"ore a bean method is invo#ed. 5he implementation o" the method is e>ec ted in an atomic manner. -ither every single step is s ccess" l and the coarse-grained transaction committed$ or it is going to be = st rolled bac#. 5he container manages the transactional reso rces "or yo . !or e>ample$ only one database connection is ret rned to the caller inside a transaction$ even 'hen it is reB ested several times "rom the connection pool. 6elational databases 'ere not the only -nterprise +n"ormation .ystems (-+.). (essage-oriented middle'are ((,()$ -6P systems 'ith proprietary inter"aces$ and even monolithic systems 'itho t any p blic inter"aces had to be seamlessly integrated. ,n the legacy hosts$ servers s ch as (T .eries or B-A 5 >edo contin e to be sed "or asynchrono s comm nication (messaging). (essaging is o"ten also introd ced = st "or the deco pling p rposes bet'een prod cer and cons mer. Applets$ -*Bs$ and .ervlets operate according to the reB est-response comm nication style. 5he client invo#es an -*B method and 'aits ntil the response is received. 5he proced ral programming model is convenient$ b t messaging appears to be even more intrig ing. 5he messaging AP+s are indeed simple. 5he hot spots are error handling and proper transaction control. +tRs impossible to send a reB est and receive the response in a single transaction and it is also hard to deal 'ith syntactical incorrect messages. Both problems donRt e>ists in the proced ral$ type-sa"e comm nication$ b t have to be addressed in message-oriented architect res.

J./- A .essaging /yste* of 'ts 01n


Altho gh messaging 'as heavily sed on the bac# enda standard *ava AP+ did not e>ist at that time. +n 4991 the *ava (essaging .ystem (*(.) AP+ 'as introd ced. +t 'as to a high degree inH enced by the +B( (T .eries prod ct$ b t the AP+ itsel" is vendor-ne tral. 5he *(. AP+ remained largely nchanged ntil today. +n parallel the prod ct /ovell ;irectly .ervices (/;.)$ integrated 'ith the operating system /et'are ('ith applet-based admin console)$ p shed the standardi?ation o" directory accessS the *ava /aming and ;irectory +nter"ace (*/;+) 'as born. +t 'as mainly sed as an 9;AP abstraction$ "or a thori?ation and a thentication p rposes. .ervlets$ *(.$ */;+$ *5A$ and -*B 'ere " lly independent speci<cationsavailable in di""erent releases and versions. 5he available application servers combined those specs 'ith di""erent versions$ 'hich made porting an application a nightmare. -ven 'orse$ portable K(9 deployment descriptors 'erenRt even invented yet. 5he -*B 4.0 deployment descriptor 'as a seriali?ed *ava class. +t 'as hardly possible to port an application "rom one application server to another. 5he problem 'as not the code$ b t the portability o" the server-speci<c con<g ration.

24
Download at WoweBook.Com

J EE- A 2e1 /tandard 's Born


5he introd ction o" *ava 2 -nterprise -dition (*2--) in late 4999 solved the incompatibility iss es. All AP+s 'ere b ndled nder a common name and the application server vendors had to certi"y their prod cts. 5he *2-- 4.2 release incl ded the "ollo'ing AP+s% Servlets 2.2 Java ServerPages (JSP) . Enter!rise JavaBeans . J"B# 2.$ R%&'&&(P .$ Java %essage Service .$ Java )a*ing and "irectory &nterface .2 Java +ransaction AP& .$ Java%ail .

B ndling the AP+ into one consistent release improved the compatibility story slightly. At least yo co ld rely on the e>istence o" a standardi?ed set o" AP+s. 5he development e>perience$ ho'ever$ 'as "ar "rom being per"ect. 5he developer had not only to rely on the lo'est common denominator$ the AP+s le"t too m ch room "or interpretation. 5he -*B 4.4F2.0$ and especially the entity beans 'ith container-managed persistence 2.0 (C(P 2.0) 'ere nderspeci<ed. +mportant "eat res s ch as pool settings$ isolation levels$ loc# behavior$ generation o" primary #eys and so on 'ere not speci<ed. 5he application server vendors had to e>tend the " nctionality o" the common core. !or this p rpose$ in addition to the standard deployment descriptors$ " rther con<g ration 'as added. 5he 'rite once$ r n any'here (E,6A) idea o" the *2-- plat"orm 'as less and less practicable. Altho gh the compiled application ran on di""erent application servers 'itho t change or recompilationthe reali?ation o" the b siness logic 'as highly dependent on the proprietary e>tensions o" a partic lar application server. 5hese e>tensions 'erenRt standardi?ed$ the con<g ration 'as very di""erent and the applications hard to migrate. +t too# a considerable amo nt o" reso rces to migrate and test the b siness logic in a migration pro=ect. 5here 'ere h ge di""erences bet'een the non" nctional aspects s ch as cl stering or "ail over. ! rthermore the -*B spec 'as not very concise and didnRt "ollo' the NdryO (donRt repeat yo rsel") principle. 5he in"ormation abo t an -*B component 'as spread across a remote inter"ace$ home inter"ace$ the Bean class and the deployment descriptor. 6e"actoring 'as very nprod ctive and tedio s 'itho t tools$ and the +;-s 'erenRt very good in re"actoring at that time. 5he deployment descriptors had to be #ept in sync 'ith the code as 'ell. -ven 'hen implementing simple tas#s$ developers had to deal 'ith a considerable amo nt o" overhead. 5he Bean class had to implement the javax.ejb.SessionBean inter"ace and "orced the implementation o" all li"e cycle methods. 5he ejbActivate and ejbPassivate methods 'ere only invo#ed in state" l session beans$ altho gh most o" the deployed session beans 'ere stateless%

22
Download at WoweBook.Com

public class public public public public public

ello!orl"Bean implements SessionBean # setSessionContext(SessionContext aContext) # ejbCreate() #$ ejbActivate() #$ %%S&SB onl' ejbPassivate() #$%%S&SB onl' ejbRemove() #$ $

voi" voi" voi" voi" voi"

public void sayHello() { System.out.println("Hello!"); } $

5he b siness method$ sa' ello$ is = st a "raction o" the overall code. 5his method 'as declared in an inter"ace as 'ell%
public inter(ace ello!orl"Remote exten"s )*BObject # voi" sa' ello() t+ro,s Remote)xception$

-very method had to thro' a (chec#ed) Remote)xception. 5his inter"ace 'as not directly implemented by the Beanthe compiler 'as not able to chec# the signat res 'hich led to "reB ent deployment errors. . ch deployment errors 'ere hard to <nd and it increased signi<cantly the ro nd trip times. +n addition to the code$ a deployment descriptor had to be provided. 5he K(9 deployment descriptor 'as the gl e "or all the disparate parts already e>isting in"ormation had to be repeated again in this place. +n a 'orst-case scenario$ even the signat re o" the method 'as listed in the descriptor$ as sho'n in the "ollo'ing e>ample%
.ejb/jar0 ."ispla'/name0 ello!orl")*B.%"ispla'/name0 .enterprise/beans0 .session0 ."ispla'/name0 ello!orl"SB.%"ispla'/name0 .ejb/name0 ello!orl"Bean.%ejb/name0 .+ome0...+ello,orl". ello!orl"Remote ome.%+ome0 .remote0...+ello,orl". ello!orl"Remote.%remote0 .ejb/class0...+ello,orl". ello!orl"Bean.%ejb/class0 .session/t'pe0Stateless.%session/t'pe0 .transaction/t'pe0Container.%transaction/t'pe0 .%session0 .%enterprise/beans0 .assembl'/"escriptor0 <container-transaction> <met od> <e!b-name>Hello"orld#ean<$e!b-name> <met od-name>sayHello<$met od-name> <$met od> <trans-attribute>%e&uires'e(<$trans-attribute> <$container-transaction> .%assembl'/"escriptor0 .%ejb/jar0

23
Download at WoweBook.Com

5he descriptor 'as intended to be created by the developer$ e>tended by the assembler and <ne t ned by the deployer. +n practice it 'as rarely the case. +n general the developer 'as responsible "or the 'hole process. -ven settings li#e transactions$ state management$ or remoting 'ere stable and didnRt change "reB ently. Eithin an enterprise conte>t$ the K(9 descriptors 'ere created once and never to ched again (at least "or con<g ration p rposes). +n most cases$ a proprietary descriptor 'as reB ired as 'ellit 'as highly vendor dependent. 5he last reB ired inter"ace 'as the "actory$ )*B ome. +t 'as the entry point to the remote inter"ace%
public inter(ace ello!orl"Remote ome exten"s )*B ome # t+ro,s Create)xception1 Remote)xception-

ello!orl"Remote create() $

-ven "or simple logic$ the developer had to create and maintain all the reB ired in"rastr ct ral arti"acts. 5he b siness code 'as highly dependent on the -*B AP+. 5he separation bet'een the " nctional reali?ation and the plat"orm 'as not given. (any patterns$ idioms$ and indirections 'ere introd ced= st to encaps late an nstable in"rastr ct re. Altho gh session beans 'ere verbose and the programming harder than necessary$ the additional bene<t 'as h ge. 6emoting$ single-threaded programming model$ state management$ transaction$ and conc rrency control co ld be applied declaratively$ 'itho t any coding. /onetheless$ session beans are transient components 'itho t direct s pport "or persistency.

JavaBlend
-ven be"ore the advent o" *2--$ or even -*B$ aro nd 4991$ the *avaBlend prod ct 'as introd ced to simpli"y ob=ect-relational mapping. +t 'as very ambitio s% ,;(D 2.0 compliance 'ith ,b=ect T ery 9ang age (,T9) s pport. *avaBlend aimed "or the elimination o" the ob=ect-relational impedance mismatch. -ven vis al tool s pport 'as provided to map the ob=ects to relational tables and design dependencies. 5he persistent classes 'ere act ally plain old *ava ob=ects (P,*,s)$ 'ith only "e' dependencies on the *avaBlend AP+. 5he programming model 'as very similar to *ava ;ata ,b=ects (*;,) and reB ired post-processing o" the byte code. +t 'as mainly motivated by per"ormance optimi?ation. +nterestingly eno gh$ the *avaBlend programming model 'as very similar to todayRs *ava Persistence AP+ (*PA). 7n"ort nately$ neither *avaBlend nor *;, made it into the *2-- spec. -ntity beans 'ith beanmanaged persistence (B(P) as 'ell as C(P 'ere introd ced instead. ++n contrast to the cleaner *;, and *avaBlend AP+s$ C(P entities 'ere highly dependent on the plat"orm. 5he programming model 'as resembled that o" session beans$ rather than the ob=ect-oriented P,*,s. 5he developer had to provide the same arti"acts as "or the development o" session beans$ namely% the remote$ home$ inter"aces$ and bean classes and the deployment descriptor. +n the <rst container-managed persistence (C(P) version (in -*B 4.4) persistent entity beans 'ere intended to be accessed remotely. Beca se entity beans 'ere active enterprise beans$ they 'ere also able to handle the transactions. 5his 'as the biggest misconception$ 'hich lead to chattiness and inconsistency. +n a

28
Download at WoweBook.Com

'orst-case scenario$ every <ne-grained getter or setter ca sed a ne' transaction. 5his "act 'as also the reason "or the introd ction o" many best practices$ s ch as .ession !a@ade. +n partic lar the problem o" in"ormation d plication and the lac# o" encaps lation o" the technical details$ inspired the comm nity to thin# abo t the alternatives. )ibernate 'as created as a po'er" l and lean alternative "or the c mbersome *2-- persistence. +n contrast to the C(P entity beans$ )ibernate 'as P,*,-based and ob=ect-oriented$ and it s pported polymorphic B eries. 5he *avaBean-based .pring "rame'or# encaps lated e""ectively the in"rastr ct re and introd ced a concept called #ependency $n%ection . 5he mi> o" these "rame'or#s became very pop lar. +t 'as o"ten sed as a viable alternative to the o"<cial *2-- stac#.

3ooking Beyond Java EE


*ava -- 'as introd ced in 200:$ a"ter a long period o" debates and dra"ts. +t ma#es intensive se o" *ava .- 2 "eat res$ incl ding annotations$ generics$ and en ms. *ava -- 2 persistence 'as highly inH enced by )ibernate. Davin &ing$ the "o nder o" )ibernate$ participated in the *PA ->pert Dro p. 5he ;ependency +n=ection (;+) pattern and the convention over con<g ration principle inspired by the 6 by on 6ails "rame'or# also inH enced the speci<cation. *ava -- 2 revol tioni?ed session beans and introd ced a viable replacement "or the entity beans$ the *ava Persistence AP+ (*PA). /onetheless the remaining AP+s$ especially *5A$ *(.$ */;+$ and .ervlets$ 'ere le"t nchanged. 5he -*B 3 programming model 'as totally re" rbished. All the red ndant$ in"rastr ct ral pl mbing became optional. +n "act$ the entire co pling to the in"rastr ct re 'as removed. 5o provide the same " nctionality as in -*B 2.4$ only one b siness inter"ace and a bean class are needed. 5he only dependency on the AP+ is the se o" the annotations 2Stateless on the class$ and 23ocal on the inter"ace. /o deployment descriptors are necessary. )o'ever$ they can still be sed to override the settings provided by the annotation. 5he b siness inter"ace is = st a s al *ava inter"ace. /o chec#ed e>ceptions on methods$ or inheritance "rom technically motivated inter"aces (s ch as )*BObject) are necessary%
2Remote public inter(ace ello!orl" # public voi" sa' ello()$

5he bean class directly implements this inter"ace$ 'hich allo's the compiler to veri"y the method signat re again. (ost o" the errors can th s be recogni?ed d ring the compilation and not at deployment time. ! rthermore$ it becomes "airly easy to deploy common P,*,s as -*B 3 components.
2Stateless public class ello!orl"Bean implements public voi" sa' ello() # S'stem.out.println(4 ello54)$ $ ello!orl" #

22
Download at WoweBook.Com

5he transaction management does not have to be speci<ed$ Container-managed transactions (C(5) 'ith the Require" attrib te is the de"a lt. 5he principle convention over con<g ration goes even " rther and ma#es premat re con<g ration s perH o s. + 'ill cover the core *ava -- 2 concepts in Chapter 2 in greater detail.

.erver-side *ava% 5he Core Principles


5he essential comple>ity in *ava -- is ca sed by its distrib ted nat re. A common *ava -application consists o" at least "o r$ o"ten distrib ted$ layers% The browser: &t renders the data and caches the ,ser in!,t in hidden fields or even JavaScri!t o-.ects. &t is res!onsi-le for synchrono,s and asynchrono,s co**,nication /ith the -ack end. The presentation: &t is ,s,ally the /e- container. +he ,ser interface can -e generated -y JS0 or other alternative fra*e/orks s,ch as We- Beans1 2oogle We- +oolkit1 Wicket1 +a!estry1 or *any others. #lient's!ecific o-.ects1 s,ch as -acking -eans in JS01 are ,sed in the /e- container for caching and transfor*ation !,r!oses. The business container: +his can -e an EJB1 2,ice1 S!ring1 or another container. EJB 3 co*es /ith a Java EE 4 co*!liant server. A -,siness container is *ainly res!onsi-le for kee!ing the consistency1 hosting the -,siness logic1 and !roviding !ersistence services. &t caches the JPA entities1 at least for the !eriod of a transaction. +he -,siness container is transactional and synchroni5es the cached state /ith the data-ase. &n case *essaging or access to legacy services is ,sed1 the container has to synchroni5e and coordinate s,ch transactional reso,rces as /ell. The undefined back end: &f yo, are l,cky1 yo, have to access only a standard1 relational data-ase via J"B#. &n this !artic,lar case1 yo, can rely on standard Java EE !ersistence1 JPA. &n other cases1 the -ack end consists of heterogeneo,s syste*s1 services1 and interfaces. %ost of the syste*s are not accessed -y the Java EE server e6cl,sively1 /hich *akes caching and data synchroni5ation es!ecially challenging.

-very layer ses$ trans"orms$ and caches the data. 5he bro'ser even relies on another lang age*ava.cript "or that p rpose. 5he main challenge o" every distrib ted system is to #eep all the data synchroni?ed and consistent. -ven i" yo r *ava -- architect re is simplistic and only consists o" one single -*B 'ith a persistent *PA entity$ yo 'ill have to deal 'ith the data distrib tion and synchroni?ation in these layers. An additional problem is the massive parallel nat re o" a *ava -- application. (any sers can access the same$ also cached$ reso rce or entity at the same time in parallel. *ava -- applications are m ltithreaded by nat re and r n on m ltiprocessor$ m lticore hard'are. +n addition$ a *ava -- application is o"ten cl steredS it r ns on di""erent application servers in a cl ster$ and th s *A( instances at the same time. +t can be especially challenging "or components 'ith a conversational state or persistence. 5he state has to be distrib ted or replicated bet'een nodes in a consistent manner. ;i""erent mechanisms are available to overcome the problem o" data distrib tion. (ost o" the c rrently available application servers rely on synchrono s or asynchrono s replication$ cache

2:
Download at WoweBook.Com

invalidation$ and so called sticky sessionsS the caller ret rns over and over again to the same cl ster node 'ith an e>isting state" l component. (ost o" the reso rces yo access ("or e>ample$ )ntit'6ana7er) are not even thread-sa"e. 5he sol tion to the problem is older than *ava itsel"transactions.

5he Case o" 5ransactions


A transaction is b t a nit o" 'or#. 6egardless o" 'hether a transaction is s ccess" l it has to remain atomic. +n a *ava -- environment$ a transaction is associated 'ith a thread'hich means everything that is synchrono sly invo#ed "rom the entry point is invo#ed in the transaction scope. Qo only have to con<g re the transactions properly. 5he rollbac# o" the transaction ca ses the rollbac# o" all reso rces accessed in the partic lar thread. 5he problem starts 'ith the introd ction o" the transient state. -ven .ervlets are not thread-sa"e$ so that access to the ttpSession has to be synchroni?ed. 5he synchroni?ation is already solved by many available 'eb "rame'or#s. !or e>ample$ *.! already manages a state" l bac#ing bean "or yo . 5he real problem comes 'ith persistent state. /o' yo not only have to synchroni?e access to a persistent reso rce$ b t also have to decide 'hen the state o" yo r persistent entity has to be 'ritten bac# to the database. ,nly then yo r changes 'ill be visible to other transactions and sers. -ven in a very simple create$ read$ pdate$ and delete (C67;) application$ m ltiple transactional reso rces are involved. !irst a *PA entity is created$ passed to a session bean$ and persisted sing an in=ected (+ 'ill cover in=ection later) )ntit'6ana7er instance. )o'ever$ the )ntit'6ana7er is not the database$ it is only responsible "or the ob=ect-relational mapping. +n step 4$ it only stores the entity bean internally and then 'aits ntil the end o" the transaction. ,nly a"ter the transaction commits s ccess" lly$ does the )ntit'6ana7er H sh its state to a relational database sing a 8ataSource and the java.sql.Connection. 5he database transaction is committed by the container. +t commits not only the single database transaction$ b t all other reso rces as 'ell (incl ding *(.$ other databases$ legacy and connections). As long as yo have a re"erence to an attached entity and yo are inside a transaction$ yo can change the state o" the entityand yo 'ill see the changes a"ter the commit%
2Stateless public class Boo967rBean implements Boo967r # %%injecte" b' t+e container 2PersistenceContext private )ntit'6ana7er em%%transaction be7in public voi" create(Boo9 boo9) # em.persist(boo9)boo9.set8escription(4ne, state4)- %%visible in t+e 8B $ %%transaction commit

20
Download at WoweBook.Com

+n a *ava -- environment$ a transaction is 'ider scoped than = st a single reso rce access s ch as java.sql.Connection. 5his lets yo invo#e several methods in the -*B container 'ithin a transaction and modi"y several *PA entities in an atomic 'ay. At the end o" this activity$ all yo r modi<cations in all session beans per"ormed in the scope o" the transaction (or reB estCthread) are H shed to the bac#-end reso rces. -verything that is going to be e>ec ted synchrono sly (in the same thread)$ inherits the transaction and involves (enlists) its reso rces to the transaction. 5he application server acts as a transaction coordinator 'hich starts a transaction$ be"ore even accessing a bac#-end reso rce. 5he application server accesses each reso rce and manages the transactions "or yo . +n case something in the process goes 'rong$ it is going to roll bac# all involved reso rces. 5ransactions are even se" l in a single-threaded application <ne-grained operations can be gro ped into logical nits and e>ec ted all at once atomically. Admittedly transactions 'ere not created "or gro ping related activities into logical ch n#s in a singlethreaded environment. 5hey are especially essential in m ltithreaded environments.

5he Conc rrency Problem


A *ava -- application server is designed to be e>ec ted in a m ltithreaded 'ay. !or this reason yo r application 'ill have to deal 'ith parallel access to a transactional reso rce. +n general$ it is a good idea to #eep the local changes hidden ntil all changes are per"ormed consistently and s ccess" l. ,ther'ise another thread (that is$ the ser) 'o ld see the hal"-per"ormed logical transaction and rely on its o tcome. +t becomes problematic in case the <rst transaction enco nters a problem and is going to be rolled bac#. 5his 'o ld be "atala dependent transaction may already rely on the res lt and per"orm its o'n independent nit o" 'or#. * st imagine an order-processing system. 5he order sho ld only be shipped$ in case the c stomer con<rmed the order$ his credit card 'as charged$ and the prod ct is in stoc#. -ven i" the shipment is triggered by the con<rmation$ the con<rmation sho ld only be visible "or other threads a"ter the credit 'as charged and the prod ct chec#ed o t "rom stoc#. +t is a b siness$ and not a technical$ decision ho' isolated s ch transactions have to be. 5he degree o" independence and isolation o" a transaction can be con<g redall transactional reso rces do s pport isolation levels. An isolation level determines ho' independent one transaction has to be "rom another. A higher isolation level implies serial e>ec tion$ a lo'er isolation level implies higher thro ghp t$ b t less isolation and consistency. +n "act$ a very high isolation level (.-6+A9+UAB9-) denotes serial access to a transactional reso rce$ the lo'est (/,/-) no restrictions at all. Eith the /,/isolation setting$ all transactions 'o ld immediately see all changes per"ormed by another transaction$ 'hich is the same behavior as 'itho t transactions. 5able 4 s mmari?es the vario s isolation levels.

21
Download at WoweBook.Com

%a4le 1- 'solation 3evels 'solation 3evel 6-A; 7/C,((+55-; Descri"tion Already 'ritten$ b t still ncommitted data is visible "or other transactions. +" any o" the changes are rolled bac#$ another transaction might have retrieved an invalid ro'. 5his setting can even be problematic "or read-only applications s ch as reporting. 6eports created 'ith 6-A;P7/C,((+55-; can be partially based on stale or even non-e>isting data. ,nly committed data is visible to other transactions. 5he isolation is higher$ beca se the stale data is isolated ntil the commitand only then visible to others. Qo can rely on the consistency o" the read dataS ho'ever$ the data remains consistent only "or the length o" the read operation. Ehen yo re-e>ec te the same B ery in the c rrent active transaction$ yo might see di""erent res lts. ,n this level$ a B ery operation 'ith the same parameters ens res the same res lts. -ven i" other transactions committed the changes$ 'hich a""ected some ro's in the res lt set$ it 'ill not change the res lt set. Altho gh delete and change operations are not visible in the res lt set$ ne' ro's can still be added by another transaction and appear in the res lt. 5his is the highest possible level. 5he name is derived "rom serial access$ no inter"erences bet'een transactions are allo'ed. 6ereading a B ery al'ays ret rns the same res lt$ regardless o" 'hether the data 'as changed$ added or deleted. 5his level is very consistent and very costly. 6ead and 'rite loc#s are needed to ens re this consistency level. 5he price "or the consistency is high as 'ell% the lo'est scalability (beca se lac# o" conc rrency) and increased chances "or deadloc#s.

6-A; C,((+55-;

6-P-A5AB9- 6-A;.

.-6+A9+UAB9-

+n a *ava -- environment$ the isolation levels are only indirectly e>posed to the developer. +n general$ all transactional reso rces can be con<g red sing isolation levels. +solation levels can be con<g red "or all transactional reso rces s ch as ;ata.o rces$ *(. "actories or destinations$ *CA connectors$ or distrib ted caches directly in the application server or in the reso rce itsel" ("or e>ample$ directly in the database). Eitho t isolation levels$ the only remaining bene<t 'o ld be the logical gro ping o" cohesive actions to one atomic nit. +n general$ the application server 'aits ntil the end o" the transactions and then 'rites the cached state to the bac#-end reso rces. )o'ever$ yo sho ldnRt rely on this r leit is con<g rable. !or e>ample$ the &lus+6o"e:'pe.AU:O setting o" )ntit'6ana7er and ;uer' ca se the changes to *PA entities to be H shed to the database immediately$ 'hereby &lus+6o"e:'pe.CO66<: only prescribes the synchroni?ation at the end o" the transaction. 6egardless at 'hich time the transactional cache ("or e>ample$ the state o" the )ntit'6ana7er) is H shed to the database$ nothing prevents other sers to access the same entity. 5his leads to " rther challenges. .everal e>isting copies may e>ist in parallel and res lt in

29
Download at WoweBook.Com

lost pdates$ 'here one transaction co ld override data "rom another. ,ne o" the sol tions to this problem is very similar to the s'nc+roni=e" #ey'ordonly one transaction can access the reso rce e>cl sively$ all the others have to 'ait.

9oc#ing "or Consistency


->cl sively loc#ing reso rces is rather pessimistic. +t is ass med that an inter"erence bet'een transactions 'ill happen. 5he conseB ences o" this ass mption are rather high tooS only one transaction at a time can access a reso rce ("or e>ample$ a ro' in a table or even the entire table). Pessimistic loc#s are one available option in the 'orld o" transactions and also the *ava -plat"orm. 9oc#ing reso rces e>cl sively <ts not very 'ell into the m ltithreaded nat re o" a *ava -- server. ,nly one thread (transaction) at time 'o ld be able to access the reso rce$ all others 'o ld have to 'ait. 5his approach hardly scales. +t is getting even 'orse in a cl stered environment. ;i""erent application server instances access no' a common reso rce$ 'hich means not only the transactions "rom one server$ b t all servers in the cl sters have to be bloc#ed. 5his increases not only the probability o" deadloc#s$ b t ma#es the implementation o" "ailover harder than necessary. Ehat happens in case one application acB ires a loc# to a database table and then diesG * st restarting the application server 'o ldnRt solve the problem$ beca se the reso rce is still loc#ed. Qo 'ill have to 'ait$ ntil the loc# 'ill be "reed by a timeo t. !ort nately$ a more optimistic approach is available. 5he term optimistic - implies lo' probability o" parallel 'rite-access to the same reso rce at the same time. (ost applications read signi<cantly more than they 'rite. 5he 'rite modi<cations o"ten access di""erent ro's or even reso rces. 5his is also the reason 'hy most o" the version control systems operate 'itho t loc#ing in optimistic mode. ,ptimistic loc#ing is sometimes re"erred to as optimistic conc rrency. 6egardless o" ho' lo' the probability o" inconsistency really is$ there sho ld be a consistent recovery strategy. As already mentioned$ optimistic conc rrency operates 'ith almost no loc#ing. A data set is "etched in a short read transaction "rom database and then it becomes disconnected. +n a *ava -environment s ch a data set is converted to a *PA entity. +n case the read entity 'as modi<ed$ it has to be H shed bac# to the database. At this point the state o" the application co ld become inconsistent$ beca se another transaction co ld have modi<ed$ or even deleted$ the entity already. +t is essentially important to chec# 'hether the database 'as changed in the meantime. 5his can be accomplished in a n mber o" 'ays% Preventing other transactions to access the resource: +his a!!roach /orks1 -,t is not really o!ti*istic. Checking the current state of the database using the before image: &n this case the state of the data-ase is ca!t,red at read ti*e and associated /ith the entity. ",ring the *odification (,!date or delete)1 the state of the c,rrent data-ase ro/ /ill -e co*!ared /ith the ca!t,red one. &n case it *atches1 the data-ase is going to -e ,!dated7 other/ise an e6ce!tion /ill -e thro/n. Checking the current state of the database using a proxy or synthetic co umn: +his strategy is very si*ilar to the !revio,s one -,t *ore light/eight. &nstead of ca!t,ring the entire ro/1 only a !ro6y ro/ (version ro/) is associated /ith the data set or entity. +his

30
Download at WoweBook.Com

ro/ is added to the /here cla,se and co*!ared /ith the c,rrent state of the data-ase. &n case the version ro/ of the *odified data set is e8,al to the ro/ in the data-ase1 the ,!date o!eration is !erfor*ed and the version changed. ),*eric ty!es are ,s,ally going to -e increased1 ti*esta*!s .,st refreshed. +his strategy can -e ,nderstood as an o!ti*i5ation of the second one. 5he <rst strategy isnRt optimistic. 5he second one is mostly sed in legacy systems and c stom persistence "rame'or#s. ,nly the last one is sed in *ava --%
2)ntit' public class Boo9# 2<" 2>enerate"?alue private 3on7 i"private Strin7 title)*ersion private lon+ version; %%@ot+er (iel"s

5he 2?ersion annotated attrib te represents s ch a synthetic <eld. +t is mapped to a database col mn. ! rthermore$ it is compared 'ith the database on every 'rite (as 'ell as delete) operation and <nally changed by the *PA provider. Qo only have to #eep the val e o" the <eld associated 'ith the entity "or the length o" the entire b siness transaction. 5he b siness transaction can be nderstood as a logical step that can be reali?ed by one or more technical transactions. Carrying the val e o" the version <eld 'ith the entity is necessary in case it becomes detached "rom the store and trans"erred to the presentation tier. +n this case$ the val e o" the version <eld has to be bo nd to the vie' and converted bac# to the entity. ,ther'ise the relationship bet'een the logical activity and the technical transactions is lost. +n some architect res$ the entity is never e>posed to the presentation tier. A dedicated ;ata 5rans"er ,b=ect (;5,) transports the in"ormation bet'een the layers instead. +n this partic lar case$ the version <eld has to be copied bac# and "orth bet'een the entity and the ;5,. ,ptimistic conc rrency solves the "ollo'ing challenges% !apping of ong"running# business activities to a se$uence of fine"grained# technica transactions: (ften it is not !ossi-le to e6ec,te a -,siness transaction in a technical one1 -eca,se of its d,ration. Everything that takes longer than a fe/ seconds has significant i*!act on scala-ility and ro-,stness. Preventing ost updates: "ifferent ,ser transactions *odify distinct attri-,tes of the sa*e entity or ta-le. Witho,t o!ti*istic locking the entity fro* the latter transaction /o,ld over/rite the already changed attri-,tes of the first one. Beca,se they are t/o inde!endent technical transactions1 s,ch a -ehavior /o,ld -e !erfectly valid fro* a technical !ers!ective. S,ch -ehavior is1 ho/ever1 not acce!ta-le fro* a -,siness !ers!ective. Preventing inconsistencies in a c ustered environment: Every cl,ster node acts *ostly inde!endently1 caches the data1 and synchroni5es itself /ith the data-ase. &n this case1 the cl,ster nodes conc,r for the sa*e reso,rce.

34
Download at WoweBook.Com

Preventing dead ocks: +his goal is achieved only indirectly. Beca,se the reso,rce (for e6a*!le1 a data-ase) is locked only for the d,ration of the ,!date o!eration (that is1 for a very short !eriod of ti*e)1 the chances of a deadlock are lo/ered.

Collisions happen b t + havenRt covered the recovery yet. A collision does res lt in stale data. Act ally$ it is very similar to collision in yo r version control system$ in case yo r colleag e modi<ed accidently the same <le as yo . 5he same strategies can be applied in both cases% %erging the cached data /ith the data-ase (verriding the data-ase Re.ecting the cached data

A collision is mani"ested as an nchec#ed e>ception (javax.persistence. Optimistic3oc9)xception)$ 'hich leads to the detachment o" all entities. 5he e>ception has to be ca ght and one o" the recovery strategies initiated a"ter this step. 5he only *ava -speci<c occ rrence is the Optimistic3oc9)xceptionS the challenge$ as 'ell as the sol tion$ is " lly *ava -- independent. 5he distrib tion o" an application into several *A( processes or address spaces ma#es maintenance o" the consistency even more challenging. (ethod parameters and ret rn val es 'ill be copied$ sometimes even trans"erred$ "rom one *A( to another.

;istrib tion$ 9atency$ and the !allacies


*ames DoslingRs and Peter ;e tschRs &allacies of #istri' ted (omp ting are independent o" the comp ting plat"orm$ lang age$ or system. ," importance "or the system architect re are the <rst$ second$ and seventh item% +he net/ork is relia-le 9atency is 5ero Band/idth is infinite +he net/ork is sec,re +o!ology doesn:t change +here is one ad*inistrator +rans!ort cost is 5ero +he net/ork is ho*ogeneo,s

5he latency$ o"ten re"erred as ping time$ has signi<cant impact on the per"ormance o" a system. )igh latency paired 'ith too <ne-grained methods can even ma#e it n sable. A remote method call is magnit des slo'er than a local one. 6ed ction o" remote calls helps to deal 'ith this "act. A remote method has to be coarser than a local one. 5he introd ction o" remote "a@ades is = st a nat ral reaction to the higher cost o" net'or# invocation. 5he p rpose o" the "a@ade is the aggregation o" <ne-grained local calls$ and e>posing them as a single coarse-grained operation. 5his approach is necessaryS other'ise the latency o" every single method 'ill be c m lated. 5he application co ld even become n sable in this case$ 'hich is a #ey reason 'hy the remote vie'

32
Download at WoweBook.Com

o" C(P entity beans 'as ridic lo s. -very single setter and getter invocation 'o ld ca se remote comm nication. !or the pdate o" a single database ro'$ several remote invocations 'o ld be necessary. A m ch harder problem is ob=ect seriali?ation "or transport p rposes. 5he data o" an ob=ect is going to be seriali?ed$ trans"erred over the 'ire$ and <nally deseriali?ed on the other end. At this point$ an additional copy o" an entity 'as introd ced. /o' 'e have one ob=ect instance in the database$ one cached in the )ntit'6ana7er$ and another one 'as copied d ring the distrib tion. ;ata consistency can still be ens red 'ith optimistic conc rrencyS ho'ever$ every additional copy increases the chance o" a collision. ! rthermore$ the copies have to be merged bac# a"ter every modi<cation. 5his hits not only the per"ormance and memory cons mption$ b t also introd ces an additional layer o" comple>ity. 5he <rst "allacy is inconvenient as 'ell. A distrib ted comm nication is nreliable by nat re. A net'or# "ail re can simply happenit ca ses nasty e>ceptions and sometimes a rollbac# o" the entire transaction. 5his is the reason 'hy in -*B 2.> every remote method thro's a java.rmi.Remote)xception. +t is chec#ed$ so the developer has to deal 'ith the e>ceptioneven i" it is not al'ays possible to recover in de<ned 'ay. +n the -*B 3 speci<cation the e>ception disappeared "rom the b siness inter"ace$ 'hich means it is invisible "or the ser o" the remote inter"ace. /onetheless$ the problem isnRt really solved$ only hidden. 5he e>ception still can happen$ b t it is 'rapped in an nchec#ed one. ,ne o" the biggest problems o" every distrib ted system is its partial "ail re. A distrib ted system is comprised o" processes$ 'hich to some degree are independent o" each other. 5he "ail re o" one s bsystem does not necessarily entail the consistent sh tdo'n o" all dependent parts. 5he dependent s bsystems are still able to accept reB ests$ b t are no longer able to handle them. 5his is one o" the essential problems o" a distrib ted system. A single-process system becomes = st completely and consistently navailable. .ometimes it is the best error recovering strategy. +n the conte>t o" *ava -- most annoying errors are ca sed by the "ail re o" bac#-end reso rces. 6eso rces involved in a distrib ted transaction coordinated by the application server are especially sensitive. A not-responding participant can lead to hanging transactions$ deadloc#s$ he ristic e>ceptions and even the "ail re o" the transaction coordinator. . ch scenarios are hard to test. . ch errors are even harder to be reprod ced in the integration environment. 5imeo ts$ bloc#ing reB ests$ and inconsistencies o"ten only occ r nder certain$ o"ten n#no'n$ circ mstances and heavy load.

/$**ary
Qo can start 'itho t *ava -- or other similar "rame'or# li#e ./-5$ .pring$ D ice$ or even systems s ch as C+C.$ b t yo 'ill have to implement the conc rrency$ transactions$ loc#ing$ sessions on yo r o'n. +tRs li#ely that the end res lt 'ill be more comple>$ than a " ll-blo'n *ava -- sol tion. +" yo nderstand the concepts o" distrib ted comp ting and #no' the challenges$ *ava -- becomes s ddenly a bree?e. +nstead o" coding$ yo can mostly rely on the provided de"a lts or con<g re the desired behavior declaratively. +n addition yo 'ill gain 'ith *ava -vendor independence. Qo r b siness logic 'ill be clearly separated "rom in"rastr ct re$ 'hich can be provided by (as o" s mmer 2009) thirteen certi<ed application servers and even the .pring "rame'or# itsel".

33
Download at WoweBook.Com

B ilding distrib ted$ rob st systems is hard. Qo have to be a'are o" the nat re o" distrib tion$ per-val e and per-re"erence semantics$ and e>ception handling. Qo have another optiondonRt distrib te yo r system. ;eployment o" the entire application to a single *A( solves the challenges in an elegant 'aythe "allacies o" distrib ted comp ting doesnRt apply any more. 5he system isnRt distrib tedS yo can 'or# 'ith the ob=ects in transparent 'ay. Qo can partially achieve that even 'ith *ava -- 2yo can r n as many layers as possible in as single process.

38
Download at WoweBook.Com

%
;nderstanding Java EE #ore #once!ts
*ava -- is a vast improvement over *2--. Altho gh the nderlying principles o" the *2-- 4." and *ava -- specs are similar$ e>perienced *2-- developers have to rethin# best practices 'hen sing the -*B 3 programming model. Concepts s ch as li"ecycle management o" session beans$ remoting$ transaction handling$ or state management have not changed. 5he improvements in the programming model and persistence$ ho'ever$ are dramatic. And altho gh the 'eb tier AP+ didnRt change in *ava -- 2$ it has been signi<cantly re"actored in *ava -- :. Altho gh the -*B 3.0 spec is lean and so nd$ the same amo nt o" metadata is reB ired as 'ith the -*B 2.4 predecessors. /onetheless$ the 'ay ho' the in"ormation is derived and leveraged has changed. +nstead o" con<g ring the obvio s$ only the deviation "rom the de"a lt has to be speci<ed. 5he de"a lt case is covered already by the sel"-contained metadata s ch as class name$ method name$ attrib te names$ and s itable de"a lts. 5he de"a lts s "<ce in abo t 10 percent o" all casesS speci<c reB irements can still be met 'ith annotations or$ i" necessary$ be overridden sing K(9 descriptor <les. 5his chapter e>plains some o" the less obvio s principles and practices o" the -*B 3." programming model$ incl ding convention over con<g ration$ ;ependency +n=ection$ and interceptors. +t also provides ans'ers to common B estions that tend to preocc py both e>perienced *2-- developers as 'ell as developers ne' to the *ava -- Plat"orm.

Convention over Con5g$ration


Convention over con<g ration (CoC) is a so"t'are paradigm borro'ed "rom the 6 by on 6ails comm nity. 5he principle is simple% decrease the n mber o" decisions that developers need to ma#e thro gh de"a lt con<g rations and only de<ne behaviors that deviate "rom the established convention. +n *ava -- terms this means that plain classes 'ith a limited set o" annotations (or modi<ers) too# the place o" large deployment descriptors and K(9 con<g ration <les. Annotations 'ere introd ced in *ava 2 .-$ b t the trend to'ards simpli"ying coding practices thro gh conventions that combine code and metadata 'as already apparent in *2--. K;oclet (an open so rce *ava;oc-driven code and con<g ration generator) leveraged the necessary in"ormation "rom the session bean class sing c stom *ava;oc tags. 5he red ndant in"rastr ct re s ch as home$ remote inter"ace$ deployment descriptors$ even val e ob=ects 'ere generated "rom the metadata provided in the *ava;oc comments. 5he c stom *ava;oc tags are similar to annotations$ b t have many dra'bac#s$ incl ding%

Download at WoweBook.Com

&ack of compi er checks: &t is !ossi-le to *iss!ell the tags < na*es and ty!es aren:t checked -y the co*!iler1 -,t d,ring the de!loy*ent cycle. &ack of structure: +ags alone are not eno,gh. &n *ost cases additional infor*ation s,ch as the na*e of the -ean or the transaction level had to -e !rovided as an attri-,te of the tag. +his can -e si*,lated -y Java"oc1 -,t cannot -e enforced -y the co*!iler. &t is i*!ossi-le to !rescri-e *andatory attri-,tes and defa,lt val,es. &ack of type safety: +he attri-,tes are not .,st strings. +he *etadata is *ainly co*!rised of constants or en,*erated val,es in Java EE (for e6a*!le1 2:ransactionAttribute(:ransactionAttribute:'pe.6AA8A:ORB)). +he co*!iler is not a-le to check the syntactic correctness of the attri-,te in !lain Java"oc as is the case in annotations.

5he introd ction o" annotations improved dramatically the sability o" metadata in *ava classes$ inter"aces$ <elds$ and methods. +nstead o" relying on the *ava;oc and deployment process$ the compiler chec#s "or syntactic correctness$ the availability o" the de"a lt val es$ and correct typing. /o additional tools or speci<c +;- e>tensions are reB ired. -*B 3.> and *PA speci<cations rely heavily on annotations. +n "act$ all the in"ormation stored previo sly in deployment descriptors is no' available in the "orm o" annotations. 5hey are s pplemented by metadata derived via reHection "rom the byte code and s itable de"a lts. 5he mi> o" convention and metadata derived "rom the components minimi?es the need o" providing additional in"ormation in the "orm o" annotations or K(9 con<g ration <les. +n "act annotations are sed as mar#ers to introd ce an -*B or persistent entity. 5he intention o" s ch annotations is identical to the (ar#er +nter"ace or 5ag +nter"ace patterns. 5he inter"aces java.io.Seriali=able and java.rmi.Remote are classic e>amples o" this pattern. An annotation does not e>tend the type$ as is the case 'ith the tag inter"ace pattern$ b t instead provides additional metadata at r ntime. ; ring the deployment phase$ the container searches "or the additional metadata and treats the classes accordingly. !or deployment o" a session bean$ "or e>ample$ only the annotation 2Stateless or 2State(ul has to be de<ned. 5he K;oclet metadata incl ded in *ava;oc has been replaced by annotations.
%CC C 2ejb.bean nameDE elloBeanE t'peDEStatelessE vie,/t'peDElocalE C% public class elloBean implements SessionBean #

5he annotations introd ced 'ith *ava -- 2 are lean and e>plicitit no/ s,ffices to mar# an ordinary *ava class 'ith the annotation 2Stateless to ma#e it an -*B%
2Stateless public class elloBean #$

5he container recogni?es it as a stateless session bean and applies the prede<ned (or conventional) behavior s ch as transactions$ state$ sec rity aspects$ and remoting. 5he stateless nat re o" the elloBean class is e>plicitly con<g red sing the annotation 2Stateless. 5he transactions$ ho'ever$ do not have to be e>plicitly speci<ed. 5he setting

3:
Download at WoweBook.Com

2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)8) is silently applied$ altho gh it isnRt e>plicitly speci<ed. +t ca ses every method to be e>ec ted in a transaction. +" a transaction already e>ists it 'ill be re sedS i" no transaction e>ists it 'ill be started "or yo . Qo can speci"y this annotation e>plicitly$ override it 'ith an K(9 deployment descriptor$ or rely on the de"a lt settings. -ven the implementation o" the inter"ace is no longer necessary. All p blic methods are a tomatically e>posed to the client (the ser o" the bean). 5he client acB ires an instance o" the bean either via a */;+ loo# p or sing ;ependency +n=ection.

De"endency 'n6ection
;ependency +n=ection (;+) re"ers to the process o" s pplying an e>ternal dependency to a so"t'are componentS in *ava -- terms$ this means that the -*B 3 container manages the dependencies "or yo . +nstead o" per"orming loo# ps$ sing "actories$ or even 'riting c stom code$ all yo have to do is declare the need "or a partic lar reso rce. !or e>ample$ instead o" 'riting c stom code li#e this% Service service D Service&actor'.7et<nstance().createService(),r this%
tr'# Context ctx D ne, <nitialContext()Object prox' D ctx.loo9up(FserviceE)Service ome +ome D (Service ome)PortableRemoteObject.narro,(prox'1Service ome.class)Service service D +ome.create()$catc+()xception ex)# %C omitte" C%$

Qo = st have to declare the dependency and the need "or a tomatic association 'ith a given instance as 2)*B annotation%
2)*B private Service service-

5he container does the 'or# "or yo . +t scans "or the annotation and in=ects the implementation be"ore a single b siness method is invo#ed. 5he process o" acB iring an implementation o" an inter"ace and associating it 'ith a <eld is completely "actored o t "rom the application code$ ma#ing the application code leaner and less error-prone. Possible misspellings o" */;+ names$ necessary e>ception handling$ or castings are gone. 5a#e a loo# at the previo s three "actory samples. +n the <rst sample$ ( Service&actor'. 7et<nstance().createService())$ the decision 'hich implementation o" the Service inter"ace 'ill be in=ected is encaps lated in the "actory (instead o" yo e>ternali?ing and storing the " lly B ali<ed name in a con<g ration <le). 5he second sample (<nitialContext#loo9up) loo#s p an -*B 2." bean. (Altho gh the bean doesnRt implement the inter"ace directly$ + speci<ed a partic lar bean class in an K(9 deployment descriptor <le.) 5he third (tr e ;+) sample needs the " lly B ali<ed name o" the implementation

30
Download at WoweBook.Com

as 'ell. 5he container has to decide 'hich implementation to in=ect. +n case there is only one implementation o" the inter"ace$ yo do not have to speci"y itCoC does it "or yo . 2ote- +n some cases yo 'ill have more than one implementation "or a given bean inter"ace. +n those cases$ the container 'ill have to di""erentiate bet'een both possibilities. P re conventions are not eno ghS the developer 'ill have to provide at least a hint$ 'hich class to se. +n the "ollo'ing e>ample$ an implementation o" the Service inter"ace is in=ected by the ClientBean%
2Stateless public class ClientBean implements Client # ),-# private Service service; public Strin7 7et ello() # return t+is.service.7et6essa7e()$ $

!or demonstration p rposes$ + introd ced more than one implementation o" the inter"ace$ so that the convention is e>plicitly violated. 5he t'o implementations ret rn di""erent messages.
2Stateless public class 8e(aultService implements Service # public Strin7 7et6essa7e() # return 4 ello (romG 4 H t+is.7etClass().7etAame()$ $

5he name o" the -*B is derived "rom the simple (not " lly B ali<ed) class name. 5here"ore t'o di""erent beans$ 8e(aultService and Speci(icService$ are going to be deployed%
2Stateless public class Speci(icService implements Service # public Strin7 7et6essa7e() # return 4 ello (romG 4 H t+is.7etClass().7etAame()$ $

5he deployment 'ill "ail in the early stage 'ith the "ollo'ing error%
Cannot resolve re(erence Unresolve" )jb/Re( com.abien.samples."i.client.ClientBean%service2jn"iG 2null2com.abien.samples."i.service.Service2Session2null because t+ere are I ejbs in t+e application ,it+ inter(ace com.abien.samples."i.service.Service

5he problem can be solved either by hardcoding the dependency 'ith annotation attrib tes or by sing the optional descriptor <le ejb/jar.xml. 5he <rst case is simple$ yo only have to set the attrib te in the 2)*B annotation and speci"y the -*B name%
public class ClientBean implements Client #

31
Download at WoweBook.Com

2)*B(bean'ameD4.e/aultService4) private Service service-

7sing the optional descriptor <le is more labor-intensiveS instead o" changing the code$ yo have to resolve the dependency in the deployment descriptor%
.ejb/jar @0 .enterprise/beans0 .session0 .ejb/name0ClientBean.%ejb/name0 .ejb/local/re(0 .ejb/re(/name0..."i.client.ClientBean%service.%ejb/re(/name0 .local0com.abien.samples."i.service.Service.%local0 .ejb/lin908e(aultService.%ejb/lin90 .%ejb/local/re(0 .%session0 .%enterprise/beans0 .%ejb/jar0

5his approach is more He>ible and allo's "or the dependency to be resolved e>ternally$ 'itho t code modi<cation. 5he declaration o" the dependency remains nchanged F no additional attrib tes have to be provided. 7sing the descriptor <le is more s itable "or testing p rposes or prod ct c stomi?ation. Qo can even se an K(9 deployment descriptor to override e>isting annotations. 5his is especially convenient i" yo 'ant to try a speci<c con<g ration d ring integration tests. * st be s re to remove the deployment descriptor in prod ction. .imilar principles can be applied "or the in=ection o" reso rces s ch as )ntit'6ana7er$ *(. destinations and Connection&actor' ob=ects as 'ell. 5he ;ependency +n=ection can be either con<g red 'ith annotations or in deployment descriptors. !or the persistence$ ho'ever$ an additional <le called persistence.xml is needed. 5he in=ection o" the )ntit'6ana7er 'itho t speci<cation o" the persistence nit 'or#s only in case there is only one persistence nit speci<ed in the persistence.xml <le%
2Stateless public class Boo9ServiceBean implements Boo9Service # %Cno a""itional in(ormation- ,or9s onl' (or one persistence unit in t+e persistence.xml (ileC% 2PersistenceContext private )ntit'6ana7er empublic voi" create(Boo9 boo9) # t+is.em.persist(boo9)$ $

+n all other cases it has to be resolved$ either 'ith an attrib te o" the annotation or again in the deployment descriptor. +t is not ncommon to have more than one persistence nit 'ith di""erent con<g rations available. -very in=ected )ntit'6ana7er instance is related to a persistence

39
Download at WoweBook.Com

nit and is independent o" others. ;i""erent )ntit'6ana7er instances have distinct caches and can be con<g red di""erently in the persistence.xml <le. An )ntit'6ana7er instance responsible "or access to the master data co ld se aggressive caching$ 'hereby the )ntit'6ana7er instance "or the operational data co ld be con<g red 'ith$ "or e>ample$ a N'ea#O re"erence cache$ or the instance responsible "or e>portCimport co ld be deployed 'ith no cache activated at all. 5hat *ava Persistence AP+ (*PA) can be sed o tside the container as 'ell. 5his "eat re is especially se" l "or testing p rposes. )o'ever it reB ires another persistence nit 'ith dedicated *;BC driver con<g ration and R)SOURC)J3OCA3 transaction handling. +t is = st another e>ample "or several persistence nits inside a persistence.xml deployment descriptor. +n the "ollo'ing e>ample$ both persistence nits are identical$ 'ith the e>ception o" the database schema generation. 5he persistence nit 8aC drops and creates all tables on deploy and ndeploy$ respectively. 5he !ersistence ,nit Aone relies only on the e>istence o" the schema.
.persistence ...0 .persistence/unit nameD4.a04 transaction/t'peD4*:A40 .provi"er0oracle.toplin9.essentials.PersistenceProvi"er.%provi"er0 .jta/"ata/source0j"bc%sample.%jta/"ata/source0 .properties0 .propert' nameD4toplin9.""l/7eneration4 valueD4"rop/an"/create/tables4%0 .%properties0 .%persistence/unit0 .persistence/unit nameD4'one4 transaction/t'peD4*:A40 .provi"er0oracle.toplin9.essentials.PersistenceProvi"er.%provi"er0 .jta/"ata/source0j"bc%sample.%jta/"ata/source0 .properties0 .%properties0 .%persistence/unit0 .%persistence0

5he in=ection o" the )ntit'6ana7er instance has to be e>plicitly con<g red in case it is arbitrary and cannot be in"erred "rom the convention. 5he most He>ible$ b t also most tedio s 'ay is the resol tion o" the dependency in the deployment descriptor. .ejb/jar @0 .enterprise/beans0 .session0 .ejb/name0Boo9ServiceK63Bean.%ejb/name0 .persistence/context/re(0 .persistence/context/re(/ name0...persistence.Boo9ServiceK63Bean%em.%persistence/context/re(/ name0 .persistence/unit/name08aC.%persistence/unit/name0 .%persistence/context/re(0 .%session0 .%enterprise/beans0 .%ejb/jar0

80
Download at WoweBook.Com

5he relation bet'een the in=ected )ntit'6ana7er instance and its persistence nit can be maintained in the e=b-=ar deployment descriptor 'itho t recompilation o" the session bean and is there"ore especially interesting "or integration tests or c stomer-speci<c settings in prod ct development. ,n the other hand the deployment descriptor is an additional arti"act 'hich has to be created and maintained$ so this approach comes not "or "ree. -specially re"actoring can be challenging$ beca se the +;- has to #eep the so rce and K(9 con<g ration consistent. !or static resol tion$ annotations are more appropriate and e"<cient. 5he name o" the persistence nit can be easily set in the 2PersistenceContext annotation. /o additional deployment descriptors are reB ired "or this p rpose.
2Stateless public class Boo9ServiceAnnotationBean implements Boo9Service # 2PersistenceContext(unitAameD48aC4) private )ntit'6ana7er empublic voi" create(Boo9 boo9) # t+is.em.persist(boo9)$ $

5he in=ection o" reso rces 'or#s slightly di""erent. Altho gh the principle is the same the data so rces$ *(. reso rces$ or mail sessions are in=ected sing the 2Resource annotation.
2Stateless public class 8ataSource<njectionBean implements 8ataSource<njection # 2Resource(name D 4mail%Context4) private Session mailContext2Resource(name D 4jms%;ueue4) private ;ueue queue2Resource(name D 4jms%Connection&actor'4) private Connection&actor' eoc&actor'2Resource(nameD4j"bc%sample4) private 8ataSource "spublic voi" accessResources()# %%use t+e "atasource $ $

5he deployed reso rces are niB ely identi<ed by the */;+ name$ 'hich is sed in the previo s e>ample "or in=ection$ instead o" a traditional loo# p. 5he mappe"Aame attrib te co ld be sed in this e>ample as 'ell$ even tho gh it is prod ct speci<c.

As"ect70riented Progra**ing and 'nterce"tors

84
Download at WoweBook.Com

5he idea behind aspect-oriented programming (A,P) is the strict separation bet'een p re b siness logic and re sable$ crossc tting code. 5he re sable$ crossc tting code$ or aspects$ is provided once and re sed in di""erent places. 5he re se$ ho'ever$ happens e>ternally$ the b siness logic classes do not even #no' that they are decorated 'ith additional " nctionality. +n "act$ A,P co ld be e>plained as He>ible and con<g rable decorator (or interceptor)$ 'hich can be applied to methods$ attrib tes$ or constr ctors in a declarative manner. 5he -*B container comes already 'ith some b ilt-in$ highly re sable aspects. 5he availability o" remote -*B via .,AP-based 'eb services$ 6-.5" l services$ or even ++,P remoting is nothing else than decoration o" an e>isting " nctionality 'ith the crossc tting aspect o" remoting. 5ransaction and e>ception handling$ sec rity$ conc rrency$ state management$ and even persistence are classic aspects. Aspects act ally e>isted "rom the beginning o" the *2-- plat"orm Ilong be"ore the acronym A,P became pop lar. Application-de<ned aspects 'ere introd ced 'ith the -*B 3.0 speci<cation. +n *2-- 4.8 only the 'eb container 'as able to intercept incoming reB ests 'ith a .ervlet <lter. +n a *ava -- application$ session beans tend to implement the ma=or portion o" b siness logic. 5his logic is rather " nctional$ or even proced ral. .ession beans are the nat ral place "or the tili?ation o" A,P ideas. .ession beans mainly consists o" methods and a de"a lt constr ctor. Attrib tes are very rare and mostly sed together 'ith state" l session beans. All other attrib tes are not client speci<c and shared by all instances. 6e"erences to )ntit'6ana7er instances$ *(. reso rces$ or other -*Bs are typical e>amples "or s ch a technical state. 5he *ava -- aspects are called interceptors. Comparing them to " lly-Hedged A,P "rame'or#s is not s itable beca se they are optimi?ed "or the se 'ith -*B and are th s rather limited. An -*B interceptor can only be applied to methods o" a partic lar -*B. +t is not possible to apply interceptors to constr ctor invocations or attrib te access. +nterceptors are nevertheless s "<cient "or most common se cases. An interceptor can be enabled either 'ith an annotation or thro gh a deployment descriptor. !rom the concept al point o" vie' its activation is identical to the ;+ approach% either annotations or deployment descriptors can be sed. An -*B 3 interceptor is = st a *ava class 'ith an annotated method%
public class :racin7<nterceptor # )1round2nvo3e public Object trace(<nvocationContext ic) t+ro,s )xception# S'stem.out.println(46et+o"G 4 H ic.7et6et+o"())return invocationContext.procee"()$ $

5he interceptor has " ll control over the e>ec tion$ it is able to invo#e the method$ change its parameters and ret rn val es$ invo#e the method several times$ trans"orm e>ceptions and so on. 5he reali?ation o" the interceptor is independent o" the act al b siness logic. An interceptor is activated "or a partic lar -*B sing the 2<nterceptors annotation.
2Stateless )2nterceptors({4racin+2nterceptor.class5 6er/ormance7easurement.class})

82
Download at WoweBook.Com

public class

elloBean implements

ello #

public Strin7 sa' ello() # return 4 ello (rom Bean4$ $

5he val e o" the annotation is an array o" classes. 5he order o" the array is eB ivalent to the order o" the interception. Beca se the 2<nterceptors annotation re"ers to the interceptors as classes and not as strings$ the +;- and the compiler ens re the consistency and provide a tocompletion and re"actoring s pport. ,n reB "or tro the other hand$ beca se the interceptors are declared in the b siness code$ every change ires recompilation and redeployment o" the 'hole application. 5his co ld become a problem tility interceptors$ 'hich are only needed in the development phase or only activated "or bleshooting.

!ort nately$ interceptors can be declared and applied in the standard deployment descriptors as 'ell. +n the "ollo'ing e>ample$ the <rst part o" the con<g ration is the act al declaration o" the interceptor. +t is needed only once. +n the second part$ the already declared interceptor can be applied to all beans "rom the ejb/jar$ a partic lar bean$ or a speci<c$ overloaded method.
.ejb/jar @0 .5// "eclaration (nee"e" once) //0 .interceptors0 .interceptor0 .interceptor/class0...6er/ormance7easurement.%interceptor/class0 .%interceptor0 .%interceptors0 .5// interceptor activation //0 .assembl'/"escriptor0 .interceptor/bin"in70 .ejb/name0Hello#ean.%ejb/name0 .interceptor/or"er0 .interceptor/class0...Per(ormance6easurement.%interceptor/class0 .%interceptor/or"er0 .%interceptor/bin"in70 .%assembl'/"escriptor0 .%ejb/jar0

5he K(9 con<g ration is not only more He>ible$ b t also more po'er" l. 5he deployment descriptor allo's the con<g ration o" de"a lt interceptors$ 'hich intercept all beans in the mod le (e=b-=ar). Qo sho ld have really good reasons "or the introd ction o" K(9 deployment descriptors. ;eployment descriptors are harder to create and maintain and have to be treated as plain so rce code. Altho gh the application is more He>ible and con<g rable 'ith e>ternali?ed K(9 con<g ration$ once deployed this advantage 'ill lose its importance. /o one 'ill change K(9 con<g rations 'itho t a test phase in prod ctionIthe additional He>ibility is there"ore only interesting in the development phase. 5he K(9 con<g ration has to be maintained and versioned

83
Download at WoweBook.Com

together 'ith so rce code. 5here"ore K(9 becomes as important as so rce code itsel" and has to be maintained 'ith the same care. Another arg ment "or the annotation-driven approach is the lo'er amo nt o" implicit behavior behind the scenes. 5he relation bet'een the main concern (the session bean)$ and the crossc tting concern (the interceptor) is sel" doc mented. 5he re"actoring o" the interceptor s ch as renaming$ moving to other pac#ages and so on can be per"ormed in every standard +;- 'itho t *ava -- or -*B s pport. +nterceptors are not = st P,*,s$ they come 'ith some interesting "eat res. 5hey participate in transactions and s pport ;ependency +n=ection. An interceptor is even able to se the " nctionality o" another -*B directly via ;+. +n the "ollo'ing e>ample$ a session bean is in=ected into an +nterceptor.
public class Au"it<nterceptor # ),-# private 1udit audit; 2Aroun"<nvo9e public Object trace(<nvocationContext ic) t+ro,s )xception# Strin7 in(o D (46et+o"G 4 H ic.7et6et+o"() H 4Ln4)in(o HD (4ObjectG 4 H ic.7et:ar7et().7etClass().7etAame())t+is.au"it.au"it(in(o)return invocationContext.procee"()$ $

+t is really convenient to access already e>isting logic o" an -*BI'ith all its provided services s ch as transactions$ conc rrency$ or sec rity. 5his ;ependency +n=ection can be con<g red in the same manner 'ith annotations or K(9$ or by relying on convention and sing the de"a lt implementation. 5he Au"it<nterceptor class is a biB ito s and rather trivial e>ample "or A,P. +nterceptors can be sed "or a variety o" p rposes$ incl ding% 'nsuring the preconditions: &nterce!tors have access to the interce!ted EJB. +herefore it is easy to access not only the *ethods1 -,t their !ara*eters /ith annotations as /ell. &t is relatively easy to eval,ate the annotations and ens,re the validity of the !ara*eters7 for e6a*!le1 the annotation 2AotAull already i*!lies that the *ethod sho,ld -e invoked /ith a non'n,ll !ara*eter. With this a!!roach the validation of the !reconditions co,ld -e easily *oved fro* the EJB into a re,sa-le interce!tor. 'nsuring the service eve agreements ()&*s+: +his case is very si*ilar to the !revio,s one. =o, co,ld *eas,re the !erfor*ance of a *ethod and escalate all too slo/ invocations ,sing1 for e6a*!le1 J%S +o!ic /ra!!ed in a session -ean. +his light/eight *onitoring ca!a-ility is es!ecially i*!ortant in S(A environ*ents1 /here *,lti!le clients have to rely on the availa-ility of a single1 re,sa-le service. 'nhancing the ,- capabi ities: An interce!tor is a-le to access the interce!ted EJB instance directly. So it is a-le to access its fields and search for annotations. Additional

88
Download at WoweBook.Com

val,es can -e in.ected directly into the fields or *ethods of a session -ean. +he fra*e/ork Sea* ,ses this a!!roach to introd,ce o/n "e!endency &n.ection se*antics. +he integration /ith 2oogle 2,ice can -e a!!roached in this /ay as /ell. Transforming or fi tering exceptions: An interce!tor invokes a *ethod of the ne6t !artici!ant in the chain. &t /ra!s the invocation1 so it is ca!a-le to catch any enco,ntered e6ce!tions1 s/allo/ the*1 or re'thro/ a clean version of an e6ce!tion. +his is !artic,lar ,sef,l for dealing /ith legacy connectors /ith e6ce!tions in the >ca,se?. )ot all e6ce!tions1 ho/ever1 can -e easily ca,ght in an interce!tor. So*e e6ce!tions1 s,ch as javax.persistence.Optimistic93oc9)xception1 *ight occ,r at the end of a transaction. Beca,se the interce!tors are involved in the sa*e transactions as /ell < it is not !ossi-le to catch s,ch e6ce!tions.

+nterceptors help yo to reali?e non-" nctional reB irements 'itho t to ching the b siness code. 5hey arenRt as po'er" l as " lly Hedged A,P lang ages$ b t s "<cient "or most o" the se cases. + 'ill cover the e>amples above in greater detail in Chapter 2 'hen disc ssing the 5hread5rac#er$ ;ependency +n=ection ->tender$ or Payload ->tractor patterns. +n an enterprise environment$ A,P and interceptors are less common than yo may thin#. 5he *ava -- container comes already 'ith a b nch o" se" l aspects$ 'hich can be enabled declaratively 'itho t any coding. +n "act$ a *ava -- developer sho ld not even #no' that persistency$ transactions$ conc rrency$ or conversational state are aspects.

EJB # and JPA /$""ort


5he s pport "or *PA in -*B 3 goes "ar beyond p re ;ependency +n=ection. 5he in=ected )ntit'6ana7er instance is managed by the container. 5his tas# is trivial in a single-threaded environment$ b t *ava -- is a m ltithreaded$ conc rrent environment. 5he -*B container does the boo##eeping and manages the )ntit'6ana7er instance in a transactional manner behind the scenes. 5he previo sly introd ced session bean e>ample is more comple> to reali?e in a 'eb container environment%
2PersistenceContext private )ntit'6ana7er empublic voi" create(Boo9 boo9) # t+is.em.persist(boo9)$ $

.ince the )ntit'6ana7er instance isnRt thread-sa"e$ it cannot be cached or stored bet'een reB ests. Be"ore every method invocation$ it has to be obtained "rom the )ntit'6ana7er&actor' ('hich is thread-sa"e) and closed a"ter every method invocation. 5he same is tr e "or e>ceptionsS the )ntit'6ana7er has to be closed in the (inall' bloc#. 5he "ollo'ing e>ample demonstrates the man al management o" )ntit'6ana7er in 'eb container%
2PersistenceUnit )ntit'6ana7er&actor' em(-

82
Download at WoweBook.Com

2Resource User:ransaction utx... public voi" create(Boo9 boo9)# )ntit'6ana7er em D em(.create)ntit'6ana7er()tr'# utx.be7in()em.join:ransaction()em.persist(boo9)utx.commit()$ catc+()xception exe)# %%+an"le exception tr' # utx.rollbac9()$ catc+ ()xception e) #$ $ (inall' # em.close()$ $

.ome o" the methods in the )ntit'6ana7er inter"ace (in=ected 'ith :RAASAC:<OA scope) reB ire an active transaction. 5hey incl de persist$ mer7e$ remove$ (lus+$ and re(res+. 5hese methods thro' an e>ception$ :ransactionRequire")xception$ i" there is no transaction and the persistence conte>t is transaction-scoped. 6egardless o" 'hether the application r ns in a 'eb container or not$ yo have to start transactions any'ay. +n a managed environment$ the transactions are started "or yo S it = st happens behind the scenes be"ore every method invocation (the convention is R);U<R)8 transaction scope "or the b siness methods). +n a 'eb container yo 'ill have to in=ect the User:ransaction instance and associate the c rrent transaction 'ith the )ntit'6ana7er instance sing the join:ransaction method. 5ransactions are reB ired in"rastr ct re "or the )ntit'6ana7er inter"ace. 5ransactions are not only reB ired "or consistent database access$ b t do control the time o" detachment o" the *PA entities.

5he 5ransaction mode


5he PersistenceContext:'pe.:RAASAC:<OA is the de"a lt con<g ration. +" yo are in=ecting the )ntit'6ana7er into a stateless session bean$ this setting is sed by convention. +n "act$ it is the only possible option "or stateless session beans. A"ter every transactional method call$ the )ntit'6ana7er gets closed and cleared. All attached or managed entities become detached. Changes to those entities 'ill be not synchroni?ed 'ith the database. 5his behavior is ca sed by transactions and not method invocations. +" the <rst stateless session bean opens a transaction and invo#es another session bean 'ith :ransactionAttribute.R);U<R)8 or :ransactionAttribute.6AA8A:ORB$ all entities remain attached "or the d ration o" the 'hole transaction. Qo can cascade the session beans in arbitrary depth in the conte>t o" a single transaction$ 'itho t loosing the consistency. 5his gives yo great He>ibility in designing the b siness logic. +t is = st

8:
Download at WoweBook.Com

eno gh to start a transaction in the bo ndary C <rst session bean (Boo9&aca"eBean). 5he transaction 'ill be propagated a tomatically to the invo#ed session beans (Boo9ServiceBean) or <ner services. 6emember$ inside the transaction all *PA entities 'ill remain attached$ regardless o" ho' many nested session bean methods are invo#ed. +n the "ollo'ing e>ample$ a service is invo#ed in the conte>t o" a transaction%
2Stateless 2:ransactionAttribute(4ransaction1ttribute4ype.71'.148%9) public class Boo9ServiceBean implements Boo9Service # 2PersistenceContext private )ntit'6ana7er empublic Boo9 (in"(lon7 i")# return t+is.em.(in"(Boo9.class1i")$ $

All the changes per"ormed to an attached entity 'ill be a tomatically and transparently synchroni?ed 'ith the database "or yo . /o additional merging is reB ired. 5his saves a lot o" boilerplate code. 5he change per"ormed by any o" the s bseB ent invocations is visible immediately to all other transaction participants. Qo are al'ays 'or#ing 'ith the entity per re"erence$ so the )ntit'6ana7er#(in" method o" any session beans involved in the active transaction 'ill ret rn the same instance o" the entity.
2Stateless 2:ransactionAttribute(:ransactionAttribute:'pe.%,:;2%,S<',") public class Boo9&aca"eBean implements Boo9&aca"e # 2)*B private Boo9Service boo9Servicepublic voi" up"ate(lon7 i"1Strin7 name)# Boo9 (oun" D t+is.boo9Service.(in"(i")(oun".setAame(name)$ $

5his is act ally the nat ral$ e>pected behavior o" a stateless session bean and it is consistent 'ith *2-- best practices. (ost o" the *2-- architect res relied on the val e ob=ect$ renamed later to ;ata 5rans"er ,b=ect (;5,) pattern. All parameter and ret rn val es 'ere copies o" the act al C(P 2.0 entities. 5his 'as necessary beca se C(P 2.0 entities co ld not be seriali?ed$ it 'as simply not possible to trans"er them to a remote *A(. 5he behavior o" a transaction-scoped )ntit'6ana7er is similar$ e>cept all the *PA entities do not have to be copied. As soon as they become detached or nmanaged$ they can be sed as ;5,s. ;edicated ;5,s became optional$ b t can still be sed "or additional deco pling o" the persistence layer "rom its clients. 5o s mmari?e% +he transaction sco!e is the defa,lt setting and s,ita-le for *ost a!!lications.

80
Download at WoweBook.Com

+he )ntit'6ana7er *aintains an internal cache for the d,ra-ility of the transaction. All entities referenced fro* the cache are *anaged7 changes to those entities /ill -e synchroni5ed /ith the data-ase at the end of the c,rrent transaction. Bet/een *ethod invocations another instance of stateless session -eans can -e associated /ith the caller. +herefore the )ntit'6ana7er has to -e cleared or closed after every call. +he closing and clearing of the )ntit'6ana7er ca,ses the detach*ent of all *anaged entities in the transaction. After co*!leting a transactional *ethod1 all entities -eco*e detached. +herefore all entities ret,rned to the caller can -e treated as "+(s. #hanges to their state /ill not -e synchroni5ed /ith the data-ase.

5he ->tended mode


5he e>tended mode is similar to the transaction mode e>cept that the )ntit'6ana7er is not going to be cleared a"ter every transactional callS instead all entities remain attached as long as the state" l session bean lives. Beca se the cache is not cleared a"ter every transaction$ the state o" the session bean becomes client-speci<c. 5his is the reason$ 'hy this mode only 'or#s 'ith state" l session beans. ,nly a 4%4 relation bet'een the client and an )ntit'6ana7er instance g arantees that all client reB ests 'ill be ro ted to the same state" l session bean instance. Any modi<cation to the entities 'ill be synchroni?ed at the end o" the ne>t transaction. .o a commit o" a transaction implies a save operation and the rollbac# an ndo operation. 5he e>tended mode is there"ore very similar to the application scope )ntit'6ana7er$ 'hich is entirely managed by the application. +n both cases the cache is not cleared a tomaticallyS instead$ clearing the cache is the responsibility o" the developer. A state" l session bean is able to #eep client-speci<c state$ and th s hold an attached *PA entity "or caching p rposes. 5his ma#es it even accessible 'itho t the invocation o" )ntit'6ana7er. ,nce located$ the *PA entity can be easily modi<ed$ even o tside o" an active transaction. +n the "ollo'ing e>ample$ a *PA entity is cached in a state" l session bean and accessible via a simple getter. +t is important to ret rn the entity per re"erence thro gh a local inter"ace. 5hro gh a remote inter"ace$ all ret rn val es 'o ld be copied 'hich 'o ld destroy the idea o" transparent persistency. A copy 'o ld have to be merged 'ith the )ntit'6ana7er.. 5he Boo9 entity has to be located only once. All relations$ regardless 'hether eager or la?y$ can be traversed "rom the Boo9 entity$ even o tside o" the session bean.
2State(ul 23ocal(Boo9&aca"e.class) 2:ransactionAttribute(:ransactionAttribute:'pe.',*,%) public class Boo9&aca"eBean implements Boo9&aca"e # )6ersistence0onte=t(type>6ersistence0onte=t4ype.,?4,'.,.) private )ntit'6ana7er emprivate Boo9 currentBoo9public Boo9 (in"(lon7 i")#

81
Download at WoweBook.Com

t+is.currentBoo9 D t+is.em.(in"(Boo9.class1 i")return t+is.currentBoo9$ public voi" create(Boo9 boo9)# t+is.em.persist(boo9)t+is.currentBoo9 D boo9$ public Boo9 7etCurrentBoo9() # return currentBoo9$ 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public voi" save()# %%not+in7 to "o +ere $ $

5he transaction setting o" the Boo9&aca"e may appear a little esoteric at the <rst glance. ,n the class level the :ransactionAttribute:'pe.A)?)R is sed. 5here"ore it is g aranteed$ that no method o" the bean 'ill be invo#ed in an active transaction. 5he method save$ ho'ever$ over'rites this r le 'ith the setting :ransactionAttribute:'pe.R);U<R)SJA)! at method level$ 'hich in t rn starts a ne' transaction every time. 5he method create in t rn 'as not annotated 'ith :ransactionAttribute:'pe.R);U<R)SJA)! even tho gh the )ntit'6ana7er#persist method is invo#ed inside. 5his invocation 'ill not "ail 'ith the :ransactionRequire")xception. +t 'ill not "ail beca se on an )ntit'6ana7er 'ith an )K:)A8)8 persistence conte>t$ the persist$ remove$ mer7e$ and re(res+ methods may be called regardless o" 'hether a transaction is active or not. 5he e""ects o" these operations 'ill be committed to the database 'hen the e>tended persistence conte>t is enlisted in a transaction and the transaction commits. +t act ally happens in the empty method save. 5he method save is annotated 'ith :ransactionAttribute:'pe.R);U<R)SJA)!$ b t comes 'itho t any implementation. 5he most interesting part happens a"ter the method is invo#edS the active transaction is going to be committed. 5he )ntit'6ana7er is =oined by the container to the transaction. +t ta#es part on it. 5he reaction o" the )ntit'6ana7er to a commit operation is the synchroni?ation o" all the attached or managed entities 'ith the database. 5his e>plains the empty body o" the save method. 5he interesting st "" happens be"ore and a"ter the methodIa per"ect sample "or an interceptor$ or a crossc tting concern. 5he invocation o" the method save ca ses a H sh o" all modi<ed entities to the database. -very change per"ormed be"ore this invocation is persisted a"ter it. 5he implementation o" a simple$ onelevel$ ndo mechanism is very simple as 'ell%
public voi" un"o()# t+is.em.re(res+(t+is.currentBoo9)$

89
Download at WoweBook.Com

5he state o" the c rrent entity$ and th s all per"ormed changes$ 'ill be ndone and replaced 'ith the c rrent state o" the database. )o'ever$ this is not a real ndo operation. 5he state o" the database co ld be ne'er than the act al state be"ore all the local modi<cations. 5he approach 'ith the )K:)A8)8 )ntit'6ana7er signi<cantly minimi?es method calls "or the p rpose o" synchroni?ation. +t integrates 'ell 'ith 'eb "rame'or#s s ch as *ava.erver !aces (*.!)$ 'here data binding allo's declarative synchroni?ation bet'een the vie' and the domain model.

5he ->tended (ode and Conc rrency


5he obvio s problem in a conc rrent environment o" a state" l session bean is its caching behavior. 5he cache o" the )ntit'6ana7er is completely disconnected "rom the database. ;atabase changes 'ill be not a tomatically propagated to the local cache or the state" l session bean. -ns ring the consistency is the responsibility o" the application developer. -very session$ or state" l session bean$ instance is completely independent o" another one. ( ltiple sessions and independent caches may e>ist in parallel. Conc rrent access to the same state" l session bean instance$ ho'ever$ is not allo'ed. Both sessions can contain entities 'ith the same identi<er. .o entities "rom di""erent sessions may act ally re"er to the same record in the database. Beca se the sessions are independent o" each other$ the cache can become inconsistent. 5he problem can be solved in one o" t'o 'ays% 'ith pessimistic loc#s or optimistic conc rrency. 5he pessimistic loc#ing 'o ld massively h rt the scalability and per"ormance o" yo r application$ so the only viable sol tion remains optimistic loc#ing. 5he data in the cache co ld become stale$ b t d ring the 'rite operations (or$ more precisely$ at the end o" the ne>t transaction) the version <eld in the database 'ill be compared 'ith the 2?ersion <eld in the entity. +" it matches$ the 'rite operations 'ill be per"ormedS i" not the e>ception Optimistic3oc9)xception 'ill be thro'n. )ence Nlost pdatesO bet'een caches and sers are detected at the end o" a transactionS the recovery "rom s ch an optimistic collision is not convenient "or the end sers. . ch a collision can occ r a"ter several min tes$ b t can also ta#e ho rs. An Optimistic3oc9)xception ca ses the detachment o" all managed entities$ so all changes get lost and have to be merged or reloaded "rom the database. 5his challenge can be approached by providing " nctionality "or re"reshing the state o" the session "rom the database. 5he method re(res+ 'ith cascading relations does the heavy li"ting. All associated entities 'ill be re"reshed 'ith the database state. Altho gh all entities remain attached and possible local changes 'ill be lost. !or non-trivial applications a more practicable merge strategy is needed. 5he conHict resol tion strategies are identical to version control systems s ch as CA. or . bversion con<g red to operate in optimistic manner% 9ocal cache over/rites the data-ase

20
Download at WoweBook.Com

"ata-ase over/rites the local cache +he end ,ser has to *erge local changes /ith the data-ase *an,ally

5hese di""erent sol tions sho ld be comm nicated in the early development stage to the domain e>perts and c stomer. -ach choice reB ires changes to the ser inter"ace and page Ho'. 5his can become B ite e>pensive in later iterations. 5he choice o" the right strategy is a b siness decision$ so it cannot be decided by the developerS it has to be made by the domain e>perts. 5he problem o" dis=oined$ independent caches is not speci<c to state" l session beans or e>tended )ntit'6ana7er. -very cl stered application server has to deal 'ith the same problem$ having independent caches o" each cl ster node. Application servers s ally broadcast messages to neighbor nodes that invalidate the changed (dirty) entity. 5his lo'ers the probability o" Optimistic3oc9)xceptions$ b t does not completely avoid them. 5he noti<cations are per"ormed asynchrono sly in most cases.

5he Problem 'ith 9a?y 9oading and 5ransparent Persistence


5he transaction-scoped )ntit'6ana7er detaches all managed entities a"ter each transaction. Beca se a transaction-scoped )ntit'6ana7er can be only be sed "rom a stateless session bean a transaction in this conte>t is synonymo s 'ith method invocation. All ret rn val es o" stateless session beans are detached and not managed entitiesIthey are comparable to ;5,s. A detached entity is no more able to transparently load its dependent entities. Any attempt to invo#e a method o" la?y-loaded relations 'ill res lt in a r ntime$ provider-dependent e>ception. 5o overcome this problem all la?y relations have to be loaded inside the stateless session bean method be"ore the transaction ends. Another sol tion 'o ld be to se eager relations e>cl sively$ b t then more ob=ects than needed 'o ld be loaded in every method. +n the 'orst case$ the 'hole database 'o ld be "etched eagerly inside a transaction. 5he *PA speci<cation "oresees fetch %oins$ speci<c B eries that eagerly load the relations$ to solve this problem. 6egardless 'hich approach yo are choosing to load the relations eagerly be"ore detaching$ the challenge here is to #no' in advance 'hich relation path is act ally needed "or a partic lar se case. An e>tended )ntit'6ana7er is more He>ible at this point. Beca se the entities are not going to be detached a"ter every transaction and th s invocation$ the decision 'hich relation has to be loaded$ can be signi<cantly de"erred. Accessing the entities thro gh a 23ocal inter"ace per re"erence ma#es even s ch a decision completely obsolete. Beca se the entities remain managed$ the relations can be conveniently loaded at any point. -ven in the presentation layer ("or e>ample$ in a *.! component) a la?y relation can be loaded = st by accessing the method or <eld. .etting all relations as la)y is not necessarythe convention is already s itable. 5he K%4 relations are loaded eagerly and all 4%/ relations la?ily by de"a lt. 5his convention is appropriate "or most se cases. -specially the de"a lt )A>)R setting o" the 4%4 relation sho ld be changed to 3AMB only rarely. A 2One:oOne relation points directly to another entity. 5he on-demand "etching can only be achieved 'ith byte code manip lation. 5he per"ormance gain is minimalS only one entity is loaded on demand. !or the dedicated loading o" the 3AMB relation at least one additional .T9 statement

24
Download at WoweBook.Com

is needed. 9a?y loading o" single val ed relations is only s itable "or h ge and rarely sed child entities. A good e>ample o" that 'o ld be an entity 'ith 23ob <elds in it. ,nly then this approach may pay o"". 5he de"a lt "etch strategy in 2One:oOne relations is already set to )A>)R$ so there is no need to speci"y it e>plicitly.
2One:oOne((etc+D&etc+:'pe.)A>)R) private C+il")ntit' entit'2One:o6an'((etc+D&etc+:'pe.3AMB) private Collection.C+il")ntit'0 entities-

,n the other hand$ 2One:o6an' relations come already 'ith 3AMB "etching as de"a lt$ 'hich is reasonable as 'ell. 5he many side o" the relation can have h ndreds$ tho sands$ or even millions o" dependent entities. 9oading them on demand can increase the per"ormance and lo'ers the memory cons mption. 5his optimi?ation$ ho'ever$ is only s itable "or rarely needed entities "rom the many side. ,ther'ise loading all needed entities 'ill res lt in more interactions 'ith the database. Accessing and modi"ying la?y relations o tside o" a stateless session bean only 'or#s in case the 'eb container and -*B container are e>ec ted in the same *A(. 5he distrib tion o" presentation and b siness components into di""erent *A(s "orces the seriali?ation o" the persistent entities. Beca se the entities are no more accessible per re"erence$ all needed relations have to be preloaded be"ore seriali?ation. 7sing an e>tended )ntit'6ana7er thro gh 2Remote inter"aces is not bene<cial and sho ld be avoidedS the la?y-loading problem still persists and the developer has to preload all relations in advance. 5he transparency o" relation "etching$ change trac#ing$ and simple save and ndo mechanisms ma#es the sage o" the e>tended )ntit'6ana7er especially interesting "or domain-driven$ ob=ect-oriented applications. +n this partic lar case$ the entities 'o ld consists o" the state and behavior. A method o" a single entity co ld change the state on the entire graph o" dependent ob=ects. Beca se at least the root entity remains managed bet'een method calls$ all changes 'ill be transparently H shed to the database. 5he entities can be treated as " lly Hedged$ 'ell encaps lated$ domain ob=ects 'ith real behavior. Qo can 'or# 'ith the ob=ects transparently$ 'itho t 'orrying too m ch abo t persistency. Beca se the graph remains attached$ there is no need "or synchroni?ation and merging. 5his greatly red ces the total amo nt o" in"rastr ct ral methods and boilerplate code.

Accessing EJB
7ntil no' + covered the ;+ mechanisms inside the -*B container. (ost enterprise applications$ ho'ever$ come 'ith more or less rich presentation layers$ 'hich have to access the b siness logic. 5he ;ependency +n=ection o" -*B and reso rces is available o tside the -*B container as 'ell. 5he "ollo'ing technologies listed are able to se ;ependency +n=ection directly% )erv et: Servlets1 Servlet filters1 event listeners .)P: +ag handlers1 tag li-rary1 event listeners

22
Download at WoweBook.Com

.)/: Sco!ed *anaged -eans .*0"1): Service end!oints1 handlers .ava '' P atform: %ain class1 login call-ack handler (of the a!!lication client) .*0"2): Root reso,rce classes1 !roviders '.3: Beans1 interce!tors

/evertheless$ the sage o" session beans is not limited to the speci<cations listed above. Any non*ava -- "rame'or#s are able to access the session beans sing the traditional loo# p mechanism. !rame'or#s s ch as Doogle D ice$ Eic#et$ .tr ts$ 5apestry$ and many others co ld = st rely on a tility class ("ormerly Service3ocator$ a Bean 9ocator pattern that + 'ill cover in Chapter 2) 'hich per"orms the loo# p internally and ret rns a re"erence to an -*B. 5he -*B 3.4 speci<cation introd ced the notion o" global */;+ naming. 5he container ses the "ollo'ing synta> to generate a global */;+ name and register a session bean 'ith it% javaG7lobalN%.app/name0O%.mo"ule/name0%.bean/name0#.(ull'/ quali(ie"/inter(ace/name0 -very deployed session bean can be conveniently accessed sing the naming scheme above via <nitialContext#loo9up. .ession beans are accessible "or standard as 'ell as non-standard "rame'or#s and *ava -e>tensions. ,nly "rame'or#s incl ded in the *ava -- mbrella$ ho'ever$ are able to access the -*Bs via ;ependency +n=ection o t o" the bo>. .ervlets are the "o ndation o" nearly all pop lar *ava 'eb "rame'or#s available today. Accessing to -*B "rom .ervlets 'or#s the same as access bet'een -*Bs. 5he re"erence to a 23ocal or 2Remote session bean can be easily in=ected sing the 2)*B annotation.
public class elloServlet exten"s ttpServlet #

2)*B private elloBean +elloBeanprotecte" voi" "o>et( ttpServletRequest request1 response) t+ro,s Servlet)xception1 <O)xception # $

ttpServletResponse

5he session beans can be either deployed to an independent e=b-=ar mod le or pac#aged 'ith the .ervlet in a 'eb archive ('ar). 5he simplest possible sol tion 'o ld be the in=ection o" a stateless session bean 'ith no-inter"ace vie'. .ervlets are stateless$ pooled components$ so the ;ependency +n=ection here is only limited to the stateless session beans. 5he in=ection o" a state" l session bean into a .ervlet 'o ld ma#e it shareable across di""erent bro'sers. -ven 'orse$ the state" l session bean 'o ld be accessed conc rrently$ 'hich is not allo'ed and 'o ld res lt in the e>ception javax.ejb.ConcurrentAccess)xception.
2Stateless public class elloBean#

public Strin7 sa' ello(Strin7 messa7e) #

23
Download at WoweBook.Com

Strin7 ret?al D 4)c+o (rom beanG 4 H messa7ereturn ret?al$ $

.imilarly all #inds o" session beans can be in=ected directly into the *.! bac#ing beans. -ven the in=ection o" state" l session beans into session-scoped bac#ing beans is s pported. 5he ;ependency +n=ection is identical to the .ervlet e>ample above% the annotation 2)*B has to be sed also in this case. Access to a state" l session bean 'ith )K:)A8)8 )ntit'6ana7er "rom a session-scoped bac#ing bean allo's access to attached entities. An attached entity can be bo nd to a *.! vie' declaratively. 5his not only minimi?es the ro nd trips$ b t ma#es the e>ternal session bean inter"aces very lean. 5he *AK-E. and *AK-6. AP+s are mainly stateless$ so only ;ependency +n=ection o" stateless session beans is s itable in this case. Also in these cases it 'or#s sing the same principle. Altho gh most o" the presentation components s ch as .ervlets$ bac#ing beans and others are not thread-sa"e$ the ;ependency +n=ection o" a stateless session bean solves the problem as 'ell. 5he container 'ill manage the conc rrency and transactions "or yo . Parallel calls 'ill be dispatched to di""erent stateless session bean$ thread-sa"e instances. .o instead o" sing$ "or e>ample$ )ntit'6ana7er directly$ it is al'ays 'orth to 'rap it 'ith a stateless session bean and se in=ection to access it.

/$**ary
Con<g ration by ->ception together 'ith ;ependency +n=ection radically simpli<ed the programming model. ->tensive K(9 deployment descriptors as 'ell as the 'hole "actoryCloo# p in"rastr ct re became s perH o s. -*B 3 components come 'ith s itable de"a lts and do not have to be con<g red. 5he same is tr e "or the ;+Ii" there is only one choice$ yo donRt have to con<g re it. +n addition$ the programming model became s rprisingly cleanIyo can deploy a P,*, as a session bean applying only the 2Stateless or 2State(ul annotations. /o reali?ation o" AP+ inter"aces or other "rame'or# dependencies are reB ired any more. 5his "act alone eliminated already the need "or patterns s ch as .ervice 9ocator or B siness ;elegate. + 'ill disc ss the more appropriate *ava -- patterns and best practices in the "ollo'ing chapters.

28
Download at WoweBook.Com

4
Rethinking the B,siness +ier
Core *2-- patterns contin e to be pop lar among *ava developers. (ost patterns$ ho'ever$ are sol tions to problems that have been addressed in *ava --. 5he contin ed se o" some o" these patterns only leads to ine"<cient and hard-to-maintain applications. Another problem 'ith *2-- applications are nrealistic$ non-" nctional reB irements and ass mptions. -specially He>ibility$ deco pling "rom partic lar services and reso rces$ or e>tensibility 'ere misinterpreted and led to over-engineered applications. .ome *2-- patterns are still valid or optional. 5his chapter 'ill help yo rethin# the Core *2-- patterns in the conte>t o" the *ava -- 2 plat"orm.

Download at WoweBook.Com

/ervice ,a8ade 9A""lication /ervice:


; ring *2-- times$ .ession !a@ade patterns 'ere = st 'rappers o" entity beans or ;A,s. 5hey 'ere motivated by the shortcoming o" the spec$ rather than by design best practices. 5he technical nat re o" the .ession !a@ade patterns 'as the reason "or their thin logic. 5he Application .ervice pattern 'as the se case controller or "a@ade that coordinated m ltiple .ession !a@ades. +n *ava --$ ho'ever$ things have changed.

Problem
5he original motivation "or the Application .ervice pattern is still valid and se" l "or serviceoriented architect re styles% NQo 'ant to centrali?e b siness logic across several b siness-tier components and servicesO ('''.core=2eepatterns.comCPatterns2nd-dCApplication.ervice.htm). 5he access to the b siness logic components has to be as convenient and as consistent as possible. ,nly a coarse-grained AP+ can meet the reB irements$ it sho ld be nderstandable by domain e>perts. +n *ava -- an e>plicit remote and transactional bo ndary is still needed. 5he e>pos re o" <negrained b siness logic over remote inter"aces simply doesnRt 'or#. /et'or# latency is too high "or <ne-grained access and it is hard to e>ec te <ne-grained methods in a transaction conte>t over the net'or#.

!orces
A !redefined1 easy'to'cons,*e1 -,siness AP& is needed. +he state of the co*!onent after the invocation of the Service 0a@ade sho,ld -e consistent. +he reali5ation -ehind the Service 0a@ade sho,ld -e enca!s,lated. +he Service 0a@ade interface sho,ld -e ,sa-le as a re*ote service. +he signat,re of the e6!osed *ethods sho,ld -e sta-le and re*ain co*!ati-le1 even if the reali5ation of the co*!onent changes.

.ol tion
.ervice !a@ade is a stateless (in e>ceptional cases also state" l) session bean 'ith a local b siness inter"ace. A remote b siness inter"ace sho ld only be provided i" it is going to be sed "rom o tside the *ava Airt al (achine (*A() and not in=ected into a .ervlet$ bac#ing bean$ or other 'eb component. 5his is the case 'ith an -clipse or /etBeans 6ich Client Plat"orm (6CP) application$ "or e>ample. 5he .ervice !a@ade methods are designed "rom the domain perspective and are there"ore coarsegrained. A relation to se cases$ ser stories$ or some other #ind o" speci<cation sho ld be identi<able at <rst glance. Best case scenario$ the methods sho ld be nderstandable "or domain

2:
Download at WoweBook.Com

e>perts or even end sers. 5he "ollo'ing e>ample sho's a do ble-vie' .ervice !a@ade 'ith standard con<g ration%
2Stateless 23ocal(Boo9Or"erin7Service3ocal.class) 2Remote(Boo9Or"erin7ServiceRemote.class) 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public class Boo9Or"erin7ServiceBean implements Boo9Or"erin7Service3ocal # public voi" cancelOr"er(Strin7 i") # $ public voi" or"er(Strin7 isbn1 Strin7 name) # $

5he .ervice !a@ade is the bo ndary bet'een the presentation and b siness layers. 5he methods o" the "a@ade are triggered by the end ser. -very interaction bet'een the ser and the system is a b siness transaction. 5he transaction is either completed in its entirety or not at all. 5he simplest 'ay to reali?e s ch b siness transactions is to map them to technical transactions. A stateless session bean 'ith container-managed transactions (C(5s) is per"ectly s itable "or that p rpose. A .ervice !a@ade is there"ore annotated 'ith the :ransactionAttribute:'pe.R);U<R)SJA)! class level. 5his setting is inherited by all methods. R);U<R)SJA)! al'ays starts a ne' transaction and s spends the e>isting one. Altho gh not mandatory$ this approach is more e>plicit. -ven tho gh a .ervice !a@ade is the bo ndary bet'een the presentation and b siness layers$ it is impossible to have an e>isting transaction. .ervice !a@ade instances sho ldnRt invo#e each otherIit = st cannot be e>pressed by o r semantics. 5he presentation components invo#e the .ervice !a@ade method$ 'hich starts a transaction and propagates it to the services. -ach interaction is modeled as a .ervice !a@ade method. A .ervice !a@ade is de<ned as a bo ndary$ so invocations bet'een .ervice !a@ade methods are there"ore e>cl ded. !rom a technical point o" vie'$ ho'ever$ there is no di""erence bet'een the R);U<R)SJA)! and R);U<R)8 transaction attrib tes o" a .ervice !a@adeIyo can se either attrib te. 5he setting R);U<R)8 either starts a ne' transaction (in case it does not already e>ist) or re ses an e>isting transaction. As mentioned earlier$ an e>isting transaction cannot e>ist in o r case. 5he stateless nat re o" the bo ndary ca ses detachment o" all *PA-entities a"ter every method call. A .ervice !a@ade implies a service-oriented 'ay o" thin#ing and promotes proced ral programming. 5he methods are act ally proced res$ 'hich e>pect parameters and ret rn the res lt per val e. 5he parameters and res lts can be either 5rans"er ,b=ects (5,s) or detached *PA entities. 5he e>posed vie' o" the .ervice !a@ade is coarse-grained and th s o" less interest "or re se. 5he logic is in general too comple> to be implemented directly in the .ervice !a@ade. +t 'o ld bloat the method implementation and lead to hard-to-maintain code. 5he .ervice !a@ade is designed to act as a se case controller and coordinate independent services. 5his ens res that the services can remain independent o" each other and can be re sed in

20
Download at WoweBook.Com

other conte>ts or se cases. 5he controlled services have to be invo#ed in the conte>t o" the .ervice !a@ade transaction. ,nly then can the reB irement "or consistency be " l<lled.

6ethin#ing
Application .ervice (.ervice !a@ade) sed to be a mandatory part o" every *2-- application. +t 'as sed to isolate the presentation tier "rom the b siness tier. 5he parameters o" the Application .ervice 'ere either primitives or ;ata 5rans"er ,b=ects (;5,s). -ntity beans 'ere not detachable$ so it 'asnRt an option to 'or# 'ith entity beans as parameters or ret rn val es. 5he remote or local vie' o" the Application .ervice as 'ell as the reali?ation 'ere dependent on the -*B 2.> AP+. 5he separation bet'een the technical in"rastr ct re and the b siness logic 'as not given$ so in most cases the Application .ervice 'as = st a delegate to a plain old *ava ob=ect (P,*,) 'hich implemented the val able b siness logic. 5his separation is no longer necessary$ beca se the .ervice !a@ade is a clean P,*, that only depends on a "e' annotations. 5he distinction bet'een a p re controller and service is bl rred as 'ell. +n *2--$ the Application .ervice tended to play the controller role only and coordinated e>isting services. 5his 'asnRt bene<cial "or simple$ C67;-li#e se cases 'here the Application .ervice only delegates all invocations to a .ession !a@ade 'ith e>actly the same signat re. 5he Application .ervice 'as a 'rapper$ 'ith virt ally no added val e. A common e>c se "or s ch architect res 'as the " t reproo" and scalability reB irements. )o'ever$ in most cases this constellation 'asnRt to ched ntil the end o" the application li"ecycle. .ervice !a@ade is no longer the only choice in *ava --. 5he clean separation bet'een technology and b siness reali?ation allo's the implementation o" domain-driven approaches directly 'ith session beans and *PA entities. . ch ob=ect-oriented systems are state" l and reB ire <ne-grained interaction bet'een the presentation and the b siness logic. 5he gate'ay can be sed to implement this principle as 'ellS it is$ ho'ever$ the e>act opposite o" the .ervice !a@ade. !rom the vie' o" the .ervice !a@ade the gate'ay co ld even be considered as an anti-pattern. Eith the introd ction o" -*B 3.0 the local and remote homes became optional and sho ld no longer be sed. Eith -*B 3.4 even the B siness +nter"ace is no longer mandatory$ so yo can se directly the bean implementation (the no-inter"ace vie'). 5he .ervice !a@ade is comprised o" a local b siness inter"ace and its implementationS it is a common stateless session bean. +t is not recommended to se a no-inter"ace vie'$ beca se it ma#es testing and moc#ing harder. All methods are transactionalIthey start a ne' transaction on every invocation.

Conventions
Service 0a@ade resides in a co*!onent that is reali5ed as a Java !ackage /ith a do*ain' s!ecific na*e1 for e6a*!le1 or"erm7mt. +he reali5ation of the fa@ade (-,siness interface and the -ean i*!le*entation) resides in a s,-!ackage /ith the na*e facade or boundary1 for e6a*!le1 or"erm7mt.(aca"e or or"erm7mt.boun"ar'. +he -,siness interface is na*ed after -,siness conce!ts1 /itho,t the o-ligatory local or re*ote s,ffi61 for e6a*!le1 Or"erService and Or"erServiceBean.

21
Download at WoweBook.Com

&t is not re8,ired to ,se the ter* facade in the na*e of the -eanAit:s red,ndant. 0or identification !,r!oses yo, co,ld ,se a 2Service&aca"e annotation. +he Service 0a@ade al/ays starts a ne/ transaction7 it is not !ossi-le to !artici!ate in a transaction in !rogress. &t is de!loyed /ith the R);U<R)SJA)! transaction attri-,te.

Participants and 6esponsibilities


+n *ava --$ the .ervice !a@ade became more pragmatic. +ts main responsibility is still the composition o" independent and re sable services$ b t "or simple se cases it can directly reali?e b siness logic 'itho t delegating to other participants. !ig re 4sho's se cases o" the .ervice !a@ade.

Figure 1. Service Faade with its participants +n more comple> scenarios a .ervice !a@ade coordinates some services or ;A,s. 5he remote b siness inter"ace sho ld be sed by remote clients only. Eherever possible$ the local inter"ace sho ld be accessed instead. -specially 'eb "rame'or#s s ch as Eic#et$ *.!$ or .tr ts sho ld rely on the local inter"ace only.

.trategies
5his section disc sses the speci<c variants and .ervice !a@ade con<g rations. ;ependent on yo r needs a .ervice !a@ade can be scaled "rom a simple C67; !acade$ 'hich reali?es generic data management operations$ to a " ll-blo'n asynchrono s .,A strategy. #R;" 0a@ade A C67; "a@ade is nothing else than an e>posed$ transactional ;A,. !rom a p ristRs point o" vie'$ a C67; se case has to be reali?ed by a service "a@ade that delegates all calls to a ;A,. +n

29
Download at WoweBook.Com

case o" C67;$ ho'ever$ even a dedicated ;A, is already an e>ample o" overengineering. A C67; "a@ade is a service "a@ade 'ith the " nctionality o" a ;A,$ or a ;A, 'ith the metadata attrib tes o" a .ervice !a@ade. !or the sa#e o" simplicity a C67; "a@ade can be deployed 'ith a no-inter"ace vie' as 'ell. All other strategies are deployed 'ith a local or remote b siness inter"ace. -specially in the case o" a generic data so rce "or the Eic#et$ Eeb Beans$ or *.! models$ there is no need "or an inter"ace. 5he )ntit'6ana7er in the C67; "a@ade can be easily moc#ed-o t i" necessary. ",al'Bie/ 0a@ade +n most cases$ the .ervice !a@ade is accessed "rom 'eb components directly and th s in process. Altho gh most application servers recogni?e this co-location and get rid o" the remote in"rastr ct re to access the -*B directly$ the -*B container is reB ired by the spec to copy all parameters and ret rn val es. 7nnecessary copying o" all parameters and ret rn val es can become B ite e>pensiveIthe per"ormance impact is dependent on the parameter. Primitive types have no impactS the impact o" copying o" a comple> graph o" interconnected val e ob=ects can be massive. 5he "ollo'ing e>ample ill strates the per-re"erence vers s per-val e semantics.
public class 3ocal?s?alue:est exten"s ttpServlet #

2)*B private Boo9Or"erin7Service3ocal boo9Or"erin7Service3ocal2)*B private Boo9Or"erin7ServiceRemote boo9Or"erin7ServiceRemoteprotecte" voi" processRequest( ttpServletRequest request1 ttpServletResponse response) t+ro,s Servlet)xception1 <O)xception # Parameter:est tst D ne, Parameter:est(PI)Object local D boo9Or"erin7Service3ocal.re(erence:est(tst)Object remote D boo9Or"erin7ServiceRemote.re(erence:est(tst)out.println(4:+e same re(erence (local service)QG 4 H (tst DD local))out.println(4:+e same re(erence (remote service)QG 4 H (tst DD remote))$ $

Both vie's are in=ected into a .ervlet. +n both cases an ob=ect is passed as parameter and ret rned 'itho t any processing%
public Object re(erence:est(Object re(erence) # return re(erence$

->actly the same method is e>posed t'ice% over the remote and local inter"aces. 5he o tp t is not really s rprising. 5he same re"erence is ret rned "rom the local b siness inter"ace and a copy in the remote case.
:+e same re(erence (local service)QG true :+e same re(erence (remote service)QG (alse

5his is ho' every -*B container sho ld behave. (ost o" the containers$ ho'ever$ provide proprietary e>tensions to ret rn a re"erence even in the remote case. !or that p rpose o"ten an

:0
Download at WoweBook.Com

application serverspeci<c deployment descriptor has to be provided. Dlass<sh ses the .pass/ b'/re(erence0true.%pass/b'/re(erence0 tag in the proprietary sun/ejb/ jar.xml <le to activate this optimi?ation. 5he "a@adeRs remote inter"ace is e>posed to e>ternal clients$ so it has to remain stable d ring the li"ecycle. ,n the other hand$ not all methods need to be e>posed remotelyS some o" them are only dedicated "or internal se s ch as 'or#Ho' engines$ 'eb applications$ or message-driven beans. 5he above reB irement co ld be solved easily in traditional ob=ect-oriented programming. A class co ld e>pose the p blic methods to e>ternal clients as a "ormali?ed contract and dedicate the pac#age private or protected methods to its "riends. Qo can approach this reB irement similarly 'ith a .ervice !a@ade. +ts remote b siness vie' co ld be e>posed to the e>ternal clients 'ith high stability reB irements$ 'hereas the local vie' co ld be e>tended on demand in a more pragmatic manner. 5he local b siness inter"ace e>tends the remote inter"ace$ 'hich ma#es maintenance easy. +t is eno gh to declare the additional " nctionality in the local inter"aceIall methods 'ill be inherited "rom the remote method (see !ig re 2).

Figure 2. The dual-view Service Faade. 5he session bean has to implement all methods any'ay. At the beginning$ the local inter"ace is probably empty and implicitly inherits all methods "rom the remote b siness inter"ace. As the implementation evolves$ the internal vie' o" the session bean can incrementally be e>tended 'itho t brea#ing the p blic vie'. Both inter"aces can be easily in=ected to their cons mers. 5he local vie' is only available "or the cons mers inside the same *A($ b t is not limited to be sed by 'eb "rame'or#s only. +t can be e>posed via a 6-.5! l inter"ace$ *(.$ or any other #ind o" adapter. S(A 0a@ade

:4
Download at WoweBook.Com

5he .,A !a@ade$ compared to the other strategies$ is asynchrono s in nat re and has rich metadata. +n an .,A-'orld$ services are e>pected to be a tonomo s and independent o" each other as 'ell as technology agnostic. 5hese t'o "acts already spea# against the se o" distrib ted transactions (2PC). A transactional and consistent serial invocation o" di""erent services is there"ore impossible. 5he sol tion to this challenge is asynchrono s messaging$ <re-and-"orget style. 5he asynchrono s comm nication implies that the error resol tion and consistency are the responsibility o" the message cons mer not the prod cer. At the implementation level$ yo have to omit the ret rn val e. All methods are voi". 5his in t rn ma#es a .ervice !a@ade especially interesting as a *(. cons mer. 5he incoming messages are cons med by a message-driven bean and trans"ormed into the .ervice !a@ade parameters. 5he "ollo'ing e>ample sho's a message-driven bean as an asynchrono s adapter.
26essa7e8riven(mappe"Aame D 4jms%Service&aca"e41 activationCon(i7 D # 2ActivationCon(i7Propert'(propert'Aame D 4ac9no,le"7e6o"e41 propert'?alue D 4Auto/ac9no,le"7e4)1 2ActivationCon(i7Propert'(propert'Aame D 4"estination:'pe41 propert'?alue D 4javax.jms.;ueue4) $) public class Boo96essa7eConsumerBean implements 6essa7e3istener # 2)*B private #oo38rderin+Service@ocal boo38rderin+Service@ocal; public voi" on6essa7e(6essa7e ms7) # i((ms7 instanceo( Object6essa7e)# tr' # Object6essa7e object6essa7e D (Object6essa7e) ms7Seriali=able pa'loa" D object6essa7e.7etObject()i( (pa'loa" instanceo( Or"er?O) # Or"er?O or"er?O D (Or"er?O) pa'loa"Strin7 name D or"er?O.7etAame()Strin7 isbn D or"er?O.7et<sbn()t+is.boo9Or"erin7Service3ocal.or"er(isbn1 name)$ else # +an"le)rror(4Pa'loa" is not a Or"er?O41 pa'loa")$ $ catc+ (*6S)xception ex) # t+ro, ne, <lle7alState)xception(4@G 4 H messa7e1ex)$ $else# +an"le)rror(46essa7e is not o( t'pe Object6essa7e41messa7e)$ $

5he message-driven bean is already transactionalS the -*B container starts a transaction be"ore the on6essa7e method. 5his becomes a problem$ beca se the .ervice !a@ade also starts a ne' transactionIit is s ally deployed 'ith the :ransactionAttribute:'pe.R);U<R)SJA)! level. *ava -- does not s pport nested transactions$ so the message-driven bean transaction 'ill s cceed$ regardless o" 'hether the .ervice !a@adeRs transaction 'as rolled bac# or not.

:2
Download at WoweBook.Com

* ccess "or a message-driven bean means removal o" the message "rom the 8estination. 5his leads to nasty errorsS the b siness logic can "ail and ca se a rollbac# o" the active transaction in the .ervice !a@ade and the message-driven bean 'ill not recogni?e this "ail re. A rollbac# can be ca sed by the invocation o" SessionContext#setRollbac9Onl' 'itho t even thro'ing an e>ception. Altho gh the transaction "ails in the .ervice !a@ade$ the message 'ill be cons med any'ay. +t silently disappears "rom the destination. . ch a case co ld have a severe impact$ especially in case the message 'as intended to be delivered reliably. 5he client relies on the g aranteed delivery o" the message$ 'hich act ally happens$ b t the message gets lost bet'een the cons mer and the b siness logic. 5he iss e above can be <>ed easily 'ith the :ransactionAttribute:'pe.R);U<R)8 attrib te or be made even more e>plicit 'ith the 6AA8A:ORB type on the .ervice !a@ade. 5he transaction started in the message-driven bean 'ill then be propagated to the .ervice !a@ade. A possible rollbac# 'ill prevent the message to be ac#no'ledgedIit 'ill ret rn to the destination and be redelivered a"ter a con<g rable period o" time (in most cases immediately). 5his in t rn can lead to inde<nite delivery attempts$ 'hich can be <>ed co nting the redelivery "ail res and moving the 6essa7e to an error B e e a"ter a certain n mber o" attempts$ or setting p the *(. provider. Erapping a .ervice !a@ade 'ith a message-driven bean is a common 'ay to invo#e synchrono s methods asynchrono sly (see .ervice Activator). 5he problem described above has nothing to do 'ith *(.$ b t 'ith transactional messaging. 5he .ervice !a@ade has to re se the propagated transaction rather than starting a ne' one. 5he <re-and-"orget comm nication style is only one aspect o" an .,A. +n the <rst place$ rich meta data and e>plicit contracts ma#e the distinction bet'een enterprise application integration (-A+) architect re and real .,A. 5he additional description o" the contract (so called meta data) can be sed "or more or less pragmatic p rposes. 5he main problem 'ith <re-and-"orget messaging is the comple> error handling and many necessary type chec#s. 5he deco pling does not come "or "ree. .ome o" the type chec#s are crossc tting " nctionality and can be "actored o t easily into a re sable interceptor. 5he e>pected type in"ormation has to be passed to the interceptor "rom the contract$ 'hich can be done 'ith a c stom annotation%
2:ar7et(#)lement:'pe.6): O81)lement:'pe.:BP)$) 2Retention(RetentionPolic'.RUA:<6)) 28ocumente" public 2inter(ace )xpecte"6essa7e:'pe # Class.Q exten"s 6essa7e0 value()$

Beca se a message-driven bean consists o" only one method$ on6essa7e$ the annotation can be declared on the class level as 'ell as the method itsel". 5he only attrib te o" the )xpecte"6essa7e:'pe is the val e 'ith the type Class. +t is intended to speci"y the e>pected type%
2)xpecte"6essa7e:'pe(8b!ect7essa+e.class) public voi" on6essa7e(6essa7e messa7e) #$

5his meta in"ormation is leveraged by the 6essa7e:'peC+ec9<nterceptor interceptor.

:3
Download at WoweBook.Com

public class 6essa7e:'peC+ec9<nterceptor # 2Aroun"<nvo9e public Object au"it(<nvocationContext ic) t+ro,s )xception# 6et+o" met+o" D ic.7et6et+o"()i((4on6essa7e4.equals(met+o".7etAame()))# )xpecte"6essa7e:'pe messa7e:'pe D met+o".7etAnnotation()xpecte"6essa7e:'pe.class)Class t'pe D messa7e:'pe.value()Object messa7eParameter D ic.7etParameters()NROi((5t'pe.isAssi7nable&rom(messa7eParameter.7etClass()))# escalate)rror(t'pe1messa7eParameter)$ $ return ic.procee"()$

5he interceptor is intended to be sed 'ith message-driven beans$ so it only t rns active "or the method on6essa7e. +t searches "or the annotation$ "etches the e>pected type$ and compares it 'ith the act al message type. +n case it matches$ the on6essa7e method 'ill be invo#edS other'ise the error 'ill be escalated. -scalation does not mean = st thro'ing an e>ceptionIthe error has to be reported to some tic#eting or emergency management system. !rom the interceptor point o" vie'$ it 'o ld s "<ce to p blish the error via a dead letter or bac#-o t B e e. 5he cons mption o" the message$ as 'ell as the act al escalation$ goes beyond the scope o" the boo# and is proprietary in general. 5he reB irement "or escalation o" s ch messages is given "or all <re-and-"orget architect res and .,As in partic lar. 5he centrali?ation o" proper error handling in an interceptor ma#es not only the code cleaner$ it also minimi?es the probability o" errors. ! rthermore$ a centrali?ed errorhandling aspect can be easily maintained and con<g red. 5he same idea o" contract enrichment 'ith metadata cannot only be applied to message-driven beans$ b t also to the .ervice !a@ade itsel". Additional c stom annotations on a class$ method$ and even parameter level co ld enrich the .ervice !a@ade and provide necessary in"ormation "or monitoring$ validation$ or e>ception handling. An 2AotAull annotation on the parameter level co ld provide a hint "or the interceptor "or notn ll chec#s%
)2nterceptors(6recondition2nterceptor.class) public class Boo9Or"erin7ServiceBean implements Boo9Or"erin7Service3ocal # public voi" or"er(2AotAull Strin7 isbn1 Strin7 name) # S'stem.out.println(4or"er <SBAG 4 H isbn H 4 nameG 4 H name)$ $

5he interceptor searches "or parameters$ chec#s "or the not-n ll condition$ and processes possible errors.
public class Precon"ition<nterceptor #

:8
Download at WoweBook.Com

2Aroun"<nvo9e public Object c+ec9Parameters(<nvocationContext invocationContext) t+ro,s )xception# 3ist.Strin70 invali"Parameters D invali"Parameters(invocationContext)i((5invali"Parameters.is)mpt'())# 6et+o" met+o" D invocationContext.7et6et+o"()escalate)rror(met+o"1invali"Parameters)t+ro, ne, <lle7alAr7ument)xception(4:+e contract o( t+e met+o"G 4 H met+o" H 4 ,as violate"54)$else# return invocationContext.procee"()$ $ private 3ist.Strin70 invali"Parameters(<nvocationContext context)# 3ist.Strin70 invali"Parameters D ne, Arra'3ist.Strin70()AnnotationNONO parameterAnnotations D context.7et6et+o"().7etParameterAnnotations()(or (int iDR-i.parameterAnnotations.len7t+-iHH) # (or (Annotation annotation G parameterAnnotationsNiO) # i((annotation instanceo( AotAull)# 8b!ect value > conte=t.+et6arameters()AiB; i/(value >> null){ 0lass parameter4ype > conte=t.+et7et od().+et6arameter4ypes() AiB; invali"Parameters.a""(iH 4 parameter o( t'pe 4 H parameter:'pe.7etAame() H 4 is null54)$ $ $ $ return invali"Parameters$ private voi" escalate)rror(6et+o" met+o"13ist.Strin70 invali"Parameters) # %%escalate errors $ $

5he 'ay error handling is reali?ed$ depends on the .,A in"rastr ct re and its reB irements. +n case o" validation errors it is s "<cient to thro' an e>ception$ 'hereby the violation o" .ervice 9evel Agreements (.9As) s ch as per"ormance contracts sho ld be escalated to an emergency management in"rastr ct re. Another e>ample o" cross-c tting chec#s is$ "or e>ample$ the 26ax:ime annotation$ 'hich de<nes the ma>im m invocation time. An interceptor co ld se this additional in"ormation$ compare it 'ith meas red time$ and report slo' methods. 9ight/eight Asynchrono,s 0a@ade !rom a concept al point o" vie'$ a light'eight asynchrono s "a@ade is an .,A "a@ade 'ith p re -*B 3.4 'itho t *(.. -*B 3.4 introd ced an easy 'ay to invo#e session bean methods

:2
Download at WoweBook.Com

asynchrono sly. +t is s "<cient to declare methods as 2As'nc+ronousS they 'ill be invo#ed in a bac#gro nd thread. )o'ever$ this approach has some limitations regarding the ret rn val e. ,nly voi" and java.util.concurrent.&uture types are allo'ed. 5he res lt val e o" an asynchrono s invocation is available to the client by ret rning a &uture.?0 ob=ect "or 'hich the 7et() and 7et(lon7 timeout1 :imeUnit unit) methods ret rn the res lt val e. A concrete &uture.?0 implementation called javax.ejb.As'ncResult.?0 is provided by the container. As'ncResult.?0 has a constr ctor that ta#es the res lt val e as a parameter. 5he "ollo'ing e>ample ses 2As'nc+ronous methods in -*B 3.4%
2As'nc+ronous 2Stateless public class Boo9Or"erin7ServiceBean implements Boo9Or"erin7Service # public &uture.Or"er?O0 or"er(Strin7 isbn1 Strin7 name) # Or"er?O or"er?O D ... return ne, As'ncResult.Or"er?O0(or"er?O)$ public voi" cancelOr"er(Strin7 i") # $ $

5he b ilt-in s pport "or asynchrono s processing is not only easier and cleaner compared to the *(. 'ay$ b t it also allo's bidirectional comm nication. 6eB est-response comm nication style is m ch harder to implement sing messaging. Qo 'o ld need an inp t B e e$ o tp t B e e$ and at least three independent transactions. ! rthermore$ the initiator o" the comm nication 'ill have to 'ait "or the response and bloc#. 5he B estion is$ ho' long to 'ait "or a responseG A timeo t is not the g arantee "or "ail reS it co ld occ r = st a"ter a s ccess" l completion o" the transaction. . ch an error is hard to handle. Also$ "rom the management and monitoring perspective$ is the 2As'nc+ronous 'ay comparable to *(.. 5he method is e>ec ted in the bac#gro nd thread$ 'hich in t rn 'ill come in general (it isnRt covered by the spec) "rom a thread pool managed and monitored by the server. 5he light'eight asynchrono s "a@ade is a viable alternative "or a service-oriented 'ay o" e>posing -*B " nctionality. ! rthermore asynchrono s -*B 3.4 methods are more appropriate "or the implementation o" asynchrono s behavior$ 'itho t typical .,A reB irements. (essaging and *(. in partic lar$ provide looser co pling$ b t are harder to develop and maintain. -specially rob st error handling is challenging and reB ires additional in"rastr ct re-li#e error B e es and even emergency management systems. +t is the developerRs responsibility to ens re not only the correct type o" the javax.jms.6essa7e$ b t also its content. Both problems simply do not e>ist in case o" 2As'nc+ronous methods. 5he compiler chec#s the method signat re "or yo . +n *2--$ *(. 'as o"ten sed = st "or asynchrono s e>ec tion o" synchrono s methods. 5here 'as no other 'ay to invo#e session beans in a bac#gro nd thread. -*B 3.4 introd ced an elegant 'ay to solve the bac#gro nd e>ec tion 'itho t relying on messaging.

::
Download at WoweBook.Com

5he &uture even allo's the cancellation o" the c rrent tas# 'ith the method boolean cancel(boolean ma'<nterrupt<(Runnin7). 5he -*B$ in t rn$ is able to chec# a cancellation reB est 'ith the invocation o" SessionContext#isCancelle"(). . ch a cancellation protocol is not available "or *(. and is hard to implement on top o" it as 'ell. %,ltichannel 0a@ade 5he .ervice !a@ade methods can be e>posed easily via local and remote b siness inter"aces 'ith almost no e""ort. 5he local methods are available only "or in-process clients$ 'hereas the remote inter"aces are accessible "or other *A(s via 6(+-++,P as 'ell. Eith additional meta data$ .ervice !a@ade methods can be e>posed via the Eeb .ervice ;escription 9ang age (E.;9) and .,AP in partic lar. 5he "ollo'ing snippet demonstrates the e>pos re o" a .ervice !a@ade as a E.;9C.,AP%
2Stateless 23ocal(Boo9Or"erin7Service3ocal.class) 2Remote(Boo9Or"erin7ServiceRemote.class) 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) )"ebService public class Boo9Or"erin7ServiceBean implements Boo9Or"erin7Service3ocal # public voi" or"er(Strin7 isbn1 2!ebParam(nameD4or"erAame4) Strin7 name) # S'stem.out.println(4or"er <SBAG 4 H isbn H 4 nameG 4 H name)$

5he Eeb .ervice annotations (*.6-414) allo' the c stomi?ation o" the E.;9 signat re s ch as parameter names or method names$ or even e>cl de partic lar methods "rom the E.;9 completely. 5he protocols described th s "ar are very 'ell integrated 'ith the -*B 3.4 spec. +n the practice$ there is still a need "or the e>pos re o" methods to non-*ava clients in a more pragmatic and compatible "ashion as is the case 'ith .,AP. 6-.5! l Eeb services (*.6-344) are = st one optionIand they are part o" the *ava -- : speci<cation. 6-.5! l Eeb .ervices$ ho'ever$ is a standalone AP+ 'hich is not as tightly integrated 'ith -*B 3.0 as *.6-414.-*B 3.4 can not only be in=ected into a *AK-6. reso rce$ b t can even e>pose itsel" as a 6-.5 reso rce and be addressed directly. A reso rce class is going to be niB ely addressed by a 769 (order$ in o r case)S its methods are associated 'ith 2>):$ 2POS:$ 2PU:$ 28)3):)$ and are invo#ed respectively.
import import import import import import import javax.,s.rs.Pro"uce6imejavax.,s.rs.Consume6imejavax.,s.rs.PU:javax.,s.rs.Pat+javax.,s.rs.>):javax.,s.rs.Pat+Paramjavax.,s.rs.;uer'Param-

2Pat+(4or"ers4) public class Or"erRestA"apter #

:0
Download at WoweBook.Com

2)*B private Boo9Or"erin7Service or"erin7Service2>): 2Pro"uce6ime(4application%xml4) 2Pat+(4#or"er<"$%4) public Or"er8:O 7etOr"er(2Pat+Param(4or"er<"4) <nte7er or"er<") # Or"er (oun" D t+is.or"erin7Service.(in"(or"er<")Or"er8:O or"er8:O D ne, Or"er8:O((oun")return or"er8:O$ 2PU: 2Consume6ime(4application%xml4) public voi" placeOr"er(Or"er8:O or"er8:O) # t+is.or"erin7Service.placeOr"er(or"er8:O.7etOr"er())$ $

5he *.6-344 provider cares abo t the marshaling o" the parameters and ret rn val es in a variety o" "ormats. 5he most common "ormats are text%plain$ application%xml$ and application%json. A 6-.5! l client only relies on plain )55P and the data "ormat. Act ally a 6-.5! l inter"ace is "ar more rob st and technology independent compared to .,AP and even the E.-V s ite. )55P didnRt changed "or years$ and the parameters and ret rn val es are = st plain payload and are as rob st as the applicationRs design. 5he class Or"erRestA"apter is enriched 'ith some javax.,s.rs annotations$ 'hich are necessary "or the e>pos re o" a 6-.5! l inter"ace. +n addition$ it is a typical adapterS it cares abo t the conversion o" the Or"er entity into K(9 "ormat. !or that p rpose a *ava Annotation "or K(9 Binding (*AKB) annotated ;5, is sed%
2KmlRoot)lement public class Or"er8:O # private Or"er or"erpublic Or"er8:O() # t+is.or"er D ne, Or"er()$ public Or"er8:O(Or"er or"er) # t+is.or"er D or"er$ 2Kml)lement public <nte7er 7et<sbn() # return t+is.or"er.7et<sbn()$ public voi" set<sbn(<nte7er isbn) #

:1
Download at WoweBook.Com

t+is.or"er.set<sbn(isbn)$

5he Or"er8:O delegates all invocations to the ,rder entity and e>poses itsel" "or *AKB seriali?ation and de-seriali?ation. 5he pop lar open so rce pro=ect )essian (http%CChessian.ca cho.comC) is a binary 'eb service protocol. +t is based on .ervlets and is very "ast and scalable. Bindings "or di""erent lang ages are already available. 5he integration 'ith a .ervice !a@ade is very similar to 6-.5! l services. A protocol adapter ta#es the responsibility "or the conversion o" parameters and ret rn val es. +t delegates the .ervice !a@ade via the local b siness inter"ace$ 'hich remains protocol agnostic. 5he #ey "or s ccess in m ltichannel scenarios is the decoration o" a protocol-independent .ervice !a@ade 'ith protocol-speci<c adaptors. 5he .ervice !a@ade remains largely technology ne tral and conseB ently can be re sed in di""erent scenarios and protocols. Eith the emerge o" *ava !K$ !le>$ Air and A=a>$ m ltichannel .ervice !a@ades become an interesting strategy "or solving the interoperability problem. (ost o" the protocols are not transactional$ so there is a h ge di""erence bet'een *(.$ 6-.5! l or )essian integration. A message-driven bean starts the transaction be"ore the invocation o" the .ervice !a@ade$ 'hich is clearly not the case in 6-.5! l and )essian scenarios. 5h s the .ervice !a@ade can be still deployed 'ith the :ransactionAttribute:'pe.R);U<R)SJA)! attrib te. 5he transaction 'ill be started as the adapter invo#es the "a@ade$ accordingly a rolled bac# transaction in the .ervice !a@ade 'ill not ca se a redelivery o" a .,AP message or 6-.5 reB est. &&(P 0a@ade ++,P !a@ade is a speci<c case o" the ( ltichannel !a@ade. +t e>poses its remote vie' in a C,6BA C ++,P compliant 'ay. -*B 2 components 'ere e>posed via C,6BA C ++,P per de"a lt. 5his is still the case 'ith -*B 3$ b t only 'ith 6emote)ome and 6emote vie's$ so some additional 'or# is reB ired. Be"ore + e>pose the inter"ace in C,6BA-compliant 'ay$ + sho ld clari"y the motivation <rst. C,6BA seems to have a bad rep tation in the enterprise$ it is said to be heavy'eight. -ven more interesting is the "act that C,6BA C ++,P c rrently seems to get traction in embedded devices. ! rthermore$ C,6BA is already 'idely deployedS bindings "or many di""erent lang ages are 'idely available. Clients 'ritten in other lang ages s ch as CWW can comm nicate easily 'ith the ++,P .ervice !a@ade directly$ 'itho t additional libraries or "rame'or#s. Altho gh it might so nd someho' esoteric$ direct ++,P comm nication bet'een legacy clients and -*Bs is o"ten the simplest and most rob st sol tion. (ore li#ely is the reB irement "or e"<cient comm nication 'ith ./-5 clients. Altho gh ./-5 clients do not s pport ++,P directly$ open so rce "rame'or#s s ch as ./-5-++,P (http%CCiiopnet.so rce"orge.netC) enable "ast (times "aster than .,AP) bridge bet'een both plat"orms. 5o ma#e a .ervice !a@ade ++,P compatible$ an -*B 2 6emote )ome inter"ace has to be provided%
public inter(ace <<OPService&aca"e ome exten"s )*B ome#

:9
Download at WoweBook.Com

public <<OPService&aca"eRemote create() t+ro,s Create)xception1Remote)xception$

+t is basically the "actory o" the 6emote +nter"ace <<OPService&aca"eRemote. +t isnRt the remote b siness inter"ace$ b t the old -*B 2 style one%
public inter(ace <<OPService&aca"eRemote exten"s )*BObject# public Strin7 or"er(Strin7 isbn1Strin7 name) t+ro,s Remote)xception$

5he Bean class is mar#ed as 2Stateless and declares <<OPService&aca"e ome 'ith the 2Remote ome annotation. 5he remote inter"ace does not have to be declared$ it is = st derived "rom the <<OPService&aca"e ome "actory method ret rn type$ as sho'n in the "ollo'ing ++,P-compatible -*B 3 snippet%
2Stateless 2Remote ome(<<OPService&aca"e ome.class) public class <<OPService&aca"eBean # 2)*B private Boo9Or"erin7Service3ocal service3ocalpublic Strin7 or"er(Strin7 isbn1Strin7 name)# t+is.service3ocal.or"er(isbn1 name)return 4Boo9 ,it+ isbnG 4 H isbn H 4 ,as or"ere"4$ $

<<OPService&aca"eBean is still an -*B 3 stateless session bean$ so that ;ependency +n=ection remains available. -ither the real .ervice !a@ade$ or a .ervice co ld be in=ected. +n case yo have only to e>pose the " nctionality o" the .ervice !a@ade via ++,P e>cl sively$ an indirection o" this #ind is not needed. !or test p rposes$ the "a@ade is invo#ed "rom an 6(+-++,P client sing the plain *;&-,6B. /o application server<speci<c *A6 is reB ired$ as sho'n in this e>ample
import import import import import com.abien.patterns.business.iiops(.<<OPService&aca"e omecom.abien.patterns.business.iiops(.<<OPService&aca"eRemotejavax.namin7.Contextjavax.namin7.<nitialContextjavax.rmi.PortableRemoteObject-

public class CorbaClient # public static voi" main(Strin7NO ar7s) t+ro,s )xception# S'stem.setPropert'(4or7.om7.CORBA.ORB<nitialPort414STRR4)S'stem.setPropert'(4or7.om7.CORBA.ORB<nitial ost414local+ost4)S'stem.setPropert'(Context.<A<:<A3JCOA:)K:J&AC:ORB1 4com.sun.jn"i.cosnamin7.CACtx&actor'4)Context context D ne, <nitialContext()Object object D context.loo9up(4...business.iiops(.<<OPService&aca"e ome4)-

00
Download at WoweBook.Com

<<OPService&aca"e ome (aca"e ome D (<<OPService&aca"e ome) PortableRemoteObject.narro,(object1 <<OPService&aca"e ome.class)<<OPService&aca"eRemote remote D (aca"e ome.create()Strin7 status D remote.or"er(4UIK414*ava )) V4)S'stem.out.println(4Or"er statusG 4 H status)$ $

5he <rst attempt 'ill end 'ith a AullPointer)xception. +t is ca sed by the lac# o" st bs. 5hey can be created easily 'ith the *;& rmic tool.
rmic /classpat+ NPA: J:OJ)*BJAP<O-NC3ASSJ&<3)SO /iiop com.abien.patterns.business.iiops(.<<OPService&aca"e ome rmic /classpat+ NPA: J:OJ)*BJAP<O-NC3ASSJ&<3)SO /iiop com.abien.patterns.business.iiops(.<<OPService&aca"eRemote

*;& lac#s o" s pport "or dynamic ++,P st b generation$ 'hat ma#es this step necessary. 5he ++,P-compatible vie' comes 'ith some additional overhead and ma#es the .ervice !a@ade less clean. -ven considering the additional overhead and gliness a ++,P .ervice !a@ade co ld be the easiest possible sol tion "or comm nication 'ith non-*ava$ and especially CWW and .net clients.

5esting
6egardless on the strategy yo choose$ .ervice !a@ade e>poses coarse-grained se cases and th s b siness " nctionality. +t is the bo ndary bet'een the presentation and b siness logic. )ence$ it is o"ten sed as a separation strategy to b ild independent design and developer teams. A .ervice !a@ade encaps lates the reali?ation o" the component and e>poses a p blic AP+ to its clients. )igh-B ality nit tests "or the p blic methods o" a .ervice !a@ade are absol tely mandatory$ 'hereby e>tensive tests o" the arti"acts behind the "a@ade are optional in the overall conte>t. +n -*B 3.0 s pport "or embeddable -*B containers did not e>istIso the bootstrapping had to be per"ormed man ally. Beca se -*B 3.0 and *PA entities are P,*,s$ it 'as rather painless. Eith "e' additional lines o" code not only the in=ection o" other beans (= st an additional line o" code) b t o" the )ntit'6ana7er is possible. 5he short initiali?ation ro tine can be encaps lated easily in a base$ abstract class. +t ta#es the responsibility "or the initiali?ation o" the )ntit'6ana7er$ as 'ell as the )ntit':ransactionG
public class AbstractPersistence:est # protecte" )ntit'6ana7er emprotecte" )ntit':ransaction etpublic voi" setUp() # em D Persistence.create)ntit'6ana7er&actor'(4NPUJAA6)O4). create)ntit'6ana7er()et D em.7et:ransaction()$

04
Download at WoweBook.Com

Both protected <elds are inherited by the concrete nit test classes%
public class Boo9Or"erin7ServiceBean:est exten"s AbstractPersistence:est# private Boo9Or"erin7ServiceBean serviceBean2Be(ore public voi" init8epen"enc'<njection()# super.setUp()t+is.serviceBean.em D emt+is.serviceBean."eliver'Service D ne, 8eliver'ServiceBean()t+is.serviceBean D ne, Boo9Or"erin7ServiceBean()$ 2:est public voi" testOr"er() # et.be7in()Strin7 isbn D 4PI4Strin7 name D 4Ret+in9in7 :+e Patterns4t+is.serviceBean.or"er(isbn1 name)et.rollbac9()$ $

5he concrete nit test = st initiali?es the .ervice !a@ade and tests its methods. /eeded reso rces can be moc#ed o t easily sing "rame'or#s s ch as =moc# (http%CC=moc#.org)$ easymoc# ('''.easymoc#.orgC)$ or moc#ito (http%CCmoc#ito.orgC)Idepending on the .ervice !a@ade comple>ity. 7nit 5ests are nice b t totally nrealistic. 5he p rpose o" a nit test is to test the isolated " nctionality o" a single nit s ch as a class. 5he entire environment is going to be em lated. A test s ite is e>ec ted in seB ential manner. +n a typical enterprise conte>t a .ervice !a@ade 'ill be e>ec ted in a massive parallel and m ltiser environment. 5he nit tests$ ho'ever$ can be easily mis sed "or load testing. Commercial as 'ell as open so rce tools s ch as =meter (http%CC=a#arta.apache.orgC=meter) provide scripting in"rastr ct re$ 'here e>isting *ava code can be e>ec ted in h ndreds o" threads$ em lating conc rrent sers. 9oad tests sho ld be per"ormed at least once a 'ee#Iyo 'ill be s rprised ho' many synchroni?ation iss es$ bottlenec#s$ deadloc#s$ memory lea#s$ and con<g ration problems 'ill be "o nd d ring the tests. -arly tests help yo not only to ens re the consistency o" the system$ b t to gather the e>perience o" its behavior nder heavy load. . ch tests do not have to be realisticIinstead they sho ld generate as m ch load as possible and try to brea# the system$ 'itho t thin# times$ net'or# throttling and so on.

;oc mentation
Eell-'ritten doc mentation is as important as good nit tests. -specially the intensions$ e>amples and sage hints are se" l "or the .ervice !a@ade sers. 5he technical responsibility can be 'ritten once in$ "or e>ample$ a 'i#i and be only re sed in di""erent components or even applications. +t

02
Download at WoweBook.Com

sho ld contain the responsibility$ transaction management$ and strategy. +n the act al pro=ect it is s "<cient = st to re"er to the conceptI'itho t repeating the already described "acts. +n 7(9$ the entire "a@ade 'ith its participants can be doc mented 'ith a single inter"ace as sho'n in !ig re 3.

Figure 3. Service Faade in UML class diagram. 5he inter"ace represents its p blic vie'S the act al implementation is not that interesting. 5he stereotype ..Service &aca"e00 ma#es it clear$ that the inter"ace is the pro>y "or the .ervice !a@ade. At the so rce level$ the .ervice !a@ade pattern can be doc mented 'ith a c stom annotation. 5he "ollo'ing e>ample ses a mar#er annotation to tag the "a@ade%
2Stateless 2Remote(8ocumente"Service&aca"e.class) )ServiceCacade(responsibility>"7ar3er annotation e=ample"5documentation@in3>" ttpD$$blo+.adam-bien.com") public class 8ocumente"Service&aca"eBean implements 8ocumente"Service&aca"e #$

An annotation has some important advantages over *ava;ocIthe meta data remains in byte code and is accessible via reHection. 5he so persisted doc mentation can even be leveraged d ring the b ild process or 'ith static analysis tools.
2:ar7et()lement:'pe.:BP)) 2Retention(RetentionPolic'.RUA:<6)) 28ocumente" public 2inter(ace Service&aca"e # %CC C A pointer to existin7 "ocumentation1 C user stor' or use case. C% Strin7 "ocumentation3in9() "e(ault 44%CC C :+e essential intension an" responsibilit' o( t+e C Service &aca"e C% Strin7 responsibilit'()$

+n the e>ample above the "ocumentation3in9 attrib te is optional$ the responsibilit' is not. An annotation can even "orce the developer to provide some essential in"ormation. As 'e already disc ssed in the .,A !a@ade strategy s ch annotation can have even more "ormali?ed meaning and provide additional meta data 'hich can be cons med by an interceptor.

03
Download at WoweBook.Com

ConseB ences
Consistency: All *ethods are transactional. +he transaction is !ro!agated to all artifacts invoked in the sco!e of a Service 0a@ade. A Service 0a@ade ens,res consistency. 'ncapsu ation: A Service 0a@ade deco,!les (de!ending on the strategy) *ore or less the client fro* the co*!onents -ehind the facade. Performance: A fa@ade *akes an interface coarser. +his is i*!ortant for re*ote co**,nication. Several local invocations are -,ndled to fe/ re*ote ones. 5sabi ity: +he *ethods of a Service 0a@ade sho,ld *ake sense even for a do*ain e6!ert. &nstead of invoking a -,nch of accessors (getters C setters)1 Service 0a@ade *ethods are *ore fl,ent. Team bui ding: Service 0a@ade is a hard interface -et/een the -,siness and the !resentation. +herefore it is a nat,ral -o,ndary -et/een ,ser interface and -ack'end tea*s. Testabi ity: A Service 0a@ade has to -e de!loyed /ith ,nit1 integration1 and1 *ost i*!ortantly1 load tests. Crosscutting: A Service 0a@ade is the single !oint of entry. All co**,nication is ro,ted thro,gh the fa@ade. +herefore it is a s,!er- !lace for the i*!le*entation of crossc,tting concerns s,ch as *onitoring1 a,diting1 or !recondition checks. ,ecoup ing: &nde!endent1 fine'grained1 services are coordinated -y the Service 0a@ade and can re*ain inde!endent and re,sa-le in other conte6t.

6elated Patterns
Application .ervice (*2--)$ .ession !a@ade (*2--)$ Date'ay (*ava --)$ .ervice (*ava --)$ ;A, (*2-- C *ava --)$ ;5, (*2-- C *ava --).

08
Download at WoweBook.Com

/ervice 9/ession ,a8ade:


5he original conte>t o" a .ession !a@ade (.!) 'as de<ned in the Core *2-- pattern as "ollo'ing% N-nterprise beans encaps late b siness logic and b siness data and e>pose their inter"aces$ and th s the comple>ity o" the distrib ted services$ to the client tierO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC.ession!acade.htmlM. 5he conte>t changed in *ava -- B ite a bit. A .ervice is rather proced ral and reali?es activities or s bprocesses. +n an ob=ect-oriented$ domain-driven conte>t$ a .ervice reali?es cross-c tting$ domain ob=ectindependent logic. +n an .,A a .ervice plays the main role and implements the act al b siness logic.

Problem
5he original intention o" the .ession !a@ade 'as to 'rap entity beans and encaps late <ne-grained interactions 'ith the b siness ob=ects% N+n a m ltitiered *ava 2 Plat"orm$ -nterprise -dition (*2--) application environment$ the "ollo'ing problems arise% L...M N)o'ever$ direct interaction bet'een the client and the b siness ob=ects leads to tight co pling bet'een the t'o$ and s ch tight co pling ma#es the client directly dependent on the implementation o" the b siness ob=ects. ;irect dependence means that the client m st represent and implement the comple> interactions regarding b siness ob=ect loo# ps and creations$ and m st manage the relationships bet'een the participating b siness ob=ects as 'ell as nderstand the responsibility o" transaction demarcationX LXM N5ight co pling bet'een ob=ects also res lts 'hen ob=ects manage their relationship 'ithin themselves. ,"ten$ it is not clear 'here the relationship is managed. 5his leads to comple> relationships bet'een b siness ob=ects and rigidity in the application. . ch lac# o" He>ibility ma#es the application less manageable 'hen changes are reB ired. LXM NA problem also arises 'hen a client interacts directly 'ith the b siness ob=ects. .ince the b siness ob=ects are directly e>posed to the clients$ there is no ni<ed strategy "or accessing the b siness ob=ects. Eitho t s ch a ni"orm client access strategy$ the b siness ob=ects are e>posed to clients and may red ce consistent sageXO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC.ession!acade.htmlM. 5he initial responsibility o" a .ession !a@ade 'as the management o" persistence relations bet'een entity beans. +t 'as in the C(P 4.4 time "rame and is totally o t o" date. +n the C(P 2.> era$ a .ession !a@ade +ight co,!ling1 /hich leads to direct de!endence -et/een clients and -,siness o-.ects7 +oo *any *ethod invocations -et/een client and server1 leading to net/ork !erfor*ance !ro-le*s7 9ack of a ,nifor* client access strategy1 e6!osing -,siness o-.ects to *is,se.

Download at WoweBook.Com

'as mainly responsible "or management o" a single entity type. +t implemented the merging and creation o" domain ob=ects directly. 5he e>ec tion o" dynamic B eriesI'as o"ten delegated to a ;A,. 5hese reB irements are completely o tdated as 'ell. -ntity beans are no more remote accessible$ the *PA is po'er" l eno gh "or most o" the se cases and container-managed relations have been available "or several years. /evertheless a .ervice (the ne' name "or the .ession !a@ade) is still sable$ 'ith slightly modi<ed responsibilities. +nstead o" <>ing in"rastr ct ral shortcomings$ the main p rpose o" a .ervice is ma#ing the reali?ation o" the b siness logic more maintainable and re sable. 5he #ey element o" .,A is a .ervice. +n practice$ ho'ever$ services are too <ne grained$ to be remotely (.,A implies the distrib tion) accessible. ,n the other hand$ a visible .,A service is too coarse grained$ to be reali?ed in single method. A common approach is to decompose the " nctionality o" an .,A .ervice into several technical .ervices (this pattern) and e>pose them via a .ervice !a@ade.

!orces
Services sho,ld -e inde!endent of each other. +he gran,larity of a Service is finer than of a Service 0a@ade. +he Services are not accessi-le and even visi-le fro* o,tside the -,siness tier. A Service sho,ld -e not accessi-le fro* an e6ternal JB%. A re*ote Service invocation doesn:t *ake sense and sho,ld -e avoided. A Service is ai*ed to -e re,sed fro* other co*!onent or Service 0a@ade. +he e6ec,tion of a Service sho,ld -e al/ays consistent. &ts *ethods sho,ld either have no side effects (-e ide*!otent)1 or -e a-le to -e invoked in a transactional conte6t.

.ol tion
As mentioned earlier$ a .ervice is a prod ct o" decomposition. 5here"ore it is not even visible "or the clients and only accessible thro gh a .ervice !a@ade. A client may be interested in ordering prod cts$ b t absol tely not interested in the re se o" the shipping logic$ availability and address chec#s$ c stomer relationship management$ or ta> comp tations. A .ervice !a@ade e>poses the act ally interesting " nctionality and coordinates independent .ervices. 5he .ervice !a@ade already provides transactions$ state management$ remoting$ and other cross-c tting " nctionality. 5he services can be developed 'itho t the consideration o" cross-c tting concerns and independently o" each other. Act ally the services m st not rely on the e>istence o" certain aspects s ch as transactions or remoting. !or this reason a .ervice is al'ays local and comes 'ith the :ransactionAttribute:'pe.6AA8A:ORB transaction attrib te%
2Stateless 23ocal(8eliver'Service.class) 2:ransactionAttribute(:ransactionAttribute:'pe.6AA8A:ORB) public class 8eliver'ServiceBean implements 8eliver'Service #

0:
Download at WoweBook.Com

A .ervice can be deployed either 'ith a dedicated local b siness inter"ace or 'ith no-inter"ace vie'. 5he choice depends on the comple>ity o" the .ervice !a@ades. An e>plicit b siness inter"ace ma#es moc#ing o" the .ervice possible and nit testing easier. 5he .ervice idiom reali?es a part o" the overall .ervice !a@ades " nctionality. 6e sable and independent parts o" the .ervice !a@ade are "actored o t into .ervices. 5he .ervices are coordinated by the .ervice !a@ade and located behind it. 5hey act ally comprise an internal component layer$ 'hich can be named a"ter the pattern. 5he component itsel" is mapped to a pac#age 'ith a domain-speci<c name$ "or e>ample$ or"erm7mt$ the layer service resides inside the component ("or e>ample$ or"erm7mt.service or or"erm7mt.control) alongside the other layers s ch as or"erm7mt.(aca"e or or"erm7mt."omain. A .ervice is = st a stateless session bean 'ith 'ell-de<ned responsibility. +t comes 'ith local or no-inter"ace vie' and the 6AA8A:ORB transaction attrib te. Eith s ch con<g ration is it impossible "or e>ternal clients to invo#e a .ervice 'itho t going thro gh a .ervice !a@ade. A .ervice has to r n in the scope o" an e>isting transaction. 6egardless o" ho' many .ervices are e>ec ted in the transactional scope$ the 'hole invocation remains consistent. All participating .ervices access reso rces in the same transaction. A .ervice ses ;ependency +n=ection to acB ire needed reso rcesItransactional reso rces 'ill be a tomatically enlisted in the c rrent transaction by the container. 5his means$ "or e>ample$ "or *;BC that all .ervices invo#ed in the conte>t o" the .ervice !a@ade 'ill share a single *;BC connection (and transaction). .ervices can be decorated 'ith interceptors. 5he " nctionality o" a .ervice interceptor$ ho'ever$ sho ld be related to the .ervice and not intersect 'ith the responsibilities o" the .ervice !a@ade. -*B 3.4 has still the rep tation o" being too heavy'eight. 5he B estion o"ten as#ed is$ 'hether a .ervice sho ld be implemented as P,*, or a stateless session bean. 5he per"ormance overhead bet'een a P,*, and a stateless session bean is negligible (abo t 3Y on Dlass<sh v2). 5he bene<ts o" a stateless session bean in respect to monitoring$ transactions$ conc rrency$ and ;ependency +n=ection are h ge. 5here is no reason "or a premat re optimi?ation$ especially considering the code red ction ca sed by the se o" session beans. A session bean can be replaced easily 'ith a P,*, at any time 'ith almost no additional overhead. ,nly the already e>isting container services have to be provided d ring that migration.

Conventions
A Service is a local1 stateless session -ean. Service resides in a co*!onent /hich is reali5ed as Java'!ackage /ith do*ain's!ecific na*e e.g. or"erm7mt. +he reali5ation of the service (-,siness interface and the -ean i*!le*entation) resides in a s,-!ackage /ith the na*e service or control1 for e6a*!le1 or"erm7mt.service or or"erm7mt.control. +his *akes the a,to*atic verification of the architect,re easier.

00
Download at WoweBook.Com

+he -,siness interface is na*ed after -,siness conce!ts1 /itho,t the o-ligatory local or re*ote s,ffi6 e.g. Or"erService and Or"erServiceBean. &t is not re8,ired to ,se the ter* >Service? in the na*e of the -eanAits red,ndant. 0or identification !,r!oses yo, co,ld ,se a 2Service annotation. +he Service is al/ays invoked in the conte6t of an e6isting transaction. &t is de!loyed /ith the 6an"ator' transaction attri-,te.

6ethin#ing
5he .ervice pattern has nothing in common 'ith the *2-- .ession !a@ade. 5he main p rpose o" the .ession !a@ade 'as the access simpli<cation to entity beans and ma#ing the gran larity coarser. +n contrast$ the *ava -- 2C: .ervice emphasi?es the domain-speci<c services and is act ally independent on the *ava -- in"rastr ct re. A .ervice itsel" is even optional. !or simple se cases a .ervice !a@ade and .ervice can collapse$ in 'hich case the " nctionality o" the .ervice moves to the .ervice !a@ade. 9i#e'ise$ " nctionality "rom .ervice !a@ades 'ith too many responsibilities can be "actored o t into ne'ly introd ced .ervices. 5he design sho ld scale in both directions.

Participants and 6esponsibilities


A .ervice is al'ays e>ec ted in the conte>t o" a .ervice !a@ade or gate'ay. +t relies on the e>istence o" transactions$ sec rity$ remoting and other cross-c tting concerns. A .ervice implements b siness logic and can se all available reso rces "or its reali?ation. 9egacy reso rces can be 'rapped in an e>plicit ;A,$ 'hich can be considered as a speci<c #ind o" a .ervice. Access to standardi?ed and 'ell-integrated reso rces s ch as *PA does not have to be " rther encaps lated. Premat re encaps lation co ld res lt in many delegate invocations and layers 'itho t any additional val e.

.trategies
A .ervice is a hidden$ or encaps lated$ .ervice !a@ade 'itho t the cross-c tting " nctionality$ 'hich is reB ired "or the e>pos re. 5h s$ the strategies o" the .ervice !a@ade .,A .ervice !a@ade and 9ight'eight Asynchrono s .ervice !a@ade can be applied directly to a .ervice. 5he protocolrelated strategies$ ho'ever$ are not applicable at all. A .ervice is not capable to handle remote calls. Stateless Session Bean Strategy 7sing stateless session beans is the de"a lt 'ay to b ild .ervices. 5he b siness logic is implemented as a stateless session bean 'ith a local b siness inter"ace or no-inter"ace vie' only. All methods are deployed 'ith the :ransactionAttribute:'pe.6AA8A:ORB transaction setting. 5he .ervice can (and sho ld) se ;ependency +n=ection to acB ire bac#-end reso rcesS it en=oys conc rrency and transaction control and can be monitored o t o" the bo>. 5he bene<ts simply o t'eigh the t'o main shortcomings% dependency on the -*B AP+ ca sed by the se o" -*B 3 annotations and potential per"ormance penalty ca sed by the container overhead. 5he dependency

01
Download at WoweBook.Com

ca sed by annotations is minimal and can even be completely removed sing deployment descriptors. Altho gh all annotations and dependencies on the -*B 3 AP+ 'o ld be removed "rom the application code$ yo sho ldnRt nderestimate the K(9 pl mbing. Eriting K(9 is laborintensive and brittle. 5he dependency on the -*B technology is really lo'Ithe annotation can be removed easily in case the -*Bs t rn o t to be not appropriate "or yo r needs. . rprisingly the -*B container overhead t rns o t to be really lo'. +n case o" the Dlass<sh v2 r2 application server$ the di""erence bet'een a p re P,*, and a stateless session bean is only a "e' milliseconds or abo t 3Y. +n the relation to distrib tion$ database access or invocation o" legacy reso rces$ the overhead ca sed by the -*B in"rastr ct re is absol tely insigni<cant. P(J( Strategy ;evelopers o"ten 'onder 'hether a .ervice sho ld be implemented as a stateless session bean or a P,*,. +n the conte>t o" *ava -- 2W$ P,*,s simply reB ire yo to 'rite more code comparing them to -*B 3.4. 5his additional e""ort has to be = sti<ed someho'. A possible reason is the integration o" already e>isting P,*,s$ 'itho t having so rce code available. 5hey co ld be integrated sing K(9$ b t this comes 'ith some relatively high amo nt o" e""ort and the violation o" the ;6Q principle. 5he " lly B ali<ed class (as 'ell as the inter"ace) name has to be de<ned in the deployment descriptor. 5his in"ormation$ ho'ever$ already e>ists in *ava code and ma#es re"actoring harder. 5o demonstrate this approach$ in=ect the .'ing javax.s,in7.table.:able6o"el class as a local b siness inter"ace into the 3e7ac':estBean class and se the javax.s,in7.table.8e(ault:able6o"el as the bean class. 7se the beanAame as logical re"erenceS yo co ld even get rid o" this completely and se the " lly B ali<ed name. 5he "ollo'ing snippet demonstrates the in=ection o" a .'ing 5able model into an -*B 3%
import !ava=.s(in+.table.4able7odel; 2Stateless public class 3e7ac':estBean implements 3e7ac':est # 2)*B(beanAameD4:able4) :able6o"el table6o"elpublic Strin7 access:able()# return 4Ro, countG 4 H table6o"el.7etRo,Count()$ $

+n the deployment descriptor$ it is s "<cient to re"er to the re"erence 'ith the val e o" the beanAame. Also$ the type o" the bean$ the b siness inter"ace$ and the implementation o" the class has to be speci<ed. 5he "ollo'ing snippet demonstrates the declaration o" the 8e(ault:able6o"el as a .tateless .ession Bean in ejb/jar.xml%
.ejb/jar0 .enterprise/beans0 .session0 .ejb/name0:able.%ejb/name0 .business/local0javax.s,in7.table.:able6o"el.%business/local0

09
Download at WoweBook.Com

.ejb/class0javax.s,in7.table.8e(ault:able6o"el.%ejb/class0 .session/t'pe0Stateless.%session/t'pe0 .%session0 .%enterprise/beans0 .%ejb/jar0

5he descriptor$ ho'ever$ is complete. ,ther beans can still be deployed sing plain annotations only. +t is sometimes more pragmatic = st to re se the legacy class as a P,*,$ instantiating it 'ith the ne' operator. 5his is especially tr e "or stateless tility classes$ especially 'ith static methods$ 'itho t any access to transactional reso rces s ch as databases or *(.. 5he -*B container is not a'are o" p re P,*,s. +t is neither able to handle their li"ecycles nor to monitor them. Be a'are o" this "act 'hen choosing this strategy "or green <eld pro=ects. "A( Hy-rid .eparation o" Concerns 'as the driving "orce "or the hard separation bet'een .ervices and ;A,s. 5he *PA -ntity(anager is act ally a ;A,$ or has at least all o" its characteristics. 5here is no real need to encaps late it " rther 'ith a dedicated ;A,. 5he constr ction and e>ec tion o" named B eries$ ho'ever$ is relatively labor intensive and can res lt in lot o" pl mbing code$ so it is a good idea to encaps late named B eries in a dedicated place. 5his tas# can be achieved either in a ;A, or a .ervice$ both layers at the same time are only needed in e>ceptional cases. +n practice$ the layers o"ten collapse$ beca se there is no need "or " rther deco pling o" the .ervice "rom )ntit'6ana7er. 5he constr ction o" B eries and even the re se o" B ery logic is o"ten pro=ect speci<c$ b t still highly re sable across services. 5he re se can be easily achieved sing inheritance. +nstead o" delegating to a ;A,$ a .ervice co ld = st inherit "rom it. +n that case$ a .ervice 'o ld act as a ;A,$ 'hich is act ally not entirely 'rong. 5he in=ection o" )ntit'6ana7er is available in the s perclass and 'o ld be available instantly "or the .ervice too. Beca se a session bean is = st a b nch o" cohesive methods and not an ob=ect$ it is nli#ely that there be a need to inherit "rom another class in addition. 5he .ervice co ld even inherit "rom an already e>isting$ generic ;A, class as sho'n in the "ollo'ing sample%
2Stateless public class Cru"ServiceBean# 2PersistenceContext protecte" )ntit'6ana7er empublic .:0 : create(: t) # t+is.em.persist(t)t+is.em.(lus+()t+is.em.re(res+(t)return t$ %%remainin7 met+o"s $<n t+at case1 t+e Cru"ServiceBean class1 as ,ell as t+e Service (8AOService 'bri"Bean) ,it+ 8AO capabilities1 ,oul" be "eplo'e" as session beans an" available in t+e *A8< tree. :+e injecte" )ntit'6ana7er +as to be

10
Download at WoweBook.Com

"eclare" as protecte" or expose" ,it+ a 7etter. Ot+er,ise it ,ill not be accessible in t+e concrete Service1 ,+ic+ is require" (or t+e implementation o( speci(ic queries. ereWs t+e co"e (or t+e 8AO serviceG 2Stateless public class 8AOService 'bri"Bean exten"s Cru"ServiceBean# 2Overri"e public voi" create(Strin7 isbn1Strin7 name)# create(ne, Boo9(isbn1name))- %%in+erite" $ $

Eith this strategy the .ervice implementation can be greatly simpli<ed and is act ally red ced to the minim m. All the pl mbing code is "actored o t in the Cru"ServiceBean and is easily accessible "rom the .ervice. /o delegation and in=ection o" additional beans is reB ired. 5his strategy is especially e"<cient and maintainable in concrete pro=ects$ 'ith pro=ect-speci<c B eries. ;omain-speci<c <lters$ role-dependent ,+ere statements$ and other conte>t-dependent behaviors can be encaps lated in the Cru"ServiceBean s perclass and be consistently re sed across di""erent .ervices.

5esting
5esting o" .ervices is identical to testing the .ervice !a@ades. 5he testing techniB es described earlier can be applied to a .ervice. .ervices are optional$ so their sage already implies additional added val e and non-trivial implementation. +t is there"ore a good idea to provide nit tests "or a .ervice as 'ell$ ho'ever it is more a s ggestion$ than a hard reB irement.

;oc mentation
;oc menting a .ervice is almost identical to doc menting the .ervice !a@ade. +n 7(9 class diagrams$ .ervices can be emphasi?ed 'ith the ..Service00 annotation. +t is s "<cient to model them as a class 'itho t the inter"aceIthe inter"ace doesnRt provide any additional in"ormation. 5he ..Service00 stereotype is the placeholder o" the session bean con<g ration and str ct re s ch as state management$ distrib tion$ or transaction handling. (ar#ing a class 'ith the stereotype ..Service00 ma#es it e>plicit$ that it is e>panded into a local$ stateless session bean 'ith the 6AA8A:ORB transaction attrib te. +t becomes clear that all associations to other services 'ill be mapped to ;ependency +n=ection o" their inter"ace$ and their relationship to entities 'ill res lt in the in=ection o" the )ntit'6ana7er. 5he pragmatic se o" c stom stereotypes "ormali?es the model and even allo's the generation o" the entire in"rastr ct re. 5he obvio s in"rastr ct re can even be generated 'ith template engines s ch as Aelocity or !reemar#er. 5he se o" generators or sophisticated (odel ;riven Architect re ((;A) tools is not al'ays bene<cial. !rom a development point o" vie'$ *ava -- is lean eno gh to be man ally coded. A generator$ on the other hand$ ens res consistent naming conventions$ patterns and layering 'hich can signi<cantly increase the maintainability. 5his becomes especially interesting "or o tso rcing pro=ects 'ith many e>ternal partners involved.

14
Download at WoweBook.Com

ConseB ences
2euse: Services enco,rage internal re,se of fine'grained logic. +hey can -e shared -et/een co*!onents and Service 0a@ades. Consistency: A service is hidden -ehind a fa@ade and al/ays e6ec,ted in the conte6t of already e6isting transaction. Testabi ity: Services can -e easily *ocked o,t1 /hich si*!lifies the testing of the Service 0a@ade. Services are P(J(s1 so they can -e tested easily as /ell. Comp exity: )ot all ,se cases are co*!le6 eno,gh to .,stify the introd,ction of an additional Service layer. +he enforce*ent of Services can res,lt in e*!ty (that is1 delegate) Services or Service 0a@ades. #R;" ,se cases can -e easily reali5ed /ith a Service 0a@ade only. )ervice orientation: A service already i*!lies a service'oriented a!!roach1 /hich res,lts in !roced,ral -,siness logic. Process' or /orkflo/'driven ,se cases can -e easily reali5ed /ith tasks (services)1 o!erating on reso,rces (entities). &n do*ain'driven a!!lications1 services sho,ld only reali5e cross'c,tting concerns1 other/ise the design /ill not -e "R=.

6elated Patterns
Application .ervice (*2--)$ .ession !a@ade (*2--)$ Date'ay (*ava --)$ .ervice (*ava --)$ ;A, (*2-- C *ava --)$ ;5, (*2-- C *ava --). A .ervice is coordinated by .ervice 0a@ades or gate'aysS it invo#es ;A,s and is able to prod ce ;5,s.

12
Download at WoweBook.Com

Persistent Do*ain 046ect 9B$siness 046ect:


5he original problem description in *2-- Core Patterns 'as short and so nd% NQo have a concept al domain model 'ith b siness logic and relationshipO L'''.core=2eepatterns.comCPatterns2nd-dCB siness,b=ect.htmM. -ven in the original description o" the B siness ,b=ect *2-- Pattern$ the reali?ation o" the concept al model 'ith proced ral approaches 'as considered as dangero s 'ith regard to bloating code d plication spread over di""erent mod les and there"ore hard to maintain. At that time$ ho'ever$ the reali?ation o" ob=ect-oriented and persistent B siness ,b=ects 'asnRt possible 'ith standard *2-- technologies. ,nly additional e>tensions s ch as *ava ;ata ,b=ects (*;,) or later open so rce "rame'or#s s ch as )ibernate 'ere able to manage the persistence o" ob=ect-oriented entities transparently.

Problem
5he vast ma=ority o" *2-- applications 'ere b ild in the proced ral 'ay. 5he b siness logic 'as decomposed into tas#s and reso rces$ 'hich 'ere mapped into .ervices and anemic$ persistent entities. . ch a proced ral approach 'or#s s rprisingly 'ell ntil type-speci<c behavior "or domain ob=ects has to be reali?ed. 5he attempt to reali?e ob=ect-oriented algorithms 'ith proced ral techniB es ends p in many instanceo( chec#s or lengthy i( statements. . ch type chec#s are reB ired$ beca se the domain ob=ects are anemic in the proced ral 'orld$ so that inheritance doesnRt really pay o"". -ven in case inheritance 'as sed "or designing the domain model$ the most po'er" l "eat re$ polymorphic behavior$ 'asnRt leveraged at all. Anemic domain model "orces the developer to implement the type chec#s o tside the entitiesIthat is$ in .ervices or .ervice !a@ades. 5he anemic str ct res (these are not ob=ects by de<nition) have to e>pose their internal states to the o tside 'orld. ,ther'ise it 'o ldnRt be accessible to the .ervices and .ervice !a@ades any more. 5he e>pos re o" an internal state is reali?ed 'ith <eld accessors (getters and setters)$ that is 'ith a lot o" pl mbing. All the shortcomings mentioned here are ca sed by the lac# o" ob=ect orientation in the persistence layer in most *2-- and *ava -- applications.

!orces
=o,r -,siness logic is co*!le6. +he validation r,les are do*ain o-.ect related and so!histicated. +he conce!t,al *odel can -e derived fro* the re8,ire*ents and *a!!ed to do*ain o-.ects. +he do*ain o-.ects have to -e !ersisted in a relational data-ase (it:s the co**on case). +he ,se cases1 ,ser stories1 or other s!ecification doc,*ents already descri-e the target do*ain in an o-.ect'oriented /ay. +he relation -et/een the -ehavior and the data can -e derived fro* the s!ecification.

Download at WoweBook.Com

&t is a green field !ro.ect1 or at least the e6isting data-ase /as designed in a /ay that allo/s the ,se of JPA. +hat is1 the ta-les and col,*ns are reasona-ly na*ed and the data-ase is not overly nor*ali5ed.

.ol tion
5he sol tion is s rprisingly simple% (odel yo r application 'ith real ob=ects and donRt care abo t the persistence at the beginning. Real o'%ects means cohesive classes 'ith encaps lated state$ related behavior$ and inheritance. * st p t b siness logic into the domain ob=ects and se inheritance 'ere appropriate. *PA t rns o t to be really He>ible in mapping rich domain ob=ects into relational tables. 5he more comple> logic yo have to reali?e$ the easier ob=ect-oriented persistence can be maintained and developed. Anemic domain models do not have any behavior by de<nition$ so it has to be provided some'here else. 7s ally the behavior is reali?ed in .ervices (stateless session beans)$ 'hich access and manip late the state o" anemic ob=ects. 5he .ervices need to access the entities state$ so it is entirely p blici?ed. 5his is achieved 'ith getters and setters$ 'hich e>pose every single attrib te to the o tside 'orld. +t is not a h ge problem in general$ b t this approach res lts in a lot o" pl mbing and ob" scates the essential b siness logic. 5he real problem is that i" statements needed to di""erentiate bet'een the entity types. . ch chec#s are needed to reali?e type-dependent behavior in a proced ral 'ay. -very introd ction o" a ne' s bclass$ or even change o" the e>isting b siness logic reB ires to <nd$ enhance$ and test the type chec#s. 5he comp tation o" shipping costs dependent on 'eight and the Or"er<tem type 'o ld loo# li#e this in a proced ral 'orld%
2Stateless public class S+ipmentService # public (inal static int BAS<CJCOS: D X2PersistenceContext private )ntit'6ana7er empublic int 7etS+ippin7Costs(int loa"<") # 3oa" loa" D em.(in"(3oa".class1 loa"<")return computeS+ippin7Cost(loa")$ int computeS+ippin7Cost(3oa" loa")# int s+ippin7Costs D Rint ,ei7+t D Rint "e(aultCost D R(or (Or"er<tem or"er<tem G loa".7etOr"er<tems()) # 3oa":'pe loa":'pe D or"er<tem.7et3oa":'pe(),ei7+t D or"er<tem.7et!ei7+t()"e(aultCost D ,ei7+t C Xs,itc+ (loa":'pe) # case BU3YBG s+ippin7Costs HD ("e(aultCost H X)brea9-

18
Download at WoweBook.Com

case 3<> :!)<> :G s+ippin7Costs HD ("e(aultCost / U)brea9case S:AA8AR8G s+ippin7Costs HD ("e(aultCost)brea9"e(aultG t+ro, ne, <lle7alState)xception(4Un9no,n t'peG 4 H loa":'pe)$ $ return s+ippin7Costs$ $

5he entire logic resides$ as e>pected$ in a .ervice or .ervice !a@ade and consists mainly o" the type chec#s. 5he .ervice has to di""erentiate bet'een the di""erent types to apply type-dependent comp tation algorithms. 5he same logic can be e>pressed 'ith only a "raction o" code in an ob=ect-oriented 'ay. -ven a .ervice is no longer neededIthe logic is implemented in the domain ob=ect itsel". 5he "ollo'ing snippet sho's polymorphic b siness logic inside a domain ob=ect$ 'itho t type chec#s%
2)ntit' public class 3oa" # 2One:o6an'(casca"e D Casca"e:'pe.A33) private 3ist.Or"er<tem0 or"er<tems2<" private 3on7 i"protecte" 3oa"() # t+is.or"er<tems D ne, Arra'3ist.Or"er<tem0()$ public int 7etS+ippin7Costs() # int s+ippin7Costs D R(or (Or"er<tem or"er<tem G or"er<tems) # s+ippin7Costs HD or"er<tem.7etS+ippin7Cost()$ return s+ippin7Costs$ %%@ $

5he comp tation o" the total costs is reali?ed inside a rich domain ob=ect$ the Persistent ;omain ,b=ect (P;,)$ and not inside a .ervice. 5his not only red ces the total amo nt o" code$ b t it ma#es the code also easier to nderstand and maintain. 5he act al comp tation o" type-speci<c costs is per"ormed in the concrete s bclasses$ 'hich ma#es it a lot easier to be tested separately%
2)ntit' public class Bul9'<tem exten"s Or"er<tem#

12
Download at WoweBook.Com

public Bul9'<tem() # $ public Bul9'<tem(int ,ei7+t) # super(,ei7+t)$ 2Overri"e public int 7etS+ippin7Cost() # return super.7etS+ippin7Cost() H X$ $

5he comp tation o" the shipping cost o" a Bul9'<tem can be changed$ 'itho t to ching the remaining classes. Also$ a ne' s bclass can be introd ced 'itho t a""ecting the comp tation o" the total costs in the class 3oa". 5he creation o" a P;, graph is easier and more int itive$ comparing it to the traditional getterCsetter-driven approach. +nstead o" creating the anemic ob=ects separately and 'iring them together a"ter'ards$ yo can ta#e a concise ob=ect-oriented approach as sho'n in the "ollo'ing snippet%
3oa" loa" D ne, 3oa"()Or"er<tem stan"ar" D ne, Or"er<tem()stan"ar".set3oa":'pe(3oa":'pe.S:AA8AR8)stan"ar".set!ei7+t(X)loa".7etOr"er<tems().a""(stan"ar")Or"er<tem li7+t D ne, Or"er<tem()li7+t.set3oa":'pe(3oa":'pe.3<> :!)<> :)li7+t.set!ei7+t(U)loa".7etOr"er<tems().a""(li7+t)Or"er<tem bul9' D ne, Or"er<tem()bul9'.set3oa":'pe(3oa":'pe.BU3YB)bul9'.set!ei7+t(U)loa".7etOr"er<tems().a""(bul9')-

5he B ilder pattern allo's the constr ction o" the 3oa" ob=ect 'ith the speci<c Or"er<tems in a convenient 'ay. As sho'n in the "ollo'ing e>ample$ the method chaining saves some s perH o s lines o" code and allo's a tocompletion s pport in common +;-s%
3oa" buil" D ne, 3oa".Buil"er(). ,it+Stan"ar"<tem(X). ,it+3i7+t,ei7+t<tem(U). ,it+Bul9'<tem(U). buil"()-

+n addition validation logic is per"ormed in the method b ild$ so that the creation o" empty 3oa" ob=ects can be avoided. 5he "ollo'ing code demonstrates the B ilder pattern reali?ed 'ith a static inner class inside a P;,%
2)ntit' public class 3oa" #

1:
Download at WoweBook.Com

2One:o6an'(casca"e D Casca"e:'pe.A33) private 3ist.Or"er<tem0 or"er<tems2<" private 3on7 i"protecte" 3oa"() # t+is.or"er<tems D ne, Arra'3ist.Or"er<tem0()$ public static class Buil"er # private 3oa" loa"public Buil"er() # t+is.loa" D ne, 3oa"()$ public Buil"er ,it+Bul9'<tem(int ,ei7+t) # t+is.loa".a""(ne, Bul9'<tem(,ei7+t))return t+is$ public Buil"er ,it+Stan"ar"<tem(int ,ei7+t) # t+is.loa".a""(ne, Stan"ar"<tem(,ei7+t))return t+is$ public Buil"er ,it+3i7+t,ei7+t<tem(int ,ei7+t) # t+is.loa".a""(ne, 3i7+t,ei7+t<tem(,ei7+t))return t+is$ public 3oa" buil"() # i( (loa".or"er<tems.si=e() DD R) # t+ro, ne, <lle7alState)xception(4@4)$ return t+is.loa"$ $ voi" a""(Or"er<tem item) # t+is.or"er<tems.a""(item)$ public int 7etS+ippin7Costs() # int s+ippin7Costs D R(or (Or"er<tem or"er<tem G or"er<tems) # s+ippin7Costs HD or"er<tem.7etS+ippin7Cost()$ return s+ippin7Costs$

10
Download at WoweBook.Com

public Or"er<tem li7+test()# i((t+is.or"er<tems DD null ZZ t+is.or"er<tems.si=e() DD R) return nullCollections.sort(t+is.or"er<tems1 ne, !ei7+tComparator())return t+is.or"er<tems.iterator().next()$ public Or"er<tem +eaviest()# i((t+is.or"er<tems DD null ZZ t+is.or"er<tems.si=e() DD R) return nullCollections.sort(t+is.or"er<tems1 ne, !ei7+tComparator())Collections.reverse(or"er<tems)return t+is.or"er<tems.iterator().next()$ public Or"er<tem "rop eaviest()# Or"er<tem +eaviest D +eaviest()i((+eaviest 5D null) "rop(+eaviest)return +eaviest$ public Or"er<tem "rop3i7+test()# Or"er<tem li7+test D li7+test()i((li7+test 5D null) "rop(li7+test)return li7+test$ public 3oa" "rop(Or"er<tem or"er<tem)# t+is.or"er<tems.remove(or"er<tem)return t+is$ public 3on7 7et<"() # return i"$ public int 7etAumberO(Or"er<tems()# return t+is.or"er<tems.si=e()$ $

5he B ilder pattern is implemented as a static inner class$ 'hich creates the 3oa" ob=ect and provides methods 'ith H ent names ("or e>ample$ ,it+Bul9'<tem). -ach method creates a corresponding s bclass o" Or"er<tem$ adds it to the load$ and ret rns the B ilder instance itsel". 5his allo's the constr ction o" the 3oa" 'ith convenient method chaining. 7p to this point$ the logic 'as limited to the constr ction and the comp tation o" the shipping costs. -ven more interesting is the reali?ation o" non-idempotent methods. 5he method "rop eaviest removes the heaviest Or"er<tem instance "rom the 3oa" instance.

11
Download at WoweBook.Com

/othing e>citing abo t that$ b t yo have to #eep in mind that the P;,s are persistent entities. -very change to the state$ and even relations$ 'ill be synchroni?ed a tomatically 'ith the persistence at the end o" the transaction. * st imagine an ob=ect-oriented implementation o" the s bversion client 'ith *PA. A change o" a versioned <le has to be propagated to all pac#ages ntil the pro=ect root is reached. 5he entire path is mar#ed as changed. An .A/ commit on the pro=ect level ca ses a rec rsive descending o" all changed "olders ntil all changed <les are committed as 'ell. 5o implement s ch a cascading algorithm in an ob=ect-oriented 'ay is straight"or'ard$ 'hereas a proced ral approach is error prone and hard to maintain.

Conventions
P"(s are JPA entities /ith e*!hasis on do*ain logic and not the technology. P"(s reside in a co*!onent that is reali5ed as a Java !ackage /ith a do*ain's!ecific na*e1 for e6a*!le1 or"erm7mt. +he P"( resides in a s,-!ackage (layer) /ith the na*e "omain or entit'1 for e6a*!le1 or"erm7mt."omain or or"erm7mt.entit'. +his *akes the a,to*atic verification of the architect,re easier. +he na*e of the do*ain o-.ect is derived fro* the target do*ain. 2etters and setters are not o-ligatoryAthey sho,ld -e ,sed only in .,stified cases. +he *ethods are not only accessors1 -,t they *odel -ehavior /hich also changes the state of the do*ain o-.ects. All *ethods are na*ed in a fl,ent /ay. &t is not re8,ired to ,se the acrony* P"( in the na*e of the entity. 0or identification !,r!oses yo, co,ld ,se a 2P8O annotation.

6ethin#ing
5he *2-- C(P persistence didnRt s pport inheritance or polymorphic B eries. 5he anemic domain ob=ect approach 'as the only viable and reasonable sol tion. 5he *2-- patterns 'ere designed 'ith those restrictions in mind. -ven the introd ction o" alternative sol tions s ch as *;, or )ibernate didnRt improve the sit ationImost o" the domain ob=ects 'ere still anemic. ; mb entities and proced ral session beans 'ere the only best practice "or *2--. Altho gh the proced ral approach can be s rprisingly e"<cient "or simplistic$ data-driven se cases$ a more complicated logic can be hardly e>pressed 'ith persistent str ct res. *ava -- 2$ together 'ith *PA$ introd ced inheritance and polymorphic B eries to the persistence layer. *PA entities are = st annotated *ava classes 'ith only insigni<cant restrictions$ so ob=ectoriented approaches and patterns can be applied to persistence layer. +tRs time to rethin# the 'ay ho' comple> logic is going to be developed. 5he persistence layer sho ld consist o" sel"-contained domain ob=ects 'ith clear responsibilities and an encaps lated state and behavior. 5he persistence is a cross-c tting concern and sho ld not have any impact on design and not in partic lar on the amo nt o" logic residing in domain ob=ects. ,nly the remaining cross-c tting and o"ten proced ral logic sho ld be implemented in a .ervice.

19
Download at WoweBook.Com

Act ally the Persistent ;omain ,b=ects become a best practice and the Anemic ;omain (odel an anti-pattern$ at least in more ambitio s pro=ects.

Participants and 6esponsibilities


5he P;, plays the most important role in a domain-driven architect re. +t represents a concept "rom the target domain. +ts responsibility is to e>press and implement the b siness logic as simple and e>plicit as possible. 5he P;,Rs state is persisted to the database by the )ntit'6ana7er. A P;, is not an active arti"act. +t has to be created and maintained by a .ervice$ .ervice !a@ade or Date'ay. A .ervice implements a cross-c tting " nctionality s ch as archiving$ reports$ or e>pos re o" the " nctionality o" bac#-end systems$ 'hereby a Date'ay helps the P;, to e>pose its " nctionality directly to the presentation.

.trategies
6egardless 'hich strategy yo are choosing$ the P;, b siness methods sho ld al'ays be e>ec ted in an attached state. ,nly then do yo get the bene<ts o" transparent state synchroni?ation and even delta comp tations per"ormed by the )ntit'6ana7er. (ost o" the *PA providers synchroni?e the *PA entities 'ith the persistent store smartlyIonly changed entities$ relations$ and even attrib tes are H shed to the database. +t only 'or#s "or changes per"ormed on an attached entity. +" yo trans"er a P;, across the net'or#$ it becomes seriali?ed and detached. 5he )ntit'6ana7er loses its lin# to the seriali?ed P;,. Qo 'ill have to merge yo r changes man allyI'hich either leads to comple> comp tation o" the delta bet'een the origin and act al state$ or <ner operations on the remote .ervice !a@ades. P;,s sho ld al'ays be accessed per re"erence$ 'hich act ally implies the e>ec tion o" the presentation layer and the P;,s in the same *A(. 5his in-process e>ec tion is very nat ral "or the 'eb clients$ 'here the 'hole -A6 is e>ec ted in the same *A( any'ay$ b t rather esoteric "or rich clients. 5he same e""ect in a rich client environment reB ires an in-process e>ec tion o" the )ntit'6ana7er 'ithin the presentation layer. A rich +nternet application t rns into a "at client. +t might so nds strange$ b t "rame'or#s s ch as Adobe A+6 or even Doogle Dears "ollo' the same strategy. 5hey even come 'ith a local database to allo' o"Hine capabilities. "S9 C +est C "o*ain "riven 5he only "orce in this strategy is the domain o" the b siness logic and nothing else. 5he P;,s are developed 'ith respect to the test-<rst approachIthe main concern is the sability and there"ore the H ent inter"ace. 5he state is entirely encaps lated$ property accessors are rarely sed. 5he intensive se o" method chaining$ B ilder patterns$ and inner classes is typical "or this strategy. 5he in"ormation needed by a P;, is trans"ormed and provided man ally. Beca se a P;, 'ith a ;.9-li#e inter"ace cannot adhere to conventions ( nli#e *avaBeans)$ it ma#es a ;.9 P;, less interesting "or vis al components 'ith declarative data binding as is #no'n in the *.6-292 (Beans Binding)$ or already mat re and heavily sed in *.!. 0at P"(

90
Download at WoweBook.Com

P;,s are real ob=ects 'ith state and behavior. 5he persistence capabilities are provided by a session bean. A Date'ay$ .ervice$ or .ervice !a@ade se an in=ected )ntit'6ana7er to persist the root entity initially. !rom this point yo can manip late the state o" the root as 'ell as the related entities$ and all changes 'ill be a tomatically H shed to the database by the )ntit'6ana7er. 5his 'or#s only as long as yo do not need to access the database directly "rom P;,s. +n=ection o" )ntit'6ana7er into persistent entities is not s pported. A P;, is a real ob=ect and can th s per"orm any arbitrary operation on its state as 'ell as manip late its child ob=ects or create ne' entities. -specially the persistence creation o" entities that are not directly related to the c rrent graph o" ob=ects is not possible. Qo 'ill have to either associate the ne'ly created entity 'ith an already attached ob=ect or invo#e )ntit'6ana7er#persist. 5he )ntit'6ana7er is not available in P;,s and the association bet'een the ne'ly created ob=ect and graph o" entities only to persist it may not be desired. A "ar more elegant 'ay 'o ld be a ;ependency +n=ection o" )ntit'6ana7er into a P;,. 7n"ort nately it isnRt s pported in *PA$ so a 'or#aro nd is reB ired. 5he 3oa" P;, is created by the Buil"er inner class$ b t the creation is s ally not persistent. Qo either have to persist the 3oa" instance in the session bean or pass the )ntit'6ana7er to the B ilder. 5he <rst case only 'or#s "or simpler casesS the latter cannot be solved 'itho t additional 'or#. 5he "ollo'ing code demonstrates accessing an )ntit'6ana7er 'ith a static method in a P;,%
import static ...persistenceutils.:+rea"3ocal)ntit'6ana7er.C2)ntit' public class 3oa" # 2One:o6an'(casca"e D Casca"e:'pe.A33) private 3ist.Or"er<tem0 or"er<tems2<" 2>enerate"?alue private 3on7 i"protecte" 3oa"() # t+is.or"er<tems D ne, Arra'3ist.Or"er<tem0()$ public static class Buil"er # private 3oa" loa"public Buil"er() # t+is.loa" D ne, 3oa"()$ public Buil"er ,it+Bul9'<tem(int ,ei7+t) # t+is.loa".a""(ne, Bul9'<tem(,ei7+t))return t+is$

94
Download at WoweBook.Com

%%...some met+o"s omitte" public 3oa" buil"() # i( (loa".or"er<tems.si=e() DD R) # t+ro, ne, <lle7alState)xception(4Cannot create 3oa"@4)$ em().persist(t is.load); return t+is.loa"$ $ public static 3oa" (in"(lon7 i") # return em()./ind(@oad.class5 id); $ %%...some met+o"s omitte"

5he client accesses the P;,s not directly b t via the .ervice !a@ade$ 'hich starts a ne' transaction. A transaction is associated 'ith the c rrent thread o" e>ec tion by the application server. +" yo manage to associate an )ntit'6ana7er instance 'ith the c rrent thread$ the P;, co ld get easily access to the transactional )ntit'6ana7er instance and se it "or B eries or "or persisting detached entities. 5he )ntit'6ana7er participates in the c rrent transactionS even better$ all other session beans ("or e>ample$ .ervice) that are enlisted in the same transaction get in=ected by the same instance o" the )ntit'6ana7er. All the transaction participants 'ill have access to the same )ntit'6ana7er and its transactional cache. All participants 'ill see the same transactional state 'hich prevents lost pdates in a transaction. 5he earliest possible point to get a re"erence to the )ntit'6ana7er is in the interceptor. Altho gh an interceptor 'raps a session bean in its entirety$ it still participates in its transaction. 5he session bean has to declare only the interceptor at the class levelIso every b siness method is 'rapped$ as the "ollo'ing e>ample demonstrates%
2Stateless )2nterceptors(,ntity7ana+er2n!ector.class) 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public class S+ipmentServiceBean implements S+ipmentService # public 3oa" createBul9'<tem(int ,ei7+t)# return ne, 3oa".Buil"er().,it+Bul9'<tem(,ei7+t).buil"()$ public 3oa" (in"(lon7 i") # return 3oa".(in"(i")$ $

5he interceptor )ntit'6ana7er<njector ses the in=ected )ntit'6ana7er and passes it to the tility class :+rea"3ocal)ntit'6ana7er sing its associate!it+:+rea" method%
import static ...persistenceutils.:+rea"3ocal)ntit'6ana7er.Cpublic class )ntit'6ana7er<njector #

92
Download at WoweBook.Com

2PersistenceContext private )ntit'6ana7er em2Aroun"<nvo9e public Object associate...(<nvocationContext ic) t+ro,s )xception # associate!it+:+rea"(em)- %%staticall' importe" met+o" tr' # return ic.procee"()$ (inall' # cleanup:+rea"()$ $ $

5he :+rea"3ocal)ntit'6ana7er is simple as 'ell. +t only 'raps and provides convenient access to the java.lan7.:+rea"3ocal. 5his class does the act al 'or# and implements the association bet'een the c rrent thread and the re"erenced ob=ect (in this case the )ntit'6ana7er). 5he :+rea"3ocal tility #eeps the )ntit'6ana7er available in the c rrent thread%
import javax.persistence.)ntit'6ana7erpublic class :+rea"3ocal)ntit'6ana7er # private static (inal :+rea"3ocal.)ntit'6ana7er0 : R)A8J!<: J)6 D ne, :+rea"3ocal.)ntit'6ana7er0()private :+rea"3ocal)ntit'6ana7er() #$ public static voi" associate!it+:+rea"()ntit'6ana7er em) # : R)A8J!<: J)6.set(em)$ public static )ntit'6ana7er em() # return : R)A8J!<: J)6.7et()$ public static voi" cleanup:+rea"()# : R)A8J!<: J)6.remove()$ $

5he :+rea"3ocal)ntit'6ana7er and )ntit'6ana7er<njector are independent arti"acts and can be re sed in di""erent pro=ects.

se case

5his approach 'or#s 'ell 'ith .ervices and .ervice !a@ades$ 'hich are accessed each time be"ore any P;, interaction. Date'ays are more problematic$ beca se a presentation tier component only comm nicates at the beginning 'ith the state" l session bean$ and then ses P;,s directly 'itho t any intermediary layer. +n this case$ yo sho ld move the interception one level p$ "or e>ample$ to the .ervletRs javax.servlet.&ilter. Qo co ld re se the )ntit'6ana7er<njector code and replace the context.procee"() invocation 'ith &ilterC+ain#"o&ilter().

93
Download at WoweBook.Com

"ata Bo,nd P"( ;ata Bo nd P;, is a pragmatic variant o" the P;,. +t is a tradeo"" bet'een the H ent inter"ace or p rely domain-driven approach and a proced ral ;5,. A data-bo nd P;, comes 'ith property accessors$ 'hich are intended "or a tomatic synchroni?ation 'ith the presentation layer components. All data binding "rame'or#s rely at least on *avaBeans conventions. /ative clients s ch as -clipse data binding or even *.6-292 e>pect the proper sage o" java.beans.Propert'C+an7eSupport and the noti < cation o" java.beans.Propert'C+an7e3isteners interested in state changes. 5he proced ral-style accessors are intended "or reHective and not man al se. (an ally cra"ted code sho ld still rely on the ob=ect-oriented vie' and not <ne-grained property access. Property accessors in general bypass cross-attrib te chec#s and sophisticated validations. 5here"ore they are act ally co nter-prod ctive 'ithin the P;, conte>t. Accessors are not mandatory "or declarative data binding. 5he binding bet'een a 7+ component and the so rce is per"ormed declaratively 'ith -9 e>pressions (strings) and th s cannot be typesa"e%
Bin"in7 bin"in7 D Bin"in7s.createAutoBin"in7(AutoBin"in7.Up"ateStrate7'.R)A8J!R<:)1 t+is1 )3Propert'.create(4[#or"er.name$4)1 txtAame1 BeanPropert'.create(4text4))bin"in7>roup.a""Bin"in7(bin"in7)-

5he e>pression [#or"er.name$ res lts in the navigation N(ormO.7etOr"er().setAame()%7etAame() "rom the vie' thro gh the P;, to the property name. 5he binding e>pression cannot be chec#ed by the compiler and misspellings 'ill res lt in r ntime errors. 5he e>istence o" e>plicit property accessors does not improve the sit ation. 5he +;- s pport s ch as code completion is not sed$ beca se the accessors are not invo#ed in a programmatic 'ay$ b t thro gh reHection. 5he main advantage o" type-sa"e accessorsIthe se o" +;- s pport ("or e>ample$ a tocompletion) is not sed. 5he only reason "or their e>istence is the reHective access by a data binding "rame'or#$ 'hich sed to be declaratively con<g red and not man ally coded. 5he P;, state$ ho'ever$ can be manip lated directly via reHection 'itho t the accessors. 5he reHection AP+ allo's direct access to even private attrib tes 'ith relatively little e""ort. 5he P;,s can remain concise$ 'itho t the need to implement the gly getters and setters. 5he 'hole access mechanism can be easily encaps lated in a tility class. 5he "ollo'ing e>ample demonstrates reHective access to private P;, members%
public class &iel"Access # public static Object 7et(Object obj1 Strin7 (iel"Aame) # tr' # return 7et&iel"(obj1 (iel"Aame).7et(obj)$ catc+ (<lle7alAccess)xception e) # t+ro, ne, <lle7alState)xception(4@G 4 H (iel"Aame1 e)$ $

98
Download at WoweBook.Com

public static voi" set(Object obj1 Strin7 (iel"Aame1 Object value) # tr' # 7et&iel"(obj1 (iel"Aame).set(obj1 value)$ catc+ (<lle7alAccess)xception e) # t+ro, ne, <lle7alState)xception(4@G 4 H (iel"Aame1 e)$ $ static &iel" 7et&iel"(Object obj1 Strin7 (iel"Aame) # tr' # &iel" (iel" D obj.7etClass().7et8eclare"&iel"((iel"Aame)(iel".setAccessible(true)return (iel"$ catc+ (AoSuc+&iel")xception e) # t+ro, ne, <lle7alState)xception(4@E1 e)$ $ $

5he class &iel"Access provides the access to private <elds 'ith static tility methods. 5his is nice$ beca se they can be statically imported%
2)ntit' 2:able(nameD48BJOR8)RJ<:)64) public class Or"er<tem # 2<" 2>enerate"?alue private 3on7 i"private int ,ei7+t2)numerate"()num:'pe.S:R<A>) private 3oa":'pe loa":'pepublic Or"er<tem(3on7 i"1 int ,ei7+t1 3oa":'pe loa":'pe) # t+is.i" D i"t+is.,ei7+t D ,ei7+tt+is.loa":'pe D loa":'pe$ $

5he se is straight"or'ard. 5he methods 7et() and set() do e>pect the instance o" the ob=ect and the name o" the attrib te%
Or"er<tem item D ne, Or"er<tem(3OA>J?A3U)1 I1 3oa":'pe.BU3YB)3on7 i" D (3on7) 7et(item1 4i"4)set(item1 4i"41Il)i" D (3on7) 7et(item1 4i"4)-

5he invocation o" the traditional accessor$ item.7et<"()$ is eB ivalent to &iel"Access.7et(item14i"4). 5he property names co ld be derived sing 7+ conventions. 5he 7+ components co ld be either annotated 'ith the property names or$ even

92
Download at WoweBook.Com

better$ the names can be comp ted "rom the component names. 5his approach red ces code d plication and pl mbing$ b t still doesnRt violate the encaps lation. (ost o" the available tools$ ho'ever$ do not s pport s ch binding vis ally$ b t it is still interesting "or meta data-driven applications.

5esting
P;,s are annotated classes and can be tested as common P,*,s. !or the b siness logic tests yo 'ill not even have to moc# o t or bootstrap the )ntit'6ana7er. 5he instances needed to per"orm the test can be easily created in the 2Be(ore or 2Be(oreClass methods and sed in the act al test methods. 5he "ollo'ing e>ample demonstrates a P;, b siness logic test 'itho t involving the )ntit'6ana7er%
public class 3oa":est # 2:est(expecte"D<lle7alState)xception.class) public voi" empt'()# 3oa" buil" D ne, 3oa".Buil"er().buil"()$ 2:est public voi" mixe"3oa"()# 3oa" loa" D ne, 3oa".Buil"er(). ,it+Stan"ar"<tem(X). ,it+3i7+t,ei7+t<tem(U). ,it+Bul9'<tem(U). buil"()int actual D loa".7etS+ippin7Costs()int expecte" D (XCX) H (X/U) H (UCXHX)assert)quals(expecte"1actual)$ 2:est public voi" +eaviest()# 3oa" loa" D ne, 3oa".Buil"er(). ,it+Stan"ar"<tem(X). ,it+3i7+t,ei7+t<tem(U). ,it+Bul9'<tem(U). buil"()Or"er<tem +eaviest D loa".+eaviest()assertAotAull(+eaviest)assert)quals(X1+eaviest.7et!ei7+t())assert:rue(+eaviest instanceo( Stan"ar"<tem)$ %%@ $

P;,s are non-trivial by de<nitionS they 'ere designed to reHect concepts "rom the target domain. 7nit tests o" P;,s are essentially important "or the overall B ality o" the system. +n addition$ yo are "orced to se the P;,s via the p blic AP+ ('hich "orces yo to thin# o tside the bo>). 7nit testing t rns o t to be a good sability chec# "or the P;,Rs inter"ace H encyIany

9:
Download at WoweBook.Com

inconveniences 'ill be e>posed to yo d ring the tests. Dood P;,s are easy to test as 'ellIitRs good B ality ass rance. 5he *PA persistence can be sed "or testing 'ith only little e""ort. ,nly the )ntit'6ana7er has to be created sing the Persistence and the )ntit'6ana7er&actor'$ as sho'n in the "ollo'ing P;, tests%
public class 3oa":est!it+Persistence # private )ntit'6ana7er emprivate )ntit':ransaction et2Be(ore public voi" setUp() t+ro,s )xception # t+is.em D Persistence.create)ntit'6ana7er&actor'(4test4). create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()$ 2:est public voi" mixe"3oa"()# 3oa" loa" D ne, 3oa".Buil"er(). ,it+Stan"ar"<tem(X). ,it+3i7+t,ei7+t<tem(U). ,it+Bul9'<tem(U). buil"()int actual D loa".7etS+ippin7Costs()int expecte" D (XCX) H (X/U) H (UCXHX)assert)quals(expecte"1actual)t+is.et.be7in()t+is.em.persist(loa")t+is.et.commit()t+is.em.clear()3on7 i" D loa".7et<"()t+is.et.be7in()3oa" (oun" D t+is.em.(in"(3oa".class1 i")t+is.et.commit()assert)quals(expecte"1(oun".7etS+ippin7Costs())assert)quals(loa".7etAumberO(Or"er<tems()1(oun".7etAumberO(Or"er<tems()) %%@ $ %%@ $

5he local nit tests co ld even have integrational character. At least r dimentary tests 'ith an )ntit'6ana7er are se" l to <nd ,6 mapping problems. +n more comple> applications$ nit tests 'itho t persistence become increasingly bloatedS in "act$ the creation o" the test <>t re may be really comple>. +n s ch cases$ a local test database can ma#e it m ch easier to pop late the test data once and re se it "or several test r ns.

;oc mentation
90
Download at WoweBook.Com

5he "oc s on the b siness logic and not technology is the #ey to s ccess. -specially the naming o" the P;, itsel"$ as 'ell as its methods is essential. Ambig o s naming sho ld be prevented even in the early iterations. A 'i#i t rns o t to be a good doc mentation tool and pragmatic inter"ace bet'een the developers and domain e>perts. A t'o-col mn table ('ith /ame and -ssential 6esponsibility headers) is good eno gh to doc ment the essential responsibilities and clari"y ambig o s names. P;,s represent #ey concepts$ or essential entities o" the target domain. +t is se" l to vis ali?e the P;,s as 'ell as their relations bet'een each other. 7(9 class diagrams are per"ectly s itable "or this p rpose. !or the doc mentation o" P;,s only a "raction o" the 7(9 capabilities is s "<cient. +n "act$ most o" the 7(9 "eat res and especially generic stereotypes and tagged val es are not 'ell s ited to doc ment the essential responsibility and conte>t o" a P;,. +nstead o" relying on the b ilt-in$ generic stereotypes and tagged val es$ introd ce a c stom$ nambig o s stereotype ..P8O00 (see !ig re 8).

Figure 4. ersistence !omain "b#ect in UML 5he P;,s are modeled as classes$ only p blic methods are vis ali?ed. -ncaps lated <elds and tility methods are not interesting "or overvie' diagrams$ beca se they only ob" scate the essential responsibilities and sho ldnRt be visible. 5he same principle sho ld be applied to *ava;oc. +t is "ran#ly not possible to doc ment private attrib tes and accessors$ especially o" a P;,$ 'itho t repeating the already e>isting tr th in so rce code. ,n the other hand$ at least the essential responsibility o" the P;, sho ld be doc mented on the class level. 5he doc mentation sho ld be 'ritten "ollo'ing the ;6Q principle as 'ellIit is better to e>isting re"erence 'i#i pages$ instead o" repeating the conte>t in *ava;oc again. 5he "ollo'ing best practices are especially important "or the doc mentation o" a P;,% "oc,*ent the -ackgro,nd kno/ledge and the intention and not the res,lt. +ry to ca!t,re the conce!ts in a central !lace (for e6a*!le1 a /iki) and !rovide a reference to the contents.

91
Download at WoweBook.Com

"oc,*ent o-vio,s facts /ith *arker tags (annotations s,ch as 2P8O)7 don:t descri-e the* over and over again (follo/ the "R= !rinci!le). &ncl,de in yo,r doc,*entation sa*!les1 ho/'tos and so on (so,rce code r,les). "on:t allo/ defa,lt Java"oc co**ents generated -y the &"E. So*eti*es1 !roviding no co**ent at all1 is the -est co**ent. +ry to *ini*i5e the a*o,nt of doc,*entation and descri-e only the key conce!ts.

ConseB ences
5sabi ity: +he /hole idea -ehind P"( is i*!roving the *aintaina-ility of co*!le6 logic -y !roviding an easy'to',se AP&1 a so'called fl,ent interface. +he P"( AP& is clean1 concise1 and sho,ld -e trans!arent to do*ain e6!erts and not .,st develo!ers. +here is only a fraction of code needed to interact /ith a P"( /hen co*!ared to the ane*ic or !roced,ral a!!roaches. ,omain expertise: +he *ost i*!ortant !rere8,isite to -,ild *aintaina-le P"(s is to have !rofo,nd do*ain kno/ledge. +he do*ain conce!ts sho,ld -e reflected directly in the P"(. &deally a do*ain e6!ert sho,ld ,nderstand the -,siness logic .,st looking at the P"( codeIthe fl,ent interface -eco*es a do*ain's!ecific lang,age ("S9). Core essentia responsibi ities: A P"( has to reflect only the key conce!ts and sho,ld not reali5e the cross'c,tting as!ects. A P"( can -e ,sed !otentially -y a variety of different a!!lications and clients. #lient's!ecific needs and re8,ire*ents sho,ld -e reflected in1 for e6a*!le1 Services and not in the i*!le*entation of the P"(. (ther/ise a P"( *ay res,lt in a *onolithic1 not cohesive1 set of ,nrelated states and *ethods. &t -eco*es the *ain challenge to kee! a P"( clean and concise. +his can -e achieved only /ith contin,o,s refactoring and testing. Testabi ity: P"(s are .,st annotated Java classes. +hey can -e ,nit tested inside1 as /ell as1 o,tside the EJB container. 0,rther*ore their f,nctionality can -e tested in attached or detached state. Too support: +he &"E s,!!ort for -,ilding P"(s is s,!er-. #ode co*!letion1 refactoring1 and de-,gging /ork really /ell. So*e &"Es co*e /ith s,!!ort for code co*!letion and synta6 highlighting of JPA D9 8,eries1 generation of persistence.xml and so on. +he o-.ect'oriented variant of P"(s is harder to ,se /ith data -inding fra*e/orks s,ch as val,e -inding in JS0 or -eans -inding. +he internal state1 ho/ever1 can -e e6!osed as accessors in addition to -e co*!ati-le /ith s,ch fra*e/orks. 'xtensibi ity: P"(s can -e easily e6tended ,sing o-.ect'oriented *echanis*s and inheritance in !artic,lar. JPA s,!!orts inheritance and !oly*or!hic 8,eries so it fits /ell /ith the P"( idea. ,ata transfer capabi ities: A P"( can -e easily transferred -et/een layers1 even re*otely as detached o-.ects. +he only re8,ire*ent is the i*!le*entation of the java.io.Seriali=able interface. Ho/ever1 a P"( contains a significant a*o,nt of -,siness logic1 /hich can -e invoked in a detached state as /ell. +his can lead to state changes in the entire gra!h. S,ch changes are hard to synchroni5e /ith the server:s state

99
Download at WoweBook.Com

and often re8,ire the co*!,tation of change sets or even kee!ing the origin state of the o-.ects se!arately (for e6a*!le1 S"(). 0or that !,r!ose P"(s are not !assed in a detached state -et/een layers in general.

6elated Patterns
Composite -ntity (*2--)$ ;omain .tore (*2--)$ B siness ,b=ect (*2--)$ ;ata 5rans"er ,b=ect (*2-- C *ava --)% A P;, is managed by a Date'ay and directly e>posed to the presentation tier. .ervices or .ervice 0a@ades provide cross-c tting$ P;,-independent aspects and can access P;,s as 'ell.

400
Download at WoweBook.Com

;ate1ay
P;,s are already consistent$ encaps lated ob=ects 'ith hidden state. 5here is no need "or " rther encaps lationIthey can be directly e>posed to the presentation. A Date'ay provides an entry point to the root P;,s. A Date'ay co ld be even considered as an anti-.ervice !a@adeIin "act its responsibilities are inverted.

Problem
P;,s are passive arti"acts. +t is not possible to access them directly 'itho t an e>ec tion conte>t. Another problem is the stateless nat re o" most *ava -- applications. A"ter a method invocation o" a transaction bo ndary ("or e>ample$ a stateless session bean)$ all *PA-entities (P;,s) become detached. 5he client loses its state. 5his "orces yo to transport the entire conte>t bac# and "orth bet'een the client and the server$ 'hich leads to the "ollo'ing problems% Heavily interconnected P"(s -eco*e hard to *erge. Even for fine'grained changes1 the /hole gra!h of o-.ects has to -e trans!orted -ack to server. &t is not al/ays !ossi-le to *erge the gra!h a,to*atically and even consistently. Beca,se the trans!ort of the conte6t -eco*es too e6!ensive and the *erging f,nctionality on the server side increasingly co*!le61 transaction -o,ndary (for e6a*!le1 Service 0a@ade) is e6tended /ith additional *ethods to *anage each !artic,lar e6cer!t of the entire gra!h. +his res,lts in the e6!losion of hard'to'*aintain *ethods (aka 2od 0a@ades)1 lots of red,ndancies1 and !roced,ral code. "e!endent P"(s cannot -e la5ily loaded in a detached state and th,s in the !resentation tier. +he server has to kno/ in advance1 /hich s,-gra!h of interconnected o-.ects has to -e trans!orted to the client. "edicated *ethods (for e6a*!le1 7etCustomer!it+A""ress()) are introd,ced to overco*e the !ro-le*. Every change of the client:s state has to -e *erged /ith the server. 0or so*e -,siness logic1 s,ch as additional 8,eries1 a P"( *ay re8,ire access to the )ntit'6ana7er. +he )ntit'6ana7er1 ho/ever1 is only availa-le on the server and not the client.

!orces
P"(s are accessi-le locally1 !er reference. P"(s are already /ell enca!s,lated7 there is no need for f,rther layering and a-straction. =o,r a!!lication o/ns the data-ase1 so it can -e changed on de*and. #hanges !erfor*ed in the ,ser interface are likely to affect the data-ase. &t is likely1 that an additional ;&'control /ill ca,se the enhance*ent of the corres!onding ta-le /ith additional col,*ns accordingly. +he a!!lication is interactive. +he validation logic is non'trivial and de!ends on an o-.ect:s state. 0or e6a*!le1 /hether the dragging of an additional 3oa" to a :ransport?e+icle is ena-led co,ld not only -e de!endent on the !artic,lar ?e+icle ty!e1 -,t also on its c,rrent load level. +he dro! action /o,ld change the c,rrent state of the ?e+icle1 /hich in t,rn /o,ld change its validation r,les.

Download at WoweBook.Com

;sers decide /hen their changes are stored and /hen not. +he -,siness logic cannot -e e6!ressed in service'oriented *anner1 /ith self'contained1 ato*ic and inde!endent services.

.ol tion
5he sol tion is very simple. Create a per"ect anti .ervice !a@ade. +nstead o" cleanly encaps lating the P;,s$ try to e>pose P;,s as conveniently "or the 7+ as possible to the ad=acent layer. Allo' the ser to modi"y the P;,s directly 'itho t any indirection. 5he described approach above act ally contradicts the common *2-- principles$ according to 'hich encaps lation is the only 'ay to achieve maintainability. 5his is only tr e "or per"ect abstractions and encaps lations$ 'hich are very hard to <nd in enterprise pro=ects. 5he inverse strategy 'or#s even better in some se casesI= st get rid o" any layer ('hich in all li#elihood is lea#y any'ay according to *oel .pols#yRs 9a' o" 9ea#y Abstractions L'''.=oelonso"t'are.comCarticlesC9ea#yAbstractions.htmlM) and e>pose the b siness logic directly to the presentation tier. -very change in the str ct re o" the persistence layer 'o ld be immediately visible in the ser inter"aceIthis ma#es the implementation o" "eat re reB ests really easy. Qo r presentation is co pled to the partic lar implementation o" the b siness logic$ b t the concrete implementation is already encaps lated. *PA abstracts "rom the partic lar provider$ and -*Bs are nothing else than annotated P,*,s. +n other 'ords$ the technology is pretty 'ell hidden already. 5he concrete state and implementation o" domain-speci<c logic is 'ell encaps lated too IitRs the main responsibility o" the P;,s. Another challenge is the implementation o" a consistent and concise transaction handling. 7s ally the transaction handling is straight"or'ard% a transaction is started and committed be"ore and a"ter every invocation o" the .ervice !a@ade (the bo ndary) method. 5his strategy 'or#s 'ell$ beca se the entire implementation o" the b siness logic resides behind the .ervice !a@ade and is e>ec ted atomically. 5he Date'ay$ ho'ever$ e>poses the P;,s directly to the presentation$ so it loses the control over the P;,s and transactions in partic lar. ! rthermore the ser is allo'ed to access and modi"y the P;,s directly$ 'hich ma#es centrali?ed transaction management 'ith a stateless .ervice !a@ade impossible. Qo can modi"y the detached P;,s directly and a Date'ay is lac#ing o" <ne grained mer7e methods. 5he sol tion to the problem is the introd ction o" state on the server side. A state" l Date'ay can #eep the P;,s attached 'ith an )ntit'6ana7er declared as PersistenceContext.)K:)A8)8. 5he )ntit'6ana7er needs a transaction only as a trigger to H sh the changes to the database$ 'hich can be started by a method that overrides the class de"a lt. 5he "ollo'ing e>amples sho's a state" l Date'ay implementation%
2State(ul 2:ransactionAttribute(:ransactionAttribute:'pe.AO:JSUPPOR:)8) 23ocal(Or"er>ate,a'.class) public class Or"er>ate,a'Bean implements Or"er>ate,a'#

402
Download at WoweBook.Com

2PersistenceContext(t'peDPersistenceContext:'pe.)K:)A8)8) )ntit'6ana7er emprivate 3oa" currentpublic 3oa" (in"(lon7 i")# t+is.current D t+is.em.(in"(3oa".class1 i")return t+is.current$ public 3oa" 7etCurrent() # return current$ public voi" create(3oa" loa")# t+is.em.persist(loa")t+is.current D loa"$ public voi" remove(lon7 i")# 3oa" re( D t+is.em.7etRe(erence(3oa".class1 i")t+is.em.remove(re()$ 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public voi" save()# %%not+in7 to "o $ public voi" up"ate()# t+is.em.re(res+(t+is.current)$ 2Remove public voi" close>ate()# $ $

5he implementation o" the gate'ay is simple. +t is a state" l session bean 'ith )K:)A8)8 )ntit'6ana7er. All incoming transactions are going to be s spended 'ith :ransactionAttribute:'pe.AO:JSUPPOR:)8 on the class level. 5his is act ally only possible 'ith an )K:)A8)8 )ntit'6ana7er$ 'hich can be in=ected only into a state" l session bean. An )ntit'6ana7er 'ith de"a lt con<g ration in=ected to a stateless session bean 'o ld thro' the e>ception javax.persistence.:ransactionRequire")xception in most o" its methods invo#ed 'itho t an active transaction. 5he method save() overrides the class de"a lt 'ith the R);U<R)SJA)! transaction attrib te 'hich "orces the container to start a ne' transaction. 5his$ in t rn$ ca ses the )ntit'6ana7er to H sh all attached entities into the database and event ally to send the commit to the database.

403
Download at WoweBook.Com

.ince the Date'ay is state" l$ it can maintain a client-speci<c state$ 'hich is also a re"erence to a P;,. Qo cache the root P;, 3oa" and ma#e it so easier accessible to the Date'ay clients. 5he re"erence to the 3oa" P;, is maintained in the (in" and create methods. 5he method mer7e is not needed$ beca se there are no detached P;,s to attach. All changed P;,s 'ill be a tomatically synchroni?ed 'ith the database at the end o" the transaction. 5he Date'ay is state" l$ so there is a 4%4 relationship bet'een the client and the Date'ay. 5his can be achieved only by in=ecting the Date'ay to a state" l 'eb component. +" yo are sing *.!$ yo can set p this relationship by in=ecting the Date'ay into a session-scoped bac#ing bean%
.mana7e"/bean0 .mana7e"/bean/name0SessionBeanU.%mana7e"/bean/name0 .mana7e"/bean/class0@..SessionBeanU.%mana7e"/bean/class0 .mana7e"/bean/scope0session.%mana7e"/bean/scope0 .%mana7e"/bean0

5he 'eb container stores a session-scoped bac#ing bean in the javax.servlet.+ttp. ttpSession so that the relationship bet'een the ser session (an open bro'ser 'indo') and the Date'ay instance is properly maintained. Qo only have to in=ect the session bean into a session-scoped bac#ing bean sing the 2)*B annotation%
public class SessionBeanU # 2)*B private Or"er>ate,a' or"er>ate,a'-

5he Date'ay can claim a signi<cant amo nt o" memory. 5he total amo nt depends on the n mber o" attached entities inside a ser session. +t might become a problem in applications 'ith many conc rrent sessions$ so yo sho ld "ree the reso rces as soon as possible. 5he li"ecycle o" the Date'ay is directly dependent on the li"ecycle o" the ttpSession. 5he destr ction o" the ttpSession sho ld ca se the immediate destr ction o" the Date'ay. 5his can be easily achieved by overriding the "estro' method o" the bac#ing bean and invo#ing an annotated 2Remove method%
2Overri"e public voi" "estro'() # %%close>ate,a' is annotate" ,it+ 2Remove t+is.or"er>ate,a'.close>ate,a'()$

+n the pop lar 'eb "rame'or# Eic#et$ yo co ld loo# p the Date'ay session bean in yo r c stom session ob=ect. A little bit tric#ier is the initial set p in a plain .ervlet environment. Qo 'o ld have to search "or the Date'ay in the ttpSession <rst. +n case the search 'as not s ccess" l$ yo 'ill " rther search "or it in <nitialContext and then store it in the ttpSession. A rich client s ch as a .'ing C .E5 application 'o ld be the most nat ral 'ay to se Date'ay$ beca se the entire application already represents the ser session. 7n"ort nately a 6+A is already distrib ted by de<nition$ so that all P;,s become a tomatically detached (beca se o" seriali?ation)$ a"ter every call. 5his "act ma#es the se o" a classical Date'ay "ar less interesting to 6+A clients. +n a "at client con<g ration a Date'ay is still an interesting option "or 6+As.

408
Download at WoweBook.Com

Conventions
A 2ate/ay resides in a co*!onent /hich is reali5ed as a Java !ackage /ith a do*ain' s!ecific na*e1 for e6a*!le1 or"erm7mt. +he 2ate/ay resides in a s,-!ackage (layer) /ith the na*e facade or boundary$ for e6a*!le1 or"erm7mt.(aca"e or or"erm7mt.boun"ar'. +his *akes the a,to*atic verification of the architect,re easier. +he 2ate/ay resides in the sa*e s,-!ackage as a Service 0a@ade. A 2ate/ay is often na*ed after the cached root entity7 it is not necessary to kee! the na*e 2ate/ay. A 2ate/ay is a local1 statef,l session -ean /ith the AO:JSUPPOR:)8 or event A)?)R transaction attri-,te on class level. "edicated1 *ostly e*!ty1 *ethods are starting a ne/ transaction /ith the R);U<R)SJA)! config,ration and fl,sh the transient state to the data-ase. 2ate/ay is de!loyed /ith a single local -,siness interface in general. +he no'interface vie/ o!ti*i5ation is !ossi-le1 -,t then the dyna*ic !ro6y !attern /o,ldn:t /ork any*ore in ,n*anaged environ*ents s,ch as R&As.

6ethin#ing
5he idea o" a Date'ay became possible only recently 'ith the introd ction o" *ava -- 2. +n a *2-- 'orld s ch a pattern 'o ldnRt ma#e any sense$ beca se the lac# o" inheritance and detaching capabilities in C(P 2.0 persistence. 5he attempt to introd ce s ch a pattern in todayRs enterprise pro=ects 'o ld probably be met 'ith resistance. +n the past years$ one o" the important meas rement points o" a scalable architect re is the degree o" co pling and the amo nt o" layers. . ch a metric applied to a Date'ay pattern 'o ld res lt in rather poor res lts. A Date'ay neither tries to encaps late the P;,s nor to introd ce another layer. 5he opposite is tr e% a Date'ay is the gl e bet'een layers$ beca se it attempts to ma#e access to the domain ob=ects as easy as possible. A Date'ay is the mani"estation o" the N9ea#y AbstractionO principle$ 'hich is de<ned as "ollo'ing% N!rom the perspective o" .poels#yRs 9a' o" 9ea#y Abstractions$ all non-trivial abstractions resist complete implementation by their very nat re. ConseB ently$ implementation details 'ill al'ays lea# thro gh$ regardless o" ho' 'ell-conceived$ and no matter ho' rigoro sly they attempt to "aith" lly represent the abstraction. .ometimes the lea#s are minor$ other times they are signi<cant$ b t they 'ill al'ays be present$ beca se there is no s ch thing as a per"ect implementation o" an abstraction...O Lhttp%CCen.'i#ipedia.orgC'i#iC9ea#yPabstractionM. 6egardless o" ho' hard yo 'ill try to encaps late a non-trivial implementation$ it 'ill al'ays be lea#y. +t is there"ore smarter to directly e>pose an already 'ell-designed entity$ instead o" trying to " rther encaps late it. 5his is especially tr e "or 7+-driven pro=ects. 5he c stomer drives the reB irements "rom the 7+ perspective$ so that the reali?ation o" a "eat re 'ill a""ect the presentation tier <rst. . ch changes are not local to the presentation and 'ill hit the ad=acent

402
Download at WoweBook.Com

layers as 'ell. 5he lea#ier the bo ndary bet'een layers$ the more bene<cial the e""ects the introd ction o" Date'ay 'ill have on yo r architect re.

Participants and 6esponsibilities


A Date'ay e>poses P;,s directly to the presentation layer. 5he most important participant is the P;, or an anemic domain ob=ect and the 7+ itsel". 5he Date'ay is = st an intermediary and provides only the e>ec tion conte>t "or the P;,s. A Date'ay is responsible "or% Eee!ing the )ntit'6ana7er o!en -et/een *ethod calls1 so that the already kno/n P"(s do not -eco*e detached. Providing as convenient and direct an e6!os,re of P"(s as !ossi-le. Providing a defined synchroni5ation !oint (the *ethod save) and o!tional ,ndo *ethod ()ntit'6ana7er#re(res+). Per'reference (local) access to the P"(s. +his re8,ires yo, to r,n the EJB container in the sa*e JB% as yo,r /e- container. &t is the defa,lt setting of the *ost a!!lication servers. &*!le*enting the cross'c,tting o!erations and es!ecially 8,ery *ethods.

A Date'ay$ ho'ever$ depends on some P;, B alities as 'ell% P"(s sho,ld -e designed to -e directly accessed in the !resentation. +heir f,nctionality sho,ld -e /ell enca!s,lated. +he !,-lic P"( *ethods sho,ld al/ays leave the do*ain o-.ect in a consistent state. +his can -e hardly achieved /ith !lain getters and setters.

5he presentation tier has to be able to #eep$ or at least determine$ the serRs state. Qo r 'eb "rame'or# sho ld be capable to #eep the re"erence to the Date'ay associated 'ith the serRs session. 5his is already given in *.!$ can be easily achieved 'ith Eic#et$ and is a little bit harder 'ith plain .ervlets.

.trategies
5he in-process e>ec tion o" the Date'ay pattern is common in all strategies. +t is also cr cial "or the notion o" transparent persistence. 5he state" l nat re is typical "or all strategies and allo's #eeping all P;,s attached "or the length o" the conversation. Server'Side 2ate/ay 5his is the most common strategy. 5he Date'ay is deployed as a state" l session bean and is accessed by the 'eb container per reference. 5he *ava Conte>t and ;ependency +n=ection Contract a#a EebBeans speci<cation (*.6-299)$ or its pop lar implementation$ *Boss .eam$ can be considered as a Date'ay pattern on steroids. 5he EebBeans speci<cation is the integration layer bet'een *.! and -*B 3 and simpli<es the access to *PA entities ma#ing the bac#ing bean s perH o s. +n addition$ EebBeans provides several conversations (similar to s bsessions) inside a ttpSession. EebBeans becomes especially interesting "or scenarios 'ith many independent

40:
Download at WoweBook.Com

s bdialogs and comple> 'i?ards. Both EebBeans and .eam are state" l "rame'or#s and are based on state" l session beans or even longer conversations s ch as b siness processes. 5he same is tr e "or the Date'ay pattern$ b t it provides only a s bset o" the EebBeans " nctionality. ,n the other hand$ its reali?ation is straight"or'ard. +" yo are sing a Date'ay on the server only$ yo can omit the b siness inter"ace. 5he Date'ay bean co ld be directly in=ected into the *.! bac#ing bean or the Eic#et EebPage. &eep in mind$ that this approach 'ill ma#e testing$ especially moc#ing$ harder and s'apping the implementation becomes impossible. R&A 2ate/ay A Date'ay is = st a P,*, so it is not limited to server se. +t can also be started in the conte>t o" a 6+A. +t is directly e>ec ted in clientRs A(. !ran#ly$ this 'o ld t rn a thin 6+A into a "at client. All the layers 'o ld be e>ec ted at the client side$ so it is a "at client by de<nition. !at client may so nd no more p to date to yo $ b t #eep in mind that several pop lar "rame'or#s are already converging into this direction. Adobe A+6 is a client r ntime that can be compared to applets or a Eeb.tart application b t is !lash based. 5he A+6 r ntime (and the A+6 applications yo b ild) also comes 'ith an embedded database. -ven more interesting is Doogle Dears. 5his in-bro'ser installed A*AK "rame'or# comes 'ith an embedded database$ A Dears application accesses the database "rom *ava.cript. +t is nothing else than an even more aggressive "orm o" a "at client. (+n general$ = st avoid to se the term fat client in meetings$ sessions$ and architect ral descriptions. +t is good neither "or yo r pro=ect nor yo r career.) A Date'ay can either access an embedded database or a remote database. +t is only dependent on the con<g ration o" the *;BC driver in the persistence. *ava ;B (A&A ;erby ;B) has been incl ded 'ith the *;& since version 4.:. +" yo s'itch to the )mbe""e"8river$ the j"bc.url 'ill not re"er to a host name$ b t to a path in the local <le system. 5he "ollo'ing snippet sho's the persistence.xml con<g ration "or local bootstrapping 'ith an embedded ;erby ;B%
.persistence/unit nameD4test4 transaction/t'peD4R)SOURC)J3OCA340 .provi"er0...essentials.PersistenceProvi"er.%provi"er0 .class0...business.7ate,a'."omain.3oa".%class0 .5// remainin7 entities //0 .exclu"e/unliste"/classes0true.%exclu"e/unliste"/classes0 .properties0 .propert' nameD4toplin9.j"bc.url4 valueD4j"bcG"erb'G.%sample-createDtrue4%0 .propert' nameD4toplin9.j"bc."river4 valueD4or7.apac+e."erb'.j"bc.)mbe""e"8river4%0 .%properties0 .%persistence/unit0

5o access the remote database$ yo 'ill only have to change the driver and the j"bc.url again%
.propert' nameD4toplin9.j"bc.url4 valueD4j"bcG"erb'G%%local+ostGUXIT%sample4%0 .propert' nameD4toplin9.j"bc."river4 valueD4or7.apac+e."erb'.j"bc.Client8river4%0

400
Download at WoweBook.Com

5he ;ependency +n=ection o" the )ntit'6ana7er is not a tomatically given o tside the container. +t has to be provided either by yo (in=ecting it man ally) or by the embeddable -*B 3.4 container. 5he bootstrapping o" an -*B 3.4 embeddable container is straight"or'ard%
javax.ejb.)*BContainer ec D )*BContainer.create)*BContainer()javax.namin7.Context ctx D javax.ejb.)*BContainer.7etContext()Or"er>ate,a' or"er>ate,a' D (Or"er>ate,a')ctx.loo9up(4javaG7lobal%7ate,a'%Or"er>ate,a'4)-

-*B 3.0$ ho'ever$ did not s pport a standardi?ed 'ay to bootstrap the -*B container o tside the application server. Beca se a session bean is a P,*,$ it can be instantiated and sed as any other *ava class. +t is basically the same approach as instantiating the bean in the 2Be(ore method in yo r nit test%
t+is.em D Persistence.create)ntit'6ana7er&actor'(4test4).create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()t is.+ate(ay > ne( 8rderEate(ay#ean(); t is.+ate(ay.em > t is.em;

Bootstrapping the )ntit'6ana7er$ instantiating the Date'ay$ and in=ecting the re"erences is a repetitive tas#. Date'ay comes already 'ith some 'ell-#no'n constraints and conventions. +t is reB ired to have a parameterless (de"a lt) constr ctor and has a <eld 'ith the )ntit'6ana7er type annotated 'ith 2PersistenceContext annotation. ! rthermore it is a state" l sesssion bean$ so its li"ecycle is 'ell de<ned as 'ell% ne,<nstance() (invocation of defa,lt constr,ctor) "e!endency in.ection (if any) PostConstruct call-acks (if any) <nit *ethod1 or e.-#reateF%E+H("G (if any)

+n general$ a Date'ay has neither a PostConstruct nor a ejbCreate method. +n most cases$ it is s "<cient to per"orm the <rst t'o steps o" the li"ecycle to sim late the reB ired containerRs li"ecycle. Both steps can be easily e>tracted into a generic "actory class. 5he 'hole li"ecycle can be even " rther a tomated 'ith reHection. Ee #no' that the Or"er>ate,a'Bean implements the local b siness inter"ace 'ith consistent naming conventions. !ollo'ing conventions$ the name o" the inter"ace 'o ld be Or"er>ate,a'\'itho t the Bean ending. 5his in"ormation is sed to derive the bean implementation "rom the local b siness inter"ace passed as a parameter to the "actory method. 5he "ollo'ing e>ample sho's the Bean3ocator generic "actory and in=ector%
public class Bean3ocator # public (inal static Strin7 SU&&<K D 4Bean4public static (inal Strin7 UA<:JAA6) D 4test4private static Bean3ocator instance D nullprivate )ntit'6ana7er emprivate )ntit':ransaction etprivate Bean3ocator() #

401
Download at WoweBook.Com

)ntit'6ana7er&actor' em( D Persistence.create)ntit'6ana7er&actor'(UA<:JAA6))t+is.em D em(.create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()$ public (inal static s'nc+roni=e" Bean3ocator locator() # i( (instance DD null) # instance D ne, Bean3ocator()$ return instance$ public <4> 4 create1nd2n!ect(0lass<4> bean2nter/ace) { Strin7 beanAame D bean<nter(ace.7etAame()beanAame HD 4Bean4tr' # Class cla== D Class.(orAame(beanAame)Object ne,<nstance D cla==.ne,<nstance()inject<nto&iel"(ne,<nstance1 PersistenceContext.class1 t+is.em)... $

5he b siness inter"ace$ passed as a parameter$ is sed to <nd the name o" its implementation (the bean class) and it sets the methodRs ret rn type as 'ell. 5he Bean3ocator is a singleton$ the )ntit'6ana7er is created in its private method once. 5he classic 7et<nstance() method 'as renamed to locator() to ma#e it more H ent% Or"er>ate,a' 7 D locator().createAn"<nject(Or"er>ate,a'.class)5he creation is straigh"or'ardS more interesting is the in=ection o" the )ntit'6ana7er into the Date'ay. 5he <eld might act ally have private visibility 'hich is act ally not a big iss e "or reHection%
public static voi" inject<nto&iel"(Object obj1Class anno1Object value)# tr' # &iel" (iel" D 7et&iel"(obj1 anno)i(((iel" 5D null) (iel".set(obj1 value)$ catc+ (<lle7alAccess)xception ex) # t+ro, ne, <lle7alState)xception(4)rror accessin7 attribute 4 Hex1 ex)$ $ public static &iel" 7et&iel"(Object obj1 Class anno) # &iel"NO "eclare"&iel"s D obj.7etClass().7et8eclare"&iel"s()(or (&iel" (iel" G "eclare"&iel"s) # i(((iel".7etAnnotation(anno) 5D null)# /ield.set1ccessible(true); return (iel"$ $ return null-

409
Download at WoweBook.Com

Qo en merate thro gh all <elds and as# "or the declaration o" the 2PersistenceContext annotation. Qo set the "o nd &iel" to be accessible$ 'hich allo's access to even private members. !inally$ the val e o" the &iel" 'ill be overridden 'ith the c rrent )ntit'6ana7er instance. 7sing only a "e' lines o" code$ yo are able not only to instantiate the Date'ay b t also to in=ect the )ntit'6ana7er into its private member. And there 'ere no changes to the e>isting Or"er>ate,a'Bean needed. A remaining challenge is the reali?ation o" the transaction management. 5he container is responsible "or the interpretation o" the annotations in con= nction 'ith de"a lts and manages the transactions "or yo . 5his " nctionality is not available o tside the (Z -*B 3.4) container$ so yo also have to control transactions. 5he creation o" the Date'ay is encaps lated in a "actory$ so yo co ld se the decorator pattern$ or even aspects$ to manage the transactions. 5he introd ction o" an entire aspect-oriented "rame'or# = st to decorate a method is over#ill. +t 'o ld introd ce additional comple>ity$ ma#e the deployment o" the libraries necessary$ and reB ire the se o" special compilers or speci<c classloaders or *ava agents. Or"er>ate,a' 'ith its b siness inter"ace is a per"ect candidate to be decorated 'ith a dynamic pro>y. ;ynamic pro>y is part o" *;& and has been available since version 4.3. +t doesnRt reB ire any additional libraries and can be considered a s bset o" a " lly Hedged A,P "rame'or#. !or o r p rposes it is good eno gh. 5he *A( is able to create instances "or a given inter"ace on the Hy. Qo only have to pass a speci<c implementation o" an <nvocation an"ler 'hich 'ill be invo#ed by the *A(%
Class cla== D Class.(orAame(beanAame)Object ins D cla==.ne,<nstance()inject<nto&iel"(ins1 PersistenceContext.class1 t+is.em)return ,it+:ransactions(ins1bean<nter(ace1t+is.em1 t+is.et)-

!ort nately$ the dynamic pro>y 'or#s 'ith reHection$ so yo are able to provide a generic and ;6Q sol tion. +n the "ollo'ing e>ample$ the dynamic pro>y tility decorates an inter"ace 'ith the transaction aspect%
import !ava.lan+.re/lect.6ro=y; import javax.persistence.)ntit'6ana7erimport javax.persistence.)ntit':ransactionpublic class 8ecorator # public static .:0 : ,it+:ransactions(Object tar7et1Class.:0 vie,1 )ntit'6ana7er em1)ntit':ransaction et) # Class all<nter(acesNO D ne, ClassNO#vie,$:ransaction an"ler +an"ler D ne, :ransaction an"ler(tar7et1em1et)Class3oa"er cl D tar7et.7etClass().7etClass3oa"er()return (:)Prox'.ne,Prox'<nstance(cl1all<nter(aces1+an"ler)$ $

440
Download at WoweBook.Com

5he java.lan7.re(lect.Prox'.ne,Prox'<nstance method reB ires a Class3oa"er instance$ all inter"aces that have to be intercepted$ and the act al handler. 5he delegation reB ires "e' lines o" code and has nothing to do 'ith the act al Bean3ocator$ so yo can "actor it o t into a standalone 8ecorator tility class. 5he cr > o" the matter is the :ransaction an"ler implementation. +t reali?es the <nvocation an"ler$ 'hich "orces yo to implement the invo9e method. 5his method represents an aro nd aspectIthe origin method is " lly 'rapped$ so yo can provide additional " nctionality be"ore and a"ter its e>ec tion. 5he "ollo'ing e>ample demonstrates the implementation o" the transaction aspect 'ith dynamic pro>y%
public class :ransaction an"ler implements <nvocation an"ler # private )ntit'6ana7er em D nullprivate )ntit':ransaction et D nullprivate Object tar7et D nullpublic :ransaction an"ler(Object tar7et1 )ntit'6ana7er em1 )ntit':ransaction et) # t+is.et D ett+is.em D emt+is.tar7et D tar7et$ public Object invo9e(Object prox'1 6et+o" met+o"1 Object parametersNO) t+ro,s :+ro,able # Object ret?al6et+o" tar7et6et+o" D nullboolean transactional D (alsetr' # tar7et6et+o" D 7et6et+o"&or:ar7et(met+o"1 met+o".7etParameter:'pes())transactional D is:ransactional(tar7et6et+o")i( (transactional) # t+is.et.be7in()$ ret?al D tar7et6et+o".invo9e(tar7et1 parameters)i( (transactional) # t+is.et.commit()$ $ catc+ (<nvocation:ar7et)xception e) # i( (transactional) # t+is.et.rollbac9()$ t+ro, e.7et:ar7et)xception()$ catc+ ()xception e) # t+ro, ne, Runtime)xception(4unexpecte" invocation exceptionG 4 @)$ return ret?al$ private boolean is:ransactional(6et+o" tar7et6et+o") #

444
Download at WoweBook.Com

:ransactionAttribute annotation D tar7et6et+o".7etAnnotation(:ransactionAttribute.class)i( (annotation 5D null) # :ransactionAttribute:'pe value D annotation.value()i( (value.equals(:ransactionAttribute:'pe.R);U<R)SJA)!)) # return true$ $ return (alse$ %%... some met+o"s omitte" $

+t is only reB ired to start transactions "or methods annotated 'ith declared the :ransactionAttribute:'pe.R);U<R)SJA)! annotation. All other methods 'o ld inherit the AO:JSUPPOR:)8 class annotation$ so yo only invo#e the target (the Date'ay instance) 'itho t pro>ying it. 5he correct implementation sho ld s spend and res me the incoming transaction. )o'ever$ this transaction is neither needed nor even possible in o r scenarioDate'ay is directly accessed by the 7+ and the 7+ m st not control transactions. Qo co ld$ ho'ever$ easily implement all :ransactionAttribute:'pes 'ith a dynamic pro>y$ b t it is not relevant "or a Date'ay implementation. Eith t'o classes and some tility methods$ yo are able to start the Date'ay o tside the container. 5he Date'ay does not have to be modi<ed$ it can even be deployed inside the origin ejb/jar.jar to the client. 5his ens res strict separation bet'een the Date'ay and its presentation tier. Hy-rid 2ate/ay 6egardless ho' 'ell yo r c stomer receives the 6+A$ it 'o ld be grossly negligent to tightly co ple the Date'ay 'ith a concrete presentation "rame'or#. Chances are that yo r c stomer 'ill insist in the near " t re to e>pose a s bset o" yo r rich client " nctionality to the 'eb. 5he Date'ay is an -*B 3$ so it sho ld be deployable to the server. A care" lly designed and deployed 6+A Date'ay has this ability already. 5he )ybrid Date'ay is tested on the client and server$ so it can be deployed in parallel to both environments. 5his is more common than yo might thin#. ;eploying the Date'ay directly to the client solves a lot o" problems$ b t it ma#es the e>pos re o" re sable services to the o tside 'orld nearly impossible. A server-side deployment ma#es the e>pos re o" e>isting " nctionality via 6-.5$ .,AP$ 6(+ or ++,P relatively easy. Qo only have to encaps late the <ne-grained Date'ay 'ith a .ervice !a@ade$ 'hich 'o ld increase the gran larity o" the services and ma#es them remote capable.

5esting
A Date'ay sho ld not contain any comple> b siness logic. +t can be sed$ ho'ever$ as a convenient entry point to the P;,s nder test. A Date'ay can be easily instantiated in the nit

442
Download at WoweBook.Com

test. Act ally there is no di""erence bet'een the e>ec tion in the 6+A or nit test conte>t. Qo co ld even se the Bean3ocator "or bootstrapping as sho'n in the "ollo'ing e>ample%
public class )mbe""ableContainer:est # private Or"er>ate,a' 7ate,a'private )ntit'6ana7er emprivate )ntit':ransaction et2Be(ore public voi" initPersistence()# )ntit'6ana7er&actor' em( D Persistence.create)ntit'6ana7er&actor'(4test4)t+is.em D em(.create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()t+is.7ate,a' D locator().createAn"<nject(Or"er>ate,a'.class)$ 2:est public voi" createAn"Save()# 3oa" loa" D ne, 3oa".Buil"er().,it+Bul9'<tem(U).buil"()t+is.7ate,a'.create(loa")3on7 loa"<" D loa".7et<"()3oa" current D t+is.7ate,a'.7etCurrent()assertSame(loa"1current)3oa" (oun" D t+is.em.(in"(3oa".class1 loa"<")assertAull((oun")t+is.7ate,a'.save()(oun" D t+is.em.(in"(3oa".class1 loa"<")assertAotAull((oun")$ $

6egardless o" ho' trivial a Date'ay implementation really is$ a nit test sho ld al'ays be 'ritten "or it. Date'ay is a central entry point to the domain logic. P;,s are non-trivial by nat re$ so possible mapping errors s ch as inconsistent transaction or state management can ca se serio s problems in latter iterations. . ch problems can be easily spotted in the early iterations$ even be"ore the integration tests. Date'ay is state" l$ so load and rob stness tests are especially important. -very ser has a Date'ay instance$ 'hich in t rn is associated 'ith an )ntit'6ana7er. -ach )ntit'6ana7er instance maintains its o'n *PA entity cache. 5he )ntit'6ana7er in=ection is con<g red as PersistenceContext.)K:)A8)8$ so the cache is not cleared a"ter every transaction. All P;,s remain attached$ in e>treme cases "or the length o" the session. 5he si?e o" P;,s in memory is hard to estimate in advance$ b t can be easily meas red d ring a load test. . ch tests do not have to be realistic$ more important is testing the behavior o" the system nder heavy load.

443
Download at WoweBook.Com

. ch tests sho ld be per"ormed as early as possible. 5his gives yo eno gh time to migrate to a stateless architect re in case the scalability o" the system does not satis"y yo r e>pectations.

;oc mentation
Beca se Date'ay does not contain sophisticated b siness logic in general$ there is no need to doc ment every occ rrence o" a Date'ay in yo r pro=ect. +t is more important to doc ment the concept behind a Date'ay once$ and then only point to the already e>isting doc mentation. A lean$ t torial-li#e doc mentation 'ith some sample code is per"ectly s itable "or that p rpose. +t is also nnecessary to doc ment a Date'ay in a 7(9 diagram. +t only provides an e>ec tion and session conte>t "or the P;,s. * st #eep the diagrams concise and emphasi?e the essential b siness logic$ that is$ the P;,s.

ConseB ences
)ca abi ity: 2ate/ay is a statef,l co*!onent. All P"(s are cached in the ,ser session. +he scala-ility of this !attern is highly de!endent on the cache si5e and the length of the session. +his !attern doesn:t scale as good as a stateless1 service'-ased architect,re in general. Ho/ever1 it is a-sol,tely s,fficient for *ost a!!lications. +he act,al scala-ility is hard to esti*ate -,t easy to verify /ith -r,te'force load tests. Performance: When the ,ser needs fre8,ent access to the sa*e data1 a statef,l architect,re co,ld !rovide -etter !erfor*ance. +he P"(s /ill -e loaded only once for the entire session and can -e locally accessed per reference. Consistency: #ached P"(s can -eco*e stale. +he -igger the session and the *ore ,sers access the sa*e data-ase1 the *ore likely are lost ,!dates and other interferences -et/een cached o-.ects. +he introd,ction of the 2ate/ay !attern a,to*atically i*!lies the ,se of o!ti*istic lock strategies. A /ell defined strategy for handling the javax.persistence.Optimistic3oc9)xception sho,ld -e defined and tested in early iterations. Testabi ity: A 2ate/ay is not only easy to test1 it also f,rther si*!lifies testing P"(s. !aintainabi ity: &n non'trivial1 !ro-le*'solving a!!lications1 a 2ate/ay can greatly i*!rove the *aintaina-ility. &t si*!lifies the architect,re and *akes the inter*ediary layers s,!erfl,o,s. +his is es!ecially tr,e in !ro.ects1 /here the data-ase is ,nder yo,r control and yo,r c,sto*er thinks in ;& for*s. (n the other hand1 2ate/ay can significantly increase the co*!le6ity of a service'oriented a!!lication /ith *any e6ternal services. &n that case1 P"(s /ill only re!resent a s,-set of the entire -,siness logic. +he interfaces to the e6ternal syste*s o!erate /ith "+(s1 /hich are detached !er definition. 0,rther*ore1 the direct e6!os,re of the internal1 not /ell'enca!s,lated state and -ehavior ("+(s and fine'grained services) together /ith enca!s,lated and attached P"(s *akes the develo!*ent of the !resentation logic *ore co*!le6 and the architect,re -rittle. Productivity: P"(s are directly e6!osed to the !resentation tier. +hey are even availa-le for declarative data -inding (for e6a*!le1 in JS0)1 or can -e directly *ani!,lated in the !resenter (AEA controller). Every e6tension in the do*ain logic is i**ediately availa-le in the !resentation.

448
Download at WoweBook.Com

'ase of use: After yo, get the idea of al/ays attached o-.ects and transaction triggered synchroni5ation1 the develo!*ent -eco*es s,r!risingly easy. &ss,es s,ch as la5y loading1 synchroni5ation of co*!le6 o-.ect gra!hs1 or co*!,tation of change sets si*!ly do not e6ist.

6elated Patterns
Composite -ntity (*2--)$ ;omain .tore (*2--)$ B siness ,b=ect (*2--)$ ;ata 5rans"er ,b=ect (*2-- C *ava --)$ .ervice !a@ade (*2-- C *ava --)$ .ervice (*2-- C *ava --)% A Date'ay e>poses P;,s to the presentation logic. +t has opposite capabilities to a .ervice !a@ade. +t is act ally an inversion o" a .ervice !a@ade and any .,A-li#e approaches.

442
Download at WoweBook.Com

Download at WoweBook.Com

,l$id 3ogic
*ava is a static lang age 'ith emphasis on its strong typing. *ava is 'ell s itable "or the implementation o" 'ell-de<ned$ stable b siness logic. Algorithms that o"ten change reB ire recompilation and even redeployment o" the 'hole application.

Problem
.trong typing and the static nat re o" *ava are "eat res and dra'bac#s at the same time. !or integration p rposes$ dynamic lang ages s ch as *ava.cript$ 6 by$ or Python are better s itable and more e"<cient. Eith *ava it is hardly possible to eval ate or interpret b siness logic at r ntime. Qo co ld se tools s ch as A/596 ('''.antlr.org) to b ild yo r o'n domain-speci<c lang age (;.9)$ 'hich 'o ld be eval ated or interpreted at r ntime. Qo sho ldnRt nderestimate the e""ort it ta#es to design$ test$ doc ment$ and deploy a c stom ;.9.

!orces
=o, /ant to e6ec,te !arts of the -,siness logic dyna*ically. Algorith*s that often change have to -e isolated and loaded dyna*icallyA/itho,t affecting the rest of the a!!lication. +he affected code changes str,ct,rallyAco*!ilation at de!loy*ent ti*e is not s,fficient. +he reali5ation of a c,sto* inter!reter is too e6!ensive and too hard to *aintain. =o, are searching for a standard /ay to integrate scri!ting co*!onents /ith yo,r Java EE environ*ent.

.ol tion
5he problem has been solved since *ava : .tandard -dition. *.6-223 (.cripting "or the *ava Plat"orm) is a thin and pragmatic AP+ that allo's interaction 'ith more than 400 scripting lang ages. Qo can even pass *ava ob=ects that become available to the script as parameter to the Script)n7ine. 5he initiali?ation o" the Script)n7ine ta#es only a "e' lines o" code. 5he script can be e>ec ted in managed and nmanaged environments as 'ell. -ven the same class can be sed o tside the container and be deployed as a stateless session bean 'itho t any change. 5he "ollo'ing e>ample demonstrates ho' to embed *ava.cript "or dynamic "orm la eval ation%
import import import import import import javax.annotation.PostConstructjavax.ejb.Statelessjavax.script.Bin"in7sjavax.script.ScriptContextjavax.script.Script)n7inejavax.script.Script)n7ine6ana7er-

2Stateless public class Calculator # private static (inal Strin7 )A><A)JAA6) D 4*avaScript4%C On 6ac OS K AppleScript)n7ine instea" o( *avaScript is available private static (inal Strin7 )A><A)JAA6) D 4AppleScript)n7ine4C% private Script)n7ine script)n7ine D null-

Download at WoweBook.Com

private (inal static "ouble &<?) D X2PostConstruct public voi" initScriptin7() # Script)n7ine6ana7er en7ine6ana7er D ne, Script)n7ine6ana7er()t+is.script)n7ine D en7ine6ana7er.7et)n7ineB'Aame()A><A)JAA6))i( (t+is.script)n7ine DD null) # t+ro, ne, <lle7alState)xception(4Cannot create@ 4 H )A><A)JAA6))$ $ public Object calculate(Strin7 (ormula) # Object ret?al D nulltr' # Bin"in7s bin"in7 D t+is.script)n7ine.createBin"in7s()bin"in7.put(4&<?)41 &<?))t+is.script)n7ine.setBin"in7s(bin"in71 ScriptContext.>3OBA3JSCOP))ret?al D t+is.script)n7ine.eval((ormula)$ catc+ ()xception e) # t+ro, ne, <lle7alState)xception(4Cannot create@G 4 H e1 e)$ return ret?al$ $

ConseB ently$ the script is going to be e>ec ted in the conte>t o" the -*B$ participates in transactions$ and has access to container services. Qo co ld even pass an attached entity to the script$ manip late the state 'ith the lang age o" yo r choice$ and let the )ntit'6ana7er on the *ava side synchroni?e the changes 'ith the database. 5his allo's yo to se scripts "or manip lation o" domain ob=ects and is especially interesting "or integration p rposes or mapping bet'een incompatible ob=ect hierarchies. 5he session bean (a .ervice in general) can be easily sed o tside the container 'itho t changes and is th s 'ell s ited to nit testing. Qo only have to e>ec te the initiali?ation o" the scripting environment be"ore accessing the script$ as sho'n in the "ollo'ing e>ample%
public class Calculator:est # private Calculator calculator2Be(ore public voi" setUp() # t+is.calculator D ne, Calculator()t+is.calculator.initScriptin7()$ 2:est public voi" calculate() # Strin7 (ormula D 4ICI4Object actual D t+is.calculator.calculate((ormula)assertAotAull(actual)assert:rue(actual instanceo( 8ouble)-

441
Download at WoweBook.Com

assert)quals(P.R1actual)$ $

*ava.cript has been available 'ith the *;& since version 4.: (on (ac ,. K the Apple.cript). +" yo plan to se other scripting lang ages$ yo 'ill have to deploy additional *A6s "or this p rpose. 5he scripting code can be loaded as a stream "rom any reso rce and is there"ore location-agnostic. +n the Calculator sample the act al script is passed as a method parameter and eval ated at r ntime. *.6-223 allo's also tighter integration bet'een *ava and scripting lang ages. A dynamic lang age o" yo r choice co ld even implement *ava inter"aces$ 'hich co ld be invo#ed "rom a *ava class.

Conventions
!l id 9ogic is a speci<c .ervice. All .ervice conventions and best practices are applicable to the !l id 9ogic service as 'ell. 6e"er to the .ervice section "or more details.

6ethin#ing
Bac# in the *2-- 4.> days$ scripting 'as considered to be inappropriate "or an enterprise application. 5his pre= dice became sometimes e>pensiveIsome pro=ects even developed a c stom interpreter to be able to provide scripting-li#e behavior. ,n the other hand$ dynamic lang ages are highly overhyped these daysS they$ too$ have their shortcomings. 5he B ality o" static analysis$ re"actoring$ and +;- s pport o" scripting lang ages is m ch lo'er compared to plain *ava. ! rthermore$ the lac# o" type sa"ety in most lang ages reB ires yo to 'rite more nit tests. 6easonable se o" scripting has its advantages. 5he H id logic is easily replaceable and can be changed in a r nning system 'itho t redeployment. Beca se the scripts are loaded dynamically$ they can be stored and managed in a database or do'nloaded "rom the net'or#.

Participants and 6esponsibilities


5he Script)n7ine is the most important player. +t is part o" the *.6-223 AP+ and responsible "or the encaps lation o" the act al e>ec tion environment (the .P+). 5he *ava code is independent o" the engine implementation. 5he generic Script)n7ine is created by the Script)n7ine6ana7er$ 'hat is comparable to the *;BC-class java.sql.8river6ana7er and its relation to the act al java.sql.8river. +t tries to <nd and instantiate an appropriate Script)n7ine "or the given name. 5he initiali?ation o" the Scriptin7)n7ine and converting the act al parameters into bindings ta#es a "e' lines o" code and is encaps lated in a simple P,*,. +n addition to the encaps lation$ the P,*, is a classic adapterIit e>poses a more meaning" l inter"ace to the ser. !or its ser it is = st another .ervice$ the e>istence o" scripting is totally transparent.

449
Download at WoweBook.Com

.trategies
5here are no limits in the scripting integrationIand there"ore co ntless strategies. 5he !l id 9ogic pattern can be sed in all tiers$ layers$ and components "or di""erent p rposes. All the variations aim "or a common goal% seamless integration bet'een *ava and scripting 'ith the best o" both 'orlds as res lt.

5esting
5esting o" the scripting integration 'ith -*B 3 is trivialS tests o" the dynamic scripts may become a challenge. +n addition to the act al logic the type sa"ety has to be tested as 'ell. +" the script is the act al ser inp t$ the rob stness o" the sol tion has to be veri<ed. -specially the resistance against malicio s code ("or e>ample$ invo#ing S'stem.exit(/U)) has to be proo"ed. 5he interpretation process is signi<cantly slo'er$ 'hen compared to the e>ec tion o" compiled *ava code. 5he e>tensive se o" scripting in yo r *ava application may res lt in per"ormance hit. Qo sho ld veri"y the act al per"ormance 'ith load and stress tests early.

;oc mentation
!l id 9ogic is a .ervice and sho ld be doc mented as s ch. +n addition$ the reasons and intentions "or the integration o" dynamic lang ages$ as 'ell as the " nctionality o" the script have to be e>plained 'ell. +ntrod cing ne' AP+s and technologies al'ays ca ses some "riction$ especially 'hen introd cing dynamic lang ages to hard-core *ava developers. Clearly stated intentions and reasons "or the integration 'ith a scripting lang age may save some time and avoid long disc ssions.

ConseB ences
Performance: 0l,id 9ogic /ill affect yo,r !erfor*ance. +he i*!ortant 8,estion is /hether yo,r a!!lication /ill -e still fast eno,gh. 2obustness: "yna*ic lang,ages are not ty!e'safe in general. =o, /ill have to invest *ore effort in testing to achieve the sa*e level or sta-ility1 as /ith !lain Java. !aintainabi ity: +he intention of the 0l,id 9ogic !attern is to *ake it easier to *aintain often changing logic. 0l,id 9ogic increases the *aintaina-ility1 !rovided that the develo!ers kno/ the lang,age. (n the other hand1 *,lti'ling,al !ro.ects are harder to ,nderstand1 test1 and de-,g. +he i*!act of scri!ting in yo,r Java !ro.ects is highly de!endent on the develo!er skills and ,se case. Portabi ity: JSR'223 scri!ts are e6ec,ted inside the JB% and are !orta-le across JB%s and a!!lication servers. / exibi ity and agi ity: Here shines the 0l,id 9ogic !attern. Scri!ts can -e *odified1 reloaded1 and re!laced at r,nti*eI/itho,t even rede!loying the a!!lication. +he scri!t does not even have to -e de!loyed inside the EAR1 WAR1 or EJB'JAR and can -e conveniently loaded fro* o,tside.

420
Download at WoweBook.Com

)ecurity: Altho,gh the scri!ts are e6ec,ted inside the JB% and r,n in an environ*ent g,arded -y the Securit'6ana7er1 introd,ction of scri!ting !rovides a !otential and ,n!redicta-le sec,rity hole. Even tho,gh the scri!t is not a-le to sh,t do/n the JB% or delete so*e files -eca,se of the Securit'6ana7er config,ration1 yo, co,ld still introd,ce a *alicio,s scri!t /hich co*!ro*ises the consistency of the -,siness logic.

6elated Patterns
!l id 9ogic is a He>ible .ervice 'ith easy-to-s'ap implementation. +t can be sed in the same conte>t as a .ervice.

424
Download at WoweBook.Com

Download at WoweBook.Com

Paginator and ,ast 3ane Reader


-*B 2.4 'as limited in terms o" persistence. +t 'as neither possible to iterate thro gh a large set o" entity bean instances$ nor to e>tract and ret rn only the interesting parts "rom the B ery res lt. 5he original !ast 9ane 6eader pattern 'as designed as a 'or#aro nd "or the shortcoming% NX.ometimes applications access data in a tab lar "ashion$ s ch as 'hen bro'sing a catalog or a list o" names or 'hen e>porting data in batches "or se else'here. 5his #ind o" data access is s ally read-only. +n s ch sit ations$ sing entity beans to represent persistent data inc rs overhead and provides little bene<t. -ntity beans are best "or coarse-grained access to individ al b siness entities$ and are not e""ective "or read-only access to large B antities o" tab lar data. N5he !ast 9ane 6eader design pattern provides a more e"<cient 'ay to access tab lar$ read-only data. A "ast lane reader component directly accesses persistent data sing *;BC components$ instead o" sing entity beans. 5he res lt is improved per"ormance and less coding$ beca se the component represents data in a "orm that is closer to ho' the data are sedX. O Lhttp%CC=ava.s n.comCbl eprintsCpatternsC!ast9ane6eader.htmM. *PA 4.0 solves already the initial problems o t-o"-the-bo>. +t provides a 'ay to e>tract only the interesting attrib tes "rom an entity and allo's pagination in a large amo nt o" res lts. 5he !ast 9ane 6eader pattern became a best practice in *ava -- "or some se cases$ rather than a 'or#aro nd "or a shortcoming o" the speci<cation.

Problem
5he *PA is not able to stream ob=ects$ rather than load the entire page into memory at once. !or some se cases s ch as e>ports$ batches$ or reports direct access to the database c rsor 'o ld provide better per"ormance.

!orces
=o, have to iterate over a large a*o,nt of data. +he data cannot -e loaded at once into the client and has to -e cached on the server. +he client is interested only on so*e attri-,tes of the entity. +he data is accessed *ostly in a read'only /ay.

.ol tion
5here is no single sol tion "or the problemS instead yo have di""erent strategies each 'ith its o'n reB irement. All the variations are reali?ed by a state" l or stateless session bean$ 'hich implements the iteration logic or e>poses the live ResultSet. 5he !ast 9ane 6eader pattern is a speciali?ed .ervice !a@ade or$ in more comple> applications$ a re sable .ervice.

Conventions
5he !ast 9ane 6eader pattern is a speci<c "orm o" a .ervice !a@ade or .erviceIthe corresponding conventions can be directly applied to this pattern.

6ethin#ing

Download at WoweBook.Com

5he )ntit'6ana7er already provides easy-to- se iteration logic. 5he classic Aal e 9ist )andler pattern is implemented by the )ntit'6ana7er and there"ore no longer reB ired. Also$ native .T9 B eries can be e>ec ted and mapped to either e>isting entities or ret rned as a list o" primitives. 5his eliminates the need "or ;A,s and ma#es the !ast 9ane 6eader implementation leaner.

Participants and 6esponsibilities


5he !ast 9ane 6eader pattern is sed directly by the application client. +n most cases the !ast 9ane 6eader operates directly on the )ntit'6ana7er. 5here is no need to access a ;A, or .ervice to get simpli<ed access to the persistenceI)ntit'6ana7er is already simple eno gh. 5he !ast 9ane 6eader pattern can be considered as a lean and standalone .ervice !a@ade$ 'hich is accessed locally by the application client.

.trategies
5he principle o" all strategies is e>actly the same% server-side iteration in a big collection o" persistent items. 5hose items do not have to be P;,sS some strategies 'or# 'ith 6es lt.et and so the database directly. Paginator and Bal,e 9ist Handler +" the res lts o" a B ery e>ceed a manageable amo nt o" entries$ it becomes hard to handle in the 7+. +nstead o" ret rning potentially h ndreds or tho sands o" records$ the entire res lt set is split into smaller ch n#s$ the pages. 5hey can be easily bo nd to 7+ models and directly handled by 7+ components. 5he classic java.util.<terator 'or#s similarlyIit traverses a java.util.Collection implementation and ret rns a single instance "or each iteration. A single instance is too <ne grained "or pagination p rposes$ b t it co ld be easily e>tended to an <terator.3ist.Customer00. A session bean can directly implement the java.util.<terator inter"ace as it b siness inter"ace. 5he classic (*;&) <terator is state" lIits implementation remembers the act al position in the collection. +t is more convenient and nat ral to implement the iteration in a state" l 'ay. 5he c rrent inde> co ld be maintained inside the state" l session bean and do not have to be passed bac# and "orth.
2State(ul public class Customer;uer'Bean implements 2terator<@ist<0ustomer>> # 2PersistenceContext private )ntit'6ana7er emprivate int in"ex D Rprivate int pa7eSi=e D URprivate boolean next D truepublic voi" setPa7eSi=e(int pa7eSi=e)# t+is.pa7eSi=e D pa7eSi=e$

428
Download at WoweBook.Com

public 3ist.Customer0 next()# 3ist.Customer0 ret?al D null;uer' quer' D t+is.em.createAame";uer'(Customer.A33)quer'.set&irstResult(7et&irst())quer'.set6axResults(pa7eSi=e)ret?al D quer'.7etResult3ist()i((ret?al.si=e()DDR)# t+is.next D (alse$ in"exHHreturn ret?al$ private int 7et&irst()# return in"ex C pa7eSi=e$ public boolean +asAext() # return t+is.next$ public voi" remove() # t+ro, ne, Unsupporte"Operation)xception(4Operation remove @4)$ 2Remove public voi" close()# t+is.em.clear()t+is.em.close()$ $

5he Paginator implements the java.util.<terator inter"aceS its ser is only interested in the iteration logic and can rely on the +teratorRs methods only. 5he -*B AP+ as 'ell as the e>istence o" a session bean implementing the inter"ace are totally hidden. 5he "ollo'ing e>ample the standalone nit test o" the pagination logic%
public class Customer;uer'Bean:est # private 0ustomer:uery#ean &uery; private Customer67rBean m7rprivate )ntit'6ana7er emprivate )ntit':ransaction et2Be(ore public voi" initiali=e() t+ro,s )xception # t+is.em D Persistence.create)ntit'6ana7er&actor'(4Pa7inator4).create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()-

422
Download at WoweBook.Com

t+is.quer' D ne, Customer;uer'Bean()t+is.quer'.em D t+is.emt+is.m7r D ne, Customer67rBean()t+is.m7r.em D t+is.emt+is.et.be7in()(or(int iDR-i.URR-iHH)# Customer customer D ne, Customer()customer.setAame(48u9eG 4 Hi)t+is.m7r.create(customer)$ t+is.et.commit()$ )4est public void ne=t() { ( ile(&uery. as'e=t()){ @ist<0ustomer> customers > &uery.ne=t(); System.out.println("SiFeD " G customers.siFe()); /or (0ustomer customer D customers) { System.out.println("0ustomerD " Gcustomer); } } } 2A(ter public voi" cleanUp()# t+is.et.be7in()t+is.m7r."eleteAll()t+is.et.commit()$ $

+n "act$ the only di""erence bet'een the classic +terator and the Paginator implementation is the page si?e. 5he <terator#next() invocation ret rns a list o" entities and not a single one. 5he client typically needs t'o nested loops to iterate over the 'hole res lt. 5he Paginator implementation as a =ava.util.<terator reB ires to be implemented as state" l session bean. 5he method next() e>tracts the c rrent e>cerpt "rom the list and moves the c rsor to the ne>t page. 5here are no parameters$ so it is not possible to pass the c rrent inde> "rom o tsideIit has to be remembered internally. 5he Paginator ses the )ntit'6ana7er 'ith the de"a lt PersistenceContext:'pe.:RAASAC:<OA type. 5here is no need to #eep the entities managedIthey become detached a"ter every iteration step. Changes to the entities are not reHected in the database. 5he behavior co ld be easily changed 'ith the PersistenceContext:'pe.)K:)A8)8 con<g ration. Eith this modi<cation yo co ld change the state o" the entities d ring the iterationIthe )ntit'6ana7er 'ill H sh the changes to the database at the end o" the transaction "or yo . +nstead o" storing the c rrent inde> (that is$ page n mber) inside the session bean$ yo co ld also pass it "rom o tside. !or this p rpose yo 'ill have to change the Paginator signat re to be able to pass the c rrent inde>Iand abstain "rom a direct java.util.<terator implementation.

42:
Download at WoweBook.Com

Page or Everything Pagination is a common reB irement in larger res lt lists. +t is very li#ely$ that yo 'ill be as#ed by yo r client to implement s ch a "eat re in a 'eb or rich +nternet application. Pagination in a large res lt set$ ho'ever$ is not ser "riendly and is rarely sed. 5he ser 'ill probably 'ant to see the most relevant res lts and then either re<ne the B ery or display a larger$ b t still limited$ amo nt o" entries at once. +" the ser is still not satis<ed 'ith the res lt$ let him or her rede<ne the B ery. 5he implementation o" the Page or -verything strategy is a simpli<ed "orm o" the classic Paginator implementation. Qo do not even have to implement the java.util.<terator. Qo only have to chec# 'hether the <rst page contains the entire res lt. +" not yo 'ill as# the ser to re-e>ec te the B ery and ret rn a still bo nded n mber o" ob=ects ("or e>ample$ the <rst tho sand) or re<ne the B ery. +" yo select one ob=ect more as reB ested$ yo get the chec# "or the e>istence o" additional pages almost "or "ree. 5he "ollo'ing code demonstrates a sample implementation o" the Page or -verything Paginator strategy.
2Stateless public class Customer;uer'Pa7eOr)ver't+in7Bean# 2PersistenceContext )ntit'6ana7er emprivate static int 6AKJPA>)JS<M) D URRRpublic 3ist.Customer0 7etAllCustomers(int maxResults)# i((maxResults DD /U ZZ maxResults 0 6AKJPA>)JS<M)) maxResults D 6AKJPA>)JS<M)else maxResults HDU;uer' quer' D t+is.em.createAame";uer'(Customer.A33)quer'.set6axResults(maxResults)return quer'.7etResult3ist()$ $

5he Page or -verything Paginator is implemented as a stateless session beanIthere is no need to maintain the c rrent inde> or cache ob=ects internally. 5he ser o" this modi<ed Paginator version$ ho'ever$ 'ill have to do a little more 'or# and chec# 'hether the ret rn val e is larger as reB ested to indicate the e>istence o" " rther pages%
2:est public voi" 7etAllCustomers() # int pa7eSi=e D X3ist.Customer0 all D t+is.quer'.7etAllCustomers(pa7eSi=e)assertAotAull(all)assert)quals(pa7eSi=eHU1all.si=e())$

+a-le Bie/

420
Download at WoweBook.Com

.ometimes it is reB ired to provide an e"<cient 'ay to iterate over an e>cerpt or even a set o" related entities b t ret rn a di""erent vie' to the client. 5his can be achieved by "etching the entities 'ith )ntit'6ana7er and trans"orming them inside a .ervice or Paginator. 5his approach is neither "ast$ nor easy to maintain. -specially the merging and e>traction o" entity data is error-prone and can become B ite comple>. Another possibility is the e>ec tion o" more comple> native .T9 statements and mapping them into e>isting entities or 5,s. 5he B ery co ld become comple> and the <lter criteria highly repetitive. Qo 'ill need the <lter in all related B eries that ret rn the partic lar s bset. -specially in the conte>t o" pagination$ 'here the data is mostly retrieved "or read-only p rposes$ database vie's are the easier and more e"<cient alternative. +nstead o" implementing a lot o" pl mbing on the *ava side all the 'or# co ld be easily done in the database. Qo only have to create a .T9 vie'Iit is a part o" the .T9 standard and is even s pported by the ;erby ;B shipped 'ith *ava as stated in the Apache ;erby 40.0 doc mentation. CR)A:) ?<)! APP.?JCUS:O6)R(AA6)1C<:B) AS S)3)C: AA6)1C<:B &RO6 APP.CUS:O6)R !or .T9 B eries there is no di""erence bet'een vie's and tables$ so yo can easily map a *PA entity to a vie' transparently. 5he code on the *ava side remains clean and simple$ and yo 'ill even get better per"ormance. 5here is a dra'bac#% not all vie's can be pdated. Ehether a vie' is pdatable highly depends on the comple>ity and partic lar database. !or e>ample$ in the ;erby ;B all vie's are not pdatable. 5his strategy is not only applicable to the di""erent Paginator strategies$ b t can be applied to all *PA entity in general. 5his provides additional He>ibility and ma#es database re"actorings easier. 9ive #,rsor and 0ast 9ane Reader All described strategies so "ar 'ere disconnected "rom the database. Altho gh the entities remain attached to the )ntit'6ana7er$ the entire page is loaded at once into the level one cache (that is$ identity as+6ap or transactional cache). +" yo are only e>porting data$ or 'ant to "etch a b nch o" primitives "rom the database as "ast as possible$ even the conversion o" *;BC types into ob=ects co ld become too m ch overhead. Eith -*B 3 yo can s rpass the )ntit'6ana7er and get access to its java.sql.Connection directly. 5he 8ataSource can be as easily in=ected as the )ntit'6ana7er. 5he 8ataSource and )ntit'6ana7er 'o ld even share the same java.sql.Connection instance$ i" yo are accessing them in the same transaction. Qo 'ill see all the changes already sent to the database "rom both reso rces. 5he application server$ ho'ever$ 'ill commit or roll bac# the (single) connection at the end o" the (*5A) transaction. 5he "ollo'ing !ast9ane6eader implementation demonstrates direct$ transactional access to the 8ataSource "rom a session bean%
2Stateless public class Customer&ast3aneRea"erBean # 2Resource(nameD4j"bc%sample4)

421
Download at WoweBook.Com

8ataSource "spublic 3ist.Strin70 7etCustomerAames()# 3ist.Strin70 allAames D ne, Arra'3ist.Strin70()Connection con D nullStatement stmt D nullResultSet resultSet D nulltr' # con D "s.7etConnection()stmt D con.createStatement()resultSet D stmt.execute;uer'(4select name (rom CUS:O6)R4),+ile (resultSet.next()) # Strin7 name D resultSet.7etStrin7(4name4)allAames.a""(name)$ return allAames$ catc+ (S;3)xception ex) # t+ro, ne, Runtime)xception(4Cannot per(orm quer'G 4 Hex1ex)$(inall'# tr' # resultSet.close()stmt.close()con.close()$ catc+ (S;3)xception ex) # %%cannot +an"le $ $ $ $

+n prod ction B ality code yo sho ld se Prepare"Statements instead o" e>ec ting B eries directly each time. Prepare"Statements not only "aster$ b t also more rob st. 5hey 'ill be constr cted once and re sed several times. 5he syntactical correctness o" the Prepare"Statement 'ill be already validated at the constr ction time and not at r ntime <rst. As mentioned earlier$ yo are iterating over the data in the database 'itho t converting the ro's into ob=ects. 5his saves time and reso rces and is especially interesting "or high-vol me$ dataoriented tas#s s ch as the creation o" reports$ e>ports$ or trans"ormations. +" yo do not need ob=ects to reali?e table or dataset-oriented logicIdirect access to the database co ld be even easier to implement. +n general$ direct *;BC sage is an e>ception rather than the r le. +t res lts in a lot o" code and is error-prone and hard to maintain. +" yo are a .T9 e>pert and yo #no' 'hat yo are doing$ yo co ld even achieve better per"ormance as 'ith *PA. ,n the other hand$ 'or#ing directly 'ith )ntit'6ana7er is "ast eno gh "or most se cases$ lean$ and easy to maintain.

5esting

429
Download at WoweBook.Com

Paginator tests are identical to ;A,$ .ervice !a@ade or .ervice tests. 5he logic o" each variant is easily nit testable. +ts especially recommended to test the iteration logic intensivelyIeven small errors can be hard to <nd d ring integration tests. .ome Paginator strategies are state" l$ so they sho ld be load and stress tested "or potential bottlenec#s$ memory lea#s$ and scalability iss es.

;oc mentation
!rom an architect ral point o" vie'$ a Paginator is a speci<c .ervice !a@ade. +t can be doc mented as s ch$ sing the ..Service&a]a"e00 stereotype or the ..Pa7inator00 stereotype depending on 'hether the iteration is an e>ception or a common approach in yo r pro=ect. +t sho ld be doc mented once ("or e>ample$ in a 'i#i) 'hich strategy is sed$ 'ith pro=ect-speci<c reB irements. A"ter doing so$ there is no " rther need to repeat the intentions and mechanics o" a Paginator in *ava;oc. +t is eno gh to re"erence the 'i#i entry or other another pragmatically 'ritten doc ment.

ConseB ences
Performance: &n general1 the !erfor*ance is -etter /hen ,sing the Paginator instead of ret,rning a h,ge res,lt set at once. =o, can achieve the -est !erfor*ance /ith the 0ast 9ane Reader !attern. )ca abi ity: Statef,l Paginator i*!le*entations have to *aintain state1 /hich has to -e re!licated to other cl,ster nodes. +his co,ld -eco*e a -ottleneck Iit is highly de!endent on the !artic,lar a!!lication server i*!le*entation and has to -e verified /ith load tests. 2obustness: Paginator ret,rns ch,nks of a !otentially h,ge res,lt set to its clients and !revents the* to r,n o,t of *e*ory. Consistency: %ost Paginator strategies cache at least the c,rrent !age. Even the entities re*ain attached7 they are not a,to*atically refreshed fro* the data-ase. +he c,rrent !age co,ld -eco*e stale .,st after fetching. Paginator sho,ld al/ays -e ,sed /ith o!ti*istic lockingIe6ce!t in the case of read'only i*!le*entations. Testabi ity: Paginator has no de!endencies to the a!!lication server or Java EE AP&s1 and th,s is /ell's,ited to ,nit testing. Portabi ity: Paginator is !orta-le across a!!lication servers. 0ast 9ane Reader is the only strategy /hich ,ses native SD9 directly and *ay -eco*e de!endent on the !artic,lar data-ase.

6elated Patterns
Paginator ses the )ntit'6ana7er. +n rare cases$ it co ld rely on an e>isting .ervice or ;A, implementation. Paginator is sed directly by its clients$ "or e>ample$ bac#ing beans$ 6-.5! l services$ .ervlets or Eic#et pages.

430
Download at WoweBook.Com

Retired Patterns
.ome o" the pop lar best practices in the *2-- no longer apply to *ava -- 2. .ome o" them became an anti-pattern. 5he patterns listed in this section are retired in mainstream *ava -- 2 applications$ b t co ld still be interesting "or special p rposes or d ring migration "rom *2-- to *ava -- 2.

.ervice 9ocator
,riginal +ntention
5he .ervice 9ocator 'as a mandatory pattern in *2--. All registered reso rces and components had to be located <rst% N.ervice loo# p and creation involves comple> inter"aces and net'or# operations. L...M N7se a .ervice 9ocator ob=ect to abstract all */;+ sage and to hide the comple>ities o" initial conte>t creation$ -*B home ob=ect loo# p$ and -*B ob=ect re-creation. ( ltiple clients can re se the .ervice 9ocator ob=ect to red ce code comple>ity$ provide a single point o" control$ and improve per"ormance by providing a caching "acilityO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC.ervice9ocator.htmlM.

6easons "or 6etirement


"e!endency &n.ection is availa-le in *ost Java EE co*!onents. J)"& look,!s are no longer re8,ired to access other session -eans or reso,rces. +he creation of a ho*e interface -eca*e o!tional1 and therefore the creation of re*ote and local interfaces6 PortableRemoteObject.narro, is o!tional in EJB 3.$Athe session -ean can -e accessed /ith si*!le Context#loo9up. +he co*!le6ity of the infrastr,ct,ral code /as greatly red,ced -y the EJB 3.$ s!ecification. A Service 9ocator /o,ld not f,rther red,ce the co*!le6ity of the code7 on the contrary1 it /o,ld increase it. =o, sho,ld ,se "e!endency &n.ection /henever !ossi-le and only in e6ce!tional cases a generic Service 9ocator i*!le*entation. 0or the e6ce!tional cases a s!eciali5ed Service 9ocator for*1 the Bean9ocator1 can -e ,sed.

Composite -ntity
,riginal +ntention
+n C(P 4.0 even relations bet'een persistent entities had to be implemented man ally. 5his 'as <>ed in C(P 4.4 'ith the introd ction o" local inter"aces$ b t 'asnRt really transparent. ! rthermore$ C(P 4.0 'ere remote visible$ so that the gran larity o" the Composite -ntities 'as o" big concern as 'ell% N-ntity beans are not intended to represent every persistent ob=ect in the ob=ect model. -ntity beans are better s ited "or coarse-grained persistent b siness ob=ects. L...M

Download at WoweBook.Com

N7se Composite -ntity to model$ represent$ and manage a set o" interrelated persistent ob=ects rather than representing them as individ al <ne-grained entity beans. A Composite -ntity bean represents a graph o" ob=ectsO L'''.core=2eepatterns.comCPatterns2nd-dCComposite-ntity.htmM.

6easons "or 6etirement


#%P 2. !ersistence didn:t s,!!ort relationshi!s very /ell. 0,rther*ore1 #%P entities ca*e /ith ho*e interfaces /hich had to -e ,sed in a si*ilar fashion as )ntit'6ana7er. With the advent of JPA1 all this overhead /as gone. &*!le*entation of relationshi!s -eca*e nat,ral. JPA entities are .,st do*ain o-.ects1 /hich are !ersistent. =o, can a!!ly /hatever !atterns yo, /ant /itho,t any overhead. JPA are o-.ect oriented !er defa,lt. +he #o*!osite Entity !attern in Java EE -eca*e degraded to a ,s,al 2o0 #o*!osite.

Aal e ,b=ect Assembler


,riginal +ntention
+n *2-- the access to persistent storage 'as associated 'ith a h ge ceremony. !etching some entities "rom a database 'asnRt an easy tas#. 5he Aal e ,b=ect Assembler 'as a dedicated pattern to merge$ trans"orm or e>tract data "rom di""erent data so rces% N+n a *ava 2 Plat"orm$ -nterprise -dition (*2--) application$ the server-side b siness components are implemented sing session beans$ entity beans$ ;A,s$ and so "orth. Application clients "reB ently need to access data that is composed "rom m ltiple ob=ects. L...M N7se a 5rans"er ,b=ect Assembler to b ild the reB ired model or s bmodel. 5he 5rans"er ,b=ect Assembler ses 5rans"er ,b=ects to retrieve data "rom vario s b siness ob=ects and other ob=ects that de<ne the model or part o" the modelO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC5rans"er,b=ectAssembler.htmlM.

6easons "or 6etirement


Even the )ntit'6ana7er i*!le*ents a !art of the origin intention of the Bal,e (-.ect Asse*-lerH it is a-le to ret,rn a s,-*odel fro* a gra!h of interconnected entities. #reation of s,-*odels and conversion of attached entities into +ransfer (-.ects is a res!onsi-ility of the Service 0a@ade or Service. +here is no need to introd,ce a s!ecific co*!onent or !attern to i*!le*ent the conversion. &n the *a.ority of all ,se cases1 yo, co,ld even get rid of ,sing dedicated +ransfer (-.ects and !ass detached and even attached entities -et/een layers or tiers.

B siness ;elegate

432
Download at WoweBook.Com

,riginal +ntention
*2-- clients 'ere directly e>posed to the *2-- AP+ (-*B$ *(.) and comple>ity (Remote)xception$ Create)xception and more comple> loo# ps). 5his "act 'as reHected in the origin intention% NA m lti-tiered$ distrib ted system reB ires remote method invocations to send and receive data across tiers. Clients are e>posed to the comple>ity o" dealing 'ith distrib ted components. L...M N7se a B siness ;elegate to red ce co pling bet'een presentation-tier clients and b siness services. 5he B siness ;elegate hides the nderlying implementation details o" the b siness service$ s ch as loo# p and access details o" the -*B architect reO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsCB siness;elegate.htmlM.

6easons "or 6etirement


+he *a.ority of all EJB 2. e6ce!tions /ere checked. +he EJB client had to catch1 or at least kno/1 the e6ce!tions and -eca*e !oll,ted /ith the EJB 2. AP&. +he se!aration -et/een -,siness logic and infrastr,ct,ral code /as not given. B,siness "elegate fi6ed this iss,e. With EJB 3.$ all checked e6ce!tions are o!tionalAthe -,siness interface is identical to the e6ternal B,siness "elegate interface. B,siness "elegate ,sed Service 9ocator to fetch the ho*e interface and created the local or re*ote interface internally. EJB'related e6ce!tions /ere converted to ne,tral syste* e6ce!tions. &n EJB 3.$1 ho*e interfaces -eca*e o!tional7 the -,siness interfaces can -e fetched directly fro* J)"&. B,siness "elegates /ere ,sed to deco,!le the -,siness logic fro* the !resentation as /ell. +his is no longer necessary1 -eca,se -,siness interfaces can -e directly in.ected into *ost of the !resentation co*!onents.

;omain .tore
,riginal +ntention
C(P *2-- 'asnRt transparent and ca sed lots o" pl mbing. 5he ;omain .tore pattern 'as designed to <> this problem% N7se a ;omain .tore to transparently persist an ob=ect model. 7nli#e *2--Rs containermanaged persistence and bean-managed persistence$ 'hich incl de persistence s pport code in the ob=ect model$ ;omain .toreRs persistence mechanism is separate "rom the ob=ect modelO L'''.core=2eepatterns.comCPatterns2nd-dC;omain.tore.htmM.

6easons "or 6etirement


)ntit'6ana7er can be considered as a standardi?ed implementation o" the ;omain .tore pattern. +t is the ;omain .tore pattern.

433
Download at WoweBook.Com

Aal e 9ist )andler


,riginal +ntention
C(P didnRt provided any semantics "or data iteration or detachment. 5he Aal e 9ist )andler pattern 'as introd ced to <> this limitation% N7se a Aal e 9ist )andler to control the search$ cache the res lts$ and provide the res lts to the client in a res lt set 'hose si?e and traversal meets the clientRs reB irementsO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsCAal e9ist)andler.htmlM.

6easons "or 6etirement


#%P 2. co,ld not -e detached. Bal,e 9ist Handler /as res!onsi-le for the conversion of #%P instances into +ransfer (-.ects. Since the introd,ction of JPA the entities can -e easily detached /itho,t additional effort. +he i*!le*entation of the Bal,e 9ist Handler is rather trivial. &t is the i*!le*entation of the classic &terator !attern. Bal,e 9ist Handler -eca*e a strategy of the Paginator !attern.

438
Download at WoweBook.Com

7
Rethinking the &ntegration +ier
.ystem integrators 'or#ing on *ava -- pro=ects have to deal 'ith lots o" legacy and incompatible code. 7n"ort nately the chances to start a totally green <eld pro=ect in the enterprise are e>tremely lo'. +n addition to -nterprise +n"ormation .ystems (-+.) and 9egacy )osts$ system integrators are con"ronted 'ith *2-- applications$ ./-5 applications$ and Eeb 2.0 logic available thro gh 6-.5 or scripting. 5he reali?ation o" the integration logic ma#es the di""erence bet'een *ava -- and *2--. +n *2--$ the integration logic is mainly "actory and P,*, based. +n *ava -- 2 and : all the "actories and in"rastr ct ral code can be replaced 'ith p re -*B 3 components. 5he patterns are more pragmatic and practical. 5he dream o" totally deco pled tiers and implementation independence is no more the driving "orce. 5he e>perience sho's that the integration tier o" an already deployed system does not change too "reB ently. +n other 'ords$ there is no need to provide an (o"ten lea#y) abstraction "or possible " t re changes. ->isting services are in general only abstracted 'ith a lean adaptation layer and are not entirely encaps lated. 5his allo's "or a more nat ral and e"<cient interaction bet'een the b siness and the integration layers and lo'ers the development costs. 5he components o" the integration layer can be in=ected into the services o" the b siness tier$ sometimes even e>posed directly to the presentation components. +t mainly depends on the comple>ity o" yo r application. 5he bo ndary bet'een the integration and b siness layers begins to bl r as 'ell. 5he ;ata Access ,b=ect (;A,) and 5rans"er ,b=ect (5,) patterns can be classi<ed as belonging to either layer. 5he responsibility o" the ;A, has a slightly more integrational character. 5he same is tr e "or a 5,. A 5, is o"ten sed in the b siness tier to implement client-speci<c vie's or pro=ections o" domain ob=ects. +n most cases$ ho'ever$ a 5, is introd ced to map incompatible data so rces s ch as Eeb.ervices$ K(9 so rces$ stored proced res$ or even native code to easier manageable *ava classes. 5his chapter disc sses integration approaches "or problematic or even *ava -- incompatible reso rces. Beyond the disc ssion o" plain reso rce integration$ + 'ill also e>plain the integration o" legacy *2-components.

Download at WoweBook.Com

Download at WoweBook.Com

Data Access 046ect


5he original conte>t o" a ;ata Access ,b=ect (;A,) is de<ned in the Core *2-- pattern catalog% NAccess to data varies depending on the so rce o" the data. Access to persistent storage$ s ch as to a database$ varies greatly depending on the type o" storage (relational databases$ ob=ectoriented databases$ Hat <les$ and so "orth) and the vendor implementationO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC;ataAccess,b=ect.htmlM. 5he motivation "or this pattern 'as the deco pling o" the b siness logic "rom the concrete reali?ation o" the data store mechanisms. 5his is no longer the main motivation "or the ma=ority o" c rrent applications.

Problem
5he real problem o" this pattern is its over se. 5he idea o" deco pling "rom the database$ and even its vendor$ is neither realistic nor$ in most cases$ necessary. +n enterprise applications a partic lar type o" database is rarely replaced 'ith another one. An application that ses a .T9 database 'ill hardly ever be ported to another storage type s ch as 9;AP$ ob=ect databases$ or even Hat <les. 9oo#ing bac# to past pro=ects$ even s'itching database vendors has happened only in rare cases. C stomers tend to stic# 'ith one relational database vendor "or the li"e cycle o" their applications. ;atabases tend to live longer than an application. ;eco pling "rom a database seems to be a strange strategy$ considering the average database li"etime$ it 'o ld be more appropriate to 'orry abo t the co pling bet'een the database and the application and not vice versa. An introd ction o" another layer o" abstraction or encaps lation ca ses additional development and maintenance e""ort. A complete abstraction o" the nderlying data store is only possible "or simplistic se cases and there"ore lea#y. 5hese days$ it is hard to = sti"y the ;A, pattern 'ith the original intention. *2-- had another problem% the ins "<cient po'er o" C(P 2.0. 5he standard persistence mechanism 'as not po'er" l eno gh "or sophisticated se cases. 5he limited -*B-T9 B ery capabilities$ no access to native .T9$ and the lac# o" dynamic B eries "orced the developers to access the database sing plain *;BC. +t 'as a good idea to encaps late database access behind a replaceable and moc#able implementation. (ost o" the C(P 2." applications today are hybrids o" C(P 2." and the ;A, pattern. ;A,s 'ere sed "or sophisticated B eries and the C(P 2." "or pdates o" b siness ob=ects. /onetheless$ enterprise applications still need to encaps late legacy reso rces. 5his reB irement$ ho'ever$ is an e>ception rather than the r le. *PA 4.0 introd ced the )ntit'6ana7er inter"ace$ a per"ect ;A, implementation that hides not only the *PA providers$ b t even translates abstract *PA B eries into database-speci<c .T9 B eries.

!orces
=o, have to access a legacy (that is1 JPA inco*!ati-le) data so,rce or reso,rce. =o, have to kee! the data access a-straction testa-le and *ocka-le. =o, /ant to deco,!le the !ro!rietary i*!le*entation of the reso,rce access fro* the rest of the a!!lication.

Download at WoweBook.Com

=o,r a!!lication is service orientedH the -,siness logic and the data access are se!arated. =o, have to deal /ith non'standard1 legacy data so,rces. =o,r 8,eries are too co*!le67 yo, /ant to *aintain the* in a dedicated !lace.

.ol tion
7se a stateless session bean 'ith a dedicated$ local b siness inter"ace to abstract and encaps late the interactions 'ith the data store. A no-inter"ace vie' session bean can be sed as 'ellS the reali?ation$ ho'ever$ is harder to replace then. 5he additional 23ocal inter"ace allo's easy replacement o" the bean implementation and th s provides additional He>ibility. A b siness inter"ace simpli<es the testing o" the ;A, o tside o" the container. A ;A, pattern is red ced in a *ava -- 2 environment to an inter"ace and a class$ 'ith some -*B-speci<c annotations. 5he session bean is not only responsible "or accessing and trans"orming the data$ b t "or reso rce and connection handling as 'ell. 5he needed reso rces ("or e>ample$ javax.persistence.)ntit'6ana7er or javax.sql.8ataSource) sho ld pre"erably be in=ectedS it drastically red ces the amo nt o" code. 5he container ta#es care abo t conc rrency$ reso rce management$ and transaction enlistment o" the in=ected reso rces. 6eso rce-speci<c details s ch as the name o" a stored proced re or the inCo t parameters have to be " lly encaps lated and not e>posed to the clients. 5he introd ction o" an additional "actory is not needed. +t 'o ld only increase the comple>ity and amo nt o" in"rastr ct ral code. 5he local vie' o" this bean can easily be in=ected to other services 'ith standard mechanisms$Ino c stom in"rastr ct re is reB ired. 5he ;A, .ession Bean is annotated 'ith 2:ransactionAttribute( :ransactionAttribute:'pe.6AA8A:ORB)$ so all ;A, methods can be invo#ed only in an already e>isting transaction. 5he transaction is going to be started by services that se the ;A, to access the persistence. Beca se the main goal o" the ;A, is the strict separation o" persistence details and b siness logic$ a ;A, has to be invo#ed "rom a b siness logic component and not directly "rom the presentation. An attempt to invo#e a ;A, directly "rom the presentation tier is the <rst indication that it is probably s perH o s. A .ervice$ or even .ervice !a@ade$ 'o ld probably do a better =ob in this case.

6ethin#ing
+n an -*B 3C*ava -- 2 environment yo donRt have to se the lo'-level *;BC to access the database any more. Qo can se the generic$ yet po'er" l *PA B ery lang age as 'ell as native .T9 to "etch not only the persistent ob=ects$ b t also ;ata 5rans"er ,b=ects and even primitive data types "rom the database. +t is even possible to e>ec te pdate and delete statements 'itho t sing the lo'-level *;BC AP+. 5he *PA comes 'ith the )ntit'6ana7er$ 'hich provides generic data access " nctionality. Access co ldnRt be simpler. 5he )ntit'6ana7er can be directly in=ected to any .ession Bean%
2Stateless 2:ransactionAttribute(:ransactionAttribute:'pe.6AA8A:ORB) public class Boo9ServiceBean implements Boo9Service # )6ersistence0onte=t

431
Download at WoweBook.Com

private ,ntity7ana+er em;

5he )ntit'6ana7er is already an inter"aceS its reali?ation belongs to the *PA .ervice Provider +nter"ace (.P+) and can be declaratively s'apped 'itho t changing the code%
.persistence @ .persistence/unit nameD4boo94 transaction/t'peD4*:A40 .provi"er0or7.eclipse.persistence.jpa.PersistenceProvi"er.%provi"er0 @

)ntit'6ana7er methods are very similar to the classical ;A, implementations (C67;)$ e>cept "or the e>tensive se o" *ava 2 .generics (http%CC=ava.s n.comC=2seC4.2.0CdocsCg ideClang ageCgenerics.html) (*ava 2 .- and so generics 'ere not available at the *2-- time). 5he )ntit'6ana7er is already an abstraction and encaps lation$ so I" rther deco pling is not necessary and 'o ld be even co nterprod ctive. 5he abstraction "rom the service provider is lea#y$ as every other abstraction$ b t the sit ation 'ill de<nitely not improve 'ith an additional layer o" indirection. 5he )ntit'6ana7er can be considered as a generic implementation o" the ;A, pattern. +t can be sed as a ;A, and be in=ected to e>isting services. )eavy se o" *PA B ery lang age$ ho'ever$ 'o ld bl r the e>pressiveness o" the b siness logic. 5he creation o" B eries can be easily "actored o t into dedicated B ery b ildersIor tility classes. 5he services co ld inherit the B ery logic "rom an abstract class as 'ell. +n *ava --$ the ;A, pattern is optional and no longer the only 'ay to access the data store. )ntit'6ana7er as an abstraction is s "<cient "or most in-ho se so"t'are pro=ects. +n prod ct development$ ho'ever$ a dedicated ;A, as an additional layer o" abstraction co ld be necessary. /onetheless$ the introd ction o" s ch a layer 'itho t clear reB irement is al'ays s spicions and sho ld be = sti<ed 'ith hard reB irements. +n short$ in *ava -- :$ a dedicated ;A, is an e>ception rather than the r le. 5he ;A, can o"ten be replaced 'ith an )ntit'6ana7er in=ected into a .ervice.

Conventions
5he concrete implementation o" the Cru"Service inter"ace is going to be in=ected into the client ("or e>ample$ a .ervice) by the container. 5he ;+ made the ;A, "actory s perH o s. All ;A, strategies are only comprised o" a b siness inter"ace and its bean implementation (a session bean). 5his str ct re is valid "or all ;A, strategies and variations. ! rther simpli<cation 'ith a no-inter"ace session bean is not s itable. A direct in=ection o" the ;A, implementation ma#es testing o tside the container harder and replacement o" the implementation nearly impossible. !ig re 4 ill strates the str ct re o" the ;A, pattern.

439
Download at WoweBook.Com

Figure 1. The Structure of the !%" pattern A generic ;A, is deployed once and re sed "rom vario s components. 5here"ore it sho ld be placed in a generic pac#age$ "or e>ample% @NapplicationJnameO.inte7ration."ataservices ;omain-speci<c ;A,s sho ld reside in the related b siness component$ "or e>ample% NapplicationJnameO.boo9."ataservices or shorter% NapplicationJnameO.boo9."s

Participants and 6esponsibilities


C ient: +he "A( client is generally i*!le*ented as a (stateless or statef,l) session -ean that accesses the "A( f,nctionality. &t ,ses the "A( to get convenient access to the data store. +he client ,ses the "A( in the conte6t of its -,siness logic reali5ation1 so the "A( is al/ays invoked in the conte6t of an active transaction. +he "A( is in.ected into the client -y the container. +he #lient is inde!endent of the s!ecific reali5ation of the data store access. ,*8: A "A( is i*!le*ented as a stateless session -ean and res!onsi-le for enca!s,lation of !ro!rietary AP&s and technologies. +his incl,des the transfor*ation of !ro!rietary e6ce!tionsAeven chained ones. A "A( !rovides convenient1 high'level access to the data store. &t raises the level of a-straction. 0or the sake of convenience and deco,!ling1 the *ain res!onsi-ility of a "A( is reso,rce *anage*ent and conversion -et/een technology's!ecific data re!resentation1 into higher'level do*ain o-.ects. Access to standard Java EE reso,rces and their *anage*ent is greatly si*!lified -y the container1 in case a session -ean is ,sed for the i*!le*entation. &n case JPA is ,sed as data store1 the )ntit'6ana7er takes the res!onsi-ility of the data conversion1 connection handling1 and transaction enlist*ent. ,ata )tore: "ata Store is a f,lly integrated (like JPA)1 standardi5ed (like J"B#1 J#A)1 or !ro!rietary reso,rce that has to -e accessed for data access. JPA access co*es already /ith Java EEAadditional enca!s,lation is rarely needed. &t is al/ays a good idea1

480
Download at WoweBook.Com

ho/ever1 to ,se "A(s to enca!s,late !ro!rietary data access and deco,!le the do*ain logic fro* !ro!rietary technology.

.trategies
All the strategies aim "or the same goal% simpli<cation o" data access and pragmatic deco pling "rom the concrete data store. ;ependent on the pro=ect-speci<c needs$ this generic reB irement can be met by di""erent implementations e"<ciently. 2eneric "A( 5he signat re o" the )ntit'6ana7er methods is already generic. 5he res lt methods o" the javax.persistence.;uer' cannot be type-sa"e$ beca se they have to materiali?e an ob=ect "rom a given ro' set o" n#no'n type. 5hese methods ret rn a single ob=ect or a java.util.3ist o" ob=ects$ respectively. 5he ser o" the ;uer' class 'ill have to cast the res lt to a partic lar *PA entity any'ay. 5he ;A, implementation ret rns only the ra' list o" ob=ects$Icasting remains the responsibility o" the client. !or all other methods the ret rn type is in"erred "rom the parameter 'here possible. 5his ma#es the sage o" the generic ;A, implementation more convenient. 5he Cru"Service inter"ace is not poll ted 'ith the -*B AP+Iit is = st a clean plain old *ava inter"ace (P,*+). +t contains not only the s al s spects (s ch as the create$ (in"$ up"ate$ and "elete methods)$ b t some <nders as 'ell. 5he "ollo'ing snippet sho's the inter"ace o" a generic ;A,%
public inter(ace Cru"Service # .:0 : create(: t).:0 : (in"(Object i"1Class.:0 t'pe).:0 : up"ate(: t)voi" "elete(Object t)3ist (in"B'Aame";uer'(Strin7 quer'Aame)3ist (in"B'Aame";uer'(Strin7 quer'Aame1int result3imit)3ist (in"B'Aame";uer'(Strin7 name";uer'Aame1 6ap.Strin71Object0 parameters)3ist (in"B'Aame";uer'(Strin7 name";uer'Aame1 6ap.Strin71Object0 parameters1int result3imit)$

+nterestingly$ the create and up"ate methods are not voi"$ b t have the same ret rn type as their parameter. 5he reason "or that is a possible modi<cation o" the *PA entity by the container. 5he create method co ld delegate the comp tation o"$ the technical$ a to-incremented #ey to the )ntit'6ana7er. 5he same is tr e "or the up"ate method$ 'here the 2?ersion <eld o" a P;, may be changed in case optimistic conc rrency is sed. 5he comp ted id is needed to <nd the created entity later. +n case yo are 'or#ing 'ith b siness #eys or 77+;s only$ yo co ld change the ret rn val e o" the create method to voi". 5he pdated domain entity 'ith the "resh 2?ersion has to be ret rned to the presentation layer and sed "or s bseB ent interactions 'ith the )ntit'6ana7er$ other'ise any " rther attempt to pdate the entity 'ill "ail 'ith javax.persistence.Optimistic3oc9)xception. 5he implementation o" the inter"ace is a stateless$ local session bean 'ith 6AA8A:ORB transaction setting. 5he ;A, e>pects to be invo#ed in a conte>t o" already active transaction. 5he

484
Download at WoweBook.Com

Cru"Service inter"ace is e>posed 'ith the 23ocal annotation$ this approach ens res its independence "rom the -*B AP+. 5he implementation o" the method create isnRt obvio s at the <rst glance. 5he passed entity is persisted <rst$ then the (lus+ method is invo#ed. 5his "orces the )ntit'6ana7er to H sh its cache to the database. 5he state o" the cached entities 'ill be 'ritten to the database 'ith one or more <AS)R: statementsIb t not committed yet. -ither the database or the )ntit'6ana7er 'ill have to comp te any technical primary #ey no'. A"ter the H sh invocation$ the entity is going to be re"reshed. 5he state o" the entity is over'ritten 'ith the state in the database. !inally$ the "resh entity is ret rned to the caller. 5his strange behavior is sometimes reB ired to "orce the *PA provider to pdate the technical #ey in the entity instance. 5he persist$ (lus+$ and re(res+ seB ence " rther en"orces the pdate o" the 2<" comp ted in the database. +t is not bac#ed by the spec$ b t it 'or#s 'ith the pop lar providers. 5he "ollo'ing e>ample sho's a generic ;A, bean implementation%
2Stateless 23ocal(Cru"Service.class) 2:ransactionAttribute(:ransactionAttribute:'pe.6AA8A:ORB) public class Cru"ServiceBean implements Cru"Service # 2PersistenceContext )ntit'6ana7er empublic .:0 : create(: t) # t+is.em.persist(t)t+is.em.(lus+()t+is.em.re(res+(t)return t$ 2Suppress!arnin7s(4unc+ec9e"4) public .:0 : (in"(Object i"1 Class.:0 t'pe) # return (:) t+is.em.(in"(t'pe1 i")$ public voi" "elete(Object t) # Object re( D t+is.em.7etRe(erence(t.7etClass()1 t)t+is.em.remove(re()$ public .:0 : up"ate(: t) # return (:)t+is.em.mer7e(t)$ public 3ist.Object0 (in"B'Aame";uer'(Strin7 name";uer'Aame)# return t+is.em.createAame";uer'(name";uer'Aame).7etResult3ist()$ public 3ist.Object0 (in"B'Aame";uer'(Strin7 name";uer'Aame1 6ap.Strin71Object0 parameters)# return (in"B'Aame";uer'(name";uer'Aame1 parameters1 R)$

482
Download at WoweBook.Com

public 3ist.Object0 (in"B'Aame";uer'(Strin7 quer'Aame1 int result3imit) # return t+is.em.createAame";uer'(quer'Aame). set6axResults(result3imit). 7etResult3ist()$ public 3ist.Object0 (in"B'Aame";uer'(Strin7 name";uer'Aame1 6ap.Strin71Object0 parameters1int result3imit)# Set.)ntr'.Strin71 Object00 ra,Parameters D parameters.entr'Set();uer' quer' D t+is.em.createAame";uer'(name";uer'Aame)i((result3imit 0 R) quer'.set6axResults(result3imit)(or ()ntr'.Strin71 Object0 entr' G ra,Parameters) # quer'.setParameter(entr'.7etYe'()1 entr'.7et?alue())$ return quer'.7etResult3ist()$ $

5he implementation o" the "elete method seems to be strange at <rst glance. Be"ore the entity is going to be removed$ a re"erence to it is "etched "rom the )ntit'6ana7er. 5his is reB ired by the specIonly managed entities can be removed. ,btaining an entity 'ith the )ntit'6ana7er#7etRe(erence method is a "aster and lighter variant. Qo co ld also merge or <nd the entity be"ore removing. Both approaches are only reB ired "or detached entities. +" yo r entity is already managed$ yo can remove it. (erging be"ore removing is reB ired "or chec#s o" the 2?ersion <eld. ,nly pto-date entities can be removed. 5he attempt to delete a stale entity 'ill "ail 'ith javax.persistence.Optimistic3oc9)xception. 7p to this point$ +Rve described ;A, methods that are delegates on steroids. 5hey are only 'rappers o" e>isting )ntit'6ana7er " nctionality. 5he implementation o" the B ery " nctionality is more challenging. + concentrate on Aame";ueries only. 5hey are good eno gh "or most scenariosS *PA T9 in=ection can be avoided and the per"ormance is better 'hen compared to dynamic B eries. 5he ;A, implementation co ld easily be e>tended to s pport any$ even dynamically created$ *PA T9 or native B eries%
public 3ist (in"B'Aative;uer'(Strin7 sql1 Class t'pe) # return t+is.em.createAative;uer'(sql1 t'pe).7etResult3ist()$

All named B eries have to be named niB ely. 5his reB irement ca ses problemsS pop lar B eries s ch as N<nd allO or N<nd by nameO are de<ned "or nearly every entity. 5o overcome the problem$ B eries sho ld be B ali<ed 'ith a niB e pre<> "ollo'ed by the act al name. 5he pre<> can be easily derived "rom the entity name and de<ned as a <nal <eld as sho'n in the "ollo'ing e>ample%
2)ntit' 2Aame";ueries(# 2Aame";uer'(nameD#oo3.1@@1quer'D4Select b &rom Boo9 b4)1

483
Download at WoweBook.Com

2Aame";uer'(nameDBoo9.BBJAA6)1quer'D4Select b &rom Boo9 b ,+ere b.name D Gname4) $) public class Boo9 implements Seriali=able# public (inal static Strin7 A33 D 4...cru"."omain.Boo9.A334public (inal static Strin7 BBJAA6) D 4...cru"."omain.Boo9.BBJAA6)4-

5his avoids not only naming conHicts$ b t increases the sability as 'ell. 5he constant can be passed to the ;A,$ and a common pit"all$ misspelling o" the B ery name$ can be avoided. A p rist may arg e that this approach brea#s encaps lation$ beca se the ;A, client has to se constants "rom the entity and bypass the layering. )o'ever$ the entity is also sed as parameter and res lt. 5he violation o" the encaps lation is intentional hereAit emphasi?es the ;6Q principle% t+is.cru"ServiceBean.(in"B'Aame";uer'(Boo9.A33).si=e() T eries can have an arbitrary n mber o" parameters$ 'hich are #ey-val e pairs. 5he B ery parameters can be conveniently chained together 'ith method invocation on a ;uer' instance%
t+is.em.create;uer'()ntit'.;U)RBJAA6)). setParameter(4(irstParameterAame41 4(irst?alue4). setParameter(4secon"ParameterAame41 4secon"?alue4)-

5he ;uer' class is " lly encaps lated inside the ;A,$ so e>posing the B ery to ;A, clients 'o ld brea# the encaps lation. Beca se the ;A, implementation is generic$ there is no 'ay to incorporate a <>ed n mber o" parameters into the method signat re in reg lar 'ay. 5he var-args style 'o ld 'or#$ b t then the <rst odd array inde> 'o ld represent the parameter name and the parameter val e$ 'hich is not convenient and error prone. +nstead$ yo can se a java.util.6ap.Strin71Object0Iit already s pports the notion o" type-sa"e #ey-val e pairs o t o" the bo>. 5he constr ction o" a 6ap$ ho'ever$ is not H ent. 5he put method ret rns the val e and not the 6ap itsel"$ 'hich ma#es chaining impossible. 5he tility class ;uer'Parameter streamlines the constr ction o" the 6ap instance sing method chaining and a simplistic implementation o" the B ilder pattern. 5he se o" the ;uer'Parameter tility is " lly optionalS the B ery parameters can still be passed as 6ap i" needed.
public class ;uer'Parameter # private 6ap.Strin71Object0 parameters D nullprivate ;uer'Parameter(Strin7 name1Object value)# t+is.parameters D ne, as+6ap.Strin71Object0()t+is.parameters.put(name1 value)$ public static ;uer'Parameter ,it+(Strin7 name1Object value)# return ne, ;uer'Parameter(name1 value)$ public ;uer'Parameter an"(Strin7 name1Object value)# t+is.parameters.put(name1 value)return t+is$

488
Download at WoweBook.Com

public 6ap.Strin71Object0 parameters()# return t+is.parameters$ $

5he method ,it+ is statically imported$ 'hich ma#es the constr ction code more readable. +t ret rns the ;uer'Parameter itsel"$ 'hich in t rn allo's " rther chaining 'ith the an" method.
import static com.abien.patterns.business.cru".;uer'Parameter.C2Stateless 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public class 8AOClient# 2)*B private Cru"Service cru"Servicepublic 3ist.Boo90 (in"(Strin7 name1int numberO(Pa7es)# return t+is.cru"Service.(in"B'Aame";uer'(Boo9.BBJAA6)JAA8JPA>)S1 ,it+(4name41name). an"(4pa7es41 numberO(Pa7es). parameters()). 7etResult3ist()$ $

/either the parameters nor the res lt o" the B ery itsel" are type-sa"e. 5his is the d e to the generic implementation o" this strategy. 5ype sa"ety has to be provided by the ;A, client$ it can easily 'rap the generic methods and provide a more speci<c and type-sa"e inter"ace. "o*ain's!ecific "A( /othing prevents s to provide a type-sa"e ;A,$ 'hich is designed to operate on a partic lar domain ob=ect. . ch a ;A, co ld be e>tended 'ith domain-speci<c e>tensions and additional " nctionality s ch as pre"etching o" dependent ob=ects$ managing common relations$ creating domain-speci<c B eries on the Hy$ or <ltering the res lts to match a speci<c ser. 5hose e>tensions are application speci<c and cannot be generali?ed in a re sable pattern. A 'elldesigned$ domain-speci<c ;A, provides added val e beyond 'rapping the )ntit'6ana7er and casting its parameters and ret rn val es. +n contrast to a generic ;A,$ this variant has to be deployed once "or an entity type$ 'hereby one instance o" a generic ;A, can manage any n mber o" di""erent entities. +n practice$ these t'o variants are sed together. 5he generic one is per"ectly s itable "or master data management and simpler C67; se cases. A domain-speci<c ;A,$ on the other hand$ reali?es speci<c " nctionality. +t can even access generic ;A,s "or re sing basic " nctionality. Attached'res,lt "A( 5he attached-res lt ;A, ret rns active ob=ects that are still connected 'ith the data store. 5his is the de"a lt "or a ;A, implemented as a stateless session bean and in=ected )ntit'6ana7er. +n

482
Download at WoweBook.Com

case the ;A, re ses the enclosing transaction ('hich is the r le)$ all ret rned entities 'ill remain managed. -ven e>ternal (e.g. per"ormed in .ervices) entity modi<cations 'ill still be visible a"ter the commit o" the transaction. 5he generic variant described so "ar$ operates in e>actly in the same 'ay. +n the conte>t o" a transaction$ the persistence sho ld al'ays operate in a managed or attached 'ay. 5his prevents the e>istence o" m ltiple copies o" the same entity and possible inconsistencies s ch as lost pdates. -specially in more ambitio s pro=ects$ several developers co ld 'or# on " nctionality behind the transaction bo ndary. An attached-res lt ;A, is compatible 'ith this idea$ beca se it al'ays ret rns the same re"erence to an entity "or a given primary #ey. All transaction participants operate on the same ob=ect instances$ so lost pdates inside a transaction are e""ectively prevented. Eor#ing 'ith attached ob=ects is pre"erred. +t is$ ho'ever$ not al'ays possible to achieve this B ality. "etached'res,lt "A( ;etached-res lt ;A, operates in the same manner as the attached-res lt ;A,% the method res lts became detached. +n "act the res lt o" a method becomes a val e ob=ect or 5rans"er ,b=ect. ;isconnecting the entities "rom the transactional cache is not desirable in a transactionIit is o"ten a limitation o" given data store implementation. /evertheless$ the ma=ority o" all enterprise reso rces are not *PA compliant. 9egacy databases 'itho t *;BC driver$ Hat <les$ and even stored proced res cannot be easily accessed via a standard *PA provider. Qo co ld implement a *PA provider to enable access to an ns pported reso rce. 5he e""ort$ ho'ever$ is m ch higher than bypassing *PA and accessing the proprietary reso rce directly. A ;A, is per"ect "or the encaps lation o" the proprietary data access$ b t ret rns ;5,s or nmanaged entities to the caller. 5he detached-res lt strategy is similar to a typical *2-- 4.8 ;A,. 5he main responsibility is the conversion bet'een an o"ten data set oriented$ proprietary reso rce and more convenient P,*,s. (ore common in *ava -- 2 is the se o" ;5,s "or ret rning a s bset o" a managed entity net'or#. 5his is o"ten done "or optimi?ation p rposes. A 2Aame";uer' is sed to search "or *PA entities$ b t the res lt is mapped to transient ;5,s%
2Aame";uer'(nameDBoo9.A33J8:O1quer'D4Select ne, ..."omain.Boo98:O(b.numberO(Pa7es1b.name) &rom Boo9 b4)

!or the B ery e>ec tion even an attached-res lt ;A, co ld be sed. 5he generic <nder ret rns in that partic lar case an nmanaged ;5, instead o" an attached entity. 3ist.Boo98:O0 "tos (in"B'Aame";uer'(Boo9.A33J8:O)D t+is.cru"ServiceBean.

+n practice s ch hybrid ;A, strategies are common. 5he semantic di""erence bet'een ret rning an attached and a detached ob=ect is not obvio s and can ca se inconsistencies. +t is a good idea to

48:
Download at WoweBook.Com

se speci<c naming conventions to di""erentiate bet'een ;5,s and real entitiesS the s "<> ;5, is good eno gh "or that p rpose. Back'end &ntegration "A( 5he Common Client +nter"ace (CC+) "rom the *ava Connector Architect re (*CA) is very similar to plain *;BC and o"ten needed to integrate e>ternal reso rces. Beca se the reso rce vendor$ and not the application developer$ has to implement the *CA .P+$ an e>isting *CA reali?ation is the easiest 'ay to interact 'ith the bac#-end system. *CA and its proprietary co nterparts are neither type-sa"e nor convenient to se. 5he developer has to deal 'ith ResultSets$ +np tC, tp t parameters$ and many other lo'-level details. ->posing this lo'-level AP+ to b siness services 'o ld poll te the code 'ith pl mbing and mi> the reali?ation o" domain-speci<c reB irements 'ith the in"rastr ct re. 5he introd ction o" a ;A, to encaps late the CC+ or other similar AP+s s ch as net'or# access$ generated screen scraper code$ trans"ormation bet'een proprietary and normali?ed "ormats and so on provides a real added val e. 5he str ct re and reali?ation o" s ch a bac#-end integration ;A, is nearly the same as a standard ;A,$ e>cept the inter"ace implementation (the act al bean) interacts 'ith e>isting bac#-end services instead o" accessing the database. Beca se it is in practice more complicated than it may seem here$ the bean o"ten delegates calls to a variety o" tilities$ services$ AP+s$ or even "rame'or#s. Altho gh at <rst glance$ the bac#-end integration ;A, loo#s li#e = st another inter"ace$ its implementation is a "a@ade that interacts 'ith vendor-speci<c$ even generated " nctionality. 5he bac#-end integration ;A, "alls into the detached ;A, categoryIthe data "etched by s ch ;A,s are 5rans"er ,b=ects converted "rom proprietary data so rces$ 'hich are detached by de<nition. A-stract "A( 5he data access logic does not al'ays have to be reali?ed as a standalone ;A,. .ession beans already s pport in=ection o" )ntit'6ana7er and have access to its " nctionality. +nstead o" delegating to a dedicated ;A,$ re sable data access logic can be inherited "rom an abstract ;A, implementation as 'ell. 5he ;A, methods 'o ld be available immediatelyI'itho t delegating and the need o" in=ecting the ;A,. A p rist may arg e$ that inheriting "rom an abstract ;A, in a .ervice class is not clean$ beca se a .ervice is not a ;A,. +nheriting "rom generic ;A, " nctionality streamlines the code and is pragmatic. 5his approach ma#es sense "or database-driven applications$ 'here a ma=or portion o" b siness logic consist o" database access. +n that partic lar case$ yo co ld even arg e that a .ervice class is act ally a ;A,.

5esting
5esting o" -*B 3.0 is not nli#e testing P,*,s. 5he ;ependency +n=ection is not available$ so it has to be em lated in the 2Be(ore method. 5he same is tr e "or declarative transactions. 5hey have to be started and committed (rolled bac#) man ally. 5he )ntit':ransaction can be obtained directly "rom the )ntit'6ana7er$ 'hich$ in t rn$ is created 'ith the bootstrapping class Persistence and the )ntit'6ana7er&actor'.

480
Download at WoweBook.Com

+t ta#es three additional lines o" code to test the ;A, o tside o" the container. 5he bootstrapping o" the *PA r ntime co ld be easily "actored o t in a s per class or a tility class 'ith a single static method. 5he "ollo'ing e>ample demonstrates testing a ;A, o tside o" the container%
public class Cru"ServiceBean:est # private )ntit'6ana7er emprivate )ntit':ransaction etprivate Cru"ServiceBean cru"ServiceBean2Be(ore public voi" setUp() t+ro,s )xception # t+is.em D Persistence.create)ntit'6ana7er&actor'(4test4). create)ntit'6ana7er()t+is.et D t+is.em.7et:ransaction()t+is.cru"ServiceBean D ne, Cru"ServiceBean()t+is.cru"ServiceBean.em D t+is.em$ 2:est public voi" cru"()# Boo9 boo9 D ne, Boo9(4U41 4Pro"uctive *ava ))4)t+is.et.be7in()int initialSi=e D t+is.cru"ServiceBean.(in"B'Aame";uer'(Boo9.A33).si=e()%%create Boo9 create" D t+is.cru"ServiceBean.create(boo9)assertAotAull(create")assert)quals(boo9.7et<sbn()1create".7et<sbn())assert)quals(boo9.7etAame()1create".7etAame())Boo9 (oun" D t+is.cru"ServiceBean.(in"(create".7et<sbn()1 Boo9.class)assertAotAull((oun")assert)quals((oun".7et<sbn()1create".7et<sbn())%%quer' int si=e D t+is.cru"ServiceBean.(in"B'Aame";uer'(Boo9.A33).si=e()assert)quals(initialSi=eHU1si=e)Strin7 ne,Aame D boo9.7etAame() H 4 Secon" )"ition4boo9.setAame(ne,Aame)%%up"ate Boo9 up"ate" D (Boo9) t+is.cru"ServiceBean.up"ate(boo9)assertAotAull(up"ate")Boo9 (oun"Up"ate" D t+is.cru"ServiceBean.(in"(create".7et<sbn()1 Boo9.class)assertAotAull((oun"Up"ate")assert)quals(up"ate".7etAame()1(oun"Up"ate".7etAame())%%"elete

481
Download at WoweBook.Com

t+is.cru"ServiceBean."elete((oun"Up"ate")Boo9 s+oul"nt)xist D t+is.cru"ServiceBean.(in"(create".7et<sbn()1 Boo9.class)assertAull(s+oul"nt)xist)int =ero D t+is.cru"ServiceBean.(in"B'Aame";uer'(Boo9.A33).si=e()assert)quals(R1=ero)t+is.et.rollbac9()$ $

5he man al bootstrapping is no longer necessary in -*B 3.4. 5he initiali?ation in the 2Be(ore method co ld be replaced 'ith the bootstrapping o" the embeddable container%
2Be(ore public voi" setUp() t+ro,s )xception # )*BContainer container D )*BContainer.create)*BContainer()Context ctx D container.7etContext()t+is.cru"ServiceBean D (Cru"Service)ctx.loo9up(FjavaG7lobal% N)*BJ*ARJAA6)O%Cru"ServiceBeanE)$

5he creation o" the container$ as 'ell as the loo# p logic$ can be " rther encaps lated in a 3oo9upUtilit' class$ 'hich ses the naming conventions and the Beans inter"ace to comp te the global =ndi name$ per"orm the loo# p$ and ret rn the inter"ace in a type-sa"e manner. 5he bootstrapping code 'o ld be e""ectively red ced to the "ollo'ing%
import static ..util.3oo9upUtilit'.C2Be(ore public voi" setUp() t+ro,s )xception # t+is.cru"ServiceBean D loo9up(Cru"Service.class)$

;ependency in=ection and transaction management$ "or e>ample$ 'o ld be per"ormed by the container. 5here is no need to reboot the container be"ore every single 2:est method. +t is smarter to start it once and re se it not only "or testing a single class$ b t "or all classes to be tested. 5he )*BContainer can be transparently cached inside the 3oo9upUtilit'. 5his is good "or per"ormance$ b t 'o ld also imply the re se o" already created bean instances$ 'hich co ld lead in t rn to non-reprod cible tests. Beyond the approach described above the se o" moc#s is possible as 'ell. 5he )ntit'6ana7er is an inter"ace$ 'hich can be implemented anonymo sly "or the tests. 5he se o" an embedded database s ch as *ava ;B or ).T9 (better per"ormance in memory mode) is in most cases absol tely s "<cient "or ;A, testing. +n case yo are going to se a real )ntit'6ana7er and not a moc#$ it has to be con<g red di""erently. 5he )ntit'6ana7er cannot se *5A transactions o tside o" the container and the

489
Download at WoweBook.Com

*;BC connection has to be con<g red e>plicitly in the persistence.xml <le as sho'n in the "ollo'ing e>ample ('ith an embedded ;erby *ava database)%
.persistence versionD4U.R4 @40 .persistence/unit nameD4test4 transaction/t'peD4R)SOURC)J3OCA340 .provi"er0oracle.toplin9.essentials.PersistenceProvi"er.%provi"er0 .class0@.business.cru"."omain.Boo9.%class0 .exclu"e/unliste"/classes0true.%exclu"e/unliste"/classes0 .properties0 .propert' nameD4toplin9.j"bc.user4 valueD4APP4%0 .propert' nameD4toplin9.j"bc.pass,or"4 valueD4APP4%0 .propert' nameD4toplin9.j"bc.url4 valueD4j"bcG"erb'G.%test8B-createDtrue4%0 .propert' nameD4toplin9.j"bc."river4 valueD4or7.apac+e."erb'.j"bc.)mbe""e"8river4%0 .propert' nameD4toplin9.""l/7eneration4 valueD4"rop/an"/create/tables4%0 .%properties0 .%persistence/unit0 .%persistence0

5his co ld be easily achieved = st adding an additional persistence- nit 'ith e.g. the name NtestO. 5he declaration o" additional nit has a ma=or dra'bac#Iit becomes ambig o s and has to be speci<ed "or in=ection in the 2PersistenceContext annotation. . ch an enhancement co ld even brea# prod ction code. +nstead o" changing the prod ction persistence.xml <le$ it is better to provide an additional$ independent one. +t = st has to be visible in the classpath o" the test r nner.

Figure 2. !ifferent persistence.&ml files for test and production. 5his can be achieved creating a "older (-5A-+/! in the test so rce "older. 5he persistence.xml <le 'ill be incl ded in the classpath o" the test r nner and is available "or

420
Download at WoweBook.Com

the persistence provider. 5he contents o" the test "older are not deployed into prod ction. 5his approach 'or#s across pop lar +;-s and is even easier to achieve 'ith A/5 or (aven.

;oc mentation
A ;A, has to provide added val e beyond simple C67; operations and 'rapping the )ntit'6ana7er. 5his added val e$ has to be doc mented in one$ easily accessible place (= st li#e the ;A, implementation details$ incl ding the transaction management attachedCdetached mode or the decision 'hether to se 23ocal$ 2Remote or no-inter"ace vie'). Ei#is are = st per"ect "or this p rpose. +nstead o" repeating the description over and over again in *ava;oc$ the central doc mentation co ld be re"erenced "rom the ;A, implementations. 5he ;6Q principle applies to the doc mentation as 'ell. +t is act ally eno gh to mar# a class as ;A,. Annotations are = st per"ect "or this p rpose%
28ocumente" 2Retention(RetentionPolic'.C3ASS) 2:ar7et()lement:'pe.:BP)) public 2inter(ace 8AO # $

. ch an annotation designates a class as a ;A,$ 'hich ma#es searching "or all ;A,s at b ild time possible. +t is very se" l "or a tomatic code revie's and B ality ass rance. +n *ava;oc only the remaining deHections or e>tensions "rom the already described principles have to be doc mented. 5he dependencies bet'een ;A,s and their clients can be vis ali?ed in a standard 7(9 class diagram. 5he ;A, concept can be easily emphasi?ed 'ith a stereotype ..8AO00Ia nat ral co nterpart o" an annotation. . ch stereotypes sho ld be b ndled in an e>ternal 7(9 pro<le. Also$ in this case it is not necessary to vis ali?e all ;A, methods. ,nly the delta "rom the de"a lt$ s ch as additional methods$ has to be vis ali?ed. 5he ;A, principles can be easily e>pressed 'ith a one class-iconno need to model the inter"ace.

ConseB ences
*dditiona comp exity: A "A( introd,ces at least t/o additional ele*ents1 an interface and its i*!le*entation. +hey have to -e develo!ed1 doc,*ented1 and *aintained. 9ot ,2:: +he )ntit'6ana7er already enca!s,lates different JPA i*!le*entations very /ell. &t is f,rther co*!ara-le /ith a generic "A( interface A #R;" "A( is .,st a re!etition of already e6isting f,nctionality. A "A( sho,ldn:t -e ,sed .,st for the i*!le*entation of si*!le #R;" ,se cases or as a thin /ra!!er aro,nd an )ntit'6ana7er. &eaky abstraction prob em: Es!ecially the attached'res,lt "A( i*!le*entation is hard to -e re!laced /ith 9"AP or flat file access. +he introd,ction of a "A(1 *otivated -y deco,!ling of a !artic,lar data store1 is hard to achieve and /ill !ro-a-ly not !ay off. 'ncapsu ation of reusab e data access functiona ity: +he introd,ction of "A(s is only -eneficial in case additional a!!lication's!ecific logic can -e enca!s,lated in a central !lace. S,ch an a!!roach *ini*i5es the d,!lication of code and i*!roves the

424
Download at WoweBook.Com

*aintaina-ility. &t is hard1 ho/ever1 to find good re,se candidates ,! front. &n !ractice they are incre*entally generali5ed and e6tracted in the refactoring !hases. 1idening the scope: A classical "A(1 /hich enca!s,lates access to relational data-ases1 -eca*e far less interesting /ith the introd,ction of JPA. Raising the level of a-straction and enca!s,lation of !ro!rietary AP&s !rovides still added val,e and *akes the code *ore *aintaina-le.

6elated Patterns
5he ;A, pattern is a generic Havor o" the ;omain .tore$ !ast-9ane 6eader$ or Aal e 9ist )andler patterns. A ;A, is sed by a .ervice or .ervice !a@ade. A ;A, may se Deneric *CA to access proprietary legacy reso rces.

422
Download at WoweBook.Com

%ransfer 046ect and Data %ransfer 046ect


5he original description o" a ;ata 5rans"er ,b=ect (;5,) or 5rans"er ,b=ect (5,) de<ned in the Core *2-- patterns catalog emphasi?es the deco pling "rom the -ntity Beans% NApplication clients need to e>change data 'ith enterprise beans. N*ava 2 Plat"orm$ -nterprise -dition (*2--) applications implement server-side b siness components as session beans and entity beans. .ome methods e>posed by the b siness components ret rn data to the client. ,"ten$ the client invo#es a b siness ob=ectRs get methods m ltiple times ntil it obtains all the attrib te val esX LXM N-ntity beans$ on the other hand$ are m lti ser$ transactional ob=ects representing persistent data. An entity bean e>poses the val es o" attrib tes by providing an accessor method (also re"erred to as a getter or get method) "or each attrib te it 'ishes to e>pose. N-very method call made to the b siness service ob=ect$ be it an entity bean or a session bean$ is potentially remote. 5h s$ in an -nterprise *avaBeans (-*B) application s ch remote invocations se the net'or# layer regardless o" the pro>imity o" the client to the bean$ creating a net'or# overhead. -nterprise bean method calls may permeate the net'or# layers o" the system even i" the client and the -*B container holding the entity bean are both r nning in the same *A($ ,.$ or physical machine. .ome vendors may implement mechanisms to red ce this overhead by sing a more direct access approach and bypassing the net'or#. NAs the sage o" these remote methods increases$ application per"ormance can signi<cantly degrade. 5here"ore$ sing m ltiple calls to get methods that ret rn single attrib te val es is ine"<cient "or obtaining data val es "rom an enterprise beanO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC5rans"er,b=ect.htmlM. 5he conte>t changed dramatically in *ava -- 2Iit 'as even inverted. 5he *PA persistence is only visible and sable locally. 5he entities do not have any remote capabilitiesIthey are = st P,*,s. +n contrast to C(P 2.0$ they are not even activeIthey can be e>ec ted only in the conte>t o" a session bean. 5he original motivation o" hiding remote entities and e>posing 5,s instead is deprecated.

Problem
5he origin problem statement 'as% NQo 'ant to trans"er m ltiple data elements over a tierO (http%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC5rans"er,b=ect.html). 5his partic lar problem 'as elegantly solved in *ava -- 2 'ith detachment o" persistent entities. 5here is no need "or the introd ction o" another class = st "or trans"erring the entities data. *PA entities can implement a java.io.Seriali=able inter"ace and be trans"erred bet'een tiers$ even remote ones. C(P 2." entities 'erenRt Seriali=able$ the developer 'as "orced to copy their states to a remotely trans"erable str ct reIthe 5rans"er ,b=ect. +n most *2-- pro=ects this proced re 'as a tomated 'ith K;oclet$ 'here a "actory method 'as generated. 5his method created a 5, 'ith the state o" the C(P 2.0 entity. K;oclet even converted dependent entities rec rsively. 5his process isnRt obvio sly ;6Q$ beca se the 5,s had e>actly the same

Download at WoweBook.Com

str ct re as the persistent entities. +n that case$ no real deco pling bet'een the 5,s and the entities occ rs. -very change in the entities 'as propagated immediately to the 5,s. Beca se o" the lac# o" real encaps lation$ an additional layer o" indirection 'as introd ced in most *2-- pro=ectsI'ith man ally cra"ted 5,s. +n theory$ the 5,s had to deco ple "rom the persistence layer and there"ore sho ld have had a di""erent str ct re. +n practice they 'ere very similar$ i" not identical to the generated 5,s. 5his additional trans"ormation too# place in several layers above the act al persistence. 5he man al conversion bet'een the generated 5,s (or even the entity inter"aces) and the man ally cra"ted 5,s 'as and is tedio s$ b t provided higher deco pling. 5his additional layer o" abstraction 'as rather lea#y. 5he most common scenario is the addition o" a 7+ element in a "ormIyo r client = st 'ants to have an additional te>t <eld$ chec# bo> or another component incl ded in an e>isting "orm. . ch an e>tension reB ires changes in the presentation layer and the 5,$ 'hich is responsible "or data transport bet'een the presentation and the b siness tiers. 5he man ally 'ritten conversion has to be c stomi?ed 'ith the copy logic o" the additional attrib te. 5he data o" the additional <eld has to be stored someho'$ so the persistence as 'ell as the act al database table have to even be e>tended. 5he vast ma=ority o" "eat re reB ests reB ire changes in several layers. -ven in case each layer 'o ld be per"ectly encaps lated$ the additional in"ormation has to be transported and processed thro gh the entire system. +t seems li#e an introd ction o" a ;5,$ = st "or isolation o" " t re changes is not a good strategy. 5he reverse is tr e$ it even ma#es the system less maintainable and more comple>. -specially in service-oriented applications$ yo have several cons mers 'ho access one service instance. +n this partic lar case$ " nctional e>tensions o" one partic lar cons mer are not interesting to the others. ,n the contrary$ e>tensions o" the " nctionality m st not brea# the inter"aceIall methods and especially the parameters have to remain binary compatible. A service parameter can be either represented by a 5, or a detached entity. A detached entity does not provide s "<cient encaps lation "or database schema changes ca sed by a "eat re reB est o" a single client. A modi<cation o" that *PA entity 'o ld brea# the binary compatibility o" all services 'hich se it as a parameter or ret rn val e$ and th s also brea# the compatibility o" all clients. +n *ava --$ 5,s are mostly sed to provide cons mer-speci<c vie's to the persistence layer and to #eep the e>ternal inter"aces stable. Altho gh hard to b ild and maintain$ additional deco pling is one o" the ma=or .,A impacts% once deployed$ the service contract m st not change. ->posing the domain layer directly to the service cons mer 'o ld ma#e " t re e>tensions impossible. -ven minor changes in the persistence layer 'o ld brea# the binary compatibility o" the service contract. Eith 5,s and an additional translation layer$ local changes to the domain model can be hidden to some degree and donRt have to brea# the service cons mer. 5he translation layer$ in general a dedicated -*B$ has to be maintained "or every cons mer separately$ 'hich is e>pensive to develop$ manage$ and maintain. 5he main goal o" .,A is agility$ 'hich is reali?ed 'ith independent$ sel"-contained services. -ach service provides b siness val e to its cons mer b t it has to evolve 'itho t impacting other services. +t is rather simple to prevent invocations bet'een services and avoiding direct

428
Download at WoweBook.Com

dependenciesIrelations bet'een entities ma#e the deco pling a lot harder. 5he parameters o" one service may point to the parameters o" the other$ 'hich res lts in direct dependency bet'een services ca sed by passed data. +n practice$ it is hard to <nd independent persistent entities (P;,s) that are not related to entities "rom other components or namespaces. *PA entities are ob=ectsIdirect re"erences bet'een them are the r le. -ven in a trivial case$ 'here a Customer entity points to an A""ress (4%4 relation)$ the CustomerService 'o ld be dependent on the A""ressService (act,ally the co*!onent of this service). -ven 'orse$ s ch an approach 'o ld res lt in class d plication. (ost tools se inter"ace description lang ages s ch as E.;9 or +;9 as inp t to generate *ava st bs. 5he A""ress entity 'o ld be generated t'ice$ probably in di""erent namespacesS in the conte>t o" the CustomerService and the second time as a parameter o" the A""ressService. ;5,s can easily brea# those hard dependencies replacing the relation 'ith a pro>y. +nstead o" sing a hard re"erence$ the "oreign #ey and entity type can be sed to niB ely identi"y the relation. 5he relation bet'een the entities co ld be resolved on demand$ loading la?ily the dependent entity 'ith a service. +n this sample$ the Customer 'o ld be loaded 'ith the CustomerService$ b t the relation to the A""ress 'o ld be e>plicitly and la?ily loaded 'ith the A""ressService. 5here 'o ld be no direct dependency (re"erence) bet'een the t'o 5,s. 5his proced ral approach reB ires more server ro ndtrips and ma#es the code more complicated$ b t deco ples entities (and th s services) "rom each other. -ven 'ith the se o" code generators the ;5,s (and the services) 'ill remain independent. 5his approach$ ho'ever$ is not a best practice and 'or#s only "or "e' entities. 9oading many entities over a 'eb service becomes too slo' "or most se cases. +n traditional applications$ s ch an approach is rather esoteric and overblo'n. +n an .,A$ it is the only 'ay to deco ple independent service contracts by pro>ying the re"erences bet'een entities. (ore "reB ently$ ;5,s are introd ced "or per"ormance improvements o" se cases 'ith deeply interconnected entities. +t is in general "aster to trans"er only a s bset o" the interconnected graph o" entities$ instead o" the entire tree. !or that p rpose$ even 4%4 relations co ld be condensed into one ;5,. 5he ;5, can be directly created by the )ntit'6ana7er as a res lt o" a Aame";uer'. +tRs a more common *ava -- se caseIthe ;5, acts as a pro>y on the client side and represents an e>pensive-to-constr ct-and-transport tree o" detached entities. 5he ;5, constr ction can either ta#e place directly in the service$ in an )ntit'6ana7er$ or be encaps lated in a ;A,.

!orces
=o, /ant to kee! the e6ternal service -inary co*!ati-le. +he changes of one client sho,ld not affect the others. +he transfer of dee!ly interconnected entities has to -e o!ti*i5ed. "ifferent vie/s for a single do*ain *odel are re8,ired. "ata of !ro!rietary reso,rces and infor*ation syste*s has to -e transferred to the client.

422
Download at WoweBook.Com

=o, have to co**,nicate /ith a legacy1 dataset'oriented reso,rce /ith P(J(s. =o, /ant to trans!ort !resentation tiers!ecific *etadata for -,ilding ;&s on the fly. +he o-.ect'oriented JPA entities have to -e transfor*ed into a si*!lified for*at for transfer over RES+0,l1 S(AP1 #(RBA1 or even AS#&&.

.ol tion
5he act al implementation o" a ;5, is trivial and didnRt change since the introd ction o" the java.io.Seriali=able inter"ace in *;& 4.4. +t is a plain *ava class that implements the Seriali=able inter"ace$ in case it has to be trans"erred bet'een *A(s. 5he state is transported as attrib tes$ each e>posed 'ith getter and setter accessors. 5he "ollo'ing e>ample sho's a nonseriali?able ;5, implementation "or local se%
public class Boo98:O # private int numberO(Pa7esprivate Strin7 namepublic Boo98:O(int numberO(Pa7es1 Strin7 name) # t+is.numberO(Pa7es D numberO(Pa7est+is.name D name$ public Strin7 7etAame() # return name$ public voi" setAame(Strin7 name) # t+is.name D name$ public int 7etAumberO(Pa7es() # return numberO(Pa7es$ public voi" setAumberO(Pa7es(int numberO(Pa7es) # t+is.numberO(Pa7es D numberO(Pa7es$ $

+n case the ;5, is going to be seriali?ed$ it co ld even implement the java.io.)xternali=able inter"ace. Qo 'ill have to implement the ,rite)xternal and rea")xternal methods respectively as sho'n in the "ollo'ing optimi?ed )xternali=able ;5, implementation%
public class )xternali=ableBoo98:O implements )xternali=able# private int numberO(Pa7esprivate Strin7 namepublic )xternali=ableBoo98:O(int numberO(Pa7es1 Strin7 name) #

42:
Download at WoweBook.Com

t+is.numberO(Pa7es D numberO(Pa7est+is.name D name$ %CC 6an"ator' (or )xternali=ableC% public )xternali=ableBoo98:O() # $ %%7etters an" setters ommitte" public voi" ,rite)xternal(ObjectOutput out) t+ro,s <O)xception # out.,riteU:&(name)out.,rite<nt(numberO(Pa7es)$ public voi" rea")xternal(Object<nput in) t+ro,s <O)xception1 ClassAot&oun")xception # t+is.name D in.rea"U:&()t+is.numberO(Pa7es D in.rea"<nt()$ $

5his approach not only increases the control over the compatibility$ b t has positive impact on per"ormance. 5he )xternali=able representation o" the ob=ect is smaller$ the reconstr ction happens e>plicitly$ 'itho t heavy se o" reHection as is the case in de"a lt seriali?ation. -ven in this simple case$ the si?e o" the )xternali=able ob=ect is over 20 percent smaller (9: bytes) than the identical Seriali=able ;5, (428 bytes). 5he nice thing abo t )xternali=able is the "act that it e>tends .eriali?able$ so the optimi?ation can be introd ced a"ter'ards. 5he ObjectOutputStream and Object<nputStream accept both (act ally only Seriali=ableI)xternali=able is a Seriali=able ;5,)$ so there is no di""erence "or yo r seriali?ation in"rastr ct re. Altho gh the per"ormance gain is considerable$ it is not recommended to implement the rea")xternal$ ,rite)xternal methods man ally as a general strategy. . ch an implementation is coding intensive and error prone. 5he seriali?ation is based on class metadata$ a per"ect case "or code generation. An already e>isting model-driven architect re ((;A) or modeldriven so"t'are development ((;.;) in"rastr ct re ma#es s ch generations more viable. -ven having generators available the )xternali=able sho ld be sed 'ith careIits implementation reB ires a considerable amo nt o" code$ 'hich has to be maintained and nderstood.

6ethin#ing
A 5rans"er ,b=ect doesnRt reB ire ma=or rethin#ing$ e>cept the "act that it became s perH o s "or the ma=ority o" all se cases. *PA entities do a great =ob trans"erring data bet'een layers$ especially in a single *A(. A 5, se to be common as a general best practice in *2-- to hide C(P-speci<c details$ 'hich is no longer necessary.

420
Download at WoweBook.Com

;eco pling is no longer a s "<cient = sti<cation "or sing 5,s neither. 5,s are str ct rally very similar$ i" not identical$ to *PA -ntities and there"ore not ;6Q. -very change driven by a "eat re reB est 'ill not only hit the *PA entities$ b t in most cases 5,s as 'ell. 5here are eno gh cases beyond encaps lation and deco pling$ 'here 5,s provide real added val e s ch as reali?ation o" additional vie's to a domain model$ abstracting "rom legacy data stores$ en"orcement o" eager loading in heterogeneo s teams or even transport o" client-speci<c metadata.

Conventions
5he str ct re o" a 5, is obvio s. +t is a trans"erable P,*, that is created directly "rom the data store or b siness logic. 5,s are b ilt as *avaBeansS they are comprised o" a de"a lt constr ctor and getters and setters "or every attrib te. +" the intent o" introd cing 5,s 'as deco pling$ 5,s sho ld be stored in a dedicated s bpac#age that belongs to the contract$ "or e>ample$ NappnameO.business.customerm7mt.boun"ar' or NappnameO.business.customerm7mt.boun"ar'.to. ,ther'ise it is s "<cient to place the 5,s near the origin o" their creation$ "or e>ample$ in the same pac#age as P;,s$ ;A,s$ and so on. 5,s sho ld be easily disting ishable "rom attached entities (P;,s). A naming convention s ch as the s "<> 5, ("or e>ample$ Customer:O) sho ld <> this iss e. A 5, annotation 'o ld 'or# as 'ell$ b t it is not visible in the e>plorer in most +;-s.

Participants and 6esponsibilities


5he main responsibility o" the 5, is the highest possible deco pling and data trans"er optimi?ation. A 5, can be cons med and prod ced by the ma=ority o" all patterns and components. +n most cases it is created in a ;A, as a res lt o" a B ery. .ervices$ or more o"ten the .ervice !a@ade$ may ret rn 5,s to provide client-speci<c vie's to domain ob=ects as 'ell.

.trategies
5he de"a lt strategy "or a 5, is = st a Seriali=able *ava class that con"orms to the *avaBean pattern. +t comes 'ith a de"a lt constr ctor and every attrib te is e>posed via a getter and setter pair. B,ilder'style +( A b ilder-style 5, is a s al 5, 'ith a H ent 'ay o" constr ction. Beca se o" the lac# o" named parameters in *ava$ especially 5,s 'ith many attrib tes become hard to create. -ither constr ctors 'ith a h ge n mber o" parameters or many setters have to be invo#ed "or that p rpose. 5he "ollo'ing e>ample sho's a B ilder pattern 'ith consistency chec#s and H ent constr ction%
public class Buil"erSt'le8:O implements Seriali=able# private int numberO(Pa7esprivate Strin7 nameprivate Buil"erSt'le8:O(int numberO(Pa7es1 Strin7 name) #

421
Download at WoweBook.Com

t+is.numberO(Pa7es D numberO(Pa7est+is.name D name$ private Buil"erSt'le8:O() #$ public static class Buil"er# private Buil"erSt'le8:O buil"erSt'le8:OBuil"er()# t+is.buil"erSt'le8:O D ne, Buil"erSt'le8:O()$ public Buil"er numberO(Pa7es(int pa7es)# i((pa7es . U) t+ro, ne, <lle7alAr7ument)xception(4A boo9 s+oul" +ave at least one pa7e4)t+is.buil"erSt'le8:O.setAumberO(Pa7es(pa7es)return t+is$ public Buil"er name(Strin7 name)# i((name DD null) t+ro, ne, <lle7alAr7ument)xception(4A boo9 s+oul" +ave a name4)return t+is$ public Buil"erSt'le8:O buil"()# return t+is.buil"erSt'le8:O$ $ %% remainin7 7etters % setters ommitte"

5he B ilder pattern ma#es the constr ction o" a ;5, 'ith many attrib tes more convenient and allo's additional validation o" the state at creation time.
2:est public voi" construct() t+ro,s )xception # t+is.buil"erSt'le8:O D ne, Buil"erSt'le8:O.Buil"er(). name(48u9e Stories4). numberO(Pa7es(UR). buil"()$

5his strategy is hard to se 'ith data binding "rame'or#s$ beca se most o" them (*.6-292$ -clipse Binding and *.!) rely on *avaBeans patterns and not the b ilder style signat re. B,ilder'style &**,ta-le +( Eith a B ilder pattern yo can prescribe the setting o" certain attrib te. All the mandatory attrib tes are declared as (inalItheir e>istence is chec#ed by the compiler.
public class Buil"erSt'le<mmutable8:O implements Seriali=able# private (inal int numberO(Pa7esprivate (inal Strin7 name-

429
Download at WoweBook.Com

private Strin7 "escriptionprivate Buil"erSt'le<mmutable8:O(Buil"er buil"er) # t+is.numberO(Pa7es D buil"er.numberO(Pa7est+is.name D buil"er.namet+is."escription D buil"er."escription$ public static class Buil"er# private (inal int numberO(Pa7esprivate (inal Strin7 nameprivate Strin7 "escriptionpublic Buil"er(int numberO(Pa7es1 Strin7 name) # t+is.numberO(Pa7es D numberO(Pa7est+is.name D name$ public Buil"er "escription(Strin7 name)# i((name DD null) t+ro, ne, <lle7alAr7ument)xception(48escription cannot be null4)return t+is$ public Buil"erSt'le<mmutable8:O buil"()# return ne, Buil"erSt'le<mmutable8:O(t+is)$ $ public Strin7 7etAame() # return name$ public int 7etAumberO(Pa7es() # return numberO(Pa7es$ public Strin7 7et8escription() # return "escription$ public voi" set8escription(Strin7 "escription) # t+is."escription D "escription$

5he mandatory parameters come 'itho t settersIthey have to be passed to the b ilder constr ctor e>plicitly. ,nly "or the optional parameters the H ent b ilder methods are provided.
2:est public voi" construct() t+ro,s )xception #

4:0
Download at WoweBook.Com

#lient's!ecific +(

t+is."to D ne, Buil"erSt'le<mmutable8:O. Buil"er(UR148u9e :ales4). "escription(4Cool boo9 about *ava an" 8u9e4). buil"()$

5he strategies above 'ere = st variations o" a 5, that is aimed to transport the ra' data bet'een tiers. 5his 'as also the main goal o" the 5, "rom *2-- times. Eith the advent o" *ava 2 .- and en ms and annotations$ not only data b t also metadata can be easily transported 'ith the payload. 5his is especially se" l as an additional hint "or the parameteri?ation and even dynamic creation o" 7+s. +n addition to the name and type o" every attrib te$ 'hich is accessible via reHection$ an arbitrary n mber o" additional in"ormation can be attached sing annotations. !or more convenient access to the metadata$ it is better to annotate methods (the getters) instead o" <elds as sho'n in the "ollo'ing client-speci<c annotation%
2Retention(RetentionPolic'.RUA:<6)) 2:ar7et()lement:'pe.6): O8) public 2inter(ace Attribute # Strin7 "ispla'Aame() "e(ault 44int max8ispla'3en7t+() "e(ault URboolean require"() "e(ault (alseStrin7 vali"ationRe7exp() "e(ault 44Strin7 vali"ation6essa7e() "e(ault 4:+e attribute is not vali"4$

5he type-sa"e metadata can be compiled into methods (or <elds). 5he metadata is highly presentation speci<c$ b t the client-speci<c ;5,s 'ere designed 'ith client-speci<c reB irements in mind%
public class ClientSpeci(icBoo98:O implements Seriali=able# private int numberO(Pa7esprivate Strin7 name2Attribute("ispla'AameD4User Aame41 max8ispla'3en7t+DIR1require"Dtrue) public Strin7 7etAame() # return name$

5he additional metadata "alls into t'o categories% s pportive in"ormation "or 7+ c stomi?ation or creation and metadata "or syntactic validation o" the attrib tes. +n both cases the metadata is conveniently accessible via reHection%
public voi" accessAnnotations()# 6et+o" met+o"sNO D ClientSpeci(icBoo98:O.class.7et6et+o"s()boolean (oun" D (alse(or (int i D R- i . met+o"s.len7t+- iHH) # Attribute meta8ata D met+o"sNiO.7etAnnotation(Attribute.class)i((meta8ata 5D null)# S'stem.out.println(46et+o" nameG 4 H met+o"sNiO.7etAame() H 4 "ispla' nameG 4 H meta8ata."ispla'Aame())-

4:4
Download at WoweBook.Com

(oun" D true$ $

+t is al'ays a good idea to pre"er standards over home-gro'n sol tions and "rame'or#s. 5he Bean Aalidation *ava .peci<cation 6eB est (*.6-303) already de<nes a set o" annotations s ch as 2AotAull$ 26in or 26ax to e>press constraints "or client-side validation. Borro'ing some ideas "rom a *.6 is a good strategy. +n best case a *.6 becomes a standard$ so yo co ld get rid o" yo r c stom library or "rame'or#Iit 'ill become a part o" the plat"orm (.- or --). +n 'orst case$ the *.6 'ill die$ and yo end p having a proprietary$ home-gro'n sol tion. 2eneric "+( 5he idea o" reHective eval ation o" the ;5, is not limited to the metadata and can be even applied to the payload. A generic 7+ does not need statically de<ned$ se case dependent ;5,s. +t is eno gh to provide a reHective access to the ;5,s metadata and its contents. A java.util.6ap.Strin71Attribute0 is a per"ect str ct re "or the transportation o" dynamic payload. A ra' 6ap is$ ho'ever$ not convenient eno gh. ! rthermore$ it is hard to enrich the payload 'ith additional metadata and to model relations bet'een ;5,s having only a plain 6ap. A lean 'rapper aro nd the attrib te and relation maps 'ith validation logic is s "<cient "or this p rpose. 5he "ollo'ing e>ample sho's a H id ;5, "or all se cases%
public class >eneric8:O implements Seriali=able # private private private private static (inal lon7 serial?ersionU<8 D U36ap.Strin71 Attribute0 attributes D null6ap.Strin71 Set.>eneric8:O00 relations D nullStrin7 name D null-

public >eneric8:O(Strin7 name) # notAull(name1 4:+e name o( t+e 8:O cannot be null...4)t+is.attributes D ne, as+6ap.Strin71 Attribute0()t+is.relations D ne, as+6ap.Strin71 Set.>eneric8:O00()t+is.name D name$ public >eneric8:O a""(Strin7 name1 Attribute attribute) # notAull(name1 4Attribute name cannot be null4)notAull(attribute1 4Attribute ,it+ nameG 4 H name H 4 is null54)t+is.attributes.put(name1 attribute)return t+is$ public >eneric8:O a""Strin7(Strin7 name1 Strin7 value) # notAull(name1 4Attribute name cannot be null4)notAull(value1 4Attribute ,it+ nameG 4 H name H 4 is null54)t+is.attributes.put(name1 ne, Strin7:'pe(null1value))return t+is$ %%some a""@ met+o"s ommitte"

4:2
Download at WoweBook.Com

public >eneric8:O remove(Strin7 name) # notAull(name1 4Attribute name cannot be null4)t+is.attributes.remove(name)return t+is$ public >eneric8:O a""Relation(Strin7 relationAame1 >eneric8:O 7eneric8:O) # notAull(relationAame1 4:+e name o( t+e relation cannot be null 54)notAull(7eneric8:O1 4:+e tar7et cannot (or t+e relation ,it+ name 4 H relationAame H 4 be null4)a"":ar7et(relationAame1 7eneric8:O)return t+is$ private >eneric8:O a"":ar7et(Strin7 relationAame1 >eneric8:O tar7et) # Set.>eneric8:O0 tar7ets D t+is.relations.7et(relationAame)i( (tar7ets DD null) # tar7ets D ne, as+Set.>eneric8:O0()t+is.relations.put(relationAame1 tar7ets)$ tar7ets.a""(tar7et)return t+is$ public Attribute 7et(Strin7 name) # notAull(name1 4Attribute name cannot be null4)return t+is.attributes.7et(name)$ public Set.>eneric8:O0 7et:ar7ets(Strin7 name) # notAull(name1 4:+e name o( t+e relation cannot be null 54)return t+is.relations.7et(name)$ public >eneric8:O 7et:ar7et(Strin7 name) # notAull(name1 4:+e name o( t+e relation cannot be null 54)return t+is.relations.7et(name).iterator().next()$ public <terator.Strin70 7etAttributeAames() # return t+is.attributes.9e'Set().iterator()$ public <terator.Strin70 7etRelationAames() # return t+is.relations.9e'Set().iterator()$ public <terator.Attribute0 7etAttributes() # return t+is.attributes.values().iterator()$ public <terator.Set.>eneric8:O00 7et:ar7ets() #

4:3
Download at WoweBook.Com

return t+is.relations.values().iterator()$ public >eneric8:O vali"ate() t+ro,s Composite?ali"ation)xception # Set.6ap.)ntr'.Strin71 Attribute00 attibute)ntries D t+is.attributes.entr'Set()<terator.6ap.)ntr'.Strin71 Attribute00 attribute<terator D attibute)ntries.iterator()Composite?ali"ation)xception composite?ali"ation)xception D ne, Composite?ali"ation)xception(t+is.name)6ap.)ntr'.Strin71 Attribute0 entr' D null,+ile (attribute<terator.+asAext()) # tr' # entr' D attribute<terator.next()Attribute attribute)ntr' D entr'.7et?alue()attribute)ntr'.vali"ate()$ catc+ (?ali"ation)xception ex) # composite?ali"ation)xception.a""(entr'.7etYe'()1 ex)$ %%some vali"ation errors occure" i( (5composite?ali"ation)xception.is)mpt'()) # t+ro, composite?ali"ation)xception$ $ return t+is$ public int 7etAumberO(Attributes() # return t+is.attributes.si=e()$ public boolean is)mpt'() # return (t+is.attributes.is)mpt'() ^^ t+is.relations.is)mpt'())$

5he >eneric8:O is not type-sa"e b t very dynamic. +t allo's the <ltering o" attrib tes and there"ore gro'ing and shrin#ing on demand. Eith this approach$ itRs trivial to send only attrib tes intended "or a partic lar sec rity role over the 'ire. A statically typed 5, cannot provide s ch He>ibilityS all its <elds have to be send any'ay. Qo 'ill get a problem d ring the interpretation o" the classical 5,s contents on the client side. +t is impossible to disting ish bet'een <elds that are empty or sho ld be not visible to the ser 'itho t additional metadata. 5he metadata does not have to be de<ned in annotations statically$ it can also be provided on the Hy. 5his is especially interesting "or applications 'ith content management system (C(.) " nctionality behind. +n that case$ the metadata can be even stored in a database and accessed 'ith *PA entities. 5he attrib tes are reali?ed as classes 'ith the ability to constr ct itsel" "rom Strin7. 5he validation logic is implemented in the concrete attrib te type. +n this e>ample$ the reg lar

4:8
Download at WoweBook.Com

e>pressions are sed "or the validation. 5he validation is not limited to reg lar e>pressions$ b t they are s "<cient "or the ma=ority o" all cases.
public inter(ace Attribute.:0 exten"s Seriali=able# public public public public public public $ voi" vali"ate() t+ro,s ?ali"ation)xceptionvoi" instantiate&romStrin7(Strin7 content)voi" setRe7exp(Strin7 re7)xp)voi" set<"(): 7et?alue()boolean is<"()-

5he Abstract:'pe is generic and provides the common in"rastr ct re "or concrete attrib tes. +t delegates the constr ction to the s btypesIit is an implementation o" the 5emplate pattern$ as sho'n in the "ollo'ing e>ample%
public abstract class Abstract:'pe.:0 implements Attribute # private : t D nullprotecte" Strin7 re7)xpprivate Strin7 contentAsStrin7 D nullprivate boolean i" D (alseprivate Pattern p D nullprivate 6atc+er m D nullpublic Abstract:'pe(Strin7 re7)xp) # t+is.setRe7exp(re7)xp)$ public voi" instantiate&romStrin7(Strin7 content) # t+is.contentAsStrin7 D contentt D construct(content)$ protecte" abstract : construct(Strin7 content)public voi" vali"ate() t+ro,s ?ali"ation)xception# i((t+is.re7)xp 5D null)# m D p.matc+er(t+is.contentAsStrin7)boolean vali" D m.matc+es()i((5vali")# t+ro, ne, ?ali"ation)xception(t+is.re7)xp1t+is.contentAsStrin7)$ $ $ public voi" setRe7exp(Strin7 re7)xp) # t+is.re7)xp D re7)xpcompileRe7exp()$ public : 7et?alue() # return t$

4:2
Download at WoweBook.Com

public boolean is<"() # return t+is.i"$ public voi" set<"() # t+is.i" D true$ private voi" compileRe7exp() # i( (t+is.re7)xp 5D null) # p D Pattern.compile(t+is.re7)xp)$ $ $

Beca se all attrib tes can represent itsel" as a Strin7$ the contents can be already validated in the Abstract:'pe class. +t ses the compiled reg lar e>pression to validate the in a Strin7 seriali?ed content. 5he remaining responsibility o" the concrete type is the conversion o" a Strin7 to the payload implementing the abstract construct method. 5he "ollo'ing e>ample sho' a generic intattrib te%
public class <nt:'pe exten"s Abstract:'pe.<nte7er0# public <nt:'pe(Strin7 re7)xp) # super(re7)xp)$ public <nt:'pe(Strin7 re7)xp1Strin7 contentAsStrin7) # super(re7)xp)t+is.instantiate&romStrin7(contentAsStrin7)$ public <nt:'pe()# t+is(null)$ protecte" <nte7er construct(Strin7 content) # return <nte7er.parse<nt(content)$ $

5he sample above implements only one Havor o" the basic generic ;5, idea. Be"ore yo are going to implement yo r o'n 5, "rame'or# it is better to rely on e>isting semi standards. ,ne pop lar library is the Apache BeanUtils library (http%CCcommons.apache.orgCbean tilsC). -specially the vario s reali?ations o" the or7.apac+e.commons.beanutils.8'naBean inter"ace provide similar implementations$ 'ith a map-li#e AP+. 5here is also a "ormali?ed and even lang age-ne tral reali?ation o" the generic ;5, available. 5he *.6-232$ .ervice ;ata ,b=ects (.;,) is not only standardi?ed by the *CP$ b t is maintained by the ,pen .,A initiative ('''.osoa.orgCdisplayC(ainC.erviceW;ataW,b=ectsW)omeM). 5he

4::
Download at WoweBook.Com

.;, speci<cation describes the idea o" a disconnected graph o" ob=ects 'ith implemented change trac#ing. 5he tree o" .;, 5,s can be sent bac# and "orth bet'een the client and the service. 5he ob=ects and relations can be modi<edS the change set 'ill be a tomatically comp ted by the "rame'or# and can be sent bac# to the origin service. 5he .;, AP+ emphasi?es its reHective nat reS everything is a 8ataObject that consists o" Properties 'ith their :'pes. 5he generic ;5, is rather an e>ception$ than a general 'ay o" data transportation. +t can be e"<ciently sed "or the implementation o" master data management or generic se cases s ch as C67;. +ts ma=or dra'bac# is the e>plosion o" instances needed "or transportation. !or every attrib te at least t'o instances are neededS one "or the #ey and one "or the val e. 5he metadata has to be carried either$ so at least one additional instance is reB ired. +n best case yo 'ill get three times more instances "or every attrib te$ comparing the generic ;5, to a statically typed 5,. +t doesnRt have to be a real problem in practice$ b t yo have to be a'are o" it. 5he main advantage o" a generic 5, is its ma=or dra'bac# at the same time. 5he lac# o" typing ma#es its content very dynamic$ b t hard to develop and maintain. 5he +;- s pport is very limitedS a tocompletion 'or#s only "or the generic ;5, AP+ and not its contents.

5esting
5,s are d mb data str ct res 'ith very simple inter"ace. -very attrib te o" a type-sa"e 5, is e>posed 'ith$ in most cases by the +;--generated$ getter and setter pair. Detters and setters are empty in the vast ma=ority o" all cases. 5here is really no need to test d mb accessors. ;espite their straight"or'ard str ct re$ 5,s are tested in practice too heavily. 5he main driver is the T ality ;epartment (TA)$ 'hich prescribes a certain amo nt o" test coverage and the "astest 'ay to achieve good test coverageS is the generation o" nit tests "or getters and setters. A generic 5, is an e>ception "rom the r le. +t isnRt type-sa"e and hard to deb g. At least its generic " nctionality has to be tested once.
2:est public voi" construction()# >eneric8:O "to D nullStrin7 "escription D 4"escription4Strin7 name D 4name4Strin7 numberO(Pa7es D 4numberO(Pa7es4tr' # "to D ne, >eneric8:O(4Boo94). a""Strin7("escription1 48u9eWs A"ventures4). a""Strin7(name1 4*ava4). a""<nt(numberO(Pa7es1 UR). vali"ate()$ catc+ (Composite?ali"ation)xception ex) # (ail(4Aot excecte" 4 H ex)$ int numberO(Attributes D "to.7etAumberO(Attributes()assert)quals(4S+oul" be t+ree41S1numberO(Attributes)-

4:0
Download at WoweBook.Com

assert&alse(4>eneric8:O isnWt empt'41"to.is)mpt'())Object "escription?alue D "to.7et("escription).7et?alue()assertAotAull("escription?alue)assert)quals(48u9eWs A"ventures41"escription?alue)$

! rthermore the a generic ;5, sho ld be tested together 'ith its generic controllers C models co nterparts "rom the presentation layer. +tRs almost d c# typingIan attrib te 'hose name is d ck co ld be a d c#Iit 'ill event ally t rn o t a"ter casting.

;oc mentation
5he 5, principle is straight"or'ard. +tRs s "<cient to describe the idea 'ith one short e>ample and the strategy in the 'i#i once and re"erence it "rom code sing e.g. the 2:O annotation. +n addition a 5, sho ld be recogni?able by its name. 5his can be achieved 'ith a 5, s "<>$ "or e>ample$ Boo9:O. 5,s are mostly motivated by the shortcomings o" the technology$ and not the act al " nctional reB irements. +n addition they represent an already e>isting b siness entity. 5here"ore it is not recommended to capt re them 'ith an 7(9 tool. . ch diagrams 'o ld contain red ndant in"ormation (violate the ;6Q principle) and there"ore 'o ld be harder to model$ nderstand and #eep in sync 'ith the code.

ConseB ences
9ot ,2:: +(s are a re!lication of already e6isting infor*ation. +hey have to -e ke!t in sync /ith the -,siness entity or another re!resentation of the conce!t. &eaky abstractions: A "+( /as originally intended to deco,!le the do*ain o-.ects fro* its ,sers. +his enca!s,lation or a-straction is leaky. &n !ractice1 the "+(s are *aintained in !arallel to the do*ain entities. (ther/ise the changes in the -,siness logic /o,ld not -e visi-le for the !resentation co*!onents. &n *ost cases1 the c,sto*er only /ants an additional field in the for*1 /hich res,lts in the e6tension of all layers -ack to the !ersistence. Per"va ue semantics: +he original na*e of a +( /as val,e o-.ect. &t already i*!lied its !er'val,e se*antics in contrast to !er'reference. A +( is in fact a co!y of a data-ase record or JPA entity. +his can -eco*e a !ro-le* in a transactional syste*. Every "A( fetches o!eration res,lts in a ne/ co!y of a +( in a single transaction. +his is an essential difference to the -ehavior of *anaged JPA entities. )ntit'6ana7er /ill al/ays ret,rn the sa*e reference to an already kno/n o-.ect in the sa*e transaction. Heavy ,se of +(s can lead to inconsistencies and lost ,!dates1 even inside a transaction. )ynthetic entity: +(s can re!resent a conce!t in "R= *anner as /ell. Es!ecially legacy reso,rces and syste*s are not accessi-le via JPA1 often only a dataset'oriented AP& (J#A1 J"B#) is availa-le. A +( can !rovide an o-.ect'oriented vie/ to s,ch syste*s. +hen1 ho/ever1 it is either read'only1 or every +( change has to -e *an,ally synchroni5ed /ith the -ack'end reso,rce.

4:1
Download at WoweBook.Com

6elated Patterns
6elated patterns are ;ata Access ,b=ect$ .ervice !a@ade$ and .ervice. 5hey can cons me and prod ce ;5,s in addition to reg lar entities.

4:9
Download at WoweBook.Com

Download at WoweBook.Com

EJB

'ntegration and .igration

5here is no dearth o" e>isting *2-- applications. 5hese legacy applications have to be migrated to -*B 3 or at least integrated 'ith ne' *ava -- 2C: applications. 5he e>isting -*B 2 components are accessible "rom o tside sing the traditional */;+ loo# p$ 'ith 6(+ (*6(P) or ++,P protocol. -*B 3 s pports more e"<cient and intelligent 'ays to leverage the e>isting " nctionality.

Problem
-*B 3 is a great simpli<cation o" the -*B 2 speci<cation and red ces red ndancies. -*B 3.4 has only a "raction o" the arti"acts reB ired to implement the same behavior as -*B 2. +ronically$ the -*B versions prior 3.0 'ere nderspeci<ed$ the missing parts had to be con<g red in proprietary deployment descriptors. 5his in"ormation can get lost d ring the migration. +t is al'ays problematic in case o" cross-vendor migration$ beca se every vendor o""ered a di""erent set o" proprietary "eat res. .ession beans and message-driven beans are not the act al problem$ in 'orst case the proprietary pooling and caching in"ormation gets lost. (ore challenging$ b t still viable$ is the migration o" C(P 2.4 entities to *PA.

!orces
+he legacy EJB 2.& so,rce code is still availa-le. &t is likely that yo, /ill have to e6tend and *aintain the legacy code. A significant a*o,nt of ne/ feat,res is in the !i!eline. ;nit tests are availa-le1 or yo, have eno,gh ti*e to !rovide these. )e/ f,nctionality is !lanned to -e /ritten /ith EJB 3.&.

.ol tion
Qo have t'o viable and similar strategies to approach this problem% Accessing and in.ecting e6isting EJB 2.& co*!onents fro* EJB 3 %igrating the EJB 2 co*!onents to EJB 3

5he latter sol tion is in the long term the most promising one. -*B 3.4 components are lean and concise. A migration "rom -*B 2 to -*B 3 enco rages the removal o" many s perH o s$ in"rastr ct ral arti"acts and there"ore has a positive e""ect on the maintainability. 5he s al -*B 2.> s spects s ch as ome$ 3ocal ome$ Remote$ and Remote ome inter"aces respectively$ as 'ell as the implementation o" the SessionBean inter"ace and the li"ecycle methods became s perH o s 'ith the advent o" -*B 3.0. (ore precisely% these arti"acts are optional$ so yo can still deploy -*B 3.> beans 'ith the -*B 2.> ballast. B t yo sho ldnRt go too "ar and migrate the old ejb/jar.xml < les and especially the proprietary descriptors to -*B 3. +nstead o" porting the pl mbing$ it is easier to designate the e>isting -*B 2 components 'ith "e' annotations 'itho t heavy re"actoring. +t is eno gh to deploy them as " lly "eat red -*B 3. A"ter s ccess" l migration and testing$ yo co ld remove the pl mbing (home and

Download at WoweBook.Com

remote inter"aces). 5his$ ho'ever$ reB ires a little bit more o" man al 'or#$ beca se the -*B contract 'ill change and reB ire the compilation o" its clients as 'ell. 5o migrate an -*B 2." to -*B 3 yo 'ill have to per"orm the "ollo'ing steps% Set ,! a #ontin,,s &ntegration (#&) environ*ent s,ch as h,dson (htt!HCCh,dson.dev..ava.net). +his ste! is not *andatory -,t highly reco**ended. #heck the e6istence and 8,ality of ,nit tests. &f they do not e6ist1 create and e6ec,te the* on the legacy code. &ntegrate the* /ith #&. ;se the* to verify the *igration. "elete all I%9 de!loy*ent descri!tors. Annotate the EJB 2.& Bean class /ith the 2Stateless annotation and e6!ose its 3ocal ome or Remote ome res!ectivelyH
)Stateless )@ocalHome(@e+acyCacade@ocalHome.class) public class 3e7ac'&aca"eBean implements SessionBean

Re!lace look,!s /ith "e!endency &n.ection. +he Re*ote or 9ocal Ho*e get in.ected1 not the Re*ote C 9ocal interfaces1 as it is the case of EJB 3H
public class 3e7ac'&aca"eBean implements SessionBean # 2)*B private 3e7ac'Service3ocal ome +ome-

#reate the Re*ote and 9ocal interfaces /ith the in.ected ho*e instances as is co**on in EJB 2.&. +his sho,ld ha!!en at the -eginning of the EJB 2 lifecycle1 in the *ethods setSessionContext1 or ejbCreate. &n general1 the references -et/een the -eans /ere resolved ,sing the Service 9ocator !attern or dedicated hel!er *ethods. +his a!!roach -eco*es s,!erfl,o,s after the *igration inside the container1 -,t it nicely si*!lifies the !rocess. All Service 9ocator occ,rrences or ,tility *ethod invocations can -e safely re!laced /ith "e!endency &n.ection. =o, can resolve the references -et/een -eans in la5ily or eager /ay. =o, sho,ld code in res!ect to the e6isting strategy and *odify as little code as !ossi-le.
private 3e7ac'Service3ocal loo9up3e7ac'ServiceBean() # tr' # return t is. ome.create(); $ catc+ (Create)xception ex) # t+ro, ne, )*B)xception(ex)$ $ public Strin7 7et6essa7e() # return 4@4 H t+is.loo9up3e7ac'ServiceBean().7etCurrent:ime()$

Alternatively yo, co,ld ,se traditional look,!s instead of "&. +his a!!roach is es!ecially ,sef,l for a!!lications /itho,t centrali5ed Service 9ocator or a consistent look,! strategy. =o, co,ld re,se yo,r e6isting look,! *echanis* in the EJB 3 container1 .,st -y resolving the Bean references /ith an additional annotation. +he na*e attri-,te in the 2)*B annotation has to corres!ond /ith the javaGcomp%env look,! na*e. 0or the

402
Download at WoweBook.Com

follo/ing sa*!le1 the look,! na*e /o,ld -e javaGcomp%env%ejb%3e7ac'Service3ocalG


2)*B(name D 4ejb%3e7ac'Service3ocal41 bean<nter(ace D 3e7ac'Service3ocal ome.class) public class 3e7ac'&aca"eBean implements SessionBean #

&t is very likely1 that the code /ill co*!ile1 de!loy1 and even /ork. =o, sho,ld1 ho/ever1 re'e6ec,te the load and stress tests. +he *igration can only -e considered as s,ccessf,l in case these tests !ass. After s,ccessf,l e6ec,tion of integration and load tests1 yo, co,ld consider to incre*entally re*ove the s,!erfl,o,s Ho*e and Re*ote interfaces and refactor the co*!onents into tr,e EJB 3. +his ste! is o!tional1 -,t highly reco**ended. &t increases the risk of *igration1 -eca,se yo, /ill have to re*ove lots of code and introd,ce the -,siness interface or the no'interface vie/.

,nly the bean implementation 'as to ched. 5he 9ocal and 6emote )ome as 'ell as 9ocal and 6emote inter"aces remain nchanged. 5his is essential beca se this 'ill not brea# the e>isting clients. 5he C(P 2." persistence is harder to migrate$ b t a systematic migration is still possible. 5o migrate C(P 2." persistence "ollo' these steps% Search for co**on !atterns. So*eti*es #%P 2.6 entities i*!le*ented a -,siness interface. &t /as an interface that e6!osed the accessors as /ell as the relations in a clean /ay. Reali5e this interface /ith a JPA entity and yo, are done. I"oclet Jhtt!HCC6doclet.so,rceforge.netK generated ho*e1 local interface1 de!loy*ent descri!tors as /ell as +(s. +(s are act,ally interesting1 -eca,se they /ere ,sed as act,al !ara*eters and ret,rn val,e of the #%P 2.6 cons,*ers (session -eans). +his +( is a concrete class /ith accessors1 as /ell as *ethods for relation *anage*ent and can -e directly *igrated to a JPA entity. Re*ove all s,!erfl,o,s -ookkee!ing *etadata (internal collections1 *ethods and so on) and ,se the +( as JPA entity candidate. 0or the *igration to JPA1 the necessary *etadata has to -e !rovided as annotations or orm.xml config,ration. +he e6isting ejb/jar.xml and vendor's!ecific de!loy*ent descri!tors !rovide val,a-le (R infor*ation. I"oclet genereted additional -ookkee!ing collections for re*oved C changed o-.ect inside the +(s1 /hichsho,ld -e *arked as 2:ransient in the first iteration and can -e safely re*oved after s,ccessf,l tests and refactoring. &f there is neither a -,siness interface nor I"oclet1 yo, can !ort the #%P 2.& entities directly to JPA. +he signat,re of the 9ocal interface can -e ,sed as a hint or te*!late for the i*!le*entation of JPA entities. +he 9ocal Ho*e interface itself is a "A( candidate Ait -asically *anages the #%P 2.& entity.

5he migration o" the persistence layer is the most challenging$ b t at the same time$ the most re'arding tas#. A"ter the migration process$ the deployment descriptor$ the )ome and 9ocal inter"aces$ the Bean class$ and the generated ;5, 'ill collapse into a single *PA entity.

403
Download at WoweBook.Com

.o "ar$ +Rve described the migration o" -*B 2 into -*B 3 components. B t yo co ld even deploy the -*B 2 session beans into the -*B 3 container. 5his only 'or#s$ i" yo are pgrading the application server and not changing the vendor. ,nly then can the proprietary deployment descriptors be " lly leveraged 'ith no additional e""ort. -ven in this case$ yo sho ld al'ays pre"er migration over integration. +n the long term$ yo 'ill have to migrate. 5he migration process cleans the code and removes a lot o" pl mbing and repetition.

.trategies
+n the case o" -*B2 integration and migration$ yo have t'o strategies. Single'vendor %igration +" yo do not change the application server$ the migration is li#ely to be painless. Qo co ld even deploy the e>isting components <rst$ integrate them 'ith the -*B 3 logic$ 'rite the tests$ and re"actor incrementally. #ross'vendor %igration -*B 2." 'ere nderspeci<ed$ so that the really interesting in"ormation is contained in proprietary deployment descriptors. 5hese descriptors are not portable. +t is even nli#ely$ that the speci<c$ proprietary "eat res can be ported bet'een the vendors at all. Qo sho ld start 'ith the mapping o" " nctionality and chec# 'hether a s ccess" l -*B 2 port is act ally possible. ,n the other hand$ the migration "rom 2." to 3." speci<cation 'or#s 'ell even in the cross-vendor scenario.

ConseB ences
!aintainabi ity: +he *igration fro* EJB 2 to 3 *akes it easier to *aintain yo,r code. A radical *igration /ill re*ove the !l,*-ing co*!letely. Testabi ity: EJB 3 co*!onents are easy to test1 even o,tside the container. +his is not tr,e for the EJB 2 co*!onents. ,ep oyment: +he EJB 3 -,ild !rocess is si*!ler and faster -eca,se the additional generation ste!s (for e6a*!le1 I"oclet tasks) are no *ore re8,ired. +his shortens the -,ild and increases significantly !rod,ctivity. Portabi ity: EJB 3 co*!onents are !orta-le. =o, need neither !ro!rietary nor standard de!loy*ent descri!tors. -ntegration capabi ities: 9egacy EJB 2 co*!onents as /ell as *igrated EJB 2 co*!onents can -e easily accessed fro* EJB 3.

5esting
5he s ccess o" the entire migration or porting process can only be meas red 'ith e>cessive testing. +" there are no testsIthe res lt is npredictable. -specially important are the integration and load tests. 7nit tests are sel"-evident$ b t they only test the e>pected behavior$ 'hich sho ld not change d ring the migration or porting. +ntegration tests$ ho'ever$ might help yo to ncover potential changes ca sed by the paradigm shi"t in the persistence layer. *2-- persistence 'or#s

408
Download at WoweBook.Com

mostly 'ith 5,s$ 'hich are al'ays a copy o" the act al data$ 'hereby the *PA persistence ses the per-re"erence semantics. +n *ava -- 2C: yo are accessing the attached *PA entities directly$ so every change 'ill be p shed bac# to the database at the end o" the transaction.

402
Download at WoweBook.Com

Download at WoweBook.Com

3egacy P0J0 'ntegration


/ot everything is a session bean$ act ally only a minority o" all deployed components today are -*Bs. 5here is an obvio s need to integrate e>isting P,*,s 'ith yo r *ava -- application and access them in a convenient and "rictionless 'ay.

Problem
;ependency in=ection only 'or#s in managed classes s ch as .ervlets$ .ervlet <lters$ event listeners$ tag handlers$ tag library event listeners$ scoped managed beans (*.!)$ service endpoints (*AK-E.)$ handlers (*AK-E.)$ root reso rce classes (*AK-6.)$ providers (*AK-6.)$ and$ o" co rse$ in beans and interceptors itsel". 5hese managed classes are able either to loo# p or to in=ect reso rces or -*Bs "rom the */;+ tree. A legacy class is neither managed nor a reso rce stored in the */;+ tree. ," co rse$ yo can instantiate s ch a class 'ith ne, and se it in the conte>t o" an -*B 3$ b t then the container services s ch as ;ependency +n=ection$ li"ecycle$ and conc rrency management 'o ldnRt be accessible.

!orces
+he integration sho,ld /ork /itho,t legacy code *odificationAit is not al/ays availa-le. +he legacy class sho,ld -e a-le to leverage the container services and !artici!ate in transactions. +he legacy P(J( has to -e co*!liant /ith the EJB 3 !rogra**ing restrictions. +he legacy P(J( has to -e either thread'safe or -e ca!a-le to -e de!loyed as a singleton.

.ol tion
5he sol tion is straight"or'ardIthe legacy P,*, has to be deployed as an -*B 3. 5hen it co ld easily participate in transactions and be managed by the container. ! rthermore$ the P,*, co ld be conveniently in=ected to an already e>isting session bean. 5he reB irements "or an -*B 3.0 session bean are really lo'% A class has to implement an inter"ace and provide a de"a lt constr ctor. +n the -*B 3.4 spec$ the reB irements are even lo'er% yo have to provide the de"a lt constr ctorIno inter"ace is reB ired. 5he only problem is the 2Stateless annotation 'ith 'hich a session bean has to be designated. Qo 'ill have to annotate yo r P,*,$ and this is only possible having so rce code and being able to recompile it. ;ecompilation and recompilation co ld 'or#$ b t this is not al'ays a viable option (= st thin# abo t licensing and legal iss es). !ort nately$ yo can also provide the reB ired metadata in ejb/jar.xml. +nstead o" annotating a class 'ith 2Stateless$ yo can declare it as a Bean in the deployment descriptor. Contrary to the -*B 2.K speci<cation$ it is not an all or nothing principle. Qo can even mi> and match both approaches and se ejb/jar.xml = st to integrate the legacy P,*,s. !or native -*B 3$ yo can still rely on p re annotations. +t is even possible to t rn classes shipped 'ith *;& into -*B 3. Qo only have to declare them as -*B 3 in the ejb/jar.xml. +t is straight"or'ard to deploy the 8e(ault:able6o"el as an -*B 3 and in=ect it into a reg lar session bean.

Download at WoweBook.Com

.ejb/jar0 .enterprise/beans0 .session0 .ejb/name0:able.%ejb/name0 .business/local0javax.s,in7.table.:able6o"el.%business/local0 .ejb/class0javax.s,in7.table.8e(ault:able6o"el.%ejb/class0 .session/t'pe0Stateless.%session/t'pe0 .%session0 .%enterprise/beans0 .%ejb/jar0

5he ejb/jar.xml is straight"or'ard. Qo only have to speci"y the class$ the b siness-local inter"ace and the session bean type (Stateless or State(ul).
2Stateless public class 3e7ac':estBean implements 3e7ac':est # 2)*B :able6o"el table6o"elpublic Strin7 access:able()# return 4Ro, countG 4 H table6o"el.7etRo,Count()$ $

!or the client o" the legacy P,*, there is no di""erence bet'een a reg lar -*B 3 and an integrated P,*,. 5he re"erence is in=ected in both cases. -ven the convention over con<g ration mechanisms 'or#s as s alIi" there is only one implementation o" the inter"ace$ yo do not even have to speci"y it. 5he no-inter"ace vie' introd ced in -*B 3.4 even lets yo integrate classes 'itho t inter"aces. 5he only reB irement here is the e>istence o" an accessible de"a lt constr ctor.

6ethin#ing
+n *2--$ it 'as not possible to deploy P,*,s as -*B 2 'itho t changing the code. ->isting P,*, in"rastr ct re 'as treated as something incompatible and had to be 'rapped 'ith -*B 2. -*B 3 ob=ects are nothing b t annotated P,*,s$ so that the option to deploy e>isting P,*,s as -*B 3 components became not only available$ b t also viable. Bac# in the -*B 2 days$ there 'as a common concern abo t the overhead associated 'ith the containerRs r ntime. +t 'as the advent o" many light'eight and P,*, "rame'or#s and architect res. 5he overhead introd ced by the -*B 3 container is really lo'Iit is act ally only a lean (o"ten dynamic$ pro>y-based) indirection layer bet'een the caller and the bean. 5he overhead is absol tely comparable 'ith other ;ependency +n=ection "rame'or#s. ,n Dlass<sh v2$ the overhead o" an -*B 3 comparing it to the same P,*, is abo t 3 percent and can act ally be meas red (only a "e' milliseconds). 5he synergy bet'een ;ependency +n=ection and convention over con<g ration ma#es a lot o" in"rastr ct ral code s perH o s. 5here is act ally nothing more le"t to optimi?e or remove. Applications b ilt 'ith -*B 3 are leaner (in respect to code$ amo nt o" K(9$ and libraries) than the alternative "rame'or#s or even p re P,*,s.

401
Download at WoweBook.Com

+n *ava -- 2$ yo sho ld = sti"y 'hy yo are not deploying -*Bs and are still relying on P,*,s instead. +t is nothing else than an inversion o" arg mentation.

Participants and 6esponsibilities


5he legacy P,*, implements " nctionality 'hich is interesting "or e>isting *ava -- applications. 5he "or deployment as a session bean necessary meta data is provided as an ejb/jar.xml descriptor. 5he reg lar -*Bs can then get access to the legacy P,*, via ;ependency +n=ection. 5his proced re is totally transparent "or the rest o" the application. 5he P,*, became an -*B 'itho t code modi<cation.

5esting
5he compiler does not chec# K(9 and partic larly not the correctness o" the declared types. 5he legacy P,*, integration sho ld be tested 'ith integration tests to veri"y the in=ection and so on. 9egacy code is al'ays s spicio s regarding thread sa"ety and consistency$ so that load and stress testing is recommended in this case. 7nit tests are irrelevant in this conte>t and only se" l "or the veri<cation o" the e>isting " nctionality o" the legacy P,*,.

;oc mentation
5he ;ependency +n=ection o" a legacy P,*, into a session bean sho ld be doc mented 'ith a short hint in *ava;oc. Qo sho ld mention this strategy in t torials and pragmatic architect ral doc ments as 'ell.

ConseB ences
Portabi ity: =o, do not change the legacy codeAonly additional *eta data is !rovided. +he legacy P(J(s can -e ,sed in another conte6t /itho,t any friction. Performance: +he EJB 3 overhead is very lo/7 on 2lassfish v2 it:s a-o,t 3 !ercent co*!ared to a !lain Java class. +his co*!arison1 ho/ever1 is acade*icAin an enter!rise conte6t1 yo, /ill have to start transactions and *anage P(J(s as /ell. &n that case1 yo, /ill achieve si*ilar !erfor*ance. )ca abi ity: =o, often hear that EJB co*!onents scale -etter than P(J(s -eca,se of !ooling and cl,stering. %ean/hile the !erfor*ance of JB% and gar-age collection /as significantly i*!roved1 so that instance !ooling can even have negative i*!act on scala-ility. &n general1 EJBs can -e considered as ne,tral regarding scala-ility. #l,stering is only availa-le thro,gh re*ote -,siness interfaces and legacy P(J(s are al/ays accessed locally.

6elated Patterns
-*B 2 integration is similar$ ho'ever it 'or#s inverselyIit replaces ejb/jar.xml 'ith annotations$ 'hereby in the legacy P,*, integration$ reg lar *ava classes 'ere introd ced as session beans 'ith ejb/jar.xml.

409
Download at WoweBook.Com

Download at WoweBook.Com

;eneric JCA
5he application server manages the conc rrency$ component li"ecycle$ and reso rce access "or yo . Qo are even not allo'ed to access incompatible reso rces or manage threads in yo r -*Bs.

Problem
+t is not possible to access legacy reso rces s ch as <les$ native libraries$ or starting ne' threads "rom -*Bs 'itho t violating the programming restrictions4. -ven i" the application 'ith violated speci<cation is deployable and all tests pass$ the portability is still not given. 5he application server can become more restrictive 'ith every ne' installed version$ or even patch. ! rthermore$ commercial s pport o"ten re" ses to help in case yo r application does not con"orm to the speci<cation. +" yo 'ant to access an incompatible reso rce 'ithin a transaction$ it 'ill be really hard to implement it "rom -*Bs. Qo 'ill have to s'itch to bean-managed transactions$ or implement the javax.ejb.SessionS'nc+roni=ation inter"ace in a state" l session bean to trac# o" the c rrent transaction stat s. Access to incompatible reso rces$ ho'ever$ is still nsolved.

!orces
=o, have to interact /ith Java EE inco*!ati-le reso,rces. =o, need transactional access to legacy reso,rces. +he legacy reso,rces cannot scale infinitely for technical and licensing reasons7 yo, have to throttle the thro,gh!,t. +he legacy reso,rce has to -e accessi-le fro* EJBs. +he sol,tion sho,ld -e !orta-le across servers. &t is re8,ired (for e6a*!le1 -y o!erations) to *anage and *onitor the connector r,nti*e fro* the ad*inistration console.

.ol tion
5he programming restrictions apply to the -*B container only$ so yo co ld integrate the reso rce in a .ervlet$ (Bean$ or a *CA connector. /either .ervlets nor (Beans can control a transaction declaratively. A *CA adapter$ on the other hand$ can access every -*B-incompatible reso rce yo 'ant as 'ell as actively participate in transactions and 'ithin a sec rity conte>t. +ts li"ecycle and connections are managed by the application server. A *CA connector is the best possible sol tionit is portable$ standardi?ed$ easily accessible$ and managed by the application server. 5he only caveat is its nat re. A *CA connector is a set o" AP+ and .P+ inter"aces$ 'hich have to be implemented <rst. 5his can be comple>$ especially i" yo are trying to implement all "eat res and capabilities. ,n the other hand$ a minimal *CA-implementation is s rprisingly simple. +t comprises t'o inter"aces$ "o r classes$ and one K(9 <le. 5'o classes are highly re sableS the remaining part is reso rce dependent.

Chapter 24.4.2$ *.6 220% -nterprise *avaBeans5($Aersion 3.0$ -*B Core Contracts and 6eB irements

Download at WoweBook.Com

Qo donRt even have to implement the Common Client +nter"ace (CC+). 5his AP+ loo#s very m ch li#e *;BC$ b t is too abstract "or the pro=ect-speci<c$ pragmatic integrations. +nstead o" implementing the 'hole CC+ AP+$ yo co ld provide a c stom inter"ace as 'ell. A *CA adapter is connection-oriented$ so yo 'ill have to map the idea o" a connection to yo r reso rce. +t can be a soc#et connection$ a handle to a native reso rce$ or a re"erence to an open <le (<le descriptor). -*Bs are not allo'ed to access <les$ so transactional <le access is per"ectly s itable "or a *CA implementation.
public inter(ace Connection # public voi" ,rite(Strin7 content)public voi" close()$

A re"erence to a <le maps 'ell to the idea o" connecting to a reso rce. 5he inter"ace Connection represents a pointer to an open <le. 5his inter"ace does not even have to inherit "rom *CA-speci<c arti"acts. 5he ne>t step is the declaration o" the inter"ace "or the Connection "actory. 5he 8ataSource inter"ace is simple as 'ell$ b t it has to inherit "rom the javax.resource.Re(erenceable and java.io.Seriali=able inter"aces%
public inter(ace 8ataSource exten"s Seriali=able1 Re(erenceable # Connection 7etConnection()$

5his allo's the registration o" the 8ataSource in a */;+ conte>t$ 'hich is reB ired "or the in=ection into -*Bs. Qo are not constrained by the naming or signat re o" this inter"ace. 5he names Connection and 8ataSource are absol tely arbitrary. 5he 'hole integration logic "or the <le access is reali?ed in the &ileConnection implementation o" the Connection inter"ace. !or the integration o" more inconvenient reso rces yo co ld se the Connection only as a "a@ade and not the act al implementation o" the integration logic. 5he "ollo'ing e>ample demonstrates the implementation o" the transactional <le access%
pac9a7e ...inte7ration.7enericjca%%...ot+er imports import javax.resource.Resource)xceptionimport javax.resource.spi.ConnectionRequest<n(oimport javax.resource.spi.3ocal:ransactionpublic class &ileConnection implements Connection1 3ocal:ransaction# private Strin7 bu((erprivate &ileOutputStream (ileOutputStreamprivate ConnectionRequest<n(o connectionRequest<n(opublic (inal static Strin7 &<3)JAA6) D 4%temp%jca(ile.txt4private >eneric6ana7e"Connection 7eneric6ana7e"Connectionprivate Print!riter outpublic &ileConnection(Print!riter out1>eneric6ana7e"Connection 7eneric6ana7e"Connection1ConnectionRequest<n(o connectionRequest<n(o) #

412
Download at WoweBook.Com

t+is.out D outout.println(4#&ileConnection 4 H connectionRequest<n(o H 4 4 HtoStrin7())t+is.7eneric6ana7e"Connection D 7eneric6ana7e"Connectiont+is.connectionRequest<n(o D connectionRequest<n(ot+is.initiali=e()$ private voi" initiali=e()# tr' # t+is.bu((er D nullt+is.(ileOutputStream D ne, &ileOutputStream(&<3)JAA6)1true)$ catc+ (&ileAot&oun")xception ex) # t+ro, ne, <lle7alState)xception(4Cannot initiali=e ..G 4 H &<3)JAA6))$ $ public voi" ,rite(Strin7 content) # out.println(4#&ileConnection.,rite 4 H content)t+is.bu((er D content$ public voi" close() # t+is.7eneric6ana7e"Connection.close()$ public voi" "estro'()# out.println(4#&ileConnection.cleanup4)tr' # i((t+is.(ileOutputStream 5D null) t+is.(ileOutputStream.close()t+is.(ileOutputStream D nullt+is.bu((er D null$ catc+ (<O)xception ex) # t+ro, ne, <lle7alState)xception(4Cannot close streamG 4 Hex1ex)$ $ public voi" be7in() t+ro,s Resource)xception # out.println(4#&ileConnection.be7in 4 HtoStrin7())t+is.initiali=e()$ public voi" commit() t+ro,s Resource)xception # out.println(4#&ileConnection.commit 4 HtoStrin7())tr' # t+is.(ileOutputStream.,rite(t+is.bu((er.7etB'tes())t+is.(ileOutputStream.(lus+()t+is.(ileOutputStream.close()$ catc+ (<O)xception ex) # t+ro, ne, Resource)xception(ex)$

413
Download at WoweBook.Com

$ public voi" rollbac9() t+ro,s Resource)xception # out.println(4#&ileConnection.rollbac9 4 HtoStrin7())t+is.bu((er D nulltr' # t+is.(ileOutputStream.close()$ catc+ (<O)xception ex) # t+ro, ne, Resource)xception(ex)$ $ $

5he implementation o" the act al b siness logic$ the method ,rite$ is s rprisingly simpleit stores the parameter in a <eld. 5he &ileConnection is aimed to be transactional$ so it implements the be7in$ commit$ and rollbac9 methods$ 'hich are declared in the 3ocal:ransaction inter"ace. 5he constr ctor and the be7in method initiali?es the stream and opens the <le$ the method commit 'rites the content o" the internal b ""er <eld (the act al b ""er) to the <le. 5he stream is closed and the b ""er cleared in the method rollbac9. 5he method close delegates the invocation to the >eneric6ana7e"Connection$ 'hich 'ill be covered later. 5he ConnectionRequest<n(o is only sed in the equals and +as+Co"e methods. +t is a handle 'hich is sed by the application and the *CA-connector to identi"y the connection. 5he implementation o" the 8ataSource inter"ace$ &ile8ataSource$ is even simpler%
pac9a7e com.abien.patterns.inte7ration.7enericjcaimport import import import import import java.io.Print!riterjavax.namin7.Re(erencejavax.resource.Resource)xceptionjavax.resource.spi.Connection6ana7erjavax.resource.spi.ConnectionRequest<n(ojavax.resource.spi.6ana7e"Connection&actor'-

public class &ile8ataSource implements 8ataSource # private private private private 6ana7e"Connection&actor' mc(Re(erence re(erenceConnection6ana7er cmPrint!riter out-

public &ile8ataSource(Print!riter out16ana7e"Connection&actor' mc(1 Connection6ana7er cm) # out.println(4#&ile8ataSource4)t+is.mc( D mc(t+is.cm D cm-

418
Download at WoweBook.Com

t+is.out D out$ public &ileConnection 7etConnection()# out.println(4#&ile8ataSource.7etConnection 4 H t+is.cm H 4 6C&G 4 H t+is.mc()tr' # return (&ileConnection) cm.allocateConnection(mc(1 7etConnectionRequest<n(o())$ catc+ (Resource)xception ex) # t+ro, ne, Runtime)xception(ex.7et6essa7e())$ $ public voi" setRe(erence(Re(erence re(erence) # t+is.re(erence D re(erence$ public Re(erence 7etRe(erence() # return re(erence$ private ConnectionRequest<n(o 7etConnectionRequest<n(o() # return ne, ConnectionRequest<n(o() # 2Overri"e public boolean equals(Object obj) # return true$ 2Overri"e public int +as+Co"e() # return U$ $$ $

5he accessors to the javax.namin7.Re(erence <eld are needed "or the */;+ registration. 5he method 7etConnection = st delegates the reB est "or the connection to the Connection6ana7er$ 'hich is implemented by the application server. 5he anonymo s implementation o" the ConnectionRequest<n(o inter"ace overrides the equals and +as+Co"e methods. All connections to the <le are eB al$ yo donRt need any di""erentiation bet'een them. +n general$ yo co ld consider sing ser names or connectorspeci<c to#ens to di""erentiate bet'een connections. 5he remaining t'o classes are integration logic agnostic. Qo co ld re se them "or any connector implementation yo 'ant.

412
Download at WoweBook.Com

5he >eneric6ana7e"Connection implements the 6ana7e"Connection inter"ace 'hich belongs to the .P+ and is sed by the application server behind the scenes. 5he main responsibility o" the >eneric6ana7e"Connection is the creation o" the &ileConnection and <ring events 'ith the noti<cation abo t the connection stat s (started$ committed$ rolled bac# and closed).
pac9a7e com.abien.patterns.inte7ration.7enericjca%%java.util.C etc. imports omitte" import javax.resource.Resource)xceptionimport javax.resource.spi.3ocal:ransactionimport static javax.resource.spi.Connection)vent.Cimport javax.resource.spi.Connection)ventimport javax.resource.spi.Connection)vent3istenerimport javax.resource.spi.ConnectionRequest<n(oimport javax.resource.spi.6ana7e"Connectionimport javax.resource.spi.6ana7e"Connection&actor'import javax.resource.spi.6ana7e"Connection6eta8ataimport javax.securit'.aut+.Subjectimport javax.transaction.xa.KAResourcepublic class >eneric6ana7e"Connection implements 6ana7e"Connection1 3ocal:ransaction # private private private private private 6ana7e"Connection&actor' mc(Print!riter out&ileConnection (ileConnectionConnectionRequest<n(o connectionRequest<n(o3ist.Connection)vent3istener0 listeners-

>eneric6ana7e"Connection(Print!riter out16ana7e"Connection&actor' mc(1 ConnectionRequest<n(o connectionRequest<n(o) # t+is.out D outout.println(4#>eneric6ana7e"Connection4)t+is.mc( D mc(t+is.connectionRequest<n(o D connectionRequest<n(ot+is.listeners D ne, 3in9e"3ist.Connection)vent3istener0()$ public Object 7etConnection(Subject subject1 ConnectionRequest<n(o connectionRequest<n(o) t+ro,s Resource)xception # out.println(4#>eneric6ana7e"Connection.7etConnection4)(ileConnection D ne, &ileConnection(out1t+is1 connectionRequest<n(o)return (ileConnection$ public voi" "estro'() # out.println(4#>eneric6ana7e"Connection."estro'4)t+is.(ileConnection."estro'()$

41:
Download at WoweBook.Com

public voi" cleanup() # out.println(4#>eneric6ana7e"Connection.cleanup4)$ public voi" associateConnection(Object connection) # out.println(4#>eneric6ana7e"Connection.associateConnection 4 H connection)t+is.(ileConnection D (&ileConnection) connection$ public voi" a""Connection)vent3istener(Connection)vent3istener listener) # out.println(4#>eneric6ana7e"Connection.a""Connection)vent3istener4)t+is.listeners.a""(listener)$ public voi" removeConnection)vent3istener(Connection)vent3istener listener) # out.println(4#>eneric6ana7e"Connection.removeConnection)vent3istener4)t+is.listeners.remove(listener)$ public KAResource 7etKAResource() t+ro,s Resource)xception # out.println(4#>eneric6ana7e"Connection.7etKAResource4)return null$ public 3ocal:ransaction 7et3ocal:ransaction() # out.println(4#>eneric6ana7e"Connection.7et3ocal:ransaction4)return t+is$ public 6ana7e"Connection6eta8ata 7et6eta8ata() t+ro,s Resource)xception # out.println(4#>eneric6ana7e"Connection.7et6eta8ata4)return ne, 6ana7e"Connection6eta8ata() # public Strin7 7et)<SPro"uctAame() t+ro,s Resource)xception # out.println(4#6'Connection6eta8ata.7et)<SPro"uctAame4)return 4>eneric *CA4$ public Strin7 7et)<SPro"uct?ersion() t+ro,s Resource)xception # out.println(4#6'Connection6eta8ata.7et)<SPro"uct?ersion4)return 4U.R4$ public int 7et6axConnections() t+ro,s Resource)xception # out.println(4#6'Connection6eta8ata.7et6axConnections4)-

410
Download at WoweBook.Com

return X$ public Strin7 7etUserAame() t+ro,s Resource)xception # return null$ $$ public voi" set3o7!riter(Print!riter out) t+ro,s Resource)xception # S'stem.out.println(4#>eneric6ana7e"Connection.set3o7!riter4)out D out$ public Print!riter 7et3o7!riter() t+ro,s Resource)xception # S'stem.out.println(4#>eneric6ana7e"Connection.7et3o7!riter4)return out$ 2Overri"e public boolean equals(Object obj) # %%omitte" return true$ 2Overri"e public int +as+Co"e() # %%omitte" return +as+$ public ConnectionRequest<n(o 7etConnectionRequest<n(o() # return connectionRequest<n(o$ public voi" be7in() t+ro,s Resource)xception # t+is.(ileConnection.be7in()t+is.(ireConnection)vent(3OCA3J:RAASAC:<OAJS:AR:)8)$ public voi" commit() t+ro,s Resource)xception # t+is.(ileConnection.commit()t+is.(ireConnection)vent(3OCA3J:RAASAC:<OAJCO66<::)8)$ public voi" rollbac9() t+ro,s Resource)xception # t+is.(ileConnection.rollbac9()t+is.(ireConnection)vent(3OCA3J:RAASAC:<OAJRO33)8BACY)$

411
Download at WoweBook.Com

public voi" (ireConnection)vent(int event) # Connection)vent connnection)vent D ne, Connection)vent(t+is1 event)connnection)vent.setConnection an"le(t+is.(ileConnection)(or (Connection)vent3istener listener G t+is.listeners) # s,itc+ (event) # case 3OCA3J:RAASAC:<OAJS:AR:)8G listener.local:ransactionStarte"(connnection)vent)brea9case 3OCA3J:RAASAC:<OAJCO66<::)8G listener.local:ransactionCommitte"(connnection)vent)brea9case 3OCA3J:RAASAC:<OAJRO33)8BACYG listener.local:ransactionRolle"bac9(connnection)vent)brea9case COAA)C:<OAJC3OS)8G listener.connectionClose"(connnection)vent)brea9"e(aultG t+ro, ne, <lle7alAr7ument)xception(4Un9no,n eventG 4 H event)$ $ $ public voi" close() # t+is.(ireConnection)vent(COAA)C:<OAJC3OS)8)$ $

5he event noti<cation is important. 5he application server is listening "or these events and ses the in"ormation to "ree connections "rom the pool. Eitho t these event noti<cations$ yo r pool 'ill go empty and bloc#. 5he remaining methods are straight"or'ard$ b t necessary pl mbing. 5he >eneric6ana7e"Connection&actor' implements$ in t rn$ the 6ana7e"Connection&acator' inter"ace and is responsible "or the creation o" the &ile8ataSource and the >eneric6ana7e"Connection instances.
pac9a7e com.abien.patterns.inte7ration.7enericjca%%java.io.C etc. imports omitte" import javax.resource.Resource)xceptionimport javax.resource.spi.Cimport javax.securit'.aut+.Subjectpublic class >eneric6ana7e"Connection&actor' implements 6ana7e"Connection&actor'1 Seriali=able # private Print!riter outpublic >eneric6ana7e"Connection&actor'() # out D ne, Print!riter(S'stem.out)$

419
Download at WoweBook.Com

public Object createConnection&actor'(Connection6ana7er cx6ana7er) t+ro,s Resource)xception # return ne, &ile8ataSource(out1t+is1 cx6ana7er)$ public Object createConnection&actor'() t+ro,s Resource)xception # return ne, &ile8ataSource(out1t+is1 null)$ public 6ana7e"Connection create6ana7e"Connection(Subject subject1 ConnectionRequest<n(o in(o) # return ne, >eneric6ana7e"Connection(out1t+is1 in(o)$ public 6ana7e"Connection matc+6ana7e"Connections(Set connectionSet1 Subject subject1 ConnectionRequest<n(o in(o) t+ro,s Resource)xception # (or (<terator it D connectionSet.iterator()- it.+asAext()-) # >eneric6ana7e"Connection 7mc D (>eneric6ana7e"Connection) it.next()ConnectionRequest<n(o connectionRequest<n(o D 7mc.7etConnectionRequest<n(o()i(((in(o DD null) ZZ connectionRequest<n(o.equals(in(o)) return 7mc$ t+ro, ne, Resource)xception(4Cannot (in" connection (or in(o54)$ public voi" set3o7!riter(Print!riter out) t+ro,s Resource)xception # t+is.out D out$ public Print!riter 7et3o7!riter() t+ro,s Resource)xception # return t+is.out$ $

5he method matc+6ana7e"Connection is intended to <nd a partic lar connection "rom a set o" available connections sing the already described ConnectionRequest<n(o ob=ect. 5he remaining boo##eeping methods are sel"-e>planatory. !inally$ yo 'ill have to 'rite the ra.xml deployment descriptor$ 'hich contains all the inter"aces and implementations.
.connector xmlnsD4+ttpG%%java.sun.com%xml%ns%jIee4 xmlnsGxsiD4+ttpG%%,,,.,S.or7%IRRU%K63Sc+ema/instance4 xsiGsc+ema3ocationD4+ttpG%%java.sun.com%xml%ns%jIee +ttpG%%java.sun.com%xml%ns%jIee%connectorJUJX.xs"4 versionD4U.X40 ."ispla'/name0>eneric *CA.%"ispla'/name0 .ven"or/name0a"am/bien.com.%ven"or/name0 .eis/t'pe0>eneric *CA.%eis/t'pe0 .resourcea"apter/version0U.R.%resourcea"apter/version0 .resourcea"apter0

490
Download at WoweBook.Com

.outboun"/resourcea"apter0 .connection/"e(inition0 .mana7e"connection(actor'/ class0.7enericjca.>eneric6ana7e"Connection&actor'.%mana7e"connection(actor'/ class0 .connection(actor'/inter(ace0.7enericjca.8ataSource.%connection(actor'/ inter(ace0 .connection(actor'/impl/ class0.7enericjca.&ile8ataSource.%connection(actor'/impl/class0 .connection/inter(ace0.7enericjca.Connection.%connection/ inter(ace0 .connection/impl/class0.7enericjca.&ileConnection.%connection/ impl/class0 .%connection/"e(inition0 .transaction/support03ocal:ransaction.%transaction/support0 .aut+entication/mec+anism0 .aut+entication/mec+anism/t'pe0BasicPass,or".%aut+entication/mec+anism/t'pe0 .cre"ential/ inter(ace0javax.resource.spi.securit'.Pass,or"Cre"ential.%cre"ential/inter(ace0 .%aut+entication/mec+anism0 .reaut+entication/support0(alse.%reaut+entication/support0 .%outboun"/resourcea"apter0 .%resourcea"apter0 .%connector0

Qo start the transactions on the application server and propagate them into the e>ternal reso rce$ so it has to be declared as an outboun"/resourcea"apter. 5he descriptor contains the classes described in this e>ample in the corresponding K(9 tags. Eriting the ra.xml deployment descriptor isnRt very hardIyo can se any K(9 editor 'ith K.; validation "or this p rpose. 5he compiled classes and the ra.xml descriptor have to be archived into a .rar <le. 5he connector is deployed = st as any other -A6Imainly dropping the archive into an a todeploy directory. 5he last step is application server speci<c. Qo 'ill have to set p the connection pool and deploy the data so rce nder a */;+ name o" yo r choice. 5he connector sho ld be available in the */;+ tree and ready "or se. 5he 8ataSource inter"ace can be easily in=ected into a bean o" yo r choice sing the 2Resource annotation. 5he val e o" the attrib te name or mappe"Aame has to correspond to the con<g red */;+ name. 5he "ollo'ing e>ample demonstrates ho' to se o" the *CA connector in a session bean%
import import import import import com.abien.patterns.inte7ration.7enericjca.Connectioncom.abien.patterns.inte7ration.7enericjca.8ataSourcejavax.annotation.Resourcejavax.ejb.SessionContextjavax.ejb.Stateless-

2Stateless public class *CAClientBean implements *CAClientRemote # 2Resource(nameD4jca%&ile&actor'4) private 8ataSource "ataSource-

494
Download at WoweBook.Com

2Resource private SessionContext contextpublic voi" access&ile(Strin7 content)# Connection connection D "ataSource.7etConnection()connection.,rite(content)connection.close()$ public voi" access&ileAn"Rollbac9(Strin7 content)# Connection connection D "ataSource.7etConnection()connection.,rite(content)context.setRollbac9Onl'()$ public voi" access&ileAn":+ro,)xception(Strin7 content)# Connection connection D "ataSource.7etConnection()connection.,rite(content)t+ro, ne, Runtime)xception(4&orce Rollbac94)$ $

5o compile the -*B yo 'ill only need the Connection and 8ataSource inter"aces. 5he generic *CA participates in declarative transactions started by the -*BIit is completely transparent to the developer. 5he method access&ile starts a ne' transaction$ 'hich is propagated to the *CA connector. 5he &ileConnection is noti<ed by the container at the commit time and H shes the contents o" its b ""er to the <le.
#&ile8ataSource.7etConnection #>eneric6ana7e"Connection&actor'.create6ana7e"Connection #>eneric6ana7e"Connection #>eneric6ana7e"Connection.a""Connection)vent3istener #>eneric6ana7e"Connection&actor'.matc+6ana7e"Connections #>eneric6ana7e"Connection.7etConnection #&ileConnection #>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.be+in HCile0onnection.(rite a #>eneric6ana7e"Connection.cleanup #>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.commit

5he method access&ileAn"Rollbac9 as#s "or rolling bac# the c rrent transaction 'ith the invocation o" SessionContext#setRollbac9Onl'. 5he connector is noti<ed as 'ell. the "ollo'ing snippet sho's the tracing o tp t%
#&ile8ataSource.7etConnection #>eneric6ana7e"Connection&actor'.matc+6ana7e"Connections #>eneric6ana7e"Connection.7etConnection #&ileConnection #>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.be+in HCile0onnection.(rite a

492
Download at WoweBook.Com

#>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.rollbac3

!inally the method access&ileAn":+ro,)xception "orces the container to roll bac# the transaction by thro'ing a Runtime)xception.
#&ile8ataSource.7etConnection #>eneric6ana7e"Connection&actor'.matc+6ana7e"Connections #>eneric6ana7e"Connection.7etConnection #&ileConnection #>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.be+in HCile0onnection.(rite a #>eneric6ana7e"Connection.cleanup #>eneric6ana7e"Connection.7et3ocal:ransaction HCile0onnection.rollbac3 javax.ejb.)*B)xception at com.sun.ejb.containers.BaseContainer.processS'stem)xception(BaseContainer.javaGS _V`)

5he *CA connector 'or#s as e>pected and rolls the transaction bac# "or yo . 5his c stom connector co ld be easily e>tended to s pport KA transactions and more complete <le handling. 5he Apache Commons !ile 5ransactions pro=ect (http%CCcommons.apache.orgCtransactionC<leCinde>.html) provides a 'or#ing implementation "or KA-compliant <le access. +t co ld be easily 'rapped 'ith the generic *CA connector as 'ell.

6ethin#ing
5he *CA connector e>ample +Rve described here is nothing ne'. Aersion 4.0 has been available since 2004 and 'as one o" the <rst *.6s (*.6 4:). Aersion 4.2 has been available since 2003 and is speci<ed in the *.6 442. 5he problem is not the act al comple>ity$ rather than the common perception o" it. A c stom *CA adapter implementation can be the easiest and the most pragmatic choice. +t becomes comple> i" yo are going to implement the entire spec 'hich is neither needed nor reB ired. ,n the other hand$ home-gro'n 'or#aro nds that bypass the container are more comple> (and li#ely to be erroneo s) than a straight"or'ard *CA implementation.

Conventions
A *CA adapter implementation is a standard application server e>tension$ not application code. Qo r applications 'ill se the connector 'itho t having the so rce code and #no'ing the implementation details. /onetheless$ it is reasonable to "ollo' some conventions% +he connector i*!le*entation -elongs to the integration layer1 so it sho,ld -e !laced into the inte7ration !ackage. &f yo, are going to !rovide a c,sto* connector interface1 yo, sho,ld se!arate the internal i*!le*entation fro* the !,-lic AP&. +he !,-lic AP& is needed for the co*!ilation of the client a!!lications1 so it /ill have to -e distri-,ted as a standalone li-rary. +he connector

493
Download at WoweBook.Com

i*!le*entation resides in a se!arate !ackage1 for e6a*!le1 spi. &t is -etter to *ove the J#A i*!le*entation into a dedicated !ackage1 than to !oll,te the !,-lic AP& /ith an additional1 *eaningless s,-!ackage s,ch as api or contract. Regardless of ho/ co*!le6 the internal i*!le*entation of the connector really is1 the !,-lic AP& sho,ld -e designed as convenient and si*!le as !ossi-le. +he interesting -,siness logic sho,ld -e accessi-le in less than three lines of code after the in.ection.

Participants and 6esponsibilities


5here are three ma=or participants% The app ication server: +his server is res!onsi-le to f,lfill the syste* contracts and !ro!agate the transactions fro* the a!!lication to the connector -ack (in-o,nd) and forth (o,t-o,nd). 0,rther*ore it !rovides a *anaged r,nti*e for the connector as /ell as for the a!!lication. The connector imp ementation: +his i*!le*entation relies on the !rovided contracts and interacts /ith the a!!lication server. &t is invoked -y the container to !ass the transaction stat,s and it re!orts the c,rrent connection stat,s -ack ,sing events. +he connector !rovides a high'level interface to a-stract fro* the inco*!ati-le reso,rces to its clients. The app ication ('.3+: +he a!!lication ,ses the !,-lic connector AP&. All the container services (s,ch as transactions1 sec,rity1 !ooling1 connection *anage*ent or conc,rrency) are *anaged and !ro!agated trans!arently to the a!!lication and even the connector -y the a!!lication server.

.trategies
5here are no note'orthy strategies. ;epending on yo r reB irements$ yo can choose 'hich parts o" the *CA speci<cation yo are going to implement.

5esting
5he *CARs adapter act al integration logic$ as 'ell as parts o" the *CA gl e code$ sho ld be nit tested. +ntegration tests in an environment identical to prod ction are even more important. Qo sho ld plan some deb gging and pro<ling ho rs$ or even days "or more comple> *CA adapter implementations. -specially the interaction bet'een the application server$ the -*B container$ and the *CA connector sho ld be tested. 5o save time$ yo sho ld a tomate the b ild and deployment process o" the connector to yo r application server. *CA connectors are shared reso rces accessed in parallel by several transactions and there"ore -*B instances. 9oad and stress tests are essentially important to validate the stability o" the c stom *CA implementation. -specially interesting is the behavior in e>treme cases$ "or e>ample$ in case the connection pool r ns empty and there are still inHight transactions 'aiting "or processing. 5he e>act behavior is hard to predict$ it is easier and more e"<cient to test early and o"ten$ than trying to implement a scalable and high-per"ormance sol tion 'ith a lot o" p"ront analysis.

498
Download at WoweBook.Com

;oc mentation
5he .P+ does not need e>tensive and detailed doc mentation. 5he description o" connection management and transaction concepts sho ld be s "<cient to nderstand the implementation. Qo can re"er to the detailed (<ve-h ndred page) *CA speci<cation doc ment. Qo sho ld spend more time on the AP+ doc mentation instead. -specially se" l are t torial-li#e descriptions 'ith easy-to- nderstand 'or#ing e>amples. 5he p blic AP+ 'ill be e>posed to "ar more developers than the encaps lated and hidden .P+. 7(9 seB ence and activity diagrams may be se" l "or the description o" interactions bet'een the application and the connector$ as 'ell as the description o" system contracts and internal concepts.

ConseB ences
Portabi ity: +he !orta-ility of J#A ada!ters is far -etter1 than EJB 2.6 co*!onents. &t is co*!ara-le /ith the !orta-ility of J2EE .L WAR archives. =o, don:t need any vendor' s!ecific e6tensions. )ca abi ity: J#A is only a s!ecification. +he scala-ility /ill only de!end on yo,r i*!le*entation and the scala-ility of the legacy reso,rce. 2obustness: +he ro-,stness is also highly de!endent on the connector i*!le*entation1 -,t the availa-ility of syste* contracts s,ch as lifecycle1 transaction1 and connection *anage*ent allo/s the reali5ation of *ore ro-,st integrations. Comp exity: +he J#A connectors and reso,rce ada!ter i*!le*entation are said to -e co*!le6. &n fact1 a !artial i*!le*entation of a J#A ada!ter co,ld -e easier and faster than an atte*!t to -,ild a co*!ara-le sol,tion fro* scratch. Consistency: J#A reso,rce ada!ters can !artici!ate in local as /ell as distri-,ted transactions. +he a!!lication server !ro!agates the transactions to the reso,rce ada!ter and notifies its i*!le*entation a-o,t the c,rrent stat,s of the transaction. +his allo/s yo, to integrate a legacy1 even non'transactional reso,rce /ith A#&" 8,alities. !aintainabi ity: J#A ada!ter forces re,se. +he i*!le*entation of the reso,rce ada!ter is not visi-le to its clients7 they are forced to ,se the !,-lic AP&. A connector is de!loyed inde!endently of the a!!lications /hich enco,rages re,se and avoids code re!etition. +he strict se!aration of !,-lic AP& and internal SP& allo/s changes of internal connector i*!le*entation /itho,t -reaking its clients.

6elated Patterns
5he p blic AP+ is comparable 'ith a ;A, or even a service. A *CA reso rce adapter is sed by services or ;A,s. 9o'-level$ NinconvenientO *CA implementations are o"ten 'rapped by a ;A, to ma#e them more accessible. )igh-level connectors can be accessed by services or even .ervice !a@ades. Asynchrono s service integration can be considered as a messaging-speci<c or narro'ed variant o" the generic *CA pattern.

492
Download at WoweBook.Com

Download at WoweBook.Com

Asynchrono$s Reso$rce 'ntegrator 9/ervice Activator:


(essage-driven beans are mapped to a javax.jms.8estination. +t can be either ;ueue "or point to point$ or :opic "or p blish-s bscribe comm nication. *(. is only a set o" AP+s and does not speci"y the 'ire protocol. 5he implementation o" the *(. AP+$ the act al message server is responsible "or the message transport. .ome prod cts s ch as (T .eries$ Active(T (http%CCactivemB.apache.orgC) or open(T (http%CCopenmB.dev.=ava.net) provide binding "or di""erent lang ages and can be sed as integration middle'are.

Problem
+n most companies the ma=ority o" b siness logic still r ns on legacy systems and not on a *ava application server. *ava applications have to access those reso rces in a standard 'ay 'itho t a lot o" proprietary pl mbing. Beca se s ch logic on bac#-end systems tends to be essential "or the enterprise$ non" nctional B alities s ch as g aranteed$ once and only once delivery$ and transactional access to the reso rces become essential as 'ell. ,lder legacy hosts in partic lar are o"ten based on message-oriented middle'are ((,(). 5he b siness logic is 'ritten in programming lang ages s ch as 6PD$ P9C4$ or Cobol 'hich ma#es the direct integration o" s ch reso rces even harder. !ort nately$ some message servers allo' seamless interaction bet'een *ava and the legacy 'orld. 5he same protocol is sed "or message delivery$ regardless o" 'hich lang age or plat"orm is sed to cons me and prod ce messages. A message sent by a P9C4 program is directly cons med by a message-driven bean mapped to a javax.jms.;ueue or javax.jms.8estination. 5his allo's the reali?ation o" lean and pragmatic integrations o" proprietary reso rces.

!orces
=o, need -idirectional co**,nication -et/een Java EE and the -ack'end services. =o, need ro-,st access to legacy reso,rces. =o, need a /ay to access asynchrono,s services. =o, need a sol,tion to sea*lessly integrate yo,r e6isting Java EE services /ith -ack'end services. &t is i*!ortant to !rovide a high level of consistency1 scala-ility1 sec,rity1 and ro-,stness. +ransactional access is re8,ired. =o, need to e6change *essages over !rotocols s,ch as H++P1 RES+1 or S(AP.

.ol tion
+" yo r *(. provider s pports the target legacy plat"orm yo are basically done. Qo 'ill only have to agree on a common destination to e>change messages. 5he message server does the heavy li"ting and integrates both 'orlds "or yo . 5he *ava -- code remains simpleS it is a standard message-driven bean that is mapped to the integrational destination. 5he message-driven bean is associated 'ith a 8estination (;ueue or :opic) that is sed by the legacy reso rces as a sin#. 5he application and messaging servers care abo t the comm nication$ b t not the conversion o" the message payload. +n most cases yo can only rely on javax.jms.:ext6essa7e and javax.jms.B'tes6essa7e "or

Download at WoweBook.Com

integration p rposes. ,ther types and javax.jms.Object6essa7e in partic lar = st cannot 'or# bet'een *ava and other programming lang ages. +n rare cases$ yo can even r n into tro ble 'ith javax.jms.:ext6essa7e$ beca se some legacy hosts 'or# 'ith the -BC;+C Lhttp%CCen.'i#ipedia.orgC'i#iC-BC;+CM character set$ 'hich is not compatible 'ith A.C++.
26essa7e8riven(mappe"Aame D 4ajax41 activationCon(i7 D # 2ActivationCon(i7Propert'(propert'Aame D 4ac9no,le"7e6o"e41 propert'?alue D 4Auto/ac9no,le"7e4)1 2ActivationCon(i7Propert'(propert'Aame D 4"estination:'pe41 propert'?alue D 4javax.jms.;ueue4) $) public class A*AK3istenerBean implements 6essa7e3istener # 2)*B private 6essa7eConsumer consumerpublic voi" on6essa7e(6essa7e ms7) # :ext6essa7e tm D (:ext6essa7e) ms7tr' # Strin7 messa7e D tm.7et:ext()consumer.consume(messa7e)$ catc+ (*6S)xception ex) # t+ro, ne, )*B)xception(4Cannot receive pa'loa" G 4 Hex1ex)$ $ $

5he responsibility o" the message-driven bean is the e>traction o" the payload$ its conversion into meaning" l parameters and "or'arding to a service. 5he service is acB ired 'ith ;ependency +n=ection and #no's nothing abo t the act al origin o" the parameters.
2Stateless 2:ransactionAttribute(:ransactionAttribute:'pe.6AA8A:ORB) public class 6essa7eConsumerBean implements 6essa7eConsumer # public voi" consume(Strin7 messa7e) # %%business lo7ic... $ $

5he service is deployed$ as al'ays$ 'ith the :ransactionAttribute:'pe.6AA8A:ORB con<g ration$ so it can be only invo#ed in the conte>t o" a transaction. 5he transaction is started by the container be"ore the invocation o" the method on6essa7e. +t is important to cons me the message and invo#e the service in the same transaction. 5he message is deleted "rom the destination at s ccess" l transaction completion. +n case the transaction "ails$ it 'ill be a tomatically redelivered. 5he message-driven bean is there"ore only able to delegate the messages to a service and not a .ervice !a@ade. A .ervice !a@ade 'o ld al'ays start a ne'$ independent transaction. 5he cons mption o" the message and the e>ec tion o" the b siness logic 'o ld be deco pled. -ven i" .ervice !a@ade rolls bac# its

491
Download at WoweBook.Com

transaction$ the message-driven bean 'o ld still s ccess" lly cons me the message. 5he message 'o ld = st silently disappear "rom the destinationIa hard-to-<nd error.

6ethin#ing
5he scope o" .ervice Activator in -*B 2.0 changed completely in -*B 3.4. +n -*B 2$ a messagedriven bean 'as the only 'ay to invo#e synchrono s -*Bs in asynchrono s 'ay% N-nterprise beans and other b siness services need a 'ay to be activated asynchrono sly. NX+" an application needs synchrono s processing "or its server-side b siness components$ then enterprise beans are an appropriate choice. .ome application clients may reB ire asynchrono s processing "or the server-side b siness ob=ects beca se the clients do not need to 'ait or do not have the time to 'ait "or the processing to complete. +n cases 'here the application needs a "orm o" asynchrono s processing$ enterprise beans do not o""er this capability in implementations prior to the -*B 2.0 speci<cation. N5he -*B 2.0 speci<cation provides integration by introd cing message-driven bean$ 'hich is a special type o" stateless session bean that o""ers asynchrono s invocation capabilities. )o'ever$ the ne' speci<cation does not o""er asynchrono s invocation "or other types o" enterprise beans$ s ch as state" l or entity beansXO Lhttp%CC=ava.s n.comCbl eprintsCcore=2eepatternsCPatternsC.erviceActivator.htmlM. 5he .ervice Activator 'as act ally a decorator or adapter LDo!M that mis sed the messageoriented middle'are to invo#e synchrono s components asynchrono sly. +n -*B 3.4$ a simpler and more nat ral option is available. Qo only have to annotate a method 'ith the annotation 2As'nc+ronous to be e>ec ted in a bac#gro nd threadIno 'or#aro nd or pattern is reB ired. 5he se o" message-driven beans as an adapter is still interesting$ b t only "or integrational p rposes and deco pling. 5his is the reason "or renaming .ervice Activator to Asynchrono s 6eso rce +ntegrator. 6ich +nternet applications$ and A*AK in partic lar$ rely increasingly on asynchrono s comm nication styles 'ith bac#-end services . *(. is asynchrono s by nat re$ b t most messaging servers se binary protocols only$ 'hich ma#es them inappropriate "or the 'eb. .ome message providers$ s ch as open(T (https%CCmB.dev.=ava.netC8.3contentC msC ms(ain.html)$ o""er a 6-.5-based "ront end "or internal messaging. open(T calls it 7niversal (essage .ervice (7(.). Also$ active(T provides a similar 6-.5" l bridge(http%CCactivemB.apache.orgCrest.html). 5he sol tion is in both cases .ervlet based. Qo only have to deploy a EA6$ 'hich converts the 6-.5 reB ests into corresponding *(. actions s ch as login$ send$ receive$ close$ commit$ or rollbac# in the case o" open(T. A 6-.5" l inter"ace can be easily sed by all )55P enabled devicesIit is not only restricted to A*AK and bro'sers. 7n"ort nately$ the 6-.5" l protocol itsel" is not standardi?ed yet$ altho gh yo co ld se$ "or e>ample$ the open(T bridge to comm nicate 'ith an active(T server. 5here is a standard Advanced (essage T e ing Protocol (A(TP) (http%CCamBp.org)$ 'hich tries to standardi?e the 'ire protocol as 'ell$ b t it is not very pop lar at the moment.

499
Download at WoweBook.Com

5he asynchrono s reso rce integrator pattern can be sed "or "ront-end and bac#-end integration. 5he only di""erence is the con<g ration o" the message provider. !or the integration o" asynchrono s reso rces in the presentation tier$ yo 'ill need to con<g re )55P C6-.5" l bridges (o"ten available as EA6s). 5he legacy reso rces$ on the other hand$ rely already on an e>isting$ binary protocol$ 'hich is hard to change.

Conventions
5he message-driven bean is only responsible "or payload "or'arding "rom a javax.jms.6essa7e to the service. +t has no domain-speci<c responsibility and sho ld not contain any b siness logic. 5here"ore it sho ld be named as the service 'ith the s "<> A.+Ithe abbreviation o" asynchrono s service integration$ or = st 9istener$ "or e>ample$ Or"erServiceBean$ Or"erService3istenerBean or Or"erServiceAS<Bean. +t 'ill be hard to <nd any other meaning" l name. +n the case o" the integration o" asynchrono s presentation components$ the message-driven bean co ld reside in the same pac#age as the service ("or e>ample$ business.or"erm7mt.service.Or"erServiceAS<Bean). 5he A.+ has similar responsibilities to a .ervice !a@ade$ so it co ld be also placed in the s bpac#age business.or"erm7mt.(aca"e or business.or"erm7mt.boun"ar'. 5he latter approach sho ld be pre"erred "or asynchrono s components$ 'here an A.+ is sed consistently instead o" a .ervice !a@ade. !or the comm nication 'ith bac#-end services$ the message-driven bean 'o ld act ally belong to the integration tier$ and there"ore the s bpac#age 'ith the name inte7ration. !rom an implementation perspective$ there is no di""erence bet'een these scenarios. +n both cases$ the message-driven bean is mapped to a destinationIthere is no additional integration logic involved. !or pragmatic reasons$ yo co ld also p t the message-driven bean into the same pac#age as the service. +n case yo need more comple> data trans"ormations or conversions$ yo sho ld move the message-driven bean 'ith the corresponding integration logic into the integration tier.

Participants and 6esponsibilities


5he message-driven bean plays the act al integrator role. +t is responsible "or% %essage cons,*!tion and service invocation /ith A#&" 8,alities. Payload e6traction and conversion into *eaningf,l *ethod !ara*eters. Error handling of syntactically incorrect *essages AEA !oisoned *essages. +hese can -e *essages /ith /rong ty!e or ,nrecogni5a-le !ayload res!ectively.

5he implementation o" the *(. AP+ plays an important role in this pattern as 'ell. 5he message provider is responsible "or providing the gl e " nctionality$ and especially client libraries$ "or both the *ava and legacy sides. 5he service sho ld not even #no' abo t the e>istence o" the message-driven bean. +t sho ld be indisting ishable 'hether it 'as invo#ed by the .ervice !a@ade or the asynchrono s service invo#er.

200
Download at WoweBook.Com

.trategies
!rom the concept al point o" vie'$ there are t'o di""erent strategies available. +nterestingly the implementation o" both strategies is almost identical. 5he only di""erence is the so rce o" the incoming events. 0ront'end &ntegration !ront-end integration e>pects messages "rom the presentation and even the client tier (the bro'ser). 5he messages contain ser inp t as payload and have the gran larity o" .ervice !a@ade parameters. 5rans"ormations are not reB iredS the payload o" the incoming messages o"ten contains *.,/ or K(9 ob=ects$ 'hich can be directly cons med. 5he message-driven bean e>tracts the payload and delegates it as a parameter to a service. Back'end &ntegration A legacy system is the so rce o" the incoming messages in this case. Contrary to "ront-end integration$ yo 'ill hardly have inH ence on the message payload$ type$ encoding$ and content. A"ter the cons mption o" a legacy message yo 'ill probably have to spend some e""ort to nderstand the act al payload. 5he payload itsel" is o"ten in a proprietary "ormat$ 'hich has to be converted into a more handy representation at the beginning. Byte arrays as payload are not ncommon. Comple> trans"ormations sho ld not be implemented in the A.+$ b t be "actored o t into dedicated$ testable conversion service.

5esting
Any conversion and trans"ormation logic sho ld be heavily tested 'ith nit tests. 5rans"ormation errors are hard to deb g$ especially in asynchrono s environments. 5he importance o" integration tests in an environment identical to prod ction cannot be emphasi?ed eno gh. 5he correct behavior o" the A.+ cannot be veri<ed 'ith plain nit tests. Qo 'ill have to deploy it to the application server 'ith properly con<g red and mapped destinations. 9oad tests are important "or the veri<cation o" the message provider con<g ration especially thread pooling$ thresholds$ B otas and dead letter B e es in error scenarios. Altho gh messagedriven beans are easy to develop and deploy$ proper error handling is hard and the deb g process a real challenge. Dood integration and load tests are essential "or rob st applications.

;oc mentation
5he invocation o" a message-driven bean by an A*AK application isnRt obvio s and sho ld be there"ore doc mented. -specially the mechanism$ any conversions$ transaction and error handling are important. A Ei#i is per"ectly s itable "or the description o" s ch concepts. Also$ e>isting naming conventions and patterns "or the destination naming sho ld be 'ell doc mented. As al'ays$ the intentions and bac#gro nd in"ormation is more important as the act al res lt. 5he destinations sho ld be named a"ter domain concepts (Or"er;ueue) and not technical arti"acts (Request;ueue). +n case o" bac#-end integration the naming conventions are already provided by legacy standards and have to be re sed.

204
Download at WoweBook.Com

+n class diagrams$ an A.+ can be modeled as a service 'ith the additional stereotype ..AS<00. 5here is no need "or modeling an additional message-driven bean. 5his in"ormation can already be derived "rom the stereotype.

ConseB ences
)ca abi ity: Asynchrono,s co**,nication scales significantly -etter1 than its synchrono,s co,nter!art. +he transactions are shorter7 the client does not have to /ait ,ntil the transaction co*!letion. Comp exity: Asynchrono,s co**,nication is only si*!le for fire'and'forget co**,nication styles. &t is hard to -,ild -idirectional co**,nication /ith asynchrono,s !rotocols. &t -eco*es es!ecially co*!le6 in case the client needs an i**ediate feed-ack. S,ch !se,do'asynchrono,s co**,nication is hard to i*!le*ent /itho,t /aiting for the res!onse. +his /o,ld ca,se -locking in so*e layer /hich in t,rn co,ld lead to d,!licate transactions or deadlocks. +he first !heno*enon can occ,r -y resending a *essage after a ti*eo,t1 the second in cases the server forgets to send a res!onse. &n case yo,r legacy reso,rce is a-le to co**,nicate /ith the *essaging server1 AS& -eco*es the si*!lest and *ost ro-,st sol,tion. +he alternative /o,ld -e direct co**,nication /ith the legacy interfaces /ith A#&" 8,alities /hich can -eco*e 8,ickly orders of *agnit,de *ore co*!le6. &oose coup ing: %essaging deco,!les the *essage cons,*er fro* the !rod,cer /ith an inter*ediary destination. +he de!endency is very /eak and only given -y the *essage. +he !rod,cer can -e changed and *aintained /itho,t affecting the cons,*er. )o reco*!ilation is needed as long as the *essage re*ains ,nchanged. 2obustness: Java is a statically ty!ed lang,age7 loose co,!ling can -e only achieved /ith /eakening the ty!e safety -y relying on *ore general contracts. "oing so1 yo, are act,ally disa-ling the *a.ority of co*!iler checks. +he a!!lication re*ains longer co*!ila-le1 -,t the develo!er has to !rovide its r,nti*e ro-,stness. %essage'oriented syste*s are not ro-,st !er defa,lt7 yo, have to invest a considera-le a*o,nt of effort to achieve a high level or sta-ility. Testabi ity: Asynchrono,s and *essage'oriented syste*s in !artic,lar are hard to test. &ntegration tests have to -lock a certain a*o,nt of ti*e to verify the effect of a sent *essage. %ost *essage servers are not a-le to -e e6ec,ted in !rocess and started in the 2Be(ore *ethod of the ,nit test. &ntegration and f,nctional tests are easier to !erfor* and are even *ore i*!ortant. Portabi ity: J%S does not s!ecify the /ire !rotocol. ;nless yo,r *essage server relies on standards like A%DP yo, are indirectly de!endent on the !ro!rietary ca!a-ilities of the *essage server. +he a!!lication1 ho/ever1 is still only de!endent on the J%S AP&7 there are no co*!ile'ti*e de!endencies to the J%S i*!le*entation. Performance: Altho,gh for the client the res!onse ti*es can -eco*e significantly shorter1 -idirectional co**,nication re8,ires at least three transactions. +he client has to send the *essage1 /hich -eco*es cons,*ed1 !rocessed1 and sent -ack. +he third transaction is the act,al cons,*!tion of the *essage. +he sa*e -,siness logic co,ld -e invoked /ith a single transaction in synchrono,s /ay.

202
Download at WoweBook.Com

Asynchrono s comm nication needs more transactions and generates signi<cantly more load. 5his can over'helm the server and impact per"ormance. Qo sho ld per"orm load tests to veri"y the act al demand on reso rces (6A($ CP7 and so on).

6elated Patterns
Asynchrono s service invo#er is act ally a service activator 'ith e>tended scope and responsibilities. 5he asynchrono s invocation o" synchrono s services is already provided by the -*B 3.4 speci<cation. 5he integration o" incompatible reso rces remains the main A.+ responsibility. *(. providers are pl gged into the application server sing the *CA in"rastr ct re. 5he A.+ can be considered as a speci<c "orm o" generic *CA. ;A,s have similar responsibility as 'ell$ b t they largely operate synchrono sly. A.+ "or'ards the payload to services e>cl sively. +n e>ceptional cases$ it co ld 'or# directly 'ith ;A,s. A.+ is triggered by bac#-end reso rces or directly by clients. +n some cases$ services can invo#e an A.+ by sending *(. messages as 'ell. 5he message so rce sho ld be totally transparent "or an A.+.

203
Download at WoweBook.Com

Download at WoweBook.Com

;
&nfrastr,ct,ral Patterns and ;tilities
.ome patterns are hard to classi"y beca se they can be sed in every layer. /ot all se" l patterns are relevant to the bigger pict re and can be omitted in the architect re description. 5his chapter covers s ch hard-to-classi"y yet still se" l patterns and tilities$ incl ding% Service Starter Singleton Bean locator +hread tracker "e!endency in.ection e6tender Payload e6tractor Reso,rce -inder #onte6t holder

Download at WoweBook.Com

Download at WoweBook.Com

/ervice /tarter
5he *ava -- 2 container manages the li"ecycle o" deployed components. .tateless session beans are created mainly on demandS state" l session beans are created at in=ection or loo# p time. *ava -- 2 does s pport a standardi?ed 'ay to "orce the container to initiali?e them at start p time. .tateless session bean pooling is mentioned in the spec and available in most application servers$ b t the 'ay ho' the pool is con<g red is not standardi?ed. Qo simply cannot rely on the e>istence o" settings s ch as pool/ initial/si=e or min-pool-si?e on every application server. 5here is no standardi?ed 'ay to en"orce a session bean to start at deployment time.

Problem
.ome in"rastr ct ral logic and services need to be initiali?ed be"ore the e>ec tion o" the act al b siness logic. . ch services can be e>pensive$ slo'$ or nstable ("or e>ample$ an K(9 con<g ration <le co ld be mal"ormed). +t is a good strategy to start them at the earliest possible time. ,nly the introd ction o" -*B 3.4 provided a standardi?ed sol tion "or the initiali?ation problem. /either -*B 2.> nor -*B 3.0 s pported a direct 'ay to "orce the container to start session beans at deployment time$ 'ith the e>ception o" the introd ction o" a start p .ervlet.

!orces
=o, need a !orta-le /ay to start services eagerly +he sol,tion sho,ld !rovide e6tendi-le hooks /ith /hich e6isting stateless session Beans can -e initiali5ed.

.ol tion
5he sol tion to this problem dependents on the s pported -*B version. Prior to -*B 3.4 yo co ld "orce the initiali?ation o" certain components 'ith a .ervlet. +n -*B 3.4 yo can achieve the same 'ith only t'o additional annotations. EJB 3. 5he start p problem is solved in the -*B 3.4 speci<cation. Qo can either initiali?e the services directly in the .ingleton pattern$ or even in=ect and initiali?e e>isting session beans "or that p rpose. * st annotate a class 'ith the 2Sin7leton and 2Startup annotations and deploy it together 'ith yo r services. 5his "orces the container to initiali?e the bean at deployment time$ as sho'n in the "ollo'ing snippet%
2Sin7leton 2Startup public class ServiceStarter # 2)*B private )xistin7ServiceBean service)6ost0onstruct public voi" on<nitiali=e()# S'stem.out.println(4#4 H t+is.7etClass().7etSimpleAame() H 4 2PostConstruct4)service.please<nitiali=e()-

Download at WoweBook.Com

$ $

5he container initiali?es the bean$ b t 'onJt invo#e yo r b siness logic or services. Qo can easily "orce the container to invo#e yo r hoo# by designating the initiali?ation method 'ith the 2PostConstruct annotation. 5his method (on<nitiali=e in the e>ample belo') is invo#ed = st a"ter the constr ction o" the ServiceStarter and the invocation o" a de"a lt constr ctor$ as demonstrated in the "ollo'ing e>ample%
2Stateless public class )xistin7ServiceBean # )6ost0onstruct public void on2nitialiFe()# S'stem.out.println(4#4 H t+is.7etClass().7etSimpleAame() H 4 2PostConstruct4)$ public voi" please<nitiali=e()# S'stem.out.println(4#4 H t+is.7etClass()@ H 4 please<nitiali=e()4)$ public Strin7 someBusiness3o7ic()# return 4 ello (rom bean4$ $

Qo can p t the initiali?ation logic right into the .ingletonJs 2PostConstruct method. At this point ;ependency +n=ection is already per"ormed$ so yo can rely on the e>istence o" the in=ected reso rces. Qo co ld even se the ServiceStarter as a 'rapper to initiali?e common session beans. Qo only have to in=ect the re"erence and invo#e any method yo li#e. 5his event ally 'ill "orce the container to in=ect and initiali?e the session bean. ; ring the initiali?ation the container creates the bean (i" it not already e>ists)S it then e>ec tes the 2PostConstruct method and invo#es yo r b siness method. 5his can be easily reprod ced 'ith the previo s sampleS it generates the "ollo'ing o tp t%
#ServiceStarter 2PostConstruct #)xistin7ServiceBean 2PostConstruct #)xistin7ServiceBean please<nitiali=e()

Qo can even inH ence the order in 'hich dependent .ingletons 'ill per"orm their initiali?ation. 5o demonstrate this$ yo can introd ce another .ingleton$ the <nitiali=er%
2Sin7leton public class <nitiali=er # 2PostConstruct public voi" on<nitiali=e()# S'stem.out.println(4#4 H t+is.7etClass().7etSimpleAame() H 4 2PostConstruct4)$ $

201
Download at WoweBook.Com

5he declaration o" the dependency to another .ingleton can be speci<ed 'ith the 28epen"sOn annotation. 5his annotation has only one attrib te o" type Strin7NO. +t represents the names o" the beans that have to be initiali?ed be"ore the annotated class%
2Sin7leton 2Startup ).epends8n("2nitialiFer") public class ServiceStarter # <n t+is example1 t+e <nitiali=er is initiali=e" be(ore t+e ServiceStarterG #<nitiali=er 2PostConstruct #ServiceStarter 2PostConstruct #)xistin7ServiceBean 2PostConstruct #)xistin7ServiceBean please<nitiali=e()

Workaro,nd for older EJB versions

5here is no standard 'ay to en"orce the initiali?ation o" session beans prior -*B 3.4. 5he Eeb container$ ho'ever$ 'as able to provide this " nctionality "or .ervlets d ring the *2-- days. 5o initiali?e a service$ yo have to provide a .ervlet 'ith an over'ritten init method as sho'n in the "ollo'ing snippet%
public class ServiceStarter exten"s ttpServlet # 2)*B private <n(rastructureService service2Overri"e public void init() t ro(s Servlet,=ception { S'stem.out.println(4#4 H t+is.7etClass().7etSimpleAame() H 4 init()4)t+is.service."umm'6et+o"()$ $

* st in=ect a session bean o" yo r choice into the .ervlet. A plain in=ection isnRt eno gh to en"orce the creation o" the beanS itRs the same problem as in the case o" the 2Sin7leton. 5he invocation o" any arbitrary method$ ho'ever$ 'ill ca se the container to initiali?e the session bean. 5he remaining tas# is con<g ring the .ervlet in the ,eb.xml (or 'ith annotations)$ to be started at deployment time. !or that p rpose yo 'ill have to provide a val e$ higher than ?ero$ in the loa"/on/startup tag.
.,eb/app0 .servlet0 .servlet/name0ServiceStarter.%servlet/name0 .servlet/class0...servicestarter.ServiceStarter.%servlet/class0 <load-on-startup>I<$load-on-startup> .%servlet0 .%,eb/app0

5he val e inH ences the initiali?ation orderthe higher the val e$ the earlier (relatively to others) a .ervlet is initiali?ed. 5he res lt is comparable to the 28epen"sOn annotation. 5he deployment o" the .ervlet res lts in the "ollo'ing o tp t%
#ServiceStarter init() #<n(rastructureService 2PostConstruct

209
Download at WoweBook.Com

#<n(rastructureService "umm'6et+o"

6ethin#ing
6ethin#ing is not reB ired$ b t re"actoring is. Eith the availability o" -*B 3.4 s pport by yo r prod ction server$ yo can trans"orm yo r e>isting start p .ervlets into .ingleton beans and get rid o" s perH o s EA6s.

Participants and 6esponsibilities


5he process is started either by the .ervlet or a .ingleton bean$ the service starter. +n both cases$ the container initiates the process and invo#es the init or 2PostConstruct method$ respectively. 5he initiali?ation is either per"ormed in the start p hoo#s directly$ or delegated to session beans by invo#ing d mmy methods.

5esting
Proper start p behavior can only be tested d ring deployment time. 7nit tests$ ho'ever$ are recommended to test the initiali?ation logic itsel". .ervice starter is an e>ception "rom the r leS load and stress tests are irrelevant here.

;oc mentation
.tart p service is irrelevant "or the bigger pict re$ so it sho ld not appear in the overvie' diagrams. +n -*B 3.4$ yo co ld even omit *ava;oc$ beca se the initiali?ation responsibility is already 'ell doc mented 'ith the 2Startup annotation.

ConseB ences
5he service starter improves r ntime rob stness o" the system starting critical services eagerly. 5here are no other impacts on non-" nctional reB irements.

6elated Patterns
5he service starter invo#es e>isting services $ .ervice !acades$ or Date'ays to en"orce their initiali?ation. +t is not related to other patterns regarding its responsibility. 5he .ingleton$ ho'ever$ is technically identical to the service starter.

240
Download at WoweBook.Com

/ingleton
5he single-threaded programming model is one o" the main "eat res o" -*Bs. 5he reali?ation o" the idea leads to the elimination o" shared instances and state among threads. -very ser reB est (that is$ every thread) operates on a single session bean instance. An instance can be accessed only by one thread at a time. .tate" l session beans are even more restrictive. 5hey not only have to be accessible by one thread a time$ b t every reB est has to be associated 'ith the same ser.

Problem
5he simpli<ed programming is s perb "or scalability and m lti-core programming$ b t it ma#es management o" limited reso rces hard. 5he amo nt o" active session bean instances is only dependent on the n mber o" parallel ser reB ests and the proprietary application server con<g ration. Pool settings$ the con<g ration o" ma>$ min pool si?e$ and its resi?e ability in partic lar are not bac#ed by the spec. +t is there"ore not possible to implement a .ingleton in a portable 'ayS yo can neither rely on the availability o" the ma> pool si?e parameter$ nor on its e>pected behavior. ! rthermore$ 'itho t a central instance$ it is impossible to implement an e"<cient read-only cache. Caching is especially interesting "or master data and con<g ration.

!orces
+he sol,tion has to -e !orta-le across servers. A Singleton is shared across ,ser re8,ests !er definition. Either it is accessed in read'only *ode or a synchroni5ation *echanis* has to -e !rovided -y the container. A Singleton *,st not infl,ence the gar-age collection7 it *,st not -e reali5ed /ith static and synchroni5ed *odifiers.

.ol tion
A .ingleton 'as standardi?ed 'ith the -*B 3.4 spec. +t is a bean that only e>ists once in a *A(. +n a cl stered environment$ ho'ever$ yo 'ill still get m ltiple .ingleton instances. 5he .ingleton can be started at the containerRs boot time. 5he .ervice .tarter pattern leverages this capability. !rom a technical point o" vie'$ a .ingleton is identical to the .ervice .tarter. +ts main responsibility is not the delegation o" its boot capabilities to interesting services$ b t to provide shared state and conc rrency management. 5he "ollo'ing e>ample sho's a simple caching .ingleton.
2Sin7leton public class 6aster8ataCac+e # private 6ap.Strin71Object0 cac+e2PostConstruct public voi" initCac+e()# t+is.cac+e D ne, as+6ap.Strin71 Object0()$ public Object 7et(Strin7 9e')# return t+is.cac+e.7et(9e')$

Download at WoweBook.Com

public voi" store(Strin7 9e'1Object value)# t+is.cac+e.put(9e'1 value)$ $

According to spec$ a .ingleton comes already 'ith s itable$ b t restrictive de"a lts% 2Concurrenc'6ana7ement(Concurrenc'6ana7ement:'pe.COA:A<A)R) and 23oc9(3oc9:'pe.!R<:)). 5he conc rrency is managed by the container$ b t 'itho t any parallelism. 5he 3oc9:'pe.!R<:) is e>cl sive$ so only one thread at a time can access the .ingleton instance. 5his de"a lt setting provides a high level o" consistency$ comparable 'ith the seriali?able isolation level$ b t at a high costit is a bottlenec#. 5he 3oc9:'pe.!R<:) is not appropriate "or read-only master data caches or caching o"$ "or e>ample$ parsed K(9 con<g ration. +" yo are only reading cached data stored in the .ingleton$ the 3oc9:'pe.R)A8 is the right sol tion "or yo . +t allo's sim ltaneo s access to methods designated 'ith this 3oc9:'pe. Qo co ld even ta#e over the conc rrency management and implement it 'ith standard *ava means s ch as synchroni?ed modi<ers or bloc#s. Qo 'ill gain more control. +n most cases$ ho'ever$ the containerRs conc rrency management is absol tely s "<cient. !or a more serio s cache implementation$ yo sho ld rely on "rame'or#s s ch as *Boss-Cache (http%CC'''.=boss.orgC=bosscacheC) or -)Cache (http%CCehcache.so rce"orge.netC)$ 'hich are more po'er" l$ 'ell tested$ and provide additional services s ch as re"reshing$ eviction o" stale elements$ distrib tion$ replication $invalidation$ and even disc persistence. .ome o" the cache implementations$ ho'ever$ might not be compliant 'ith the -*B 3.4 speci<cation.

6ethin#ing
5he se o" static$ non-<nal <elds is restricted. +t 'as e>tremely di"<c lt to implement a .ingleton 'itho t violating the spec. As a 'or#aro nd$ (Beans or *CA connectors co ld be sed "or this p rpose. 5he access to *(K "rom session beans is not speci<ed and error-prone$ 'hereas implementing a *CA connector = st to have a .ingleton is a slightly overengineered sol tion. +nstead o" designing esoteric sol tions 'ith -*B 3.4$ yo sho ld leverage the container capabilities and se .ingleton beans. 5hey are simple$ concise$ po'er" l$ and " lly independent o" a concrete application server implementation. 5hey are almost independent "rom the -*B AP+ itsel"$ only one annotation tights them to the spec.

Participants and 6esponsibilities


5he .ingleton bean provides already added val e and implements$ "or e>ample$ caching or con<g ration services. +t can access e>isting .ervice !a@ades $ services$ and reso rces to "etch needed in"ormation and cache it later.

.trategies
2atekee!er

242
Download at WoweBook.Com

A .ingleton can be e""ectively sed to throttle conc rrency to bac#-end reso rces. -specially legacy systems have only limited scalability$ or the conc rrency has to be restricted beca se o" licensing iss es. +n general$ throttling is the responsibility o" a *ava Connector Architect re (*CA) adapter$ i" available "or the speci<c bac#-end system. A *CA connector co ld also be implemented "rom scratch "or this p rpose. +t is$ ho'ever$ a lot more 'or# than implementing a simple .ingleton. -ven easier to implement is the seB entiali?ation o" access to legacy reso rces. -specially native legacy services are not thread-sa"e. A .ingleton designated 'ith 3oc9:'pe.!R<:) provides seB ential access to its methods and is the per"ect sol tion "or accessing single-threaded reso rces. 5hrottling$ as 'ell as seB entiali?ation o" access to a bac#-end reso rce is only given in a singlenode environment. Cl ster is a logical gro p o" identical nodes$ so that yo 'ill get one instance o" a .ingleton per node$ and several .ingleton instances per application. Cl ster-'ide .ingletons are not speci<ed in -*B 3.4. #aching Singleton A more common se case "or .ingletons is 'rapping or even the implementation o" caching sol tions. Comple> K(9 con<g ration$ internationali?ation messages$ or master data caches can be loaded at start p time and do not change at r ntime. Caching .ingletons can be deployed 'ith the 3oc9:'pe.R)A8 con<g rationonly then can the cache be accessed in parallel. +n the "ollo'ing e>ample$ a .ingleton 'raps ) Cac+e and e>poses it to other services or even the presentation layer.
2Sin7leton 2Startup 23oc9(3oc9:'pe.R)A8) public class Cac+in7Sin7leton # public static (inal Strin7 8)&AU3:JCAC )JAA6) D 4memor'4private Cac+e6ana7er cac+e6ana7erprivate Cac+e cac+e2PostConstruct voi" initiali=eCac+e()# t+is.cac+e6ana7er D Cac+e6ana7er.create()t+is.cac+e D t+is.cac+e6ana7er.7etCac+e(8)&AU3:JCAC )JAA6))i((t+is.cac+e DD null) t+ro, ne, <lle7alState)xception(4..G 4 H 8)&AU3:JCAC )JAA6))$ public Seriali=able 7et(lon7 i")# )lement element D t+is.cac+e.7et(i")i((element DD null) return nullreturn element.7et?alue()$ public voi" put(lon7 i"1 Seriali=able cac+e)#

243
Download at WoweBook.Com

t+is.cac+e.put(ne, )lement(i"1 cac+e))$ 2Pre8estro' voi" s+ut"o,nCac+e()# t+is.cac+e6ana7er.s+ut"o,n()$ $

5he Cac+in7Sin7leton is rather p ristits only responsibility is caching and not the act al data retrieval. An in=ected .ervice$ ho'ever$ co ld "etch the data in case o" a cache miss and provide a caching "a@ade. Alternatively$ a Cac+eService co ld se the Cac+in7Sin7leton = st "or caching$ and pop late the cache on demand. Eith "rame'or#s s ch as -)Cache it 'o ld even be possible to read the cache and let the "rame'or# transparently pop late it. A Cac+in7Sin7leton sho ld be eagerly initiali?ed. +n case the cache 'as not properly con<g red ("or e>ample$ e+cac+e.xml not "o nd or inconsistent)$ the application server 'o ld thro' an e>ception and the application 'o ldnRt be available at all. ! rthermore$ the method 2Pre8estro' is implemented to sh t do'n the cache grace" lly. 5his is important "or caches 'ith disc or persistent storage in partic lar. 5hey se this hoo# to H sh the contents o" the memory cache into the persistent store.

5esting
.ingletons do not reB ire any testing per se. Ehat yo sho ld test$ ho'ever$ is their behavior nder a heavy load in a prod ction environment. -specially important is the throttling " nctionality o" the >ate9eeper. Ehat yo are act ally testing is not yo r code$ rather than the container implementation and the impact o" 3oc9:'pes on yo r per"ormance and scalability.

;oc mentation
5he nat re o" .ingletons is rather technical and not concept al$ so they are less interesting "or architect ral doc mentation. +n case Date#eepers or caching .ingletons are a rec rring pattern in yo r architect re$ it is 'orth to describe them once in a concept al meta model$ and then re se this pattern over and over again. At code level$ .ingletons are already very 'ell doc mented 'ith the 2Sin7leton and (i" applicable) 2Startup annotations. Qo sho ld concentrate in yo r *ava;oc comments on more essential responsibilities s ch as a description o" ho' the cache 'or#s and ho' to se it. 5he .ingleton itsel" is already 'ell doc mented in the -*B 3.4 speci<cation.

ConseB ences
)ca abi ity: A Singleton e6ists only once !er JB%. +herefore it is a nat,ral -ottleneck1 es!ecially /ith the defa,lt config,rationH 3oc9:'pe.!R<:). Already the need for the introd,ction of a Singleton *ay indicate design !ro-le*s in yo,r a!!lication. Even the

248
Download at WoweBook.Com

3oc9:'pe.R)A8 *ay ca,se !ro-le*s -eca,se the Singleton:s i*!le*entation *ay -lock and i*!act the scala-ility. (n the other hand1 caching Singletons can save data-ase ro,ndtri!s and i*!rove the scala-ility significantly. Testabi ity: &n general1 classic Singletons are not very /ell ,nit testa-le. &t is very hard to ,n'initiali5e the* after the test. +his is not tr,e for EJB 3. Singletons. (,tside the container1 these Singletons are .,st reg,lar Java classes1 so yo, can test the* as any other P(J(. 0or integration tests yo, /ill have to de!loy the e.-'.ar to the container7 the ,nde!loy*ent /ill clean ,! the Singletons1 so yo, co,ld easily re!eat the test. Performance: #aching Singletons can i*!rove the !erfor*ance significantly. &nstead of accessing the JPA layer1 or even data-ase1 the re8,ired o-.ect can -e served directly fro* *e*ory. +his is a lot faster than accessing a data-ase. 2obustness: +he Singleton instance /ill re*ain in *e*ory ,ntil the ,nde!loy*ent or sh,tdo/n of the a!!lication. So every referenced o-.ect /ill also re*ain in *e*ory ,ntil the Singleton gets gar-age collected itself. +his can -eco*e a !otential !ro-le* for caches. #ached o-.ects /ill never -e gar-age collected1 so the a!!lication can r,n o,t of *e*ory. =o, sho,ld config,re or i*!le*ent yo,r cache !ro!erly and set the *a6i*,* a*o,nt of o-.ects to a reasona-le (load'tested) val,e. Portabi ity: An EJB 3. Singleton instance is g,aranteed to e6ist only once in a single JB%. &n a cl,stered environ*ent1 yo, /ill get *,lti!le Singleton instances. So*e vendors already !rovide cl,ster'/ide Singletons. +hese e6tensions are !ro!rietary and not !orta-le across a!!lication servers.

6elated Patterns
A Caching .ingleton can access services and can itsel" be accessed by .ervice !a@ades or .ervices. 5he Date#eeper strategy accesses bac#-end reso rces and integration services. !rom a technical perspective$ a .ingleton is closely related to a .ervice .tarter (*ava --). 5here 'as no s pport "or .ingleton beans in -*B prior 3.4.

242
Download at WoweBook.Com

Download at WoweBook.Com

Bean 3ocator
;ependency in=ection 'or#s in managed classes only. !rom P,*,s$ yo 'ill still have to se */;+ C <nitialContext to access the deployed -*Bs. A state" l session bean instanceRs li"e starts 'hen a client obtains a re"erence to the bean instance thro gh ;ependency +n=ection or */;+ loo# p. A state" l class cannot be in=ected to .ervlets$ reB est scoped bac#ing beans and so onS yo 'ill have to se */;+ loo# p to control the creation time and associate$ "or e>ample$ the state" l session bean 'ith the )55P session. .ometimes a loo# p o" a reso rce instead o" ;ependency +n=ection is necessary as a 'or#aro nd "or potential application server b gs.

Problem
5he */;+ speci<cation (javax.namin7 pac#age) is older than *2-- itsel". +t is part o" the *;& and not o" the *ava -- speci<cation. +ts se is simple$ b t comes 'ith some pl mbing. 5he Context#loo9up thro's javax.namin7.Aamin7)xception$ 'hich is chec#ed. 5he */;+ AP+ 'as designed long be"ore the availability o" generics$ so yo 'ill have to cast the res lt as 'ell. -*B 3.4 introd ced the global */;+ naming o" -*B components. 5he */;+ names come 'ith the "ollo'ing synta>% javaG7lobalN%.app/name0O%.mo"ule/name0%.bean/name0#.(ull'/ quali(ie"/inter(ace/name0. 5he app/name and (ull'/quali(ie"/inter(ace/name are optional. /either the se o" the */;+ AP+ itsel" nor the constr ction o" the */;+ names are convenient. 5he encaps lation o" both in a tility class (Bean3ocator) ma#es the loo9up not only more convenient$ b t also deco ples the application "rom the */;+ details.

!orces
+he J)"& AP& details sho,ld -e hidden. +he ,ser sho,ld -e inde!endent of the J)"& AP&. +he glo-al J)"& na*e sho,ld -e -,ilt as conveniently as !ossi-le7 the error'!rone constr,ction of the J)"& na*e sho,ld -e si*!lified. +he Bean3ocator sho,ld -e ca!a-le to -e ,sed inside as /ell as o,tside the EJB container.

.ol tion
5he sol tion "or this problem is straight"or'ard% the */;+ access as 'ell as the constr ction o" the */;+ names is going to be encaps lated inside a tility class$ the Bean3ocator. 5his class is responsible "or locating the -*Bs and constr ction o" the global */;+ names. 5he simplest possible sol tion 'o ld be the encaps lation o" the loo# p invocation%
tr' # return ne, <nitialContext().loo9up(jn"iAame)$catc+(Aamin7)xception ex)# %%...error escalation $

5he Bean3ocator is act ally almost as simple as the sample above. +n addition$ it closes the <nitialContext a"ter every se. .ome application servers reB ire this approach to release the internal <nitialContext reso rces. 5he loo9up method relies on generics to avoid casting%

Download at WoweBook.Com

public class Bean3ocator # public static .:0 : loo9up(Class.:0 cla==1 Strin7 jn"iAame) # Object bean D loo9up(jn"iAame)return cla==.cast(PortableRemoteObject.narro,(bean1 cla==))$ public static Object loo9up(Strin7 jn"iAame) # Context context D nulltr' # context D ne, <nitialContext()return context.loo9up(jn"iAame)$ catc+ (Aamin7)xception ex) # t+ro, ne, <lle7alState)xception(4...4)$ (inall' # tr' # context.close()$ catc+ (Aamin7)xception ex) # t+ro, ne, <lle7alState)xception(4...4)$ $ $ $

,nly the chec#ed e>ceptions are trans"ormed and the <nitialContext closed a"ter every se. +n addition$ the ret rn val e is casted "or convenience reasons. (ore interesting is the creation o" the */;+ name itsel". +t is error-prone and repetitiveS yo have to pass the application and mod le name (the name o" the -*B *A6 or EA6 archives) over and over again. 5he >lobal*A8<Aame class is a b ilder$ 'hich creates the */;+ name internally and passes it to the Bean3ocator. 5he classes >lobal*A8<Aame and Bean3ocator are responsible "or di""erent tas#s. A standalone se o" the >lobal*A8<Aame$ = st "or the creation o" the */;+ names$ is not very se" l. !or convenience reasons$ the >lobal*A8<Aame 'as moved into the Bean3ocator$ it is a static inner class.
public static class >lobal*A8<Aame # %%"eclarations omitte" public >lobal*A8<Aame() # t+is.buil"er D ne, Strin7Buil"er()t+is.buil"er.appen"(PR)&<K).appen"(S)PARA:OR)t+is.con(i7 D ne, Properties()tr' # t+is.con(i7.loa"(t+is.7etClass().7etResourceAsStream(PROP)R:BJ&< 3)))$ catc+ ()xception ex) #%CescalationC%$ t+is.appAame D t+is.con(i7.7etPropert'(APPJAA6)JY)B)t+is.mo"uleAame D t+is.con(i7.7etPropert'(6O8U3)JAA6)JY)B)$ public >lobal*A8<Aame ,it+AppAame(Strin7 appAame) #

241
Download at WoweBook.Com

t+is.appAame D appAamereturn t+is$ public >lobal*A8<Aame ,it+6o"uleAame(Strin7 mo"uleAame) # t+is.mo"uleAame D mo"uleAamereturn t+is$ public >lobal*A8<Aame ,it+BeanAame(Strin7 beanAame) # t+is.beanAame D beanAamereturn t+is$ public >lobal*A8<Aame ,it+BeanAame(Class beanClass) # return ,it+BeanAame(computeBeanAame(beanClass))$ public >lobal*A8<Aame ,it+Business<nter(ace(Class inter(a=e) # t+is.business<nter(aceAame D inter(a=e.7etAame()return t+is$ Strin7 computeBeanAame(Class beanClass) # Stateless stateless D (Stateless) beanClass.7etAnnotation(Stateless.class)i( (stateless 5D null ^^ isAot)mpt'(stateless.name())) # return stateless.name()$ State(ul state(ul D (State(ul) beanClass.7etAnnotation(State(ul.class)i( (state(ul 5D null ^^ isAot)mpt'(state(ul.name())) # return state(ul.name()$ Sin7leton sin7leton D (Sin7leton) beanClass.7etAnnotation(Sin7leton.class)i( (sin7leton 5D null ^^ isAot)mpt'(sin7leton.name())) # return sin7leton.name()$ return beanClass.7etSimpleAame()$ private boolean isAot)mpt'(Strin7 name)# return (name 5D null ^^ 5name.is)mpt'())$ public Strin7 asStrin7() # i( (appAame 5D null) # t+is.buil"er.appen"(appAame).appen"(S)PARA:OR)$ t+is.buil"er.appen"(mo"uleAame).appen"(S)PARA:OR)t+is.buil"er.appen"(beanAame)i( (business<nter(aceAame 5D null) # t+is.buil"er.appen"(4#4).appen"(business<nter(aceAame)-

249
Download at WoweBook.Com

$ return t+is.buil"er.toStrin7()$ public .:0 : locate(Class.:0 cla==) # return Bean3ocator.loo9up(cla==1 asStrin7())$ public Object locate() # return Bean3ocator.loo9up(asStrin7())$ $

/o' yo only have to create the >lobal*A8<Aame in the conte>t o" Bean3ocator and invo#e the b ilder methods%
2Overri"e public voi" init() t+ro,s Servlet)xception # t+is.testSin7leton D (:estSin7leton) ne, Bean3ocator.>lobal*A8<Aame(). ,it+BeanAame(:estSin7leton.class). locate()$

Qo do not even have to pass the application and mod le names. 7n"ort nately they cannot be derived "rom the Bean class or the b siness inter"ace itsel". 5he Bean3ocator searches "or the 7lobal.jn"i property <le in the classpath. +t contains only t'o entries% mo"ule.nameDBean3ocator6o"ule application.nameDBean3ocatorApp 5he application.name is optionalS it sho ld correspond 'ith the -A6 name. 5he mo"ule.name represents the name o" the -*B *A6 or EA6 archives and is mandatory. 5he Properties are read on every creation o" the >lobal*A8<Aame$ and co ld there"ore become a per"ormance hotspot. 5he creation and parsing o" java.util.Properties is s rprisingly "ast. 5he 7lobal.jn"i 'as loaded and parsed and the val es "etched in less than <ve milliseconds. +t t rns o t$ that there is another$ real hotspot. 5he <rst invocation o" the method Class#7etAnnotation ta#es abo t 22 milliseconds to complete and is abo t 40 times slo'er$ than the parsing o" 7lobal.jn"i.
Strin7 computeBeanAame(Class beanClass) # Stateless stateless D (Stateless) beanClass.7etAnnotation(Stateless.class)i( (stateless 5D null ^^ isAot)mpt'(stateless.name())) # return stateless.name()$ State(ul state(ul D (State(ul) beanClass.7etAnnotation(State(ul.class)i( (state(ul 5D null ^^ isAot)mpt'(state(ul.name())) # return state(ul.name()$ Sin7leton sin7leton D (Sin7leton) beanClass.7etAnnotation(Sin7leton.class)-

220
Download at WoweBook.Com

i( (sin7leton 5D null ^^ isAot)mpt'(sin7leton.name())) # return sin7leton.name()$ return beanClass.7etSimpleAame()$

5he method computeBeanAame loo#s "or .tateless$ .tate" l$ or .ingleton annotations and accesses the name() property "or this p rpose. 5he e>istence o" this property overrides the de"a lt naming and sho ld be considered in the constr ction o" the >lobal*A8<Aame. 5he annotations$ as 'ell as the already located stateless and .ingleton beans co ld be easily cached inside the Bean3ocator to improve per"ormance. Be"ore yo start to optimi?e the per"ormance and introd ce internal bean caching 'ith the .ingleton pattern$ #eep in mind that the Bean3ocator is sed at the creation time o" the components. 5he creation happens eagerly at the deployment or application start time. Bad Bean3ocator per"ormance 'o ld only hit the deployment or application server start p time. At r ntime$ all re"erences sho ld be resolved already. +n all other cases yo co ld still cache the re"erences o tside the Bean3ocator as 'ell. Eith caching o" the java.util.Properties some " rther minor optimi?ation is possible. 5he mod le and application archive names are stable and do not change$ even bet'een deployments. +nstead o" sing Properties yo co ld hard-code both val es inside the Bean3ocator and #eep them in sync 'ith the act al archive names.

6ethin#ing
Bean3ocator can be considered as a speci<c "orm o" the *2-- service locator. 5he service locator 'as designed to be able to "etch all sorts o" */;+ reso rces s ch as *(. destinations$ data so rces$ and session beans in partic lar. ;ependency in=ection 'as not available in *2--$ so the service locator provided a general approach to locate components and reso rces. +n *ava --$ the Bean3ocator is an e>ception "rom the r le$ rather than a common pattern or best practice. 5he Bean3ocator sho ld be sed only in classes 'here ;ependency +n=ection does not 'or# or is not available. +n the process o" migration "rom *2-- pro=ects to *ava -- the service locator can be replaced 'ith ;ependency +n=ection 'here available. +n the remaining "e' cases$ the service locator can be replaced 'ith the Bean3ocator. 5here is another di""erence bet'een both patternsS the service locator "etched the home inter"aces$ 'hereas the Bean3ocator ret rns the b siness inter"aces or bean instances (in case o" nointer"ace vie').

Participants and 6esponsibilities


5he Bean3ocator is sed by classes 'hen ;ependency +n=ection is not available. Bean3ocator ret rns remote or local stateless$ state" l$ and .ingleton beans. 5he Bean3ocator delegates the loo# p calls to the */;+ <nitialContext 'hich is con<g red 'ithin the jn"i.properties.

224
Download at WoweBook.Com

.trategies
Bean3ocator is a se" l tility that can be e>tended in many 'ays. 5he Havor presented here is = st an idea S yo can c stomi?e tility to s it yo r needs.

5esting
5he more sophisticated version o" Bean3ocator reads the application and mod le name "rom the con<g ration <le and ses reHection to access the metadata stored in annotations. 5his reB ires some processing time and impacts per"ormance. Qo sho ld load and stress test yo r application 'ith the Bean3ocator and search "or potential bottlenec#s as 'ell as memory lea#s. 5he introd ction o" Bean3ocator sho ld be ne tral to the r ntime per"ormance and only inH ence the start p time o" the application. .ometimes$ ho'ever$ even too long start p time is critical "or high-availability applications. A long start p time has impact on the comp tation o" (ean 5ime Bet'een !ail res ((5B!). Bad start p per"ormance ma#es do'ntime longer than necessary$ 'hich is cr cial "or patching and pdate strategies o" )A applications. .hort o"Hineperiods can be acceptable$ 'hereas longer do'ntimes co ld ma#e the introd ction o" a parallel cl ster necessary.

;oc mentation
Bean3ocator is re sable$ so it is 'orth to provide good ho'-to- se e>amples. (ore interesting$ ho'ever$ is the Bean3ocator at all. +n *ava --$ ;ependency +n=ection e>istence o" loo# p- tilities is s spicio s. 5he reason "or its mechanism behind Bean3ocator is rather obvio s doc mentation. *ava;oc doc mentation 'ith some reason 'hy yo act ally need a is s "<cient in most cases$ so the se sho ld be 'ell doc mented. 5he and does not reB ire e>tensive

ConseB ences
Portabi ity: Bean3ocator relies on glo-al J)"& na*es. &t is !orta-le across servers. Performance and sca abi ity: +here sho,ld -e no i*!act on the r,nti*e !erfor*ance. +he ,se of Bean3ocator can affect the start,! ti*e tho,gh. Testabi ity: =o, co,ld achieve the sa*e level of testa-ility /ith Bean3ocator as /ith !,re "e!endency &n.ection. &n -oth cases1 the ,ser relies on an interface. +he "e!endency &n.ection *echanis* is config,ra-le1 -,t yo, co,ld *ake the Bean3ocator config,ra-le as /ell. 0or ,nit testing1 yo, co,ld ski! the Bean3ocator entirely and rely on *ocking fra*e/orks instead. 2obustness: &f the Bean3ocator is ,sed eagerly1 it has no negative i*!act on ro-,stness. With this >fail fast? strategy the a!!lication /ill either start consistently or not at all. +his is co*!ara-le /ith the ,s,al "e!endency &n.ection *echanis*.

6elated Patterns
;ependency in=ection can be considered as Bean3ocator 2.0. ;ependency +n=ection ses a generic version o" Bean3ocator$ "actored o t "rom the application code into the "rame'or#.

222
Download at WoweBook.Com

. ch a generic Bean3ocator is con<g red 'ith metadata derived "rom conventions$ class <les$ annotations$ and$ optionally$ K(9. 5he located bean is a tomatically in=ected by the "rame'or#. 5he *2-- service locator is also closely related to Bean3ocator. +ts implementation 'as someho' limited beca se o" the lac# o" global */;+ names$ generics$ and annotations.

223
Download at WoweBook.Com

Download at WoweBook.Com

%hread %racker
.ession bean instances are al'ays e>ec ted by e>actly one thread. !or the entire e>ec tion time o" a method$ a single thread is associated 'ith the bean instance and probably the 'hole call tree. 5he application server pools the threads and re ses them bet'een calls to the session beans. 5he threads have arbitrary$ application server speci<c names$ and are o"ten n mbered$ "or e>ample$ http..9Eor#er5hread-1010-0$ http..9Eor#er5hread-1010-4 (Dlass<sh v2) and so on.

Problem
Beca se the threads are pooled and have generic names$ it is hard to associate a method in deadloc# scenario 'ith a st c# thread. +" yo connect to the application server 'ith *Console or Ais alA($ yo 'ill only see a b nch o" threads 'ith random names. !or tro bleshooting p rposes it 'o ld be help" l to name the threads a"ter the method "or the d ration o" its e>ec tion$ and roll bac# this change = st a"ter the method call.

!orces
+he sol,tion sho,ld -e !orta-le across servers. +he e6tension of the *onitoring ca!a-ilities sho,ld -e clearly se!arated fro* the -,siness code. +he thread tracking sho,ld -e easily activated and deactivated. &t sho,ld -e easy to re*ove all additional *onitoring f,nctionality (and class files as /ell) -efore !rod,ction de!loy*ent. +he thread tracking sho,ld -e generic eno,gh to -e a!!lied to already e6isting -eans.

.ol tion
5he b siness methods o" the bean are e>ec ted in a pooled thread. 5he challenge is to change the thread name to something h man readable$ s ch as the name o" the bean 'ith concatenated method name$ and change it to the origin a"ter the call. Qo 'ill have to intercept the call be"ore the act al method e>ec tion. 5his is act ally a per"ect tas# "or an -*B 3 interceptor. +t is even e>ec ted in the same transaction$ thread$ and sec rity conte>t as the -*B$ and has even access to the Bean instance. An interceptor 'raps the bean instance and can also easily change the name o" the thread.
public class :+rea":rac9er # 2Aroun"<nvo9e public Object annotate:+rea"(<nvocationContext invCtx) t+ro,s )xception# Strin7 ori7inAame D :+rea".current:+rea"().7etAame()Strin7 beanAame D invCtx.7et:ar7et().7etClass().7etAame()Strin7 tracin7Aame D beanAame H 4#4 H invCtx.7et6et+o"().7etAame() H 4 4 H ori7inAametr'# :+rea".current:+rea"().setAame(tracin7Aame)return invCtx.procee"()$(inall'# :+rea".current:+rea"().setAame(ori7inAame)$

Download at WoweBook.Com

$ $

5he :+rea":rac9er can be attached to a partic lar class sing annotations or K(9. 5he choice is highly dependent on yo r deployment intentions. +n case yo are planning to se the :+rea":rac9er in prod ction$ annotations is the 'ay to go. +" yo are sing :+rea":rac9er = st "or tro bleshooting$ it is better to se K(9 deployment descriptors. +n the latter case$ yo donRt even have to to ch the e>isting code.
2Stateless )2nterceptors(4 read4rac3er.class) public class 8umm'Bean implements 8umm'Remote # public Strin7 sa' ello(Strin7 messa7e)# tr' # %%actuall' not allo,e" in )*B container %%onl' nee"e" to simulate a "ea" loc9 :+rea".sleep(XRRRR)$ catc+ (<nterrupte")xception ex) # $ return 4)c+oG 4 H messa7e$ $

A"ter the activation o" the :+rea":rac9er yo sho ld be able to identi"y slo' or deadloc#ed methods already by the name o" the thread (see !ig re 4).

Figure 1. 'enamed thread in the (isual(M Changing the thread name is also se" l "or the monitoring o" b siness transactions. A Service 0a@ade starts a ne' transaction "or every incoming call. 5he transaction is propagated to all services $ ;A,s$ and other participants. 5he name o" the method is act ally the name o" the transaction$ 'hich is in t rn e>ec ted in a single thread. 5he :+rea":rac9er applied on a .ervice !a@ade changes the name o" the thread to the name o" the c rrently e>ec ted .ervice !a@ade method. 5his method represents the b siness transaction$ so 'e can easily monitor its thro ghp t$ per"ormance$ and 'rite transactionspeci<c logs. -ven more se" l is the :+rea":rac9er "or message-driven beans monitoring. 5hey are e>ec ted asynchrono sly in a separate transaction and thread. 5he threads co ld even originate "rom a distinct pool. 5he :+rea":rac9er co ld help yo <nd potential bottlenec#s and slo' on6essa7e methods. Qo only have to attach the :+rea":rac9er to a s spicio s messagedriven beanthey can be intercepted since -*B 3.0.

6ethin#ing

22:
Download at WoweBook.Com

+n *2-- 4." crossc tting interceptors (javax.servlet.&ilter) 'ere only available "or the .ervlet AP+s. 5here 'as no standardi?ed 'ay to decorate beans. Eith the advent o" -*B 3 and the introd ction o" interceptors$ crossc tting concerns can be easily "actored o t "rom the b siness logic. 5his can be achieved 'itho t third-party "rame'or#s or libraries.

Participants and 6esponsibilities


5he :+rea":rac9er can be applied to session beans and message-driven beans. P,*,s are not managed and there"ore cannot be intercepted by the container. !or P,*,s 'ith inter"aces the reg lar dynamic pro>y can be applied instead and the :+rea":rac9er implementation largely re sed.

5esting
+nterceptors can be tested o tside o" the container 'ith moc#ing. Qo 'ill need to provide an implementation o" the <nvocationContext1 'hich chec#s 'hether the name o" the c rrent thread has changed.
public class :+rea":rac9er:est # private :+rea":rac9er t+rea":rac9erprivate Strin7 t+rea"Aame2Be(ore public voi" setUp() # t+is.t+rea":rac9er D ne, :+rea":rac9er()$ 2:est public voi" testAnnotate:+rea"() t+ro,s )xception # 2nvocation0onte=t ic > ne( 2nvocation0onte=t() { public Object 7et:ar7et() # return :+rea":rac9er:est.t+is$ public 6et+o" 7et6et+o"() # tr' # return :+rea":rac9er:est.class.7et6et+o"(4testAnnotate:+rea"41 (ClassNO)null)$ catc+ (AoSuc+6et+o")xception ex) # t+ro, ne, <lle7alState)xception(4Cannot (in" met+o" 4 Hex1ex)$ $ public Object procee"() t+ro,s )xception # :+rea":rac9er:est.t+is.set:+rea"Aame(:+rea".current:+rea"().7etA ame())return null$

220
Download at WoweBook.Com

%%... irrelevant met+o"s omitte" $t+is.t+rea":rac9er.annotate:+rea"(ic)assertAotAull(t+is.t+rea"Aame)assert:rue(t+is.t+rea"Aame.starts!it+(t+is.7etClass().7etAame()))%%@some asserts omitte" $ public voi" set:+rea"Aame(Strin7 t+rea"Aame) # t+is.t+rea"Aame D t+rea"Aame$ $

Qet more important are integration and load tests. -ven 'hen the interceptor 'or#s and the names o" the threads are changed as e>pected in the nit test$ yo co ld enco nter some problems in the target environment. Act ally changing the name o" the thread is restricted by the -*B spec% N5he enterprise bean m st not attempt to manage threads. 5he enterprise bean m st not attempt to start$ stop$ s spend$ or res me a thread$ or to change a threadRs priority or name. 5he enterprise bean m st not attempt to manage thread gro ps.O 5he application server co ld change the name bac# or even thro' an AccessControl)xception (or java.securit'.Securit')xception)$ 'hich 'o ld roll bac# the c rrent transaction and destroy the a""ected component. 5he :+rea":rac9er$ as every indirection$ inH ences the per"ormance as 'ell. +nterception 'or#s on most application servers 'ith reHection. 6eHective access to methods is signi<cantly slo'er$ than a direct call$ b t still irrelevant in a distrib ted environment. A database access or call to a legacy host is a lot slo'er than a local call 'ith reHection. +n cases 'here methods are called several times per second$ the :+rea":rac9er co ld become a bottlenec#. +t is better$ "aster$ and easier to per"orm the load test and analy?e the res lts$ instead o" trying to predict the behavior and optimi?e in advance.

;oc mentation
Annotations doc ment already very 'ell the interception points. +n case yo are sing K(9 deployment descriptors to activate the :+rea":rac9er$ yo sho ld doc ment the reason "or doing so and it sho ld be clear 'hich components are r nning 'ith :+rea":rac9er$ and 'hich are not.

ConseB ences
Portabi ity: +here is nothing a!!lication servers!ecific in the :+rea":rac9er. Ho/ever1 it violates the !rogra**ing restrictions -y changing the c,rrent thread:s na*e. +he violation of the s!ec is al/ays !ro-le*atic7 yo, co,ld even r,n into tro,-le ,!grading or !atching an a!!lication server. Strictly s!eaking the :+rea":rac9er cannot -e considered as a !orta-le sol,tion. &t is good eno,gh for a single !ro.ect1 -,t has to -e caref,lly eval,ated for a *,lti' server environ*ent.

221
Download at WoweBook.Com

Performance: Every indirection slo/s do/n the !erfor*ance. +his is also tr,e for the :+rea":rac9er. Altho,gh the overhead of the act,al algorith* (changing the thread:s na*e) is negligi-le1 the interce!tion itself is several ti*es slo/er /hen co*!ared to a direct local call.

6elated Patterns
All intercepting patterns s ch as ;ependency +n=ection ->tender are similar. :+rea":rac9er is applied on .ervice !a@ades and message-driven beans. !or <ner monitoring and search "or hotspots yo co ld deploy .ervices 'ith :+rea":rac9er as 'ell.

229
Download at WoweBook.Com

Download at WoweBook.Com

De"endency 'n6ection E<tender


+nversion o" control (+oC) "rame'or#s s ch as D ice or .pring have their o'n semantics "or ;ependency +n=ection (;+). Both "rame'or#s provide richer ;+ capabilities than -*Bs. +oC "rame'or#s need bootstrapping mechanism to load the <rst class be"ore the ;ependency +n=ection becomes transparent.

Problem
5he ;+ mechanism o" "rame'or#s s ch as D ice is not compatible 'ith -*Bs. D ice ses the 2<nject annotation to indicate in=ection points and s pports constr ctor in=ection$ 'hich is not available in -*Bs. Beca se o" di""erent semantics and mechanisms$ it is not possible to directly deploy e>isting D ice or .pring components as -*Bs. 5hey have to be integrated instead.

!orces
=o, /ant to de!loy an e6isting 2,ice (other fra*e/orks /orks si*ilarly) co*!onent /itho,t *odification in an EJB a!!lication. +he legacy "& co*!onent has to !artici!ate in EJB transactions and the sec,rity conte6t. +he integration sho,ld -e trans!arent for the legacy "& co*!onent. EJBs sho,ld co'e6ist /ith *anaged classes fro* the integrated fra*e/ork. +he *anaged classes fro* the >legacy? "& fra*e/orks sho,ld -e directly in.ected into EJBs.

.ol tion
Bootstrapping and in=ection is a common$ re sable tas#. +t is also independent "rom the b siness logicitRs a cross-c tting concern. 5he in=ection logic is a per"ect candidate to be implemented as an interceptor. +t co ld then be applied to any session bean yo 'ant. D ice is similar to -*BS a managed component is comprised o" an inter"ace and a class$ 'hereas the in=ection al'ays relies on the inter"ace and the "rame'or# is responsible "or the creation and management o" the implementation. 5he association bet'een the inter"ace and its implementation is per"ormed in a H ent 'ay 'ith the implementation o" the com.7oo7le.inject.6o"ule inter"ace.
public class 6essa7in76o"ule implements 6o"ule# public voi" con(i7ure(Bin"er bin"er) # bin"er.bin"(6essa7eProvi"er.class).to(6essa7eProvi"er<mpl.class)$ $

5he 6o"ule implementation is sed "or the creation o" the in=ector instance$ 'hich is sed "or the bootstrapping process.
public class 6essa7eProvi"er:ester # public static voi" main(Strin7NO ar7s) # 2n!ector in!ector > Euice.create2n!ector(ne( 7essa+in+7odule()); 7essa+e6rovider provider > in!ector.+et2nstance(7essa+e6rovider.class); Strin7 messa7e D provi"er.7et6essa7e()S'stem.out.println(4:+e messa7e isG 4 H messa7e)$ $

Download at WoweBook.Com

D ice 'ill in=ect all dependencies into the 6essa7eProvi"er implementation transparently$ no additional steps are necessary. +t is eno gh = st to in=ect the root class o" each 6o"ule into a service or .ervice !a@ade. Ee se D ice-speci<c annotations "or this p rpose$ to di""erentiate this type o" in=ection "rom s al -*B in=ection.
2Stateless public class Service&aca"eBean # )2n!ect private 6essa7eProvi"er messa7epublic Strin7 7et ello(Strin7 ms7)# return ms7 H 4 4 H messa7e.7et6essa7e()$ $

+" yo compile and start the Service&aca"eBean$ yo 'ill r n into a AullPointer)xception. An -*B is created by the container and not >uicethe <njector 'asnRt able to process and in=ect the dependencies yet. Qo need a 'ay to in=ect the instance managed by D ice be"ore the invocation o" any b siness method. Qo co ld achieve that by coding the in=ection in every method$ 'hich is error-prone and violates the separation o" concerns idea. +nterceptor is a more nat ral place "or a tomated in=ection. +t is al'ays invo#ed be"ore the act al b siness method call and it is strictly separated "rom the b siness logic. ! rthermore$ an interceptor can react to li"ecycle events s ch as 2PostConstruct or 2Pre8estro'. 5he 2PostConstruct callbac# is per"ectly s itable "or the bootstrapping o" the <njector. Ehen sing this callbac#$ every .ervice !a@ade or .ervice instance 'ill get its dedicated <njector instance.
public class Per6et+o">uice<njector# private <njector injector2PostConstruct public voi" startup>uice(<nvocationContext invocationContext) t+ro,s )xception# invocationContext.procee"()t+is.injector D >uice.create<njector(ne, 6essa7in76o"ule())$ 2Aroun"<nvo9e public Object inject8epen"encies(<nvocationContext ic) t+ro,s )xception# t+is.injector.inject6embers(ic.7et:ar7et())return ic.procee"()$ $

5he 2Aroun"<nvo9e method inject8epen"encies per"orms the act al in=ection. !or that p rpose it "etches the instance o" the intercepted bean "rom the <nvocationContext and passes it to the method <njector#inject6embers.

232
Download at WoweBook.Com

5he D ice components are in=ected be"ore every invocation o" a b siness method. .tateless session bean instances are interchangeable bet'een the clientRs method calls. Qo m st not rely on their states. Alternatively$ yo co ld in=ect pro>ies into the session bean once at creation time and replace the real s b=ects in the ;ependency +n=ection "rame'or#. +" the legacy components are stateless and idempotent$ yo co ld even in=ect them once at the creation time o" each stateless or state" l session bean instance. 5he interceptor becomes even simpleryo donRt need the 2Aroun"<nvo9e method any more.
public class Per<nstance>uice<njector# 2PostConstruct public voi" startAn"<nject(<nvocationContext invocationContext) t+ro,s )xception# invocationContext.procee"()<njector injector D >uice.create<njector(ne, 6essa7in76o"ule())injector.inject6embers(invocationContext.7et:ar7et())$ $

6egardless o" the strategy yo are choosing$ yo 'ill have to declare and associate the interceptor 'ith a bean. Qo can se annotations or K(9 "or that p rpose. Annotations at class level do already doc ment this pattern in code and are better s pported by standard +;-s. 5his ma#es the in=ection process more e>plicit and easier to nderstand.
2Stateless 23ocal(Service&aca"e.class) )2nterceptors(6er7et odEuice2n!ector.class) public class Service&aca"eBean implements Service&aca"e# 2<nject private 6essa7eProvi"er messa7epublic Strin7 7et ello(Strin7 ms7)# return ms7 H 4 4 H messa7e.7et6essa7e()$

6ethin#ing
-*B 3 are He>ible eno gh to integrate proprietary ;+ "rame'or#s. 5he ;ependency +n=ection ->tender opens ne' 'ays "or the co-e>istence o" di""erent "rame'or#s behind a .ervice !a@ade. 5he integration o" legacy components 'ith -*Bs is simple and almost seamlessS it doesnRt reB ire any K(9 con<g ration. 5his ma#es the ;ependency +n=ection ->tender approach even interesting "or re se o" smaller ch n#s o" e>isting " nctionality.

Participants and 6esponsibilities


5he interceptor plays the most important role. +t is the act al bridge bet'een -*Bs and legacy components. 5he +nterceptor is re sable across services and .ervice !acades. +t is responsible "or% +he config,ration of the "& fra*e/ork.

233
Download at WoweBook.Com

+he -ootstra!!ing of the legacy "& fra*e/ork. Per'instance or !er'*ethod in.ection of co*!onents into the service or Service 0a@ade. 5he session bean has only to declare dependencies to managed classes sing the legacy "rame'or#Rs semantics and declare the interceptor. 5he in=ection and bootstrapping are transparent "or the application developer.

.trategies
Statef,l Session Bean &n.ector A state" l session bean remains associated "or its li"etime 'ith its client. 5here is a one-to-one relationship bet'een the client and the state" l session bean. 5he state o" a state" l session bean is never shared bet'een clients. +n that case yo can se per-instance in=ectors 'itho t any problems. 5he in=ected components can be cached "or the d ration o" the sessionS yo donJt have to in=ect "resh members be"ore every method call. 5he legacy "rame'or#$ ho'ever$ becomes responsible "or creating state" l components at in=ection time as 'ell. ,ther'ise di""erent state" l session bean co ld access the same shared state$ 'hich can lead to inconsistencies. Stateless Session Bean &n.ector +n stateless session beans yo cannot rely on any relation bet'een the bean instances and its clients. All the members have to be in=ected either every time be"ore a method call or yo have to se smart pro>ies$ 'hich react$ "or e>ample$ to transactions. +dempotent components$ ho'ever$ can be in=ected once and re sed bet'een session bean instances. +n general per-method in=ectors are a good choice. +ransactional &ntegration 5he in=ected components already participate in a transaction started in the session bean. 5he transactional reso rces are enlisted in the transaction by the -*B container a tomaticallyS the managed classes only haveto loo# p or in=ect transactional reso rces ("or e>ample$ 8ataSource$ )ntit'6ana7er$ or a 8estination) "rom the */;+ conte>t and se it. Qo co ld even in=ect the same reso rce into a reg lar session bean 'itho t losing consistency. +n the same transaction$ both the session bean and the managed class access the reso rce in the same transactional conte>t and th s see the c rrent transaction state.

5esting
5here is no logic other than integration in the ;+- pattern. +ntegration tests become essentially important. 5he in=ection process slo's do'n the application$ so yo sho ld per"orm load and stress tests as 'ell.

;oc mentation

238
Download at WoweBook.Com

Altho gh the ;+- implementation is easy$ there is still some NmagicO involved. Qo sho ld 'ell e>plain the concepts and mechanics behind the ;+- and especially the reasons "or s ch integration. ;+- is highly re sable$ so it is eno gh to doc ment it once. /ot only the pattern$ b t especially its se sho ld be doc mented. 5his can be achieved in an elegant 'ay sing the 2<nterceptor annotation instead o" the K(9 con<g ration. 5he annotation not only doc ments the occ rrence o" the ;+- in yo r code$ b t enables the developer to navigate "rom the service or .ervice !a@ade into the interceptor sing standard +;- "eat res (s ch as a C569-clic# in -clipse and /etBeans).

ConseB ences
Performance: Both interce!tors and "& rely on reflection /hich is relatively slo/. +his only *atters for the r,nti*e !erfor*ance1 if yo, are in.ecting the *e*-ers -efore every -,siness *ethod invocations. Even in this case1 the in.ection !rocess /ill -e *,ch faster than an average data-ase access. Portabi ity: +he "e!endency &n.ection E6tender relies on interce!tors only and does not ,se any !ro!rietary a!!lication server feat,res. &t is !orta-le across Java EE 4 a!!lication servers. Testabi ity: "e!endency &n.ection E6tender interce!tor i*!le*entation is hard to test1 -eca,se it relies on the e6isting EJB and "& fra*e/ork infrastr,ct,re. A!!lications that ,se the "e!endency &n.ection E6tender are easy to test1 even o,tside of the container. All yo, have to do is instantiate the -ean as a P(J( and ,se the interce!tor logic to in.ect the *e*-ers. +his is only re8,ired for EJB 3.$ containers1 in EJB 3. the e*-edda-le container can -e ,sed for ,nit testing.

6elated Patterns
All interceptor-based patterns are someho' related to the ;ependency +n=ection ->tender$ especially the .,A strategy o" the .ervice !a@ade and Payload ->tractor. ;+- is o"ten applied on .ervice !a@ades or$ in larger components on services$ to e>pose the legacy "rame'or# in an -*B 'ay to the presentation tier. ;A, co ld also rely on proprietary reso rces and integrate D ice or .pring components this 'ay.

232
Download at WoweBook.Com

Download at WoweBook.Com

Payload E<tractor
5he message-driven beanRs method on6essa7e e>pects the inter"ace javax.jms.6essa7e as a parameter that has to be cast into a more concrete representation to e>tract the payload. 5he method on6essa7e is transactional. (essages are only considered as delivered i" the transaction is going to be committed 'itho t any nhandled nchec#ed e>ceptions.

Problem
5he e>traction o" the payload reB ires yo to chec# the message type$ cast it$ e>tract the payload$ potentially cast it again ("or e>ample$ casting the Object6essa7e payload "rom Seriali=able to something more meaning" l)$ and catch and properly handle chec#ed e>ceptions. 5hese tas#s are repetitive$ verbose$ and error-prone. -specially hard to implement is proper handling o" 'rong message types. All destination instances are identicalthey are only disting ished by their names and not the message type. /othing prevents other prod cers to p t a message 'ith ne>pected types into the destination. . ch ne>pected messages co ld ca se ClassCast)xceptions$ 'hich leads to the rollbac# o" the c rrent transaction. 5he message 'o ld be p t bac# to the destination and redelivered again. 5he n mber o" attempts depends on the message providers con<g ration. +" yo = st ignore s ch messages$ it 'ill disappear "rom the destination and 'ith it the chance to <nd the act al con<g ration error. .yntactically incorrect or messages 'ith 'rong types are o"ten called poisoned messages.

!orces
Poisoned *essages have to -e handled !ro!erly. At least they have to -e redirected into a dedicated dead letter 8,e,e. +he ty!e checking and error handling is re,sa-le and has to -e factored o,t fro* the *essage'driven -eans into a dedicated co*!onent. Error handling has to -e config,red and i*!le*ented o,tside of the -,siness logic. +he sol,tion sho,ld -e transactional.

.ol tion
An interceptor is an obvio s candidate "or error handling and payload e>traction. (essage-driven beans can be decorated 'ith interceptors$ the on6essa7e method can be entirely 'rapped. )ence interceptor has access to the methodRs parameter$ here an instance o" javax.jms.6essa7e$ it can per"orm the casts and e>tract the payload "or yo . 5he e>tracted payload is passed to the method consume 'ith corresponding parameter type. +tRs only a convention. Alternatively$ yo co ld pic# a method annotated 'ith$ "or e>ample$ 26essa7eSin9 or 26essa7eConsumer annotation and pass the payload to it as parameter as 'ell. A message-driven bean sho ld not implement any b siness methods$ so that s ch He>ibility is act ally s perH o s.

Download at WoweBook.Com

5he message-driven bean only has to declare the interceptor on the class level or the on6essa7e method. +n this case$ it 'ill have e>actly the same e""ect. Annotation o" the on6essa7e method is$ ho'ever$ more clear and e>plicit so it sho ld be pre"erred.
26essa7e8riven(mappe"Aame D 4ajax41 activationCon(i7 D # 2ActivationCon(i7Propert'(propert'Aame D 4ac9no,le"7e6o"e41 propert'?alue D 4Auto/ac9no,le"7e4)1 2ActivationCon(i7Propert'(propert'Aame D 4"estination:'pe41 propert'?alue D 4javax.jms.;ueue4) $) public class 6essa7eConsumerBean implements 6essa7e3istener # 2Overri"e )2nterceptors(6ayload,=tractor.class) public voi" on6essa7e(6essa7e messa7e) # %C t+e ,or9 is "one in interceptor C% $ public voi" consume(Strin7 messa7e)# S'stem.out.println(4Pa'loa" receive"G 4 H messa7e)$ $

5he interceptor Pa'loa")xtractor is invo#ed be"ore the method on6essa7e$ it receives the act al message and detects its type. ;epending on the type$ it casts the message$ e>tracts its contents$ and invo#es the method consume sing reHection.
public class Pa'loa")xtractor # public static (inal Strin7 COASU6)J6): O8 D 4consume42)*B private 8ea"3etter an"ler "l+2Aroun"<nvo9e public Object au"it(<nvocationContext invocationContext) t+ro,s )xception# Object m"b D invocationContext.7et:ar7et()6et+o" met+o" D invocationContext.7et6et+o"()i((4on6essa7e4.equals(met+o".7etAame()))# 6essa7e jms6essa7e D (6essa7e) messa7eParameter(invocationContext)invo9e6et+o"!it+Sin7leParameter(jms6essa7e1m"b)$ return invocationContext.procee"()$ private voi" escalate)rror(6essa7e ori7in6essa7e) # t+is."l+.,ron76essa7e:'pe(ori7in6essa7e)$ private voi" invo9e6et+o"!it+Sin7leParameter(6essa7e jms6essa7e1Object m"b) # i((jms6essa7e instanceo( Object6essa7e)# tr' #

231
Download at WoweBook.Com

Object6essa7e om D (Object6essa7e) jms6essa7eSeriali=able pa'loa" D om.7etObject()invo9eConsume6et+o"(m"b1 jms6essa7e1 pa'loa")$ catc+ (*6S)xception ex) # t+ro, ne, <lle7alState)xception(4Cannot 7et pa'loa" (rom Object6essa7e 4 Hex1ex)$ $else i((jms6essa7e instanceo( :ext6essa7e)# tr' # :ext6essa7e tm D (:ext6essa7e) jms6essa7eStrin7 pa'loa" D tm.7et:ext()invo9eConsume6et+o"(m"b1 jms6essa7e1 pa'loa")$ catc+ (*6S)xception ex) # t+ro, ne, <lle7alState)xception(4Cannot 7et pa'loa" (rom :ext6essa7e 4 Hex1ex)$ $else# escalate)rror(jms6essa7e)$ $ private voi" invo9eConsume6et+o"(Object m"b16essa7e messa7e1Object met+o"Parameter)# tr' # m"b.7etClass().7et6et+o"(COASU6)J6): O81met+o"Parameter.7etClass()).inv o9e(m"b1 met+o"Parameter)$ catc+ (AoSuc+6et+o")xception ex) # escalate)rror(messa7e)$ catc+ ()xception ex) # t+ro, ne, <lle7alState)xception(4Cannot access t+e consume met+o" 4 H ex1 ex)$ $ private Object messa7eParameter(<nvocationContext context)# return context.7etParameters()NRO$ $

8ea"3etter an"lerBean is responsible "or handling already cons med messages that cannot be processed by the application. +t sends the message into a dedicated dead letter B e e. 5hese poisoned messages are handled either man ally by a system administrator or more li#ely$ they are passed to an emergency management system$ 'hich generates a tic#et and escalates it.
2Stateless public class 8ea"3etter an"lerBean implements 8ea"3etter an"ler # 2Resource(name D 4jms%8ea"3etter;ueue4) private ;ueue "ea"3etter;ueue2Resource(name D 4jms%8ea"3etter;ueue&actor'4) private Connection&actor' "ea"3etter;ueue&actor'2Overri"e public voi" ,ron76essa7e:'pe(6essa7e messa7e) # tr' #

239
Download at WoweBook.Com

t+is.sen"*6S6essa7e:o8ea"3etter;ueue(messa7e)$ catc+ (*6S)xception ex) # %%exception +an"lin7@ $ $ private voi" sen"*6S6essa7e:o8ea"3etter;ueue(6essa7e messa7e) t+ro,s *6S)xception # Connection connection D nullSession session D nulltr' # connection D "ea"3etter;ueue&actor'.createConnection()session D connection.createSession((alse1 Session.AU:OJACYAO!3)8>))6essa7ePro"ucer messa7ePro"ucer D session.createPro"ucer("ea"3etter;ueue)messa7ePro"ucer.sen"(messa7e)$ (inall' # i( (session 5D null) # tr' # session.close()$ catc+ (*6S)xception e) # %%exception +an"lin7 $ $ i( (connection 5D null) # connection.close()$ $ $ $

5he 8ea"3etter an"lerBean sho ld not e>cl sively rely on messaging to escalate the errors. 8ea"3etter an"lerBean might be called by problems 'ith the *(. server$ so yo sho ld log the messages or even send them via email as a "allbac# sol tion and not e>l sively rely on the *(. in"rastr ct re. 5he dead letter B e e sho ld be con<g red as persistentS other'ise all ncons med messages are lost on every server restart.

6ethin#ing
+n *2-- 4.8 it 'as impossible to decorate message-driven beans relying on b ilt-in " nctionality 'itho t byte code e>tension. +nstead o" "actoring o t the crossc tting concerns$ yo had to move them in an abstract s perclass$ 'hich 'as comparable to the Pa'loa")xtractor. 5his approach 'as more intr sive and comple>. +nterceptors introd ced a more pragmatic and light'eight alternative. Qo can = st apply an interceptor$ 'hich 'ill cast the message$ e>tract the payload$ and invo#e the consume method. 5he method on6essa7e remains empty$ b t 'ill still be invo#ed. 5he only overhead is the introd ction o" the method consume. +n case yo need a speci<c treatment o" messages$ yo can remove the 2<nterceptors tag and provide yo r o'n

280
Download at WoweBook.Com

e>traction and error-handling logic. Eith Pa'loa")xtractor yo can start immediately 'ith the de"a lt behavior and implement c stom code on demand.

Participants and 6esponsibilities


5he interceptor Pa'loa")xtractor is the #ey part o" this pattern. +t is responsible "or% +he interce!tion of the *ethod on6essa7e and hi.acking its !ara*eter. #asting the 6essa7e into a concrete interface ( Object6essa7e1 :ext6essa7e1 B'tes6essa7e1 Stream6essa7e or 6ap6essa7e). Payload e6traction. +he invocation of a -,siness *ethod /ith the !ayload as !ara*eter. Pro!er escalation of ,nrecovera-le errors -y invoking the 8ea"3etter an"lerBean. 5he 8ea"3etter an"lerBean only has to "or'ard the poisoned message 'ith conte>t in"ormation to an emergency management system or other reso rce. 5he remaining responsibility o" the message-driven bean is only the delegation o" the e>tracted payload to a service.

.trategies
5here is only one strategy (@+nterceptors) "or intercepting the message-driven bean$ b t co ntless error handling strategies$ 'hich are highly dependent on yo r +5 management in"rastr ct re.

5esting
Pa'loa")xtractor is a highly re sable pattern$ 'hich implements the repetitive pl mbing "or yo . -specially the error handling and "or'arding o" the poisoned messages are already implemented in a central place. +ntegration tests are still important$ beca se yo 'ill have to test the escalation o" errors as 'ell. +t is entirely based on reHection$ so that it 'ill de<nitely slo' do'n yo r system. +n the entire conte>t$ the overhead is probably negligible in general$ b t sho ld be veri<ed 'ith load and per"ormance tests. 5he method consume sho ld al'ays be nit tested to veri"y the proper trans"ormation and delegation o" messages.

;oc mentation
-mpty on6essa7e methods and standalone consume methods are not obvio s and can ca se con" sion. Qo sho ld describe the idea o" Pa'loa")xtractor in a t torial-li#e "ormat 'ith some 'or#ing hello 'orld e>amples. 5he se o" this pattern does not reB ire a lot o" doc mentation$ the 2<nterceptors annotation 'ith the Pa'loa")xtractor as a val e is e>plicit eno gh. /o additional *ava;oc is reB iredit 'o ld only repeat the "acts that the t torial already describes.

284
Download at WoweBook.Com

ConseB ences
Performance: Both the interce!tion and the invocation of the *ethod consume heavily rely on reflection. When co*!ared to the straight *ethod invocation (less than one *illisecond)1 reflection is very slo/ (a fe/ *illiseconds). &f yo, are ,sing a distri-,ted !rotocol1 or even I%9 as !ayload1 it /ill take a fe/ h,ndred *illiseconds to cons,*e and !rocess the *essage. &n high'!erfor*ance syste*s1 interce!tion co,ld -eco*e an iss,e1 -,t instead of trying to !re*at,rely o!ti*i5e yo,r syste*1 yo, sho,ld !erfor* so*e load tests and *eas,re the act,al overhead. !aintenance: Pa'loa")xtractor greatly si*!lifies the code and centrali5es error handling and !l,*-ing as a cross'c,tting concern. &t is non'intr,sive7 yo, can easily deactivate the interce!tion and !rovide yo,r o/n e6traction logic. Testabi ity: +he e6traction is cleanly se!arated fro* the act,al -,siness logic. +he *ethod consume is easily ,nit'testa-le. +esting of the act,al Pa'loa")xtractor i*!le*entation is still hard1 -,t it has to -e !erfor*ed only once. Comp exity: +he rec,rring e6traction and error'handling logic are i*!le*ented once and factored o,t into the interce!tor as a co**on cross'c,tting concern. +he *essage'driven -eans are al*ost e*!ty. +his greatly red,ces the code co*!le6ity.

6elated Patterns
!rom an implementation point o" vie'$ the Pa'loa")xtractor is similar to the ;ependency +n=ection ->tender. Pa'loa")xtractor "or'ards the content o" the message to services$ 'hich are in=ected to the message-driven bean.

282
Download at WoweBook.Com

Reso$rce Binder
*ava /aming and ;irectory +nter"ace (*/;+) is a *;& AP+ "or 'hich many .P+s (s ch as C,6BA$ 6(+$ 9;AP or even !ile .ystem) already e>ist. +t is sed in a *ava -- conte>t to register (Context#bin"$ Context#rebin") and <nd (Context#loo9up) deployed components and reso rces. 5he application servers tend to se the C,6BA implementation o" the */;+ AP+. 5he -*B 3 ;ependency +n=ection also relies on */;+ behind the scenes.

Problem
5he application server registers the components at the start p (deployment) time o" the application. 6eso rces and services s ch as 8ataSources $ 8estination services$ or *CA connectors are registered sing the administration console. +n both cases the application servers per"orm the binding o" a reso rce to a */;+ name and th s the entire registration process. 5here are no standard hoo#s "or the registration o" c stom reso rces.

!orces
=o, need a convenient and ro-,st /ay to register c,sto* reso,rces. +he registration sho,ld -e a!!lication server inde!endent. +he reso,rces sho,ld -e in.ecta-le into EJBs. )o so!histicated lifecycle *anage*ent is re8,iredH the reso,rces are stateless and can -e *aintained as a Singleton1 or *ore !recisely1 0ly/eight (2o0) !attern.

.ol tion
-*B 3.4 .ingletons can be initiali?ed at application start p time. Qo only have to designate the .ingleton 'ith the 2Startup annotation and provide a 2PostConstruct method. 5he 2PostConstruct method 'ill be invo#ed at serverRs start p$ or at the deployment time$ so it is the per"ect place "or the registration o" c stom reso rces.
2Startup 2Sin7leton public class ResourceBin"er # 2PostConstruct public voi" bin"Resources()# tr' # Context context D ne, <nitialContext()context.rebin"(CustomResource.*A8<JAA6)1 ne, CustomResource())$ catc+ (Aamin7)xception ex) # t+ro, ne, <lle7alState)xception(4Cannot bin" resource 4 Hex1ex)$ $ $

5he act al logic is trivial% yo only have to instantiate yo r reso rce$ then <nitialContext$ and register the ne'ly created reso rce sing the Context#bin" or Context#rebin" methods. 5he method bin" thro's javax.namin7.AameAlrea"'Boun")xception in case an ob=ect 'ith the passed name is already registeredS the method rebin" = st over'rites any already e>isting ob=ect.

Download at WoweBook.Com

5he c stom reso rce can be an ordinary P,*, 'itho t any special reB irements. .ome application servers may have special reB irements "or the reso rces (s ch as implementing java.io.Seriali=able or javax.namin7.Re(erenceable)$ b t it sho ld 'or# o t o" the bo> (this e>ample 'or#s 'ith the *ava -- re"erence implementation$ Dlass<sh v2 and v3).
public class CustomResource# public (inal static Strin7 *A8<JAA6) D 4t+eAame4public voi" "oSomet+in7()# S'stem.out.println(4#8one 54)$ $

5he registered reso rce can be directly in=ected to all *ava -- managed classes and -*Bs in partic lar. Qo have only to declare the dependency and annotate it 'ith the 2Resource annotation. 5he */;+ name is passed as name$ and sho ld correspond 'ith the name sed "or the registration o" the c stom reso rce. 5he "ollo'ing e>ample sho's an in=ection o" c stom reso rces into a session bean 'ith 2Resource annotation%
2Sin7leton 2Startup 28epen"sOn(4ResourceBin"er4) public class CustomResourceClient # )%esource(name>0ustom%esource.-'.2<'17,) private CustomResource resource2PostConstruct public voi" invo9eResource()# t+is.resource."oSomet+in7()S'stem.out.println(4Resource invo9e"4)$ $

5he ;ependency +n=ection 'or#s even in .ingleton beans$ i" they are created a"ter the ResourceBin"er. 5his can be achieved 'ith the 28epen"sOn annotation. +t 'ill "orce the container to instantiate the ResourceBin"er be"ore the designated class. !or all other reso rces (session beans$ .ervlets$ bac#ing beans and so on) the ;ependency +n=ection o" c stom reso rces sho ld 'or# 'itho t any limitations.

6ethin#ing
Eith eagerly startable .ingletons *ava -- lets yo register c stom reso rces be"ore the initiali?ation o" the act al b siness logic. 5his ma#es them interesting "or a variety o" initiali?ation tas#s. Prior to -*B 3.4$ the initiali?ation 'as only possible in a .ervlet or sing proprietary start p classes. ;ependency in=ection ma#es the ResourceBin"er an interesting option. Be"ore the availability o" ;+ the reso rce had to be loo#ed p <rst$ then cast$ and associated 'ith the <eld in

288
Download at WoweBook.Com

the setSessionContext method. 5he method Context#loo9up thro's a chec#ed Aamin7)xception. 5he se o" */;+ 'itho t ;+ is too verbose$ error-prone$ and comple>. *ava -- <>ed the problem 'ith in=ection and ma#es */;+ interesting "or the registration o" c stom reso rces.

Participants and 6esponsibilities


.tart p .ingleton ResourceBin"er plays the main roleS it is responsible "or% +he initiali5ation of needed reso,rces -efore any -,siness logic invocation. 9ifecycle *anage*ent of the c,sto* reso,rce. Reso,rce registration in the a!!lication server J)"& tree. Reso,rce clean,! and deregistration at server sh,tdo/n ti*e.

5he c stom reso rce can be any arbitrary *ava class$ 'itho t #no'ledge o" the */;+ registration process. 5he class sho ld be designed in reentrant 'ayit sho ld be idempotent. Eith transactional and state" l reso rces the state o" the b siness logic can become inconsistent$ beca se all transactions 'ill share the same state. .ession beans and other managed classes = st in=ect the class as any other standard *ava -reso rce sing the 2Resource annotation.

.trategies
5he ResourceBin"er is = st too simple to be viable "or di""erent strategies. 5he proprietary */;+ implementations o" the di""erent application servers may reB ire speci<c steps to bind a P,*, to the */;+ tree. +n e>treme cases$ yo 'ill have to implement additional inter"aces s ch as java.io.Seriali=able and javax.namin7.Re(erenceable. Qo co ld register an adapter that implements the reB ired inter"aces and holds the partic lar reso rce. +n this case$ the adapter$ and not the reso rce$ 'ill be in=ected. 5he reso rce client 'ill have to as# the adapter to get the act al re"erence to the c stom reso rce. +" yo r reso rces are re sable across di""erent applications$ yo co ld pac#age the ResourceBin"er 'ith all the reso rces in a dedicated archive. 5he ResourceBin"er implementation co ld be maintained separately$ b t yo 'ill still need to have the c stom reso rces in the classpath.

5esting
5he registration o" a c stom reso rce reB ires a single line o" codeS nothing can go 'rong here. Qo co ld$ o" co rse$ moc# o t the Context inter"ace and chec# 'hether this method 'as invo#ed properly$ b t it is better to invest more time into integration tests. 5he application servers may have additional reB irements "or the registration o" P,*,s in the */;+ tree. 5he ResourceBin"er pattern sho ldnJt have any e""ect on the r ntime per"ormance$ it co ld at most slo' do'n the start p time o" the application. 5here is only one instance o" the in=ected reso rce$ so it co ld become a bottlenec# in case the code is

282
Download at WoweBook.Com

s'nc+roni=e". Qo sho ld per"orm load tests 'ith per"ormance meas rements to veri"y proper behavior and scalability o" the in=ected reso rces.

;oc mentation
+n=ection o" arbitrary P,*,s into -*Bs is not obvio s. Qo sho ld clearly doc ment and comm nicate this "act in easily accessible doc mentation s ch as a 'i#i. +n addition$ yo co ld doc ment the in=ected <eld sing *ava;oc. 7(9 diagrams are not reB ired "or the e>planation o" this pattern.

ConseB ences
Portabi ity: J)"& is !art of the J"E7 nonetheless the SP& of different a!!lication servers *ay -ehave differently. =o, sho,ld not !res,*e that ResourceBin"er /ill /ork /ith every a!!lication server o,t of the -o6. !aintenance: +he in.ection of c,sto* reso,rces significantly red,ces the a*o,nt of infrastr,ct,ral code. =o, don:t have to *aintain the e6ce!tion handling of look,! *ethods or service locators. Performance: ResourceBin"er has no effect on the r,nti*e !erfor*ance1 ho/ever1 it can affect start,! ti*e. +he registration of the reso,rce1 as /ell as the in.ection1 is !erfor*ed -efore any -,siness call. )ca abi ity: ResourceBin"er has no effect on the scala-ility as /ell. Ho/ever1 it is a Singleton and the P(J(s are registered glo-ally at a!!lication start ,! (that is1 the 0ly/eight !attern). +he scala-ility of the sol,tion is de!endent on the scala-ility of the in.ected reso,rce. Testabi ity: +he in.ected reso,rce can -e easily *ocked o,t d,ring the ,nit tests. ResourceBin"er increases the testa-ility of session -eans.

6elated Patterns
.ervice locator is inversely related to the ResourceBin"er. .ervice locator is responsible "or actively "etching reso rces "rom the */;+ tree$ 'hereas the ResourceBin"er enables the ;ependency +n=ection o" c stom reso rces. 5he reso rces e>posed by the ResourceBin"er are cons med in session beans and there"ore in services$ .ervice !a@ades$ and ;A,s.

28:
Download at WoweBook.Com

Conte<t Holder
5he application server is managing conc rrency and threads "or yo . 5he invocation conte>t s ch as transaction and sec rity in"ormation are associated 'ith the c rrent e>ec tion thread by the -*B container.

Problem
+t is hard to pass additional in"ormation bet'een transaction participants. -*B 3.4 does provide a simple AP+ (javax.interceptors.<nvocationContext#7etContext8ata) "or managing the invocation conte>t$ b t only to pass in"ormation bet'een interceptors. 5here is no standardi?ed 'ay to pass in"ormation bet'een -*B instances participating in the same transaction.

!orces
=o, need to attach additional o-.ects (sec,rity tokens1 *essages) to the c,rrent thread /itho,t violating the !rogra**ing restrictions. =o,r a!!lication server *ay ,se several dedicated thread !ools1 so infor*ation stored in :+rea"3ocal *ay get lost. =o, don:t /ant to enhance the *ethod signat,res /ith an additional !ara*eter to -e a-le to !ass the conte6t. =o, need a !orta-le sol,tion.

.ol tion
5he problem is not solved by the -*B 3.4 speci<cation$ rather than by the *ava -- 2C: spec itsel". 5he :ransactionS'nc+roni=ationRe7istr' can be in=ected in any managed class sing the plain 2Resource annotationit comes already 'ith a map-li#e AP+% Object 7etResource(Object 9e') and putResource(Object 9e'1 Object value) methods. 5he :ransactionS'nc+roni=ationRe7istr' is already associated 'ith the c rrent transaction$ so yo can sa"ely se it as a conte>t-transport mechanism. An interceptor already participates in a transaction started in a session bean ("or e>ample$ in a .ervice !a@ade)$ so yo co ld even in=ect the :ransactionS'nc+roni=ationRe7istr' into it. 5he interceptor co ld store additional in"ormation$ 'hich 'o ld be accessible not only to the .ervice !a@ade$ b t also to all arti"acts behind s ch .ervices$ ;A,s$ and indirectly even P;,s.
import static @9itc+ensin9.context+ol"er.Re7istr'Ye'.Cpublic class Current:ime6illisProvi"er # 2Resource private :ransactionS'nc+roni=ationRe7istr' re7istr'2Aroun"<nvo9e public Object inject6ap(<nvocationContext ic) t+ro,s )xception# re7istr'.putResource(Y)B1 S'stem.current:ime6illis())return ic.procee"()$ $

Download at WoweBook.Com

5he :ransactionS'nc+roni=ationRe7istr' is #ey-val e based$ so yo 'ill need a #ey to store and access the conte>t in"ormation. An enum is per"ectly s itable "or this p rpose. 5he #ey can be even statically imported.
public enum Re7istr'Ye' # Y)B $

Qo donRt have to access or even in=ect the :ransactionS'nc+roni=ationRe7istr' in every layer. 5he in"ormation remains accessible as long as yo r session bean participates in the same transaction. +" there is nothing to do in a .ervice !a@ade$ yo co ld = st s#ip it and access the conte>t al in"ormation "rom a service.
2Stateless )2nterceptors(0urrent4ime7illis6rovider.class) public class Service&aca"eBean implements Service&aca"e # 2)*B private Service servicepublic voi" per(ormSome!or9()# service.service<nvocation()$ $

5o access the conte>t in"ormation$ :ransactionS'nc+roni=ationRe7istr' 7etResource method.

yo again

'ill have to in=ect the and "etch the data sing the

2Stateless public class ServiceBean implements Service # 2Resource private :ransactionS'nc+roni=ationRe7istr' tsrpublic voi" service<nvocation() # lon7 time6illis D (3on7)tsr.7etResource(Y)B)%%... S'stem.out.println(4Content is 4 H time6illis)$ $

Qo 'ill have to cast the ob=ect stored in the :ransactionS'nc+roni=ationRe7istr' to proper type a"ter "etching. 5he AP+ is available since *5A 4.4$ be"ore the availability o" generics.

6ethin#ing
5he :ransactionS'nc+roni=ationRe7istr' 'as even available 'ithin the *2-- 4.8 time"rame. +t 'asnRt a very attractive sol tion$ beca se o" the lac# o" ;ependency +n=ection. +t had to be "etched sing the */;+ loo# p mechanism 'ith a standardi?ed name% javaGcomp%:ransactionS'nc+roni=ationRe7istr'. 5his reB ired several lines o"

281
Download at WoweBook.Com

code 'ith proper e>ception handling or the se o" a service locator$ 'hich encaps lated the pl mbing. :ransactionS'nc+roni=ationRe7istr' 'as not 'idely sed as storage o" conte>t al in"ormation. *ava -- 2 introd ced ;ependency +n=ection$ 'hich dramatically simpli<ed access to */;+ reso rces. +n "act$ yo 'ill need only t'o lines o" code to either store or access the in"ormation (the act al in=ection and the invocation o" putResource or 7etResource$ respectively).

Participants and 6esponsibilities


5he act al conte>t holder is provided either by the container (:ransactionS'nc+roni=ationRe7istr') or *ava .- (:+rea"3ocal). +n both cases$ it is initiated be"ore the <rst b siness method invocation o" a .ervice !a@ade or Date'ay. 5his can be achieved 'ith an interceptor$ dynamic pro>y$ or .ervlet < lter (the in=ector). 5he in=ector e>tracts or creates the conte>t al in"ormation (s ch as sec rity$ time$ or cache) and stores it in the conte>t holder. All other participants only have to "etch the conte>t holder to access the in"ormation. An e>plicit in=ector is optionalS the conte>t holder can be in=ected in the b siness logic as 'ell and be sed as a convenient transport o" technical$ crossc tting data.

.trategies
+ransactionSynchroni5ationRegistry Strategy 5his sho ld be the pre"erred strategy "or the Context ol"erit is portable across application servers and independent o" the individ al and proprietary thread pool settings. 5he c rrent transaction is sed as the transport mechanism "or storing additional data. +hread9ocal Strategy

Altho gh less portable$ this strategy is "ar more pop lar. +t 'or#s very 'ell i" the entire invocation is e>ec ted in a single thread. +" yo de<ned distinct thread pools "or a .ervice !a@ade and .ervice$ yo r conte>t in"o sel"-healing settings$ a hard-to-<nd b g. 5his strategy relies on the :+rea"3ocal " nctionality. 5he :+rea"3ocal is 'rapped by the :+rea"3ocalContext ol"er = st "or convenience reasons.
import java.util. as+6apimport java.util.6appublic class :+rea"3ocalContext ol"er # private static (inal :+rea"3ocal.6ap.Strin71Object00 : R)A8J!<: JCOA:)K: D ne, :+rea"3ocal.6ap.Strin71Object00()private :+rea"3ocalContext ol"er() #$ public static voi" put(Strin7 9e'1 Object pa'loa") # i((: R)A8J!<: JCOA:)K:.7et() DD null)# : R)A8J!<: JCOA:)K:.set(ne, as+6ap.Strin71 Object0())$ : R)A8J!<: JCOA:)K:.7et().put(9e'1 pa'loa")$

289
Download at WoweBook.Com

public static Object 7et(Strin7 9e') # return : R)A8J!<: JCOA:)K:.7et().7et(9e')$ public static voi" cleanup:+rea"()# : R)A8J!<: JCOA:)K:.remove()$ $

:+rea"3ocalContext ol"er creates at <rst access an instance o" the 6ap.Strin71Object0$ 'hich is sed in s bseB ent calls as the act al registry. 5he p blic AP+ is very similar to the :ransactionS'nc+roni=ationRe7istr'$ the names 'ere shortened to 7et and put instead o" 7etResource and putResource. 5he tility :+rea"3ocalContext ol"er e>poses its AP+ as static methods that can be statically imported. 5his " rther simpli<es the management o" the conte>t al in"ormation. 5he "ollo'ing e>ample sho's an interceptor 'or#ing 'ith the :+rea"3ocal strategy%
import javax.interceptor.Aroun"<nvo9eimport javax.interceptor.<nvocationContextimport static ...9itc+ensin9.context+ol"er.Re7istr'Ye'.Cimport static ...9itc+ensin9.context+ol"er.t+rea"local.:+rea"3ocalContext ol"er.Cpublic class Current:ime6illisProvi"er # 2Aroun"<nvo9e public Object inject6ap(<nvocationContext ic) t+ro,s )xception# put(Y)B.name()1 S'stem.current:ime6illis())return ic.procee"()$ $

5he :+rea"3ocalContext ol"er does not reB ire ;ependency +n=ection so it is not limited to *ava -- managed classes. +t can even be sed in a 'eb container "or data transport. .imilarly to the :ransactionS'nc+roni=ationRe7istr' based sol tion yo can s#ip any n mber o" layers and access the conte>t al data 'herever yo 'ant$ "or as long as yo stay in the same thread. 5his strategy does not even depend on transactions.
2Stateless )2nterceptors(0urrent4ime7illis6rovider.class) public class Service&aca"e:+rea"3ocalBean implements Service&aca"e:+rea"3ocal # 2)*B private Service:+rea"3ocal servicepublic voi" per(ormSome!or9()# service.service<nvocation()$ $

220
Download at WoweBook.Com

5he in"ormation can be easily accessed :+rea"3ocalContext ol"er#7et.

sing

the

statically

imported

method

import static ...t+rea"local.:+rea"3ocalContext ol"er.Cimport static ...9itc+ensin9.context+ol"er.Re7istr'Ye'.C2Stateless public class Service:+rea"3ocalBean implements Service:+rea"3ocal# public voi" service<nvocation() # 3on7 millis D (3on7) 7et(Y)B.name())S'stem.out.println(4Content isG 4 H millis)$ $

5he payload can be any ob=ect yo 'ant$ so casting is still reB ired. 5his sample is a generic sol tion$ in a concrete pro=ect the #ey val es co ld be provided as concrete classes in a type-sa"e manner.

5esting
5his tility is very simpleS the comple>ity is similar to sing the java.util.6ap inter"ace. 5he Context ol"er relies on the -*B container$ so it is essentially important to test it in a prod ction-li#e environment. +ntegration and load tests sho ld be per"ormed in very early stages.

;oc mentation
Context ol"er does not have any impact on architect reS it is rather a design or even implementation arti"act. /onetheless the principle o" attaching the data to threads or transactions is not obvio s and sho ld be clearly doc mented.

ConseB ences
Portabi ity: +he :ransactionS'nc+roni=ationRe7istr' -ased sol,tion is -acked -y the Java EE 4CM s!ec and has to -e !orta-le across a!!lication servers. +he :+rea"3ocal -ased strategy /orks as long as the entire invocation is e6ec,ted in a single thread of e6ec,tion. Pro!rietary a!!lication server e6tensions s,ch as thread !ools co,ld -reak the sol,tion1 -eca,se one re8,est co,ld -e e6ec,ted -y *ore than one thread. Performance: +he !erfor*ance of the :+rea"3ocal strategy is highly de!endent on the Java SE version. +he ne/er (Java M SEN) :+rea"3ocal i*!le*entations are very fast. :ransactionS'nc+roni=ationRe7istr'1 on the other hand1 is an interface that is i*!le*ented -y the a!!lication server. +he !erfor*ance of the :ransactionS'nc+roni=ationRe7istr' -ased sol,tion is de!endent on the !artic,lar a!!lication server i*!le*entation. +he !erfor*ance of -oth strategies sho,ld -e verified /ith -asic load tests and attached !rofiler. Testabi ity: :ransactionS'nc+roni=ationRe7istr' is an interface7 its i*!le*entation is going to -e in.ected -y the container. ",ring ,nit tests a *ock i*!le*entation of this interface has to -e !rovided and the "e!endency &n.ection *echanis* has to -e i*!le*ented. +he "e!endency &n.ection can -e either solved /ith

224
Download at WoweBook.Com

reflection or direct'field setting. +he i*!le*entation of a dedicated setter is only !l,*-ing and *akes the code less reada-le. +he :+rea"3ocal -ased sol,tion is easily testa-le1 -eca,se the :+rea"3ocal i*!le*entation is not de!endent on any a!!lication server classes or services. &t can -e directly e6ec,ted in the ,nit test and /ill /ork as e6!ected. !aintainabi ity: Context ol"er greatly red,ces the a*o,nt of code and !l,*-ing re8,ired for the trans!ort of crossc,tting conte6t,al data. +he re8,est can -e easily enriched /ith additional infor*ation /itho,t changing the e6isting infrastr,ct,re and *ethod signat,res. / exibi ity: +he :+rea"3ocal strategy does not need transactions or J+A AP&s to !ass data -et/een o-.ects. &t can even -e ,sed in a !lain /e- container. &t is1 ho/ever1 li*ited to the H association -et/een the re8,est and the thread for the entire invocation. :ransactionS'nc+roni=ationRe7istr' doesn:t have this li*itation -,t it is de!endent on the e6istence of transactions.

6elated Patterns
Context ol"er is sed by .ervice !a@ades and their interceptors to pass data to services and ;A,s do'n the chain. 5he :+rea"3ocal based strategy can even be applied in a 'eb container to pass conte>t al in"ormation "rom the 7+ layer bac# to the service components. Beca se the Conte>t )older ses interceptors as 'ell$ it is similar to the 5hread 5rac#er$ Payload ->tractor$ and ;ependency +n=ection ->tender.

222
Download at WoweBook.Com

<
Prag*atic Java EE Architect,res
+n the <eld$ a nrelated collection o" patterns doesnJt solve anything. A constrained combination o" patterns F or a patterns lang age are more se" l. 5he right pattern combination depends on the conte>t o" the pro=ect$ individ al se cases$ and$ most importantly$ non" nctional reB irements. +n this chapter + disc ss t'o contrary approaches% service- and domain-driven design styles.

Pre*at$re Enca"s$lation 's the Root of All Evil


5he vast ma=ority o" *2-- applications 'as poisoned by too many lea#y abstractions$ layers$ and indirections. 5his B estionable best practice didnJt really pay o"". 5he abstractions themselves became problematic and res lted in a lot o" pl mbing. 5he motivation "or sing e>tensive abstractions and layering 'as driven by the intr sive *2-- programming model. 5he b siness logic 'as dependent on the *2-- AP+. *ava -- eliminates most o" these in"rastr ct ral dependencies. 5he b siness logic does not e>tend the *ava -- "rame'or#$ instead it is decorated 'ith annotations. 5he b siness logic is already separated "rom the in"rastr ct re by its very nat re. 5hese "act have a radical impact on the *ava -architect re and allo' not only leaner implementation$ b t also modeling.

Entity Control Bo$ndary 9ECB: %he 3ean Way


.ervice-oriented and domain-driven architect res can be e>pressed sing so-called rob stness diagrams$ championed by ;o g 6osenberg and &endall .cott. A rob stness diagram is in essence a simpli<ed 7(9 diagram that depicts -ntity$ Control$ and Bo ndary elements (as de<ned on the Agile (odeling 'eb site L'''.agilemodeling.comM). 5he Bo ndary element is the ser inter"ace$ the Control element represents the act al process or activity$ and the -ntity element is a concept "rom an enterprise conte>t. 5hese three elements are generic eno gh to be mapped either to service-oriented or ob=ect-oriented architect res. 5he -CB approach can even be re<ned "or *ava --yo can p t more semantical in"ormation into these elements% 3oundary is the fa@ade (Service 0a@ade or 2ate/ay) that e6!oses the f,nctionality of a co*!onent and directly interacts /ith the ,ser interface. Contro is a re,sa-le1 fine'grained Service -ehind a Bo,ndary. &t can -e o!tional or generic in si*!le ,se cases s,ch as #R;" or *aster data *anage*ent.

Download at WoweBook.Com

'ntity refers to o-.ect'oriented or !roced,ral do*ain o-.ects. &n *ost cases1 this conce!t,al Entity is !ersistent and *a!!ed to a single JPA entity and its s,!!ortive infrastr,ct,re s,ch as a ("ata) Service or "A(. &n rare cases (for e6a*!le1 o!ti*i5ation)1 the Entity can -e indirectly *a!!ed to a stored !roced,re ResultSet or Ro,Set as /ell.

5he -CB elements are s itable "or modeling any b siness logic or se case. +n both 'orlds$ the cohesion or elements play the most important role. Ei#ipedia de<nes cohesion as "ollo's% N+n comp ter programming$ cohesion is a meas re o" ho' strongly-related and "oc sed the vario s responsibilities o" a so"t'are mod le are. Cohesion is an ordinal type o" meas rement and is s ally e>pressed as [high cohesion[ or [lo' cohesion[ 'hen being disc ssed. (od les 'ith high cohesion tend to be pre"erable beca se high cohesion is associated 'ith several desirable traits o" so"t'are incl ding rob stness$ reliability$ re sability$ and nderstandability 'hereas lo' cohesion is associated 'ith ndesirable traits s ch as being di"<c lt to maintain$ di"<c lt to test$ di"<c lt to re se$ and even di"<c lt to nderstand.O +n short$ yo sho ld aim "or highly cohesive systems$ b t in order to do so$ yo need a vehicle to e>press a gro p o" cohesive elements. +n *ava (--) the main responsibility o" a b siness component is the e>pos re o" its speci<cation or contracts 'ith additional b siness val e and hiding its reali?ation$ 'hich is comprised o" a gro p o" cohesive elements (see !ig re 4).

&ig re +: E(B and a ' siness component


A b siness component is directly mapped to a *ava pac#age and there"ore a <le system "older. 5he e>ternal component inter"ace is reali?ed by a Bo ndary$ 'hereas the Control and the -ntity comprises its reali?ation. !rom a technical point o" vie'$ this model is not per"ect. +n practice$ the Bo ndary is not = st an inter"aceit someho' has to be reali?ed as 'ell. ,nly the Bo ndary inter"ace represents the componentJs e>ternal inter"ace and its implementation belongs to the b siness componentJs reali?ation. 5he inter"ace as 'ell as its implementation have to be stored inside the component (see !ig re 2).

228
Download at WoweBook.Com

&ig re ,: $nternal layering of a ' siness component

+nstead o" storing them directly in the pac#age representing the b siness component$ p t each o" the -CB elements in a s bpac#age 'ith the same name. Qo 'ill <nd the components inside the component s bpac#ages 'ith the names% boun"ar'$ control$ and entit'. Qo co ld even " rther emphasi?e the isolation o" a componentJs reali?ation and store the Bo ndary inter"ace directly in the component pac#age and its implementation in the boun"ar' pac#age. 5his s bpac#aging strategy "acilitates greatly the implementation o" metrics and B ality ass rance 'ith tools s ch as =depend$ sonar=$$ dependometer$ or >radar. 5he -CB-driven naming 'o ld be consistent across the service-oriented and domain-driven approaches. Alternatively$ yo co ld se the already introd ced naming conventions derived "rom the pattern names. +n this case$ yo 'o ld recogni?e the components type = st by loo#ing at the s bpac#age names. -ach approach has its pros and cons. Eith the -CB naming$ yo can re se metrics across di""erent component types. +t is harder$ ho'ever$ to implement type-speci<c re<nements. 5he pattern-driven naming is e>actly the oppositealready implemented r les are harder to re se$ b t yo can be more speci<c "or each architect ral style.

3ean /ervice70riented Architect$res


5han#s to e simpli<ed *ava -- : development model$ a "e' inter"aces and annotated classes are all yo need to implement the .ervice !a@ade$ .ervice$ and Persistent ;omain ,b=ect that constit te a lean service-oriented architect re. Altho gh *ava -- : is "ar less comple> than previo s plat"orm versions$ it can still be mis sed "or the creation o" e>aggerated and bloated architect res.

5he -ssential +ngredients o" .,As


5he cr cial arti"act in any .,A is an e>posed service. A service can be considered as a contract 'ith signi<cant b siness val e. A clear relation sho ld e>ist bet'een the service contract and a

222
Download at WoweBook.Com

b siness reB irement$ a se case$ or even a ser story. A service can be reali?ed as a single action or a set o" cohesive actions. !or e>ample$ an Or"erService might comprise a single action that per"orms the act al order$ or a gro p o" related operations that also incl de canceling the order and receiving the order stat s. An .,A does not reveal any details abo t ho' a service m st be implementedS it aims "or services to be technology- and even location-agnostic. .,A principles can be mapped to *ava -- arti"acts. 5he most important ingredients in a *avabased .,A implementation are inter"aces and pac#ages. -verything else is only a re<nement$ or design. ,nly one arti"act in the lang agea plain *ava inter"acemeets the reB irements o" a service contract. +t is o"ten sed to deco ple the client "rom the service implementation. +t can also be sed to e>pose the " nctionality o" a component. Component-based design (CB;) is the evol tionary predecessor o" .,As. Component contracts are comparable to .,A services$ e>cept "or their heavier dependence on partic lar technology and a general lac# o" operations-related metadata (s ch as service-level agreements L.9AsM) or strong governance principles. A component is b ilt on the ma"imal cohesion, minimal co pling principle. A component sho ld be highly independent o" other components$ and the implementation sho ld consist o" related (cohesive) elements. +n a *ava -- .,A implementation$ a component is a *ava pac#age 'ith these strong semantics. 5he pac#ageJs " nctionality is e>posed 'ith a single inter"ace or$ in rare cases$ m ltiple inter"aces.

5he -ssential Comple>ity o" .,As


.,A implies distrib tion o" services$ 'hich is not al'ays necessary or desirable in a *ava -application. +t 'o ld be "oolish to access a local service remotely = st to satis"y some high-level .,A concepts. ;irect local access sho ld al'ays be pre"erred over remote services. A local call is not only m ch "aster than a remote oneS the parameters and ret rn val es can also be accessed per re"erence and need not be seriali?ed. Ehether the service is local or remote$ the b siness logic sho ld be al'ays be e>ec ted consistently. A component needs a dedicated remoting and transaction bo ndary inter"ace$ 'hich acts as a gate#eeper. 5he main responsibility o" s ch a "a@ade is to #eep the gran larity o" the methods coarse and the persistent state o" the component consistent (see !ig re 3).

22:
Download at WoweBook.Com

&ig re -: Remoting/transactions 'o ndary


5he right gran larity can only be achieved by care" lly cra"ting the inter"ace so that consistency can be easily ens red 'ith b ilt-in transactions. 5hat is the essential responsibility o" the .ervice !acade pattern. +ts the Bo ndary o" a service-oriented b siness component as sho'n in the "ollo'ing e>ample% pac9a7e ...boo9store.business.orderm+mt./acade2Stateless 2Remote(Or"erService.class) 2:ransactionAttribute(:ransactionAttribute:'pe.R);U<R)SJA)!) public class Or"erServiceBean implements Or"erService #

2)*B private 2)*B private 2)*B private 2)*B private 2)*B private

Cru"Service cru"Service?atCalculator vatCalculatorPriceCalculator pcOr"erProcessor opS+ipmentService s+ipmentService-

public S+ipment or"erBoo9(int customer<"1int isbn)#

220
Download at WoweBook.Com

Bi78ecimal priceAo?at D t+is.pc.computePrice(customer<"1 isbn)Bi78ecimal price D t+is.vatCalculator.compute?at(priceAo?at)Or"er o D t+is.op.processOr"er(customer<"1 customer<"1 price)return t+is.s+ipmentService."eliver(o)$ public S+ipment (in"S+ipment(lon7 s+ipment<")# $ %%some met+o"s omitte" $

return t+is.s+ipmentService.(in"(s+ipment<")-

Applying the :ransactionAttribute:'pe.R);U<R)SJA)! annotation to a .ervice !a@ade ca ses all methods to inherit this setting a tomatically. Qo co ld also rely on the de"a lt ('hich is :ransactionAttribute:'pe.R);U<R)8) and not speci"y a transaction setting . )o'ever$ the Or"erService is the transaction and remoting bo ndary. +t is accessed e>cl sively by the ser inter"ace$ 'hich m st not start any transactions. 7sing the R);U<R)SJA)! attrib te is more e>plicit. +t al'ays starts a ne' transaction$ 'hich is 'hat yo 'o ld e>pect "rom a bo ndary. 5he R);U<R)8 con<g ration$ i" it 'ere invo#ed 'ithin a transaction conte>t$ 'o ld re se an e>isting transaction or start a ne' one. A bo ndary$ ho'ever$ 'ill never be invo#ed in an e>isting transaction$ 'hich ma#es the de"a lt setting more con" sing. A .ervice !a@ade is the standardi?ed implementation o" the here described semantics it is the Bo ndary o" a service-oriented component.

.eparation o" Concerns$ or ;ivide and ConB er


Or"erServiceBean emphasi?es the b siness logic and hides the componentRs implementation. 5hese are the responsibilities o" the classic !a@ade and also the already introd ced .ervice !a@ade patterns. ! rthermore$ the Or"erServiceBean ens res the componentRs consistency by starting a transaction be"ore every method is e>posed over the b siness inter"ace. 5ransactions are a cross-c tting concernan aspectalready implemented by the -*B container. 5he "a@ade already has eno gh responsibilities$ so it has no more room "or the implementation o" the act al b siness logic. 5he intention o" a Controller (A&A .ervice) is the act al reali?ation o" the b siness logic. +n an .,A 'orld$ it is o" a proced ral nat re. A .ervice resides behind the .ervice !a@ade$ so it can never be accessed directly by the ser inter"ace or other presentation components. A service is stateless and can only be called by the .ervice !a@ade. -very .ervice !a@ade method starts a ne' transaction$ so a .ervice can sa"ely rely on the e>istence o" the transaction. 5he "ollo'ing code sho's an e>ample o" the transaction and remoting con<g ration o" a .ervice pattern%
2Stateless )@ocal(8rder6rocessor.class) )4ransaction1ttribute(4ransaction1ttribute4ype.71'.148%9) public class Or"erProcessorBean implements Or"erProcessor #

221
Download at WoweBook.Com

2PersistenceContext private )ntit'6ana7er empublic Or"er processOr"er(int customer<"1 int pro"uct<"1 Bi78ecimal price) # Or"er or"er D ne, Or"er(customer<"1 pro"uct<"1 price)t+is.em.persist(or"er)return or"er$
$

+n this e>ample$ the concerns are clearly separated. 5he "a@ade provides the cross-c tting " nctionality and plays the coordinator role$ and the service "oc ses on the act al domain logic implementation. 5he clearly separated roles and responsibilities ma#e it possible to prede<ne a serviceJs str ct re and con<g ration easily. A service is a stateless session bean 'ith a local b siness inter"ace. +t is al'ays invo#ed by the "a@ade in a transaction$ so it can be deployed 'ith the 6AA8A:ORB setting. 5his restrictive :ransactionAttribute " rther emphasi?es the encaps lationS it is not possible to call it directly 'itho t a transaction. 5he bean implementation e>poses the b siness inter"ace 'ith the 23ocal annotation$ so the inter"ace is independent o" the -*B AP+.

Do*ain 046ects or /tr$ct$res=


.ince .ervices implement the act al b siness logic$ and the .ervice !a@ade cares abo t the crossc tting concerns$ there is no more " nctionality le"t to be implemented in the Persistent ;omain ,b=ects (P;,s). 5he *ava Persistence AP+ (*PA) entities consist only o" annotated attrib tes and gettersCsettersS they contain no b siness logic. 5he "ollo'ing e>ample sho's s ch an anemic domain ob=ect%
2)ntit' 2:able(nameD4:JOR8)R4) 2Aame";ueries(# 2Aame";uer'(nameDOr"er.(in"B'Customer<"1quer'D4S)3)C: o &RO6 Or"er o ,+ere o.customer<" D Gcustomer<"4) $) public class Or"er #

public (inal static Strin7 PR)&<K D4..or"erm7mt."omain.Or"er4public (inal static Strin7 (in"B'Customer<" D PR)&<K H 4(in"B'Customer<"42<" 2>enerate"?alue(strate7' D >eneration:'pe.AU:O) private 3on7 i"private int customer<"-

229
Download at WoweBook.Com

private int pro"uct<"private "ouble pricepublic Or"er() # $ public Or"er(int customer<"1int pro"uct<"1Bi78ecimal price)# t+is.customer<" D customer<"t+is.pro"uct<" D pro"uct<"t+is.price D price."ouble?alue()$ public 3on7 7et<"() # return i"$ public "ouble 7etPrice() # return price$ public voi" setPrice("ouble price) # t+is.price D price$ public int 7etPro"uct<"() # return pro"uct<"$ public voi" setPro"uct<"(int pro"uct<") # t+is.pro"uct<" D pro"uct<"$
$

Altho,gh the ane*ic o-.ect *odel is considered to -e an anti!attern1 it fits very /ell into an S(A. %ost of the a!!lication is data'driven1 /ith only a s*all a*o,nt of o-.ect's!ecific or ty!e' de!endent logic. 0or si*!ler a!!lications1 ane*ic JPA entities have advantages tooH ",*- entities are easier to develo!no do*ain kno/ledge is re8,ired. Ane*ic JPA entities can -e generated *ore easily. +he necessary *etadata can -e derived entirely fro* the data-ase. =o, can .,st *aintain the data-ase1 and the e6isting entities can -e safely over/ritten -y ne/ly generated entities. +he !ersistent entities can -e detached and transferred to the client. Aside fro* the classic >la5y loading? challenges1 there are no f,rther s,r!rises. +he client /ill only see the accessors and /ill not -e a-le to invoke any -,siness *ethods.

5hin#ing Abo t +nternal .tr ct re

2:0
Download at WoweBook.Com

+Jve already identi<ed some #ey ingredients o" a service-oriented component% 3oundary ()ervice /a=ade+: Provides si*!lified1 centrali5ed access to the co*!onent and deco,!les the client fro* the concrete services. &t is the net/ork and transaction -o,ndary. Contro ()ervice+: +he act,al i*!le*entation of the -,siness logic. 'ntity (domain structure# P,8+: &tOs a str,ct,re rather than an o-.ect. &t i*!le*ents the co*!onent:s !ersistence and e6!oses all of its state to the services1 /itho,t any enca!s,lation.

Qo 'ill <nd these three layers in most components. 5he component str ct re mani"ests itsel" as internal pac#ages named by the #ey ingredients (see !ig re 8).

Figure 4. )nternal structure of a service component 5he or"erm7mt component consists o" the boun"ar'%(aca"e$ control%service$ and entit'%"omain pac#ages.

;A,s% ;ead or AliveG


Behind the motivation "or this pattern 'as the desire to achieve the greatest possible deco pling "rom the concrete reali?ation o" the data store mechanics. 5he B estion to as# is ho' o"ten yo Jve had a concrete reB irement to s'itch among relational databases$ ob=ect-oriented databases$ Hat <les$ and so on in a pro=ect. +n the absence o" s ch a reB irement$ yo sho ld as# yo rsel" ho' li#ely s ch a replacement o" the data store really is. -ven i" it is li#ely to happen$ data store abstractions are rather lea#y. 5he *PA )ntit'6ana7er class is comparable to a domain store and 'or#s 'ith managed entities. ,ther data stores are more li#ely to se the per-val e approach and there"ore ret rn a ne' copy o" a persistent entity on every reB est in a single transaction. 5his is a h ge semantic di""erenceS 'ith the )ntit'6an7er$ thereJs no need to merge attached entities$ 'hereas it is absol tely necessary in the case o" a ;A, 'ith ;ata 5rans"er ,b=ects. -ven a per"ect database abstraction is lea#y. ;i""erent databases behave di""erently and have speci<c loc#ing and per"ormance characteristics. An application might r n and scale per"ectly on one database b t enco nter "reB ent deadloc#s 'ith another prod ct. . ch a variation = st cannot

2:4
Download at WoweBook.Com

be abstracted 'ith any abstractions or design patterns. 5he only possible 'ay to s rvive s ch a migration is to t'ea# the isolation levels $ transactions$ and database con<g ration. 5hese iss es canJt be hidden behind a ;A, inter"ace$ and itJs li#ely that the ;A, implementation 'o ld not even change. 5he ;A, abstraction 'o ld be only se" l i" the act al *PA T9 or .T9 statements change$ 'hich is a minor problem. .o neither the original de<nition nor a database migration se case = sti<es the implementation o" a dedicated ;A,. ;oes this mean that ;A,s are deadG !or standard se cases$ yes. B t yo still need a ;A, in most applications to adhere to the principles o" ;6Q (donJt repeat yo rsel") and separation o" concerns. +t is more than li#ely that an average application ses a set o" common database operations over and over again. Eitho t a dedicated ;A,$ the B eries 'ill be sprin#led thro gh yo r b siness tier. . ch d plication signi<cantly decreases the applicationJs maintainability. B t the red ndant code can be easily eliminated 'ith a ;A, that encaps lates the common data access logic. +n other 'ords$ even tho gh ;A,s still e>ist$ they can no longer be considered as a general best practice. 5hey sho ld be created in a bottom- p instead o" a topdo'n "ashion. +" yo discover data access code d plication in yo r service layer$ "actor it o t to a dedicated ;A, and re se it. ,ther'ise it is = st <ne to delegate to an )ntit'6ana7er "rom a service. 5he en"orcement o" an empty ;A, layer is even more harm" l$ beca se it reB ires yo to 'rite d mb code "or even simple se cases. 5he more code is prod ced$ the more time yo m st spend to 'rite tests and to maintain it. Eith *;& 4.2 and the advent o" generics$ it is possible to b ild and deploy a generic$ convenient$ and type-sa"e ;A, once and re se it "rom variety o" services. . ch a ;A, sho ld come 'ith a b siness inter"ace to enco rage nit testing and moc#ing.

A small pattern lang age "or .,A


5he essential ingredient o" a service component is not the .ervice$ b t a .ervice !a@ade. +ts main responsibility is the (as tight as possible) encaps lation o" the componentJs reali?ation and the (as convenient as possible) e>pos re o" a componentJs " nctionality to the o tside 'orld. 5he .ervice !a@ade acts as a <re'all (a really strict Bo ndary)$ it separates the componentJs speci<cation "rom its reali?ation. 5he best 'ay to achieve that in *ava is to separate the implementation "rom the contract sing distinct pac#ages. 5he arti"acts o" the componentJs AP+ can be located in the componentJs root pac#age$ 'hereas the reali?ation arti"acts are placed into the the boun"ar'$ control1 and "omain s bpac#ages respectively. 5he strict separation bet'een the components o tside vie' "rom the internal reali?ation ma#es the 5rans"er ,b=ect pattern mandatory. 5he direct e>pos re o" P;,s to the client 'o ld brea# the b siness component encaps lation. -very change to the P;,s co ld potentially brea# the sers. 5he 5rans"er ,b=ect belongs to the service componentJs AP+$ so it is located at the top-level pac#age ("or e>ample$ or"erm7mt). /ot only P;,s$ b t all other classes that are reB ired "or the interaction 'ith the component$ have to be placed in that pac#age. ->ceptions and everything that is needed "or the compilation o" the contract and client$ has to be located in the AP+ pac#age as 'ell.

2:2
Download at WoweBook.Com

.ervices are optional arti"acts and have to be introd ced only in case the .ervice !acade 'ill not degrade to a d mb delegate. As a r le o" th mb$ yo sho ld have at least t'o .ervice implementations$ other'ise the .ervice !a@ade 'ill not be eligible to be called a coordinator or even "a@ade. -specially simplistic se cases s ch as C67; can be e"<ciently reali?ed 'ith a .ervice !a@ade and a ;ata Access ,b=ect (;A,). P;,s are not mandatory elements$ b t yo 'ill <nd them in most components 'ith a persistent state. Contrary to the domain components$ P;,s in a service component mainly consist o" state 'itho t any b siness logic. 5he logic is located in .ervices. A .ervice 'ith the partic lar P;, can be considered as an atomic nit. !etching o" the P;,s can be implemented either in a .ervice or a dedicated ;A,. -ver since the release o" *;& 4.2$ generic ;A, implementations have been easy to implement. A ;A, can be sed as a convenient decorator o" the )ntit'6ana7er ('hich is optional)$ or an integration adapter that tal#s directly to the data store. 5he latter e>ample sho ld be considered mandatory "or all integration scenarios o" *ava -- incompatible reso rces (stored proced res incl sively). +ntegrational ;A,s are not able to ret rn attached P;,sthey e>pect and ret rn 5rans"er ,b=ects. Eith the introd ction o" an integrational ;A,$ yo 'ill get 5rans"er ,b=ects in the componentJs reali?ation as 'ell. A Paginator is " lly optional. +n case it is needed$ it sho ld be introd ced in a stateless con<g ration. .ervice components are inherently stateless$ so there is no need to ma#e them state" l = st beca se o" simple iteration logic. 5he !l id 9ogic pattern is more interesting. +n the domain-driven component$ the !l id 9ogic is mostly sed "or the introd ction o" more H ent access to the domain ob=ects$ or "or b ilding ;.9s. +n a service-oriented 'orld$ dynamic lang ages can be sed e"<ciently "or integration p rposes. 5he !l id 9ogic pattern is per"ect "or the reali?ation o" a He>ible adapter or gl e bet'een incompatible services or "or data trans"ormations. .ervice-oriented components are contract drivenevery single invocation is ro ted thro gh the .ervice !a@ade. +n addition$ .,A promotes the re se o" e>isting components and servicesa once deployed service might be re sed by several clients 'ith di""erent non" nctional reB irements. An .,A service needs a certain level o" B ality to be interesting "or re se. ,ther'ise the "ail re o" a single service may ca se the o tage o" several clients. .ome service-level agreement con<g ration s ch as per"ormance or simple statistics can be attached to the service as annotations and proactively monitored by an interceptor. 5he .ervice !a@ade may be decorated by additional aspects "or the p rpose. Also$ e>isting legacy .pring or D ice services can be easily in=ected into the .ervice !a@ade sing the ;ependency +n=ection ->tender$ another interceptor-based pattern. 5he Conte>t )older ma#es the transport o" additional reso rces$ also into P,*,s or legacy components (s ch as principal$ transactional reso rces or additional metadata) possible. !ig re 2 sho's s ch a service component b ilt on patterns.

2:3
Download at WoweBook.Com

&ig re 5: . service component ' ild on patterns


.,A aims "or re se$ 'hich ca ses more overhead and reB ires additional patterns. .ervice components are$ on average$ more comple> than comparable domain components.

A to ch o" pragmatism
(ost service components are not complicated and consist mainly o" basic data operations. +n these cases the "a@ade 'o ld = st delegate to a service$ 'hich in t rn delegates to the javax.persistence.)ntit'6ana7er class or a generic Cru"Service session bean to per"orm its persistence tas#s. ,ther'ise yo 'ill end p getting t'o d mb delegates% the "a@ade 'o ld only delegate to the .ervice$ and the .ervice to the Cru"Service (A&A ;A,). ;elegates 'itho t additional responsibilities are = st dead code. 5hey only increase the code comple>ity and ma#e maintenance more tedio s. Qo co ld <ght this bloat by ma#ing the service layer optional. 5he .ervice !a@ade 'o ld manage the persistence and delegate the calls to the

2:8
Download at WoweBook.Com

)ntit'6ana7er instance. 5his approach violates the separation-o"-concerns principle$ b t itJs a very pragmatic one. +t is still possible to "actor re sable logic "rom the "a@ade into the services 'ith minimal e""ort. +" yo really 'ant to encaps late the data access in a dedicated layer$ yo can easily implement it once and re se the generic access in di""erent pro=ects. . ch a generic ;A, does not belong to a partic lar b siness component. +t 'o ld violate the cohesion. +t co ld be deployed as a standalone technical component 'ith the name "ataservice.

As 9ean as Possible$ b t /ot 9eaner


+t 'o ld be hard to streamline this architect re " rther 'itho t sacri<cing its maintainability. + #no' o" no other "rame'or# that lets yo e>press a service-based architect re in s ch a lean and straight"or'ard manner. /o K(9 con<g ration$ e>ternal libraries$ or speci<c "rame'or#s are needed. 5he deployment consists o" only a single *A6 <le 'ith a short persistence.xml con<g ration <le. 5he entire architect re is based on a "e' annotated *ava classes 'ith p re inter"aces (that is$ inter"aces that are not dependent on the -*B AP+). Eith -*B 3.4 yo co ld even remove the inter"aces and in=ect the bean implementation directly. .ervices and ;A,s co ld be deployed 'itho t any inter"aces$ 'hich 'o ld c t the total n mber o" <les in hal" and ma#e the component signi<cantly leaner. )o'ever$ yo 'o ld lose the ability to moc# o t the service and ;A, implementation easily "or plain nit tests.

046ects7 or Do*ain7Driven Design


;omain-driven design and service-oriented design are opposite approaches. ;omain-driven design relies mainly on encaps lated ob=ects 'ith state and behavior$ 'hereas .,A emphasi?es the proced re (a service). ,b=ect-oriented applications tend to be state" l$ .,A tend to be stateless. 5he best practices in one case become antipatterns in the other.

5he -ssential +ngredients o" ;omain-;riven ;esigns


Both architect res can be modeled 'ith the same -CB approach. 5he responsibility o" the -CB arti"acts changes dramatically$ ho'ever-CBs become mapped to other patterns% 'ntity (P,8+H +he Entity is the *ain and *ost i*!ortant ingredient of the do*ain' driven architect,ral style. &t ,nifies the -ehavior and state *anage*ent in a single class. An Entity is !ersistent in *ost cases. A real do*ain'driven architect,re sho,ld act,ally only -e co*!rised of Entities /ith as!ects. All other artifacts sho,ld (in theory) -e s,!erfl,o,s. +he Entity is *a!!ed to the P"( and -y e6tension a JPA entity. Contro ()ervice+H +he #ontrol degrades to a s,!!ortive class /hich only cares a-o,t cross'c,tting as!ects. +he "A( *ay -e considered as a s!ecial kind of a #ontrol. A #ontrol is f,lly o!tional and is only introd,ced in case there is so*e Entity'inde!endent1 re,sa-le logic availa-le. &n !ractice1 a #ontrol is often ,sed for the i*!le*entation of re,sa-le 8,eries1 data /areho,se .o-s1 re!orts and so on.

2:2
Download at WoweBook.Com

3oundary (>ateway+H As in the service'oriented flavor1 the Bo,ndary re!resents the -order -et/een the ,ser interface and the -,siness logic. +he res!onsi-ilities of -oth Bo,ndaries1 ho/ever1 are e6actly inverted. +he service'oriented Bo,ndary tries to enca!s,late as tight as !ossi-le the co*!onentOs reali5ation1 /hereas the do*ain'driven Bo,ndary e6!oses the Entities (P"(s) as directly and as conveniently as !ossi-le. 0,rther*ore1 the o-.ect'oriented Bo,ndary is in *ost cases statef,l1 /hereas the service' oriented Bo,ndary is *ostly stateless. )evertheless1 the Bo,ndary in the do*ain'driven set,! is only necessary -eca,se of the Java EE 4CM shortco*ings. At least a single active co*!onent (a session -ean) is needed. &t !rovides the conte6t for the e6ec,tion of JPA entities. &n an ideal environ*ent1 a 2ate/ay co,ld also -e i*!le*ented as an as!ect1 or even a static *ethod on a P"(. &n !ractice1 the Bo,ndary (2ate/ay) is ,sed as an entry !oint to the -,siness logic and contacted first -y the ,ser interface.

As in the service-oriented e>ample$ the b siness component is comprised o" three internal s bpac#ages named a"ter the -CB approach or the patterns ((aca"e%7ate,a'$ control%service$ entit'%"omain). 5he b siness component also hosts cohesive elements only. 5here is$ ho'ever$ no separation bet'een the speci<cation and the reali?ation. Beca se the P;,s are already 'ell encaps lated$ they are directly available to the ser inter"ace. 5here is no need "or " rther encaps lation.

5he -ssential Comple>ity o" ;omain-;riven ;esigns


5he domain-driven approach is nothing else than ob=ect-oriented principles applied to the *ava -'orld. 5he essential comple>ity is tac#led 'ith 'ell-de<ned and encaps lated P;,s. 5he Date'ay is relatively easy and can also be introd ced at a later point 'ith the bottom- p approach. 5he .ervice is optional and is o"ten created in bottom- p "ashion$ a"ter the <rst re"actoring cycles to c t red ndancies. 5he big di""erence bet'een the service-oriented and domain-driven approaches is the state management. 5he .,A-li#e approaches are o"ten reB est-response or even <re-and-"orget based. 5he client sends a reB est and receives an ans'er$ mostly in an asynchrono s 'ay. 5he parameters as 'ell as the ret rn val es becomes detached a"ter every call. 5his behavior (passing the parameters and ret rn ob=ects per val e) is desired by an .,A$ so that the b siness component can remain stateless. 5he domain-driven approach relies on a P;,Js statethe client 'o ld li#e to access the ob=ects directly$ 'itho t synchroni?ing the state 'ith the bac#-end database. 5he P;,s have to remain attached "or the d ration o" the conversation. 5he P;,s remain attached in the )ntit'6ana7er and the transactions initiate the synchroni?ation 'ith the persistent store. 5his can be achieved only 'ith a state" l Date'ay$ 'hich holds a re"erence to an attached root P;,. 5he state" lness itsel" isnJt a scalability problem$ rather than the amo nt o" attached entities d ring the transaction. -very entity that 'as "o nd or re"erenced 'ill remain in the )ntit'6ana7er cache "or the length o" the session. 5he essential comple>ity o" service-oriented applications is the synchroni?ation o" the P;, graph 'ith the persistent store. Both 'rite and read operations are complicated. 5he 'rite operations are per"ormed on the server 'hen the client sends bac# the changed ob=ect graph. 5he read operations

2::
Download at WoweBook.Com

are mostly per"ormed on the client side$ 'hen the vie' tries to "ollo' the relations and load detached ob=ects. A state" l$ domain-driven component solves both iss es "or yo $ b t yo 'ill have to thin# abo t "reeing the reso rces and detaching s perH o s P;,s. 5his co ld become as comple> as the synchroni?ation o" detached entities or loading o" la?y relations in a service-oriented component. Eith the de"a lt con<g ration o" most *PA providers$ all read P;,s 'ill remain in memory "or the length o" the session. Qo 'ill either change the cache settings or 'or# 'ith pro>ies ("or e>ample$ ,+;s) and load ob=ects as needed to address the iss e. Be"ore starting any optimi?ation$ yo sho ld per"orm load and stress tests <rst. Ehether the aggressive caching behavior o" yo r provider becomes a problem or not depends on many "actors$ incl ding the n mber o" conc rrent sessions$ the session length$ and the n mber o" accessed P;,s per session.

(onolithic or 9oosely Co pledG


A b siness component is b ild according to the ma>imal cohesionCminimal co pling principle. +t contains elements that reali?e a single aspect o" the target domain. 6egardless o" ho' deco pled a component is "rom its neighbors$ its elements 'ill have to comm nicate 'ith each other. +n theory$ this direct dependency bet'een b siness components sho ld be eliminated$ or at least "actored o t into the client. +n practice$ this means that container-managed relations bet'een P;,s co ld not be spanned across components. Altho gh it seems reasonable it is not practicable. A Customer P;, "rom customerm7mt component 'o ld not be able to directly access the A""ress P;, "rom the a""ressm7mt components. 5he alternative is to c t the direct dependencies bet'een P;,s and se B eries to b ild the relations la?ily. 5his cannot only have a h ge impact on per"ormance$ b t it also ma#es the implementation "ar more complicated. 5he main advantage o" the state" l domain-driven approach is the transparent synchroni?ation and la?y loading o" dependent entities. 5o leverage this advantage yo 'ill have to reali?e direct dependencies bet'een P;,s. 5he entityCdomain layer o" one component sho ld be able to access the P;,s directly "rom the other one. +t is$ ho'ever$ not necessary "or the remaining layers to comm nicate 'ith each other. +" yo allo' direct dependencies bet'een the entityCdomain layers yo 'ill probably r n into the ne>t problem% circ lar dependencies bet'een components and even single P;,s (see !ig re :). +n *PA$ bidirectional dependencies are common and are sed heavily in *PA 4.0 (to get rid o"" the intermediary mapping table in 2One:o6an' relations).

2:0
Download at WoweBook.Com

&ig re /: Possi'le dependencies 'etween layers0


5his "act ca ses long disc ssions and "reB ent meetings and leads event ally to the "ollo'ing compromises% ,ocumented exceptions: 0e/ -idirectional de!endencies -et/een co*!onents are har*less. &tOs !rag*atic to allo/ the* instead of introd,cing co*!le6 and hard'to' *aintain /orkaro,nds s,ch as additional look,!s1 8,eries1 or resolving services. Proxying: +his is the S(A /ay of re'solving the de!endencies. &nstead of !ointing directly to the target entity1 yo, co,ld ,se a !ro6y that can -e resolved -y a 8,ery service on de*and. +he de!endent P"( /ill have to -e !rocessed -y a s!ecific service to resolve the !ro6y on de*and. +his a!!roach is less trans!arent7 it act,ally only o-f,scates the de!endency -et/een t/o entities. Component refactoring?restructuring: +his is the *ost !o!,lar and convenient sol,tion for the resol,tion of ,n/ished de!endencies. +he de!endent ele*ents are gro,!ed in a single -,siness co*!onent. +he -idirectional de!endency -et/een the P"(s still e6ists1 -,t is isolated in a single -,siness co*!onent. +his a!!roach is convenient1 -,t -reaks the *a6i*al cohesionC*ini*al co,!ling r,le. +he P"(s (for e6a*!le1 Customer /ith its A""ress) do not have to -e cohesive. +he first indicator of a non'cohesive co*!onent are diffic,lties to find the right na*e (for e6a*!le1 customera""ressm7mt).

2:1
Download at WoweBook.Com

A .mall Pattern 9ang age "or ;omain-driven Components


5here are only t'o mandatory patterns in a domain-driven component$ the P;, and the Date'ay. All other patterns and layers are optional and have to be introd ced only in case there is a reasonable need. -ven the control s bpac#age (and by e>tension a .ervice) are optional. A typical domain-driven component consists o" a single Date'ay and "e' (<ve to ten) P;,s. 5he remaining patterns (bo>es 'ith a dashed o tline in !ig re 0) can be nderstood as 'or#aro nds% Transfer ob@ect (T8+: A +( is needed for o!ti*i5ation !,r!oses. +he client is often only interested in a tiny s,-set of the entire P"(. +his is co**on for !re'filling co*-o -o6es for the i,ser interface at the -eginning of ,se cases1 for e6a*!le. &nstead of ret,rning f,ll'fledged P"(s1 yo, can let the )ntit'6ana7er !o!,late a +( and ret,rn it to the client. So*eti*es a client needs a different vie/ of the data1 as it is !rovided -y the P"(s. A +( can *eet that re8,ire*ent -y holding the res,lts of a 8,eries s!anning *,lti!le P"(s. )ervice: A Service is only needed to reali5e !roced,ral logic1 /hich cannot -e associated /ith a !artic,lar P"( /itho,t negatively infl,encing its cohesion. +herefore a Service is an e6ce!tion in the do*ain'driven /orldyo, sho,ld reali5e *ost of the -,siness logic in P"(s and crossc,tting as!ects in 2ate/ays. +here is al*ost no roo* for !roced,ral Sevice in do*ain'driven /orld. Paginator: A Paginator is a s!ecific kind of service that is a-le to iterate efficiently over a collection of P"(s. A Paginator is also an o!ti*i5ation1 /hich sho,ld only -e introd,ced in case the iteration over a collection of attached P"(s ca,ses !erfor*ance or reso,rce !ro-le*s. / uid &ogic: +his !attern is *ore likely to -e ,sed in con.,nction /ith do*ain o-.ects. A 0l,id 9ogic !attern is a-le to integrate dyna*ic lang,ages for the *ani!,lation of static P"(s. 9ang,ages s,ch as 2roovy1 JR,-y1 or Scala are /ell s,ita-le for the definition of do*ain's!ecific lang,ages1 /hich can -e a!!lied to *ani!,late attached P"(s. ,ata *ccess 8b@ect (,*8+: Whether a "A( is re8,ired is al*ost a religio,s 8,estion. &n fact the )ntit'6ana7er is already a generic "A(. &n *ost !ro.ects1 ho/ever1 yo, /ill still find a "A( that -,ilds and e6ec,tes re,sa-le 8,eries. &t is *ostly created as a !rod,ct of refactoring1 instead of -eing introd,ced ,!front. =o, can consider a "A( as a domain repository. -ntegrationa ?-nfrastructura patterns: +he ,se of integrational and infrastr,ct,ral (kitchen sink) !atterns is a lot harder to !redict. +he need for those !atterns is highly de!endent on yo,r environ*ent and its Java EE co*!liance. +he *ore inco*!ati-le reso,rces yo, have to integrate1 the *ore hacking is re8,ired. Patterns s,ch as "A(1 Asynchrono,s Reso,rce &ntegrator1 or 2eneric J#A *ay hel! yo, to cleanly integrate a inco*!ati-le reso,rce and enca!s,late the (often ,gly) gl,e code. +he infrastr,ct,ral !atterns are even *ore de!endent on yo, !artic,lar sit,ation.

2:9
Download at WoweBook.Com

&ig re 1: . domain!driven component ' ilt on patterns

200
Download at WoweBook.Com

Alphabetical Index
A active(T............................................................................................................................... 1>?+ 1>> antlr................................................................................................................................................ 11? A,P............................................................................................................................. & + &&+ &(+ 11@ Apple.cript-ngine......................................................................................................................... 11? Applets....................................................................................................................................... 1>7 1 Application .ervice....................................................................................................... ()+ (A+ ?&+ A aspect-oriented programming.................................................................................................... &1+ & Asynchrono s 6eso rce +ntegrator....................................................................................... 1>?+ @@ B Bean 9ocator.................................................................................................................... (#+ @(+ 1? beans binding............................................................................................................................. >@+ >> Bo ndary...........&?+ ()7(A+ ?1+ ?&+ 1@1+ 1@ + 1@(+ 1@)+ 1#(+ 1&)+ 1(A+ @@+ (#7 (A+ )1+ ) + )) b ilder........................................................... A)7AA+ >@7> + >)+ >?+ 11#+ 1#>+ 1&&+ 1(A71)1+ 1A7 @ B siness ;elegate............................................................................................................ (&+ 1# + 1## b siness inter"ace (+ ##+ ()+ (A7)1+ )?+ )>+ ?@+ ??7?>+ 1@(+ 1@?711@+ 1 &+ 1##+ 1#A+ 1#>+ 1?#+ 1?>+ @+ 1+ (A+ (>+ ) b siness ob=ect................................................................... ?(+ A#+ 1@@+ 11(+ 1#1+ 1# + 1#?+ 1(#+ 1>> C Caching .ingleton.......................................................................................................... 11+ 1#+ 1( Caching.ingleton................................................................................................................... 1#+ 1& CC+................................................................................................................................... # + 1&?+ 1A C(P............................................. + &+ (+ ##+ &?+ ?(+ A>+ 1@(+ 1#171#&+ 1#?+ 1(#+ 1(?+ 1?1+ 1?# C(5........................................................................................................................................... )+ (? cohesion.......................................................................................................... (&+ ()+ )(+ )?7 )> Common Client +nter"ace...................................................................................................... 1&?+ 1A conc rrency......1>+ @+ &+ A7#1+ ##+ & + &&+ &(+ (@+ (&+ ??+ ?A+ 1#A+ 1&1+ 1??+ 1A1+ 1>&+ 117 1#+ &? conHict resol tion............................................................................................................................ (@

204
Download at WoweBook.Com

consistency.............................................................................................. 1>7 1+ &+ )+ A7#@+ # + ## Conte>t )older.............................................................................................. @(+ &?+ &>+ ( + )# control1>+ 1+ &+ #@+ # + & + &)+ (@+ ??+ ?A+ 1@1+ 1@ + 11@+ 11 + 11&+ 1#1+ 1#&+ 1(?+ 1A1+ 1 + 1?+ #1+ (#7 ((+ )1+ ) + )(+ ))+ )> convention over con<g ration .................................................................................... (+ )+ #(+ 1?A C,6BA............................................................................................................... @+ )>+ ?@+ 1()+ &# create-ntity(anager!actory.............................................................. ?1+ >?+ 1@A+ 1@>+ 11#+ 1 (+ 1&A create/ativeT ery......................................................................................................................... 1&# Cr d............................ ?+ (A7)@+ A@7A + 1#>+ 1&1+ 1& + 1&&71&)+ 1&A71(1+ 1)?+ (#+ (?+ )#+ )& ; ;A,.......()+ (>+ )@+ ?&+ ?)+ ?A+ A@7A + 1 &+ 1#@+ 1# + 1#(+ 1#?71&>+ 1(1+ 1( + 1((+ 1(A+ 1)A+ 1?#+ 1>(+ @#+ )+ #(+ &)+ &?+ ( + (&+ )17 )(+ )> ;ata 5rans"er ,b=ect.............................................................. 1)+ #1+ &?+ (A+ 1@@+ 11(+ 1#A+ 1(#+ )1 ;ata.o rce........................................... ?+ >+ &1+ 1 A+ 1 >+ 1#A+ 1A + 1A&+ 1A(+ 1A>71>#+ #&+ &# ;e"a lt5able(odel.................................................................................................... ?>+ A@+ 1??+ 1?A ;ependency +n=ection 1)+ (+ #(+ #?+ #>+ &&+ &(+ ( 7(&+ ?@+ ??+ ?A+ A1+ >1+ 1@)+ 1@A+ 1#1+ 1&?+ 1&>+ 1? + 1??71?>+ 1>A+ @(+ @A+ 1?+ 1+ + >+ #1+ ##+ #(+ & 7 &&+ &)+ &A7 ( + )# ;ependency +n=ection ->tender....................................... &(+ @(+ >+ #1+ ##+ #(+ & + ( + )#

dependometer................................................................................................................................. (( deployment descriptor................ 17 (+ #(7#?+ #>7&#+ (&+ )1+ ?>+ 1?171?&+ 1??+ 1>@+ 1>1+ )+ A

;erby ;B............................................................................................................................... 1@?+ 1 A detached entity......................................................................................................................... (1+ 1(& ;omain ;riven.......................................................................................................................... 1)+ >@ domain store................................................................................................... 1@@+ 11(+ 1##+ 1( + )1 ;omain-;riven ;esign.................................................................................................. (#+ )(+ )) ;.9............................................................................................................................ >@+ >>+ 11?+ )# ;5,..................................................................................................................................................... ;ata Access ,b=ect............................................................................ 1)+ 1#(+ 1#?+ 1)>+ )#+ )> -CB........................................................................................................................ (#7 ((+ )(+ )) ehcache................................................................................................................................... 1 7 1&

202
Download at WoweBook.Com

-+........................................................................................................................................................ -nterprise +n"ormation .ystem.......................................................................................... 1+ 1#( -*B 1)+ @7 )+ A+ ##+ #(7&(+ &?+ ( 7(&+ (A+ )@7) + )(7?1+ ??7A@+ >>+ 1@ + 1@&+ 1@)+ 1@A+ 11@+ 11 + 11?+ 11A+ 1 @+ 1 #+ 1 (+ 1 A+ 1#1+ 1##+ 1#(+ 1#?+ 1#A+ 1&1+ 1& + 1&(+ 1&?+ 1&>+ 1(#+ 1(&+ 1?17 1?&+ 1??71?>+ 1A1+ 1A + 1>171>(+ 1>A+ 1>>+ @#+ @?+ @>7 1(+ 1?+ 1A+ @+ (7 A+ #17 #(+ #A+ &#+ &&+ &)7 &A+ (@+ (1+ (?7 (>+ )( e=b-=ar.............................................. #+ #A7&1+ &#+ (#+ )1+ ?>+ A@+ 11 + 1 @+ 1?1+ 1?#+ 1??71?>+ 1( entity. . + &7 ?+ >7#1+ ##+ #)+ &?+ &A+ (@7( + (&+ ()+ (A+ )A+ )>+ ?1+ ?(+ ?)+ ?A+ A&7A)+ A>7>1+ >(+ >?+ 1@@+ 1@(+ 1@A+ 11@+ 111+ 11#+ 11(+ 11A+ 1 #+ 1 (+ 1 A+ 1#1+ 1# + 1&171&A+ 1(#71((+ 1)A+ 1?#+ 1>>+ (#7 ((+ (>+ )1+ )(7 )A -ntity Control Bo ndary............................................................................................................... (# -ntity(anager.....1)+ ?+ >+ ##+ #>7& + &(7( + (&+ )@+ ?1+ A@+ A1+ A&+ >@7>#+ >)+ >?+ 1@171@#+ 1@)+ 1@A7111+ 11#+ 11A+ 1 &71#@+ 1# + 1##+ 1#?71&#+ 1&(+ 1&?71&>+ 1(1+ 1((+ 1)A+ #&+ (>+ )17 ))+ )> ->tended mode............ &+ &A7( + (&+ )1+ >>+ 1@171@#+ 11#+ 1 &+ 1 )+ 1&#+ 1&(+ 1(&+ 1>#+ @#+ ->ternali?able........................................................................................................................ 1()+ 1(? ! !allacies o" ;istrib ted Comp ting................................................................................................. # !ast 9ane 6eader................................................................................................... 1 #+ 1 &+ 1 A+ 1#@ "etch =oin.......................................................................................................................................... (1 !ieldAccess................................................................................................................................ >&+ >( !l id 9ogic...................................................................................................... 11?+ 11>71 1+ )#+ )> !l sh(ode5ype............................................................................................................................... > D Date'ay...........................1)+ (A+ ?&+ ?A+ A + >@+ >1+ >#+ 1@@711@+ 11 711(+ 1@+ &>+ (#+ ))+ )> Date'ay li"ecycle.......................................................................................................................... 1@A Deneric *CA.................................................................. 1( + 1A1+ 1A?+ 1>@+ 1> + 1>#+ 1>(+ @#+ )> generics.................................................................................................... (+ 1#>+ 1?+ #+ &A+ )

getConte>t;ata.............................................................................................................................. &? global */;+ name............................................................................................ (#+ 1&>+ 1?+ + #

D ice........................................................................................ 1)+ )+ ##+ &(+ (#+ #17 ##+ #(+ )# )

203
Download at WoweBook.Com

)ttp.ession...................................................................................................................... 20$ 408$ 40: + ++,P.......................................................................................................... + & + )?+ )>7?1+ 11 + 1?1 1+ &#

+nitialConte>t............................................................................... #?+ (#+ ?@+ 1@&+ 1?+ 1A+ +nterceptor.....1)+ #(+ &17&(+ (#+ )&+ ??+ > + 1??+ (@+ ( )+

?+ ##+ #(+ #?+ #A+ &@+ &1+ &?+ &A+

+nvocation)andler.................................................................................................................. 11@+ 111 isCancelled....................................................................................................................................... )? isolation level................................................................................................. 1>+ + A+ >+ 1 + )

iterator.............................................................................................. AA+ 1 &71 ?+ 1#&+ 1)#+ 1)&+ 1>@ * *2--............................................................................................................................... 1>+ + &+ (

*ava --.......1+ + 1(+ 1)+ 1>+ (7#?+ & + &&+ &(+ (#7()+ (A+ (>+ ) + )?+ ?1+ ?&+ ?(+ ?A+ ?>+ A17A#+ A>+ 1@@+ 1@1+ 1@(+ 11(+ 11?+ 1 #+ 1#@71# + 1#(+ 1#A71&@+ 1&)+ 1&A+ 1(#71((+ 1?1+ 1?(+ 1??+ 1?>+ 1A1+ 1>?+ @?+ 1?+ 1+ + #(+ &#7 &(+ &?+ &>7 (1+ (#+ ((+ ()+ )#+ ))+ )> *ava Eeb .erver............................................................................................................................... @ =ava%compCenv........................................................................................................................ 1? + 1?# =ava%global............................................................................................................... (#+ 1@A+ 1&>+ 1? *avaBlend......................................................................................................................................... & *Boss-Cache................................................................................................................................... 1 *CA..................... 1)+ >+ 1&@+ 1&?+ 1( + 1)A+ 1A1+ 1A + 1A&+ 1A?+ 1>@71>(+ @#+ 1 + 1#+ &#+ )> *Console......................................................................................................................................... (

=depend........................................................................................................................................... (( *(........ 1+ (+ ?+ >+ #>+ &1+ & + &&+ )17)#+ )(7)?+ )>+ A@+ 1##+ 1>?7 @@+ @ + @#+ 1+ #?7 &@

*(K............................................................................................................................................... 1 */;+ 1)+ 1+ (+ #?+ #A+ &1+ (#+ ?@+ A@+ 1#1+ 1##+ 1&>+ 1?1+ 1??+ 1A + 1A(+ 1>1+ 1?7 #+ #&+ &#7 &)+ &A+ &> *PA 1)+ &7#1+ #)+ &@+ &(7&A+ (1+ (?+ (A+ ?1+ ?)+ ?A+ A@+ A&+ A>7>1+ >?+ >>+ 1@1+ 1@ + 1@)+ 11#+ 1 #+ 1 A+ 1 >+ 1# + 1#&+ 1#?71&#+ 1&)+ 1&A+ 1(171(A+ 1)&+ 1)A+ 1?1+ 1?#+ 1?(+ 1(+ (&+ (>7 ) + )(7 )? *.6-414........................................................................................................................................... )? *.6-220......................................................................................................................................... 1A1

208
Download at WoweBook.Com

*.6-223.................................................................................................................... 1)+ 11?+ 11>+ 1 @ *.6-232......................................................................................................................................... 1)) *.6-292............................................................................................................................. >@+ >&+ 1(> *.6-344............................................................................................................................................ )? 9 la?y loading........................................................................................................ (1+ ( + 11(+ )@+ )? lea#y abstraction............................................................................................ 1@ + 1@(+ 1(1+ 1)A+ (# 9ea#y Abstractions........................................................................................................................ 1@ loc#ing................................................................................................... #@+ #1+ ##+ (@+ 1#@+ @ + )1 9oc#5ype.6-A;........................................................................................................... 1 + 1#+ 1( 9oc#5ype.E6+5-.................................................................................................................. 1 7 1& loo# p. .1)+ #?+ &1+ (#+ (&+ ?@+ ?(+ 1@A+ 1#1+ 1##+ 1&>+ 1?171?#+ @?+ 1?+ 1A+ &)+ &A+ )A @7 + &#+ &(+

9oosely Co pled............................................................................................................................ )? ( ma>imal cohesion$ minimal co pling............................................................................................ () (Bean................................................................................................................................... 1A1+ 1 (-5A-+/!.................................................................................................................................... 1(@ moc#ing....................................................................................................................... )@+ ? + A + &) (onolithic......................................................................................................................... 1+ >>+ )? / /amedT ery.......................................................................................................................... 1&#+ (> ne'Pro>y+nstance.................................................................................................................. 11@+ 111 /,5P.7PP,65-;............................................................................................... 1@ + 1@#+ 1@(+ 11 , on(essage.......................................................................... ) 7)&+ 1)1+ 1>A+ )+ #?+ #A+ &@+ &1

open(T................................................................................................................................. 1>?+ 1>> ,ptimistic................................................................................. #@7##+ &(+ (@+ (1+ 11&+ 1#@+ 1&1+ 1&# optimistic loc#ing strategies............................................................................................................ #@ ,ptimistic#9oc#->ception.............................................................................................................. &(

202
Download at WoweBook.Com

P Paginator................................................................................................. 1 #71 A+ 1#@+ 1#&+ )#+ )> Payload ->tractor............................................................................................ &(+ @(+ #(+ #?+ ( Payload->tractor............................................................................................................ #A+ &@7 & P;,......A(+ A)+ A>7>&+ >)71@ + 1@&71@)+ 11 711(+ 1 &+ 1&1+ 1((+ 1(A+ &?+ (>+ )17 )#+ )(7 )> persistence.>ml............................................................................................ #>+ &@+ >>+ 1@?+ 1(@+ )( Persistent ;omain ,b=ect.................................................................................... A#+ A(+ >@+ ((+ (> poisoned message.................................................................................................. @@+ #?+ #>+ &1 P,*,... &+ (+ &&+ (&+ (A+ ?1+ ??+ ?>+ A@+ A + >)+ 1@ + 1@?+ 1@A+ 11>+ 1#(+ 1&)+ 1&?+ 1(#+ 1()+ 1(A+ 1??71?>+ 1(+ 1?+ ?+ #(+ &&7 &)+ )# Premat re -ncaps lation......................................................................................................... ?A+ (# Prepared.tatement......................................................................................................................... 1 > Python............................................................................................................................................ 11? T T eryParameter..................................................................................................................... 1&&+ 1&( 6 ra.>ml..................................................................................................................................... 1>@+ 1>1 rebind............................................................................................................................................. &# re"resh.............................................................................. #1+ &)+ &>+ (@+ A@+ 1@#+ 1@)+ 1#@+ 1& + 1 replication........................................................................................................................ )+ 1)A+ 1 reB ired....1(+ &+ )+ #(7#?+ &1+ &)+ &?+ (&+ (?+ (>+ )@+ )#+ )>+ ?@+ ?(+ ?A+ A1+ A#+ A>+ >1+ 1@A+ 11 + 1 &+ 1 A+ 1#1+ 1# + 1#A+ 1& + 1&#+ 1((+ 1)1+ 1)?+ 1?1+ 1?&+ 1??+ 1A1+ 1A + 1>#+ 1>?+ 1>>+ @1+ 1@+ 1(+ #(+ &1+ &#+ &(+ &)+ &A+ (1+ ( + (A+ )@+ ) + )> 6-T7+6-.P/-E................................. &?+ &>+ (?+ (>+ ) + )?+ )>+ > + 1@#+ 1@(+ 11 + 1&(+ (?+ (A 6eso rce Binder.................................................................................................................... @(+ &# 6-.,76C-P9,CA9..................................................................................................... &@+ 1@?+ 1(@ rest. .1(+ 1)+ @+ &+ A+ #@+ &17&&+ &>+ ( + (?+ )1+ ) + )?7)>+ ?#+ ?)+ ?>+ A1+ AA7>@+ >&+ >)+ >A+ 1@&+ 1@)+ 1@?+ 1@>+ 11 + 11?+ 11A+ 1 #+ 1 (+ 1 >71#1+ 1#(+ 1#?+ 1&1+ 1( + 1(&+ 1()+ 1)&+ 1?#+ 1?&+ 1??+ 1?>+ 1A1+ 1>&+ 1>?+ 1>>7 @1+ 117 1&+ 1A+ + A+ ##+ &@+ &&+ &(+ &?+ (>+ )#+ )A+ )> 6es lt.et........................................................................................................ 1 #+ 1 &+ 1 >+ 1&?+ (& 6etired Patterns.............................................................................................................................. 1#1 rmic.................................................................................................................................................. ?1

20:
Download at WoweBook.Com

6 by........................................................................................................................... (+ #(+ 11?+ )> . .cript-ngine........................................................................................................................... 11?711> .;,............................................................................................................................... 1@@+ 1))+ 1)? seB entiali?ation............................................................................................................................ 1# .eriali?able...... A+ >+ #)+ ) + >>+ 1&&+ 1(#+ 1()71(>+ 1)1+ 1) + 1)(+ 1A + 1A>+ 1 + 1#+ #?+ #>+ &&+ &( service..1)+ @7 + )+ #?7& + &&+ &?+ (#7A(+ A>7>#+ >>71@ + 1@(+ 11 + 11&+ 11(+ 11A71 1+ 1 #+ 1 &+ 1 A+ 1#@71##+ 1#(+ 1#A71& + 1&&71&>+ 1( 71((+ 1(A+ 1))+ 1)?+ 1)>+ 1? + 1?#+ 1??+ 1>&+ 1>(+ 1>?7 @#+ @(+ @?7 1(+ 1+ #+ )+ >+ # 7 #(+ &17 &#+ &)7 (>+ )17 )> service activator....................................................................................................... )#+ 1>?+ 1>>+ @# .ervice ;ata ,b=ects..................................................................................................................... 1)) .ervice !a@ade. .()7)&+ )?+ )>7?&+ ?)7?A+ A17A#+ A(+ >@7>#+ 1@@71@ + 1@(+ 11 + 11(+ 1 #+ 1 &+ 1#@+ 1# + 1#A+ 1( + 1(A+ 1)>+ 1>(+ 1>A+ @@+ @1+ 1 + 1(+ )+ >+ # 7 #(+ &)7 &>+ ( + (#+ ((+ (A+ (>+ )17 )& service locator.......................................................................... (&+ 1#1+ 1##+ 1? + 1+ #+ &)+ &>

.ervice .tarter................................................................................................ @(+ @?+ 1@+ 11+ 1( .ervlet. . @7 + (+ ?+ & + ( 7(&+ ()+ )@+ )>+ >#+ 1@&+ 1@)+ 1#@+ 1??+ 1A1+ 1>>+ @?+ @>+ 1@+ 1?+ @+ ?+ &&+ &> .ession !a@ade............................................................................................. (+ ()+ (A+ ?&7?)+ ?A+ A set6ollbac#,nly...................................................................................................................... )#+ 1> .ingleton.............................................................. 1)+ 1>+ 1@>+ 1??+ @(+ @?7 1(+ 1>7 1+ &#7 &) .,A....&&+ (>+ )17)#+ )(+ ))+ ?#+ ?(+ ?)+ ?A+ 11(+ 1(&+ 1((+ 1))+ #(+ ((+ ()+ (A+ )@+ ) 7 ))+ )A sonar=............................................................................................................................................. (( .pring........................................................................................................... (+ )+ ##+ #1+ #(+ )# 5 5hread 5rac#er............................................................................................................... @(+ (+ (

5hread9ocal........................................................................................................ >17>#+ &?+ &>7 ( transaction. 1>7#1+ ##+ #(7#?+ &@+ & + &&7(1+ (&+ ()7(>+ ) + )#+ ))+ )?+ )>+ ?1+ ?#7?A+ A@7A + A>+ > + >?+ 1@171@(+ 1@?711#+ 11(+ 11A+ 1 (+ 1 )+ 1 A+ 1#A71& + 1&(71(1+ 1(#+ 1)A+ 1?(+ 1??+ 1?>+ 1A1+ 1A + 1A&+ 1A)71A>+ 1>171>(+ 1>?71>>+ @17 @#+ (+ )+ A+ #1+ #&+ #?+ &(+ &?7 ( + ()7 (>+ )17 )#+ ))

200
Download at WoweBook.Com

transaction-type................................................................................................. #+ &@+ 1@?+ 1#>+ 1(@ 5ransactionAttrib te5ype./-A-6............................................................................................ &A+ &> 5ransactionAttrib te5ype.6-T7+6-.P/-E.....&?+ &>+ (?+ ) + )?+ )>+ > + 1@#+ 11 + 1&(+ (?+ (A 5ransaction6eB ired->ception.......................................................................................... &)+ &>+ 1@# 5ransaction.ynchroni?ation6egistry..................................................................................... &?7 ( 5rans"er ob=ect. .1)+ #1+ &?+ (?+ (A+ 1@@+ 11(+ 1# + 1#&+ 1#(+ 1#A+ 1&)+ 1&?+ 1(#+ 1(?+ )17 )#+ )> transparent persistence............................................................................................................. (1+ 1@) 7 ltra-thin client................................................................................................................................ @ 7niversal (essage .ervice............................................................................................................ 1>> A Aal e 9ist )andler......................................................................................................... 1 &+ 1#&+ 1( Aal e ,b=ect Assembler................................................................................................................. 1# Ais alA(............................................................................................................................... E 'eb.>ml......................................................................................................................................... @> EebBeans.............................................................................................................................. 1@)+ 1@? Eeb.ervice.............................................................................................................................. )?+ 1#( K K;oclet.............................................................................................................. #(+ #)+ 1(#+ 1?#+ 1?& >radar............................................................................................................................................. (( @ @Aro nd+nvo#e...................................................... & + &&+ )&+ )(+ >#+ (+ # + ##+ #A+ &?+ (@ (+ )

@Asynchrono s...................................................................................................................... ))+ 1>> @9ocal)ome................................................................................................................................. 1? @(essage;riven............................................................................................................ ) + 1>A+ #A @PostConstr ct...................................................................... 11A+ @?7 11+ 1#+ # + ##+ &#+ && @Pre;estroy.......................................................................................................................... 1&+ # @6eso rce................................................................. &1+ &)+ 1 A+ 1>1+ 1> + #>+ &&+ &(+ &?+ &A @.ingleton..................................................................................... @?7 @>+ 11+ 1#+ 1&+ &#+ &&

201
Download at WoweBook.Com

@.tart p........................................................................................ @?+ @>+ 1@+ 1#+ 1&+ &#+ && @.tateless..... (+ ?+ #)+ #A+ #>+ &1+ & + &?+ (#+ (&+ (?+ ))+ )?+ ?@+ ?#+ ?)+ ?>7A1+ A&+ > + 11?+ 1 ?+ 1 A+ 1#A+ 1& + 1&(+ 1? + 1??+ 1?A+ 1>1+ 1>A+ @A+ )+ # + ##+ #>+ &A+ (@+ (1+ (?+ (A @Aersion................................................................................................................... #1+ (@+ 1&1+ 1&# @Kml6oot-lement......................................................................................................................... )A

209
Download at WoweBook.Com

You might also like