Building Java Enterprise Systems with J2EE


325 68 15MB

English Pages 1288

Report DMCA / Copyright

DOWNLOAD PDF FILE

Recommend Papers

Building Java Enterprise Systems with J2EE

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CONTENTS ABOUT THE AUTHORS ...............................................................................................2 ACKNOWLEDGMENTS .................................................................................................2 TELL US W HAT YOU THINK! ......................................................................................3 INTRODUCTION ...........................................................................................................4 This Is Your Enterprise on Caffeine! ................................................................4 This Is the Book to Address Your Needs! .......................................................5 This Is Your Brain After Reading This Book! ..................................................8 PART I: ENTERPRISE FOUNDATIONS .......................................................................10 I N THI S PART..................................................................................................10 CHAPTER 1. ENTERPRISE ARCHITECTURAL OVERVIEW .........................................10 The Enterprise ...................................................................................................11 Enterprise Components ...................................................................................13 Information Technology in the Enterprise .....................................................14 Conclusions........................................................................................................16 CHAPTER 2. OBJECT-ORIENTED SOFTWARE DEVELOPMENT FOR THE ENTERPRISE ..................................................................................................................................16 Enterprise Objects.............................................................................................17 The Object-Oriented Development Process .................................................20 Unified Modeling Language.............................................................................25 Conclusions........................................................................................................32 CHAPTER 3. COMPONENT-BASED SOFTWARE DEVELOPMENT FOR THE ENTERPRISE .............................................................................................................32 Enterprise Components ...................................................................................32 Component Models...........................................................................................34 Component-Based Development ...................................................................38 Standards ...........................................................................................................40 Conclusions........................................................................................................43 CHAPTER 4. JAVA FOUNDATIONS FOR ENTERPRISE DEVELOPMENT .....................44 Java Features and Versions............................................................................44 Java Platform Architecture...............................................................................47 Java Files and Tools.........................................................................................49 Java Language ..................................................................................................52 Core Java Language APIs...............................................................................57 Collection APIs ..................................................................................................64 Input/Output and State Persistence APIs......................................................68 Threading APIs ..................................................................................................73 Date and Time APIs..........................................................................................77 Java Applets.......................................................................................................78 Conclusions........................................................................................................82 CHAPTER 5. JAVA ENTERPRISE SYSTEM ARCHITECTURE WITH THE J2EE ...........82 The J2EE Model................................................................................................83 J2SE V1.2 VERSUS J2SE V1.3..........................................................................85 Enterprise Java and J2EE Architecture.........................................................87 Data Connectivity ..............................................................................................90 Communication Mechanisms ..........................................................................91 Assurance Mechanisms ...................................................................................93 Client Connectivity ............................................................................................94 Web Connectivity ..............................................................................................95

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Application Connectivity ...................................................................................96 The J2EE Future ...............................................................................................96 Conclusions........................................................................................................98 CHAPTER 6. ENTERPRISE USER INTERFACING .......................................................99 The Distributed Enterprise User Interface.....................................................99 Java AWT Components .................................................................................102 Java Swing Components ...............................................................................103 Utility and Accessibility Components ...........................................................105 Graphics and Multimedia Components .......................................................106 Web Page Interfaces ......................................................................................107 Conclusions......................................................................................................109 CHAPTER 7. MODELING COMPONENTS WITH JAVABEANS ...................................110 JavaBeans Overview ......................................................................................111 JavaBeans Containers ...................................................................................112 JavaBeans Events ..........................................................................................116 JavaBeans Properties ....................................................................................118 JavaBeans Introspection................................................................................124 JavaBeans Persistence..................................................................................126 JavaBeans Customization .............................................................................127 The InfoBus......................................................................................................130 Conclusions......................................................................................................131 PART II: ENTERPRISE DATA ENABLING .................................................................132 I N THI S PART................................................................................................132 CHAPTER 8. ENTERPRISE DATA ............................................................................133 Database Basics..............................................................................................133 Relational Databases .....................................................................................136 Object Databases............................................................................................142 RDBMSs Versus ODBMSs............................................................................144 Relational/Object Translations ......................................................................146 CLIs ...................................................................................................................148 Embedded SQL ...............................................................................................148 ODBC ................................................................................................................150 JDBC .................................................................................................................150 Conclusions......................................................................................................151 CHAPTER 9. BASIC JDBC .....................................................................................151 JDBC Architecture...........................................................................................152 JDBC Drivers and their Types.......................................................................155 THE J2EE AND JDBC DRIVER TYPE SELECTION ............................................155 JDBC Driver Configuration ............................................................................159 THE J2EE AND JDBC DRIVER CONFIGURATION .............................................159 JDBC Connections..........................................................................................162 THE J2EE AND JDBC CONNECTIONS ..............................................................162 JDBC Statements............................................................................................167 JDBC Result Sets............................................................................................176 SQL and Java Mappings................................................................................183 JDBC MetaData...............................................................................................184 Conclusions......................................................................................................189 CHAPTER 10. ADVANCED JDBC...........................................................................189 Scrollable Result Sets ....................................................................................190 Updateable Result Sets .................................................................................199

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Batch Updates .................................................................................................208 Advanced Data Types ....................................................................................211 Row Sets ..........................................................................................................224 Stored Procedures ..........................................................................................226 Database Naming via JNDI ...........................................................................231 THE J2EE AND JDBC 2.0 ................................................................................231 Connection Pools ............................................................................................233 Distributed Transactions ................................................................................235 Conclusions......................................................................................................236 PART III: ENTERPRISE DATA ENABLING ................................................................238 I N THI S PART................................................................................................238 CHAPTER 11. DISTRIBUTED ENTERPRISE COMMUNICATIONS ..............................239 Distributed Systems ........................................................................................239 Distribution Mechanisms ................................................................................241 The Network Client..........................................................................................243 The Network Server........................................................................................244 Conclusions......................................................................................................246 CHAPTER 12. NETWORK COMMUNICATIONS ........................................................246 Network Computing ........................................................................................247 TCP/IP Protocol Suite.....................................................................................249 JAVA SOCKET PROGRAMMING AND THE J2EE .................................................255 CHAPTER 13. WEB COMMUNICATIONS .................................................................275 The Internet and the World Wide Web ........................................................275 HTTP .................................................................................................................278 CGI ....................................................................................................................287 Servlets .............................................................................................................288 HTML Documents ...........................................................................................289 Dynamic HTML Generation ...........................................................................289 Conclusions......................................................................................................290 CHAPTER 14. MODELING COMPONENTS WITH CORBA ......................................290 CORBA Overview............................................................................................291 The ORB...........................................................................................................294 GIOP and IIOP.................................................................................................296 Services, Facilities, and Business Objects .................................................298 IDL .....................................................................................................................302 Objects by Value .............................................................................................308 Conclusions......................................................................................................313 CHAPTER 15. CORBA COMMUNICATIONS ...........................................................313 The Very Distributed CORBA........................................................................314 THE J2EE AND CORBA ...................................................................................315 CORBA Vendors .............................................................................................316 Java IDL............................................................................................................318 CORBA Interfaces...........................................................................................319 CORBA Servers and Skeletons ....................................................................321 Implementation Repository ............................................................................333 Object Adapters...............................................................................................333 Interface Repository........................................................................................337 CORBA Clients and Stubs.............................................................................341 CORBA Naming ..............................................................................................346 Conclusions......................................................................................................348

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CHAPTER 16. RMI COMMUNICATIONS ..................................................................349 RMI Basics .......................................................................................................349 THE J2EE AND RMI ..............................................................................................350 JRMP.................................................................................................................354 RMI and IIOP ...................................................................................................355 RMI/IIOP VERSUS JAVA IDL ................................................................................355 Java-to-IDL Mapping ......................................................................................356 Objects by Value and RMI .............................................................................357 RMI Interfaces..................................................................................................357 RMI Servers and Skeletons...........................................................................360 RMI Registration..............................................................................................372 RMI Clients and Stubs....................................................................................380 RMI Lookup ......................................................................................................385 RMI Object Activation .....................................................................................386 Custom Sockets ..............................................................................................392 Conclusions......................................................................................................394 CHAPTER 17. MODELING COMPONENTS WITH COM/DCOM ..............................394 COM and DCOM in a Nutshell......................................................................395 COM/DCOM Services ....................................................................................399 Interface Definition Language .......................................................................400 Conclusions......................................................................................................403 CHAPTER 18. DCOM COMMUNICATIONS .............................................................404 DCOM in the Machine ....................................................................................404 DCOM Interfaces.............................................................................................406 DCOM Identifiers.............................................................................................408 DCOM Types ...................................................................................................409 DCOM Servers and Skeletons ......................................................................409 DCOM Server Registration ............................................................................422 DCOM Clients and Stubs...............................................................................425 DCOM Client Registration and Spawning ...................................................427 DCOM Bridging................................................................................................428 Conclusions......................................................................................................428 PART IV: COMMON SERVICES FOR DISTRIBUTED ENTERPRISE COMMUNICATIONS ................................................................................................................................430 I N THI S PART................................................................................................430 CHAPTER 19. NAMING SERVICES .........................................................................431 Naming Services in a Nutshell ......................................................................431 JNDI Naming Services ...................................................................................433 THE J2EE AND JNDI.........................................................................................437 Naming Files ....................................................................................................453 CORBA Naming ..............................................................................................455 RMI Naming .....................................................................................................462 DNS ...................................................................................................................468 DCOM Naming ................................................................................................470 Conclusions......................................................................................................472 CHAPTER 20. DIRECTORY AND TRADING SERVICES ............................................472 Directory and Trading Services in a Nutshell .............................................473 JNDI Directory Services .................................................................................474 NIS as a Directory Service.............................................................................481 NDS as a Directory Service...........................................................................482

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

LDAP as a Directory Service.........................................................................484 CORBA as a Trading Service........................................................................496 Jini as a Trading Service................................................................................502 Microsoft Active Directory Services..............................................................513 Conclusions......................................................................................................514 CHAPTER 21. ACTI VATI ON SERVI CES ................................................................514 Act ivat ion Services Overview .................................................................515 RMI Act ivat ion Fram ework.......................................................................517 CORBA Act ivat ion Fr am ework ................................................................519 CORBA Lifecycle Service...........................................................................522 DCOM Act ivat ion Fr am ework ..................................................................524 JavaBeans Act ivat ion Fram ework .........................................................526 Web and Applicat ion Act ivat ion Fram eworks ...................................528 Conclusions ....................................................................................................529 CHAPTER 22. MESSAGI NG SERVI CES .................................................................530 Messaging Overview ..................................................................................531 MOM..................................................................................................................536 Java Message Service ................................................................................539 THE J2EE AND JMS.........................................................................................542 CORBA Messaging .......................................................................................578 JavaMail...........................................................................................................587 THE J2EE AND JAVAMAI L ....................................................................................600 Conclusions ....................................................................................................617 CHAPTER 23. TRANSACTI ON SERVI CES .............................................................618 Transact ions ..................................................................................................619 Transact ion Services ..................................................................................624 Obj ect Transact ion Service......................................................................629 Java Transact ions API ................................................................................635 JTA Transact ion Manager I nt erface......................................................636 JTA Applicat ion I nt erface .........................................................................638 JTA and X/ Open XA ....................................................................................640 Java Transact ions Service........................................................................642 Conclusions ....................................................................................................643 PART V: ENTERPRI SE SYSTEMS ASSURANCE .....................................................645 I N THI S PART................................................................................................645 CHAPTER 24. HI GH- ASSURANCE ENTERPRI SE APPLI CATI ONS.........................646 What I s Assurance?....................................................................................646 General Assurance Process .....................................................................650 To Be Assured or Not t o Be Assured? .................................................654 Securit y ...........................................................................................................656 Reliabilit y ........................................................................................................658 Availabilit y ......................................................................................................660 Maint ainabilit y ..............................................................................................662 Safet y ...............................................................................................................664 Conclusions ....................................................................................................665 CHAPTER 25. SECURI TY BASI CS ........................................................................666 The Basic Securit y Model .........................................................................667

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Crypt ography ................................................................................................668 Aut hent icat ion and Nonrepudiat ion......................................................673 Secure Socket Layer ( SSL) ......................................................................678 Access Cont rol ..............................................................................................679 Dom ains ..........................................................................................................681 Audit ing ...........................................................................................................682 Policies and Adm inist rat ion .....................................................................682 Conclusions ....................................................................................................683 CHAPTER 26. BASI C JAVA SECURI TY .................................................................684 The Hist ory of Securit y in Java ..............................................................685 Java Securit y Archit ect ure .......................................................................687 Byt e Code Verifier .......................................................................................691 Class Loader ..................................................................................................692 Securit y Manager ........................................................................................698 Java Crypt ography Archit ect ure ............................................................703 Conclusions ....................................................................................................708 CHAPTER 27. ADVANCED JAVA SECURI TY .........................................................708 Perm issions....................................................................................................709 Securit y Policies ...........................................................................................717 Java Access Cont rol ....................................................................................723 Principal I dent ificat ion ...............................................................................734 Prot ect ing Obj ect s.......................................................................................744 Signing Code .................................................................................................753 Java Securit y Ex t ensions..........................................................................758 Conclusions ....................................................................................................765 CHAPTER 28. CORBA SECURI TY.......................................................................766 CORBA Securit y Overview .......................................................................768 D I GESTI NG THE CORBA SECURI TY SERVI CE SPECI FI CATI ON .........................768 Aut hent icat ion ..............................................................................................775 Delegat ion ......................................................................................................780 Aut horizat ion .................................................................................................781 Audit ing ...........................................................................................................783 Nonrepudiat ion .............................................................................................785 Encrypt ion ......................................................................................................789 Securit y Policies ...........................................................................................791 Securit y Adm inist rat ion ............................................................................792 Conclusions ....................................................................................................793 PART VI : ENTERPRI SE W EB ENABLI NG ..............................................................794 I N THI S PART................................................................................................794 CHAPTER 29. W EB BROWSERS AND SERVERS I N THE ENTERPRI SE ................795 Web Browsers ...............................................................................................795 Web Browser Securit y ...............................................................................798 Java Plug- in ...................................................................................................801 Web Servers ..................................................................................................804 Web Server Securit y ..................................................................................807 Web Server Availabilit y .............................................................................811 Conclusions ....................................................................................................812

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CHAPTER 30. TRADI TI ONAL W EB PROGRAMMI NG AND JAVA ...........................812 HTML Program m ing ....................................................................................813 CGI Program m ing .......................................................................................824 Script ing Languages...................................................................................830 Act ive Server Pages ...................................................................................836 Java- Based Web Pr ogram m ing ..............................................................837 Conclusions ....................................................................................................839 CHAPTER 31. XML...............................................................................................839 XML Overview ...............................................................................................840 XML Form at t ing ............................................................................................842 DTD Declarat ion ...........................................................................................849 Hyperlinking in XML....................................................................................858 XML St yle Sheet s.........................................................................................863 Sim ple API for XML.....................................................................................866 Docum ent Obj ect Model ...........................................................................882 Java and XML ................................................................................................897 Conclusions ....................................................................................................902 CHAPTER 32. JAVA SERVLETS .............................................................................903 Servlet Archit ect ure ...................................................................................904 Servlet I nt erfaces........................................................................................906 Servlet HTTP I nt erfaces ............................................................................915 Request Processing.....................................................................................923 Response Generat ion .................................................................................936 Session Managem ent .................................................................................945 Servlet Deploym ent ....................................................................................953 Servlet Configurat ion .................................................................................968 Servlet Service Managem ent ..................................................................972 Conclusions ....................................................................................................981 CHAPTER 33. JAVASERVER PAGES .....................................................................982 JSP Overview ................................................................................................983 JSP Language Basics..................................................................................988 JSP Translat ion and Com pilat ion Direct iv es......................................991 Java Script ing from JSP............................................................................997 Java Abst ract ions of JSP.........................................................................1000 St andard Java Obj ect s from JSP.........................................................1007 St andard Java Act ions from JSP..........................................................1013 JSP Configurat ion and Deploym ent ....................................................1026 Cust om Java Act ions and Tags from JSP.........................................1033 Conclusions ..................................................................................................1038 PART VI I : ENTERPRI SE APPLI CATI ONS ENABLI NG ..........................................1040 I N THI S PART..............................................................................................1040 CHAPTER 34. ENTERPRI SE APPLI CATI ON PLATFORMS ....................................1041 Ent erprise Plat form s Overview ............................................................1042 TP Monit or Plat form s................................................................................1043 OTMs ..............................................................................................................1044 Generic Applicat ion Fram eworks.........................................................1046 St andard Java- Based Generic Applicat ion Fram ework ...............1048

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CORBAcom ponent s ...................................................................................1050 Microsoft 's Generic Applicat ion Fram ew ork ....................................1051 Applicat ion- Specific Plat form s ..............................................................1053 Ent erprise Applicat ion Managem ent ..................................................1054 Conclusions ..................................................................................................1055 CHAPTER 35. APPLI CATI ON SERVERS AND ENTERPRI SE JAVABEANS............1056 St andalone Ent erprise Applicat ions....................................................1057 Applicat ion Server–Based Ent erprise Applicat ions.......................1059 Applicat ion Server Archit ect ure Provider Roles.............................1062 Applicat ion Server Com ponent s ..........................................................1064 Applicat ion Server Client I nt erfaces ..................................................1068 Applicat ion Server Client I m plem ent at ions ....................................1070 Ent erprise Applicat ion Configurat ion and Deploym ent ...............1075 Applicat ion Service Managem ent ........................................................1079 Conclusions ..................................................................................................1081 CHAPTER 36. MODELI NG COMPONENTS WI TH ENTERPRI SE JAVABEANS ......1082 EJB Overview ..............................................................................................1083 EJB Configurat ion and Deploym ent Basics......................................1095 Session Bean Server Com ponent s .....................................................1102 Session Bean Client I nt erfaces ............................................................1117 Session Bean Configurat ion and Deploy m ent ................................1129 EJB and JDBC..............................................................................................1133 Ent it y Bean Server Com ponent s .........................................................1135 Ent it y Bean Client I nt erfaces................................................................1157 Ent it y Bean Configurat ion and Deploym ent ...................................1166 Conclusions ..................................................................................................1173 CHAPTER 37. ADVANCED ENTERPRI SE JAVABEANS SERVI NG .......................1174 EJB Transact ions........................................................................................1175 EJB Securit y .................................................................................................1185 EJB SECURI TY AUTHENTI CATI ON MODEL LI MI TATI ONS .............................1191 EJB/ Web Connect iv it y..............................................................................1194 EJB/ CORBA Connect ivit y ........................................................................1203 EJB and XML................................................................................................1206 EJB and JMS ................................................................................................1209 EJB and JavaMail .......................................................................................1215 Conclusions ..................................................................................................1218 CHAPTER 38. ENTERPRI SE APPLI CATI ON I NTEGRATI ON .................................1218 Ent erprise Applicat ion I nt egrat ion Overview ..................................1219 EAI wit h JNI .................................................................................................1221 EAI wit h Dist r ibut ed Ent erprise Com m unicat ion Paradigm s ....1225 EAI wit h Messaging Services and JMS ..............................................1230 EAI wit h XML ...............................................................................................1231 EAI wit h J2EE Connect ors ......................................................................1233 Em bedded Applicat ions I nt egrat ion ...................................................1235 Conclusions ..................................................................................................1237 PART VI I I : APPENDI XES ....................................................................................1238 I N THI S PART..............................................................................................1238

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

APPENDI X A. SOFTWARE CONFI GURATI ON ......................................................1239 Soft ware on t he CD ..................................................................................1239 Soft ware Configurat ion per Chapt er ..................................................1241 J2SE Configurat ion ...................................................................................1242 J2EE Configurat ion ....................................................................................1242 Java Env ironm ent Variable Configurat ion .......................................1243 Microsoft Java Configurat ion.................................................................1243 BEA WebLogic Server Configurat ion ..................................................1244 Sam ple Soft ware Configurat ion ...........................................................1245 Dat abase Configurat ion ..........................................................................1246 Web Configurat ion ....................................................................................1257 Applicat ion Server Configurat ion ........................................................1260 JavaBeans Configur at ion ........................................................................1263 XML Configurat ion .....................................................................................1264 CORBA ORB Configurat ion .....................................................................1264 CORBA Services Configurat ion .............................................................1264 RMI / I I OP Configurat ion...........................................................................1265 JNDI Configurat ion....................................................................................1266 LDAP Configurat ion ...................................................................................1267 Jini Configurat ion.......................................................................................1268 JMS Configurat ion .....................................................................................1268 JavaMail Configurat ion ............................................................................1269 APPENDI X B. ADDI TI ONAL RESOURCES ...........................................................1270 Obj ect - Orient ed and Com ponent - Based Soft ware Developm ent ..........................................................................................................................1270 Java Basics...................................................................................................1271 J2EE Basics ..................................................................................................1271 User I nt erfacing .........................................................................................1271 JavaBeans ....................................................................................................1272 Dat abase Developm ent and JDBC ......................................................1272 General Dist ribut ed Com m unicat ions and TCP/ I P........................1273 CORBA ...........................................................................................................1273 RMI ..................................................................................................................1273 COM/ DCOM ..................................................................................................1274 JNDI , Nam ing, Direct ory, Trading, and Jini Services ..................1274 MOM, JMS, and Jav aMail ........................................................................1275 Dist ribut ed Transact ions, JTA, and JTS ............................................1275 General Assurance and Securit y .........................................................1276 General Web, HTML, and Script ing ....................................................1276 XML .................................................................................................................1277 Java Servlet s and JSP..............................................................................1277 Applicat ion Serving and EAI ..................................................................1277 Ent erprise JavaBeans...............................................................................1278

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Building Java Ent erprise Syst em s wit h J2EE Paul J. Perrone Venkat a S. R. " Krishna" R. Chagant i Publisher: Sam s Publishing First Edit ion June 07, 2000 I SBN: 0- 672- 31795- 8, 1536 pages

The pract ical angle of Building Java Ent erprise Syst em s wit h J2EE provides t he concept ual background and wealt h of code exam ples needed t o act ually assem ble syst em s in a useful m anner w it h t he J2EE t echnologies. Furt herm ore, t his book dem onst rat es how t he t echnologies com plem ent and build on t op of one anot her via evolut ion of a cohesive and real sam ple applicat ion. You can use t his book t o learn, develop, and design your cust om applicat ions im m ediat ely.

-1-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

About The Authors Paul J. Perrone is the Founder, the President, and a Senior Software Consultant for Assured Technologies, Inc. Through Assured Technologies (ht t p: / / www.assuredt ech.com ), Paul provides software consulting, training, products, and research for companies interested in economical, scalable, secure, and Internet-enabled distributed enterprise systems used for ecommerce, business-to-business (B2B) transactions, and general enterprise-wide application. Paul has enabled his specialized background in high-intelligence and high-assurance (for example, security) systems to be reflected in Assured Technologies's business practice and pursuits. Paul has been a key player in the architecture, design, and development of numerous large-scale n-tier distributed systems and products for both Fortune 500 and medium-sized organizations. Paul's key technology and training expertise areas are enterprise Java and the J2EE, Enterprise JavaBeans, embedded-enterprise system connectivity, CORBA, XML, UML, and object- oriented/component-based software. In addition to this book, Paul publishes his work in various trade journals. He has an MSEE from the University of Virginia and a BSEE from Rutgers University. He is a member of the IEEE and ACM and has served as chapter chair for the Northern Virginia IEEE Computer Society. Paul can be reached at pperrone@assuredt ech.com or (703) 728-0115. Venkata S. R. "Krishna" R. Chaganti is a senior software engineering consultant and has been developing distributed computing software for the past seven years using Java and C++ programming environments. Krishna has been working with Fortune 500 companies to develop EJB, CORBA, and DCE software for their distributed computing needs. He has also been teaching Java and related technologies for two years. He has an MSEE in Computer Engineering and an MSEE in Electrical Engineering from the University of Alabama in Huntsville. He also has a B.Tech in Electronics and Communications Engineering from Nagarjuna University, A.P., India. Krishna can be reached at chagant [email protected] .

Acknowledgments This book has been a major undertaking that has consumed a considerable amount of time both to write and to develop supporting code examples. Paul Perrone has drawn upon both his communications and his software architect/designer/developer skills to write the book's material, develop the book's diagrams, help define the book's sample e-commerce application design, and develop a few snippets of code. Krishna Chaganti has drawn upon his software development skills to develop the supporting sample software, define the steps and scripts for building and executing the software, perform testing, and help verify technical accuracy of the manuscript. The Sams Publishing staff have been absolutely fabulous and instrumental in making this a successful project. Steve Anglin deserves many thanks for managing the overall creation of this book and working with us on numerous issues. We would like to thank Songlin Qiu for enthusiastically managing the development side of this book with the utmost attention to detail and perfection. We'd also like to thank Tim Ryan for working with us early on to help promote this project and for having vision with its kickoff. The many other folks at Sams, including Elizabeth Roberts, Charles Ashbacher, Cheri Clark, Jason Haines, and Maggie Malloy (to name a few), have all also been instrumental in making this project a success. In what follows, we would like to individually acknowledge those who have helped us make this project a reality in their own way. Paul J. Perrone: Family and the culture they create have been the most influential factors that enabled me to make a book like this one a reality. To begin, I owe many thanks to Janie Perrone, my wife, for providing love, patience, understanding, and her unique ability to manage work, home, and both of our lives throughout this effort. I also thank my parents, Don S. Perrone and Judy Perrone, for fostering an independent, imaginative, and active thought process in the context of a close-knit family culture; my brother, Don A. Perrone, for helping me keep life in perspective and maintain a balance between realism and open-mindedness; my sister-in-law, Denise Perrone, and my nieces/goddaughters, Allison Perrone and Julia Perrone, for their love and perspective on life; my grandmother Catherine Stiles for love and prayers; my parents-in-law, Reid Vance and Margaret Vance; John and Joanne Heilmann and family;

-2-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Frank and Caroline Izzo and family; and in general, my extremely large and extended family. Finally, I also owe much gratitude to my grandfather Anthony Perrone and my uncle Louis Perrone who helped me understand work, independence, courage, honor, loyalty, and family love. I know how proud they would have been and Imiss them. Many friends and colleagues also help make my life's work fun and possible, and contribute to its development. Of course, my friend and co-author, Krishna, deserves many thanks for being able to go the distance and work with me on a huge project such as this one. I also thank friends and colleagues including (to name a few) Caroline Russo, Dana Krochmal, Gary Miller, Dave Remkes, Mark Madalena, Karen Eglin, Dan Estepp, Tom Dickey, Peter Dahlstrom, Jeff Gilliatt, Jaime McKenzie, Mark Snyder, Dick Krol, Andy Stauffer, Jim Wamsley, Anup Ghosh, Paul Kirkitelos, Jeff Ebert, Charles Choi, Tom Schwenk, Doug Szajda, Geoff Hoekstra, Mike Woosley, Tom Hubbard, Frank Baglivio, Richard Hatch, Steve Wynne, Mike Carr, Catherine "McGill" Longo, Ben Collingsworth, Roy Tharpe, John Rollins, Malcolm McRoberts, Barry Clinger, Dave Castillo, Mark Thomas, Joe Hoff, Scott Lewand, Rami Zanoun, Kent Banks, Stefan Buchanan, Denise Taylor, Barry Johnson, Michael Bushnell, Richard Mammone, Julio Barros, Peter Thaggard, Fabrice Sarciaux, Eric Watson, Steven Sandler, Jim Moore, Jeff Oelschlagel, Anthony Guarino, Alan Polivka, Chris Roney, Christine Pepin, Jerome Pepin, and Vince Williams. Finally, thanks to "Cappy," who has kept me company while I was writing this book and has occasionally tried to stop me from writing by plunging his fangs and claws into my typing hands from time to time. Venkata Chaganti: There are many people to thank who have helped me in some way to make this book possible, including family, friends, and co-workers. First and foremost, I would like to thank Geetha, my wife and friend, for all of her support, encouragement, and patience during the endless hours spent developing and testing the code used with this book. I would also like to thank my parents, Sitaravamma and Veera Reddy, who always encouraged and taught me the importance of education. I would like to thank Abhijit for his understanding and for not complaining about his dad being attached to the computer for the past six months. I would like to thank Mr. Tommy Erskine and family for their help during my Huntsville stay and later. I would also like to thank Dr. Nagendra Singh, professor at the University of Alabama in Huntsville, who was a mentor during my graduate studies. For continually offering me challenging assignments, I thank Alok Nigam. I would also like to thank my friend Rajasekhar Ramireddy, who generously gave his time to verify our JavaMail code and write comments for a few code segments. I would like to thank my friend and co-author, Paul Perrone, for his encouragement and patience while I fixed code problems as they arose. I would also like to thank all of my friends and co-workers who have helped me along the way, including Dr. William S. Paciesas, Dr. Ray Emami, Dr. Narayan Reddy Ponaka, David Potter, Dan Parkins, Brian Mulrony, Julio Barros, Ram Sudireddy, Andy Wills, Jeff Phelps, Bhaskar Gudimetla, Srinivas Pasupuleti, Sankuratri V. Rao, Srinivas Mutyala, Caroline Russo, Dana Krochmal, Kartik Shyamsunder, Ted Kakavas, and many others. Finally, I would like to thank the Almighty God, who has been the true guide in my life.

Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we're doing right, what we could do better, what areas you'd like to see us publish in, and any other words of wisdom you're willing to pass our way. As a Publisher for Sams Publishing, I welcome your comments. You can fax, email, or write me directly to let me know what you did or didn't like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book's title and author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book. Fax: 317-581-4770 Email: feedback@sam spublishing.com

-3-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Mail:

Michael Stephens Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA

Introduction Before you delve into the contents of a huge tome such as this one, it is a good idea to first acquire an understanding of the problem you are trying to solve. In this way, you can best ensure that our book is addressing your needs. Furthermore, you should be aware of the topics to be presented that address such problems to ensure that our book's material is relevant to your technology interests. This introduction describes the problem being solved by this book, an overview of the topics discussed, the target audience addressed, and the approach for presenting the material.

This Is Your Enterprise on Caffeine! Let's first acquire an overview of the scope and problems being addressed by this book. As software consultants who provide enterprise system solutions and who have used the technologies described in this book under the pressure of deadlines and schedules, we very much wish we had a book like this at our disposal a long time ago. Of course, such a book must also reflect the current technologies being used to build enterprise systems. We thus consider this book to be an extremely market-driven and technology-driven book directly addressing the needs of enterprise system developers. We begin this section by defining the mission statement and battle cry that have both initiated this book's effort and that have driven the course of its development along the way. We then specifically address the type of problems we are trying to solve, and describe how information technology and the Java enterprise solution can be infused throughout the veins of an enterprise.

Scope of the Book, Mission Statement, and Battle Cry Building Java Enterprise Systems with J2EE provides a comprehensive and practical guide for building scalable, secure, Webenabled, and distributed enterprise systems with Java enterprise technologies and the Java 2 Platform, Enterprise Edition (J2EE). The technologies presented in this book can be used to rapidly build ecommerce (aka business-to-consumer or B2C) systems, business-tobusiness (B2B) systems, enterprise application integration (EAI) approaches, and general distributed and Internet-based enterprise wide systems with systems assurance for security, reliability, availability, maintainability, and scalability as a fundamental underlying consideration. Problem to Be Solved Enterprise systems encompass those distributed, scalable, multiuser, and business-critical systems that are intimately related to enhancing the productivity of a corporate or organizational enterprise via information technology. We are in the midst of an information and knowledge technology revolution that has catapulted economies and ways of life far beyond those that even the industrial revolution wrought. A primary engine of automation and productivity enhancement behind this revolution is the enterprise system. More and more, corporations and organizations are tying themselves into a complex informational network in an effort to further enhance the productivity of their operations for competitive and costreduction reasons. E-commerce, Internet/Web enabling, B2B connectivity, EAI, and data mining are just a few of the requirements that must be satisfied by enterprise system designs.

-4-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

This is why effective means for building enterprise systems that address the unique problems and high demand for enterprise software development effectiveness are always being sought out by enterprise system development teams. Corporations and organizations more and more look for enterprise-class developers and engineers who can solve enterprise system problems. Java enterprise technologies and the J2EE in particular provide an approach for more rapidly and effectively building enterprise systems which address the needs for producing enterprise software that is reusable, scalable, distributable, maintainable, secure, reliable, and available.

This Is the Book to Address Your Needs! This book is partitioned into seven major parts and a set of appendixes. The structure of the book is presented here so that you can better understand what to expect from each major part of the book. You can thus tailor how you'll approach reading the book and perhaps determine which chapters cover material with which you are already familiar. Finally, in this section, we also describe the notation conventions used within the chapter text.

Pa r t I : Ent e r pr ise Founda t ions The first part of the book explores the foundational concepts and solution paradigms on which the rest of the book depends. We begin with a description of the enterprise system development problem addressed by this book and a description of a generic framework for understanding solutions to this problem. The solution paradigms of object-oriented and component-based software development are then briefly highlighted in the context of how such paradigms are key to building enterprise systems. Descriptions of the foundational features of the Java programming and platform solution paradigm are then given, along with a brief coverage of those aspects of Java that make it a significant enabler for rapid enterprise system development. All of these fundamental features are tied together along with the Java 2 Platform, Enterprise Edition to define the generic architectural solution for building Java enterprise systems as advocated by this book. This part of the book closes with a discussion of user interfaces to the types of enterprise systems described herein and provides a more indepth discussion of the JavaBeans component model on which a few core Java enterprise concepts depend. This part of the book thus serves as both an overview and a refresher to the primary audience of the book and as a rapid introduction to many basic concepts for an extended audience.

Pa r t I I : En t e r pr ise D a t a En a blin g Access to warehouses of enterprise data is extremely important to building useful enterprise systems. There are various ways to connect enterprise Java applications with enterprise data stored in databases, but the Java Database Connectivity (JDBC) API is the most common and feature-rich Java-based enterprise data enabling framework. JDBC is a core part of the J2EE and has most often been used by organizations in its JDBC 1.0 flavor shipped with the JDK v1.1. JDBC 2.0 offers new core functionality in the Java 2 Platform, Standard Edition (J2SE) and a few important enterprise-specific extensions in the J2EE. The second part of the book covers the foundations of enterprise data enabling in general and then focuses on JDBC concepts and a practical step-by-step illustration of how to build JDBC API client applications. The gamut from basic to advanced JDBC topics is discussed. After reading this part of the book, you should be armed with the critical knowledge needed by enterprise systems developers for understanding enterprise data enabling issues, along with the primary mechanisms used to enable data in enterprise Java systems using the J2EE's JDBC underpinnings.

Pa r t I I I : D ist r ibut e d Ent e r pr ise Com m unica t ions Ena bling The third part of the book covers the foundations of distributed enterprise communications enabling in general and then focuses on a few key solutions available to the enterprise Java

-5-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

engineer. Because all solutions depend in some way on the TCP/IP protocol suite, we describe the architecture of TCP/IP and any direct Java-based interfaces to TCP/IP. After giving an architectural description of Web-based HTTP communications, we focus on three key distributed object communication models. The CORBA distributed object model is incorporated into J2SE and J2EE environments via Java IDL and represents the most interoperable and standard model for distributed communications enabling. Also part of J2SE and J2EE environments, RMI provides a Java-based communications model that has more recently begun to merge with the CORBA communications model via RMI/IIOP. Finally, though not part of the J2EE, DCOM provides a means to interact with distributed components built on top of one very specific yet significant computing platform known as the Microsoft Windows platform.

Pa r t I V: Com m on Se r vice s for D ist r ibut e d Ent e r pr ise Com m u n ica t ions The fourth part of the book describes many of the services that are built on top of or augment the communication models described in the previous part of the book to make distributed enterprise communications more immediately useful in enterprise applications. Naming services are first described as a means for mapping between distributed object references and human-readable object names using technologies such as JNDI, the RMI registry, and the CORBA Naming Service. We then describe a means for locating and discovering distributed objects on a network both using descriptive attributes about such objects and via type information about those objects when we discuss directory and trading services using technologies such as JNDI, LDAP, Jini, and the CORBA Trading Service. The means by which objects are brought into active memory from dormant persistent storage are then described under the broad topic of activation services, including a discussion of the Java Activation Framework. We also discuss how asynchronous messages sent between message producers and consumers are encapsulated within one of various messaging service options available to the Java enterprise system developer, including JMS, JavaMail, and the CORBA Event Service. Finally, we describe the means for providing atomic, consistent, isolated, and durable transaction semantics to distributed operations across distributed resources using the CORBA Object Transaction Service, JTS, and the JTA. The services described here are thus common to many distributed enterprise communications-based applications and are also fundamental components of an integrated Java enterprise and J2EE solution.

Pa r t V: Ent e r pr ise Syst e m s Assur a nce Assurance deals with providing for the security, reliability, availability, maintainability, and perhaps safety of your enterprise system. Although time-to-market demands may lead to a lack of assurance in these areas, the costs associated with not providing assurance can be particularly expensive with respect to an enterprise system. With a knowledge of how to practically trade off delayed deployment with a lack of assurance, you can make intelligent decisions when considering how far you should address your enterprise assurance needs. The fifth part of the book describes general assurance concepts and techniques and soon thereafter focuses on security assurance as one of the more involved facets of enterprise assurance. The basic security problem, concepts, and security models on which Java and CORBA security depend are first described. We then cover the basic Java security architecture and follow up that discussion with an in-depth look at how to use the Java security model in your enterprise applications. We also describe the CORBA security model for building secure CORBA-based systems.

Pa r t VI : Ent e r pr ise W e b Ena bling Putting an enterprise on the Internet for the sake of e-commerce has been a major objective for many organizations since the mid-1990s. Although selling products and services via the Web is a key focus of many enterprises, productivity enhancements to be achieved by providing seamless distributed access to applications from anywhere in the world also motivate enterprises to consider Web-enabled access to business applications for employees

-6-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and business partners. In the sixth part of the book, we specifically address those technologies and approaches to Web-enabling an enterprise system using Java enterprise technologies and the J2EE. We describe how markup languages such as HTML and XML play key roles in representing enterprise data that traverses between Web server and Web client. HTML is most popularly used for creating Web-based presentation content, whereas XML is used in more general ways to represent J2EE component deployment information, as well as for representing messages passed between systems. Java Servlets and JavaServer Pages represent the two J2EE-based technologies that we explore in depth as the means by which enterprises are Web-enabled.

Pa r t VI I : En t e r pr ise Applica t ion s En a blin g Many of the technologies and services described in this book can operate either as standalone enterprise applications or from within enterprise application framework environments. The seventh part of the book focuses on the use of component-based application server frameworks to make access to such technologies and services an easier proposition for developers than is the case when developing standalone applications. The J2EE Enterprise JavaBeans (EJBs) component model serves as the core way in which distributed Java enterprise applications can be rapidly built. We describe how to build and deploy J2EE-based EJBs, as well as how thick clients and Web clients can connect to EJBs. We also describe more advanced EJB topics, such as EJB-CORBA connectivity, EJB security, EJB transactions, and the relationship between EJB and the many other technologies described in this book. Finally, we close this part of the book with a discussion of how both EJBs and standalone Java enterprise applications can be used for B2B transactions and to integrate with auxiliary and legacy enterprise applications.

Appendixes The final part of the book contains appendixes that support the content of this book. We describe how to configure the commercial and sample software used with this book, as well as provide additional references used to augment the book's material.

Notation Conventions Throughout this book, we use certain notation conventions when presenting the material. The conventions used throughout the book can assume different meanings depending on the con text in which they are used. For example, conventions used to describe artifacts of code or programming can differ from those used in textual descriptions. Although these conventions are often intuitive and easily understood when used in context, we list the conventions here for your reference: • •

• •



• • •

Three consecutive dots, …, in text refers to additional text that naturally follows. Three consecutive dots, …, in code refers to code that has been left out of a code listing. Square brackets, [ ], in directory names or filenames can serve as placeholders for information that should be replaced with an actual directory name or filename. Square brackets, [ ], in text or code encapsulate information that is optional and can be replaced with some other data. Angle brackets, < >, used in text or code encapsulate information that is required and should be replaced with some other data. Italicized words in artifacts of code and programming also can be used to identify information that is required and should be replaced with some other data. Italicized words in plain text can be used to simply accentuate particular words to focus on. Boldface words in code and generic file formats accentuate key words or terms.

-7-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Code that is inserted into a chapter from sample code on the CD is most often inserted as it was on the CD with any indentation left as is to preserve consistency between the manuscript and the CD as much as possible.

Other Conventions Used in This Book This book uses different typefaces to differentiate between code and regular English, and also to help you identify important concepts. Text that you type and text that should appear on your screen is presented in monospace type. It will look like this to mimic the way text looks on your screen. This arrow ( ) at the beginning of a line of code means that a single line of code is too long to fit on the printed page. Continue typing all characters after the as though they were part of the preceding line. Note

A Not e pr esent s i nt er est i ng pi eces of i nf or mat i on r el at ed t o t he sur r oundi ng di scussi on.

Tip

A Ti p of f er s advi ce or t eaches an easi er way t o do somet hi ng.

Caut i on

A Caut i on advi ses you about pot ent i al pr obl ems and hel ps you st eer cl ear of di sast er .

This Is Your Brain After Reading This Book! Now that you've seen the problems this book addresses and an outline of the topics discussed that help solve these problems, we want to describe the intended audience for this material and describe what you will have learned after reading the book. We also take the opportunity here to describe our specific approach to presenting the material.

Intended Audience Building Java Enterprise Systems with J2EE will be of interest to professional software engineers fulfilling roles such as software developer, designer, and architect. The formally trained software developer, designer, and architect with a background in object-oriented software development and Java who has a demand for acquiring enterprise-level development skills using Java is the primary target audience for this book. However, enough background material is established early in the book to provide an overview and refresher of the core concepts and technologies on top of which enterprise-level Java technologies are built. As a side benefit of this overview and refresher material, formally trained and experienced software engineers who have little Java background but who have been thrust into an enterprise software development project using Java may also benefit from reading this book. Finally, managers and technically savvy business folk who aim to understand the basic concepts involved in building enterprise, e-commerce, and B2B systems can refer to this

-8-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

book's "front" material presented early in each chapter as well as in chapters specifically designed to be conceptual overviews for more technical chapters that follow.

Approach of the Book Although many of the Java enterprise technologies that we use in this book have been around for some time, the J2EE platform integrates these technologies into one cohesive platform. Of course, the J2EE alone does not currently solve all Java enterprise problems. Consequently, we also describe other Java-based technologies that will be encountered during actual Java enterprise development efforts. We in fact are incorporating into this book a lot of practical and real-world experience with these technologies. Therefore, at times we stray from purist views in the interest of describing practical enterprise development solutions. Since this book's inception, our battle cry has been to provide a comprehensive and practical guide for building Java enterprise systems. To this end we not only provide detailed coverage of Java enterprise architectural and design concepts, but also illustrate much of the material with practical examples and code. We focus on describing how to build Java enterprise applications via illustration of how to use core APIs and how to configure your Java enterprise system applications. We from time to time keep certain examples simple and deviate from pure object-oriented abstraction techniques and style in the interest of directly demonstrating how to use specific APIs for pedagogic reasons. Because the J2EE and auxiliary Java enterprise APIs are extremely rich with features, we focus on how to use the core and most commonly encountered APIs. Furthermore, because this book is meant to be a step-by-step guide for building applications and not an API reference, we also avoid defining and describing every possible API you might encounter. Instead we offer plenty of Web-based API references in Appendix B, " Addit ional Resources," to which you may refer. Because we are describing how to build Java enterprise systems in a practical manner, we also occasionally describe those APIs that are technically not part of the J2EE but have significant enterprise system relevance. Note that we often refer to the J2EE to collectively mean the J2SE in addition to those extensions to the J2SE that form the J2EE. We focus on those aspects of a system that are utilized by middle-tier server-side applications. Thus, in a Model-View-Controller (MVC) approach to describing a system, you might say that we are primarily interested in the "C" aspect of a system. We are largely only interested in describing how to enable the "V" to be realized (user and Web interfaces) as well as encapsulate and enable access to the "M" (data enabling).

The End Result In summary, after reading this book, you will walk away with a knowledge of how to apply and use Java enterprise technologies for enterprise distributed communications enabling, data enabling, assurance provisioning, Web enabling, and application enabling. Your knowledge will be comprehensive and practical by nature. Knowledge of the J2EE and other Java enterprise technologies will then serve as your primary toolkit for building enterprise systems. So pour yourself a warm cup of joe, sit back, and enjoy the rest of the book as we describe for you how Building Java Enterprise Systems with J2EE can fully caffeinate your enterprise. We hope you enjoy, learn, and provide us with any feedback via ht t p: / / www.assuredt ech.com / books/ j 2ee/ feedback.ht m l.

-9-

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Part I: Enterprise Foundations I N TH I S PART 1 Ent erprise Archit ect ural Overview 2 Obj ect - Orient ed Soft ware Developm ent for t he Ent erprise 3 Com ponent - Based Soft ware Developm ent for t he Ent erprise 4 Java Foundat ions for Ent erprise Developm ent 5 Java Ent erprise Syst em Archit ect ure wit h t he J2EE 6 Ent erprise User I nt erfacing 7 Modeling Com ponent s wit h JavaBeans

Chapter 1. Enterprise Architectural Overview

- 10 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

IN THIS CHAPTER • • •

The Ent erprise Ent erprise Com ponent s I nform at ion Technology in t he Ent erprise

This chapter provides an overview of the assumed boundaries of an enterprise as it is scoped by this book, its components, the relation between components, and the vision for how information technology can streamline the operations of an enterprise. In particular, we describe how the use of Java enterprise technology with the J2EE platform can help solve enterprise computing problems in a cohesive and comprehensive fashion. In this chapter, you will learn: • • • •

The definition of an enterprise as used in this book, the components of an enterprise, and how these components are related. The fundamental components of an enterprise system as they relate to needs driven by the goals and objectives of an enterprise. How information technology is utilized by and energizes the enterprise. How Java enterprise technologies provide a fully "caffeinated" enterprise, helping it to accomplish all its goals and objectives.

The Enterprise In its most generic form, the term enterprise can simply refer to an organization that has set out to accomplish certain goals. The organization may be a small-, medium-, or large-scale commercial corporation; a nonprofit institution; or perhaps a government organization. In some contexts, including the context of this book, the term enterprise is typically used to refer to a large organization. It is usually assumed that enterprises have a desire to grow and expand their operations and human/inter-enterprise associations over time. It is also often assumed that pursuit of the enterprise's goals are essential both for survival of the enterprise and for the growth of the enterprise. Figure 1.1 depicts the main components of an enterprise that are used to help the enterprise accomplish its goals. Physical resources and assets are one component of an enterprise utilized to accomplish enterprise goals. For example, computing equipment, manufacturing facilities, product supplies, and corporate accounts are all examples of resources and assets that are essential to the operations of an enterprise. People and users are another fundamental component of an enterprise, with customers, employees, contractors, and partners (with other enterprises) forming the core of those classes of people who help the enterprise accomplish its goals. Finally, enterprise information and enterprise knowledge are also key ingredients used to help further the goals of an enterprise. Figure 1.1. The components of an enterprise.

- 11 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Because the various enterprise components help an enterprise accomplish its goals, they offer some value to the enterprise. It is in the best interest of an enterprise to preserve, protect, grow, make accessible, make efficient, and be sensitive to change in the value offered by the various enterprise components. These interests and primary objectives of an enterprise are to foster such desirable outcomes as these: • • • • • • • • • • • • • •

Growth of a customer base Preservation of a customer base Sensitivity to a changing customer base Growth of an employee base Efficiency of an employee base Growth of a partnership base Growth of resources/assets Preservation of resources/assets Protection of resources/assets Accessibility of resources/assets Sensitivity to a change in resources/assets Growth of information and business knowledge Preservation of information and business knowledge Protection of information and business knowledge

- 12 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •

Accessibility of information and business knowledge Sensitivity to changes in information and knowledge

Enterprise Components Given those components of an enterprise that have some value to the enterprise and the pursuit of an enterprise's interest in these valued components, Figure 1.2 presents the type of system a modern enterprise will strive to incorporate into its operations to maximize its goals. An enterprise generally attempts to develop the following example features shown in Figure 1.2 given the interests it has in striving to achieve its goals: Figure 1.2. The components of an enterprise system.





Growth of a customer base can lead an enterprise to provide Internet/Web connectivity perhaps in the form of a Business-to-Commerce (B2C) or E-commerce application to open up the opportunity for more customers to patronize the enterprise. Furthermore, a growing customer base will also require the provision of a scalable Web and application connectivity solution. Preservation of a customer base may be accomplished by streamlining connectivity to legacy distribution supply chains so that customer satisfaction remains high due to the speed with which an enterprise can satisfy customers'orders.

- 13 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • • • • • •

Sensitivity to a changing customer base can also be facilitated via a tailored presentation interface for different Web-based customers depending on customer profiles persisted in an enterprise database. Growth of an employee base can be managed by a streamlined and scalable human resources Enterprise Resource Planning (ERP) application. Efficiency of an employee base can be offered via direct connection to enterprise applications through a distributed enterprise client application over an intranet. Growth of a partnership base can be managed via the establishment of secure Business-to-Business (B2B) application logic and transaction handling. Growth and preservation of resources/assets can be managed and provided via Enterprise Application Integration (EAI) with legacy applications, distributed enterprise applications, and connectivity to embedded resources. Protection of resources/assets can be provided via the establishment of a security domain to protect valued resources distributed on an enterprise network. Accessibility of resources/assets can be provided via use of various distributed communications technologies to connect resources to the enterprise. Growth and preservation of information and knowledge can be efficiently managed in an enterprise Database Management System (DBMS). Protection of information and knowledge can also be managed in an enterprise database as well as by provision of assurance techniques to provide information and knowledge security and reliability. Accessibility of information and knowledge can also be provided via Web connectivity and various distributed communications paradigms.

Information Technology in the Enterprise Information technology employed by an enterprise system can be broadly classified along the lines of the various enabling and service technologies depicted in Figure 1.3. These various enterprise enablers and services drive the very outline and approach taken by this book. The Java enterprise technologies described throughout the book can all be categorized according to the generic enterprise system architecture of Figure 1.3. These generic enterprise system architecture technology classifications are listed here: Figure 1.3. Information technology in an enterprise system.

- 14 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Enterprise User Interfacing: Provides a means to present content to both Web-based and standard applicationsbased users of an enterprise system. We highlight user-interface content development techniques in this book only via a brief discussion of Java-based AWT and Swing applications and applets, other Java-based user interface components, and Web-based presentation content via HTML and XML technologies.



Enterprise Data Enabling: Provides a means to access, store, and manage enterprise information and knowledge via enterprise databases. Part I I , " Ent erprise Dat a Enabling," is dedicated to a discussion of data enabling using JDBC technology.



Distributed Enterprise Communications Enabling: Provides a means to access information and applications throughout a distributed enterprise system. Such a service is considered a global service that permeates every aspect of a distributed enterprise system. Part I I I , " Dist ribut ed Ent erprise Com m unicat ions Enabling," is dedicated to a discussion of communications enabling via such technologies as TCP/IP, CORBA, RMI, and DCOM.



Common Services for Distributed Enterprise Communications: Provides a set of common services used by distributed object communications paradigms. Such services are also considered global services that permeate every aspect of a distributed enterprise system. Part I V, " Com m on Services for Dist ribut ed Ent erprise Com m unicat ions," is dedicated to a discussion of higherlevel communications services with a focus on Java-based naming and directory services via JNDI, CORBA trading services, Jini, activation services, messaging services via JMS and JavaMail, and transaction services using JTA and JTS.

- 15 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Enterprise Systems Assurance: Provides for the secure, reliable, available, maintainable, and safe qualities of an enterprise system. Such services are also considered global services that permeate every aspect of a particular enterprise system domain. Part V, " Ent erprise Syst em s Assurance," is dedicated to a systems-assurance discussion with a focus on Java 2 platform security and CORBA security.



Enterprise Web Enabling: Provides for the connectivity of the enterprise to the Internet/Web, as well as for generating Web-based presentation content. Part VI , " Ent erprise Web Enabling," is dedicated to a Web-enabling discussion with a detailed discussion of Java Servlets, JSP, and XML.



Enterprise Applications Enabling: Provides for the middle tier of application logic management with the connectivity to legacy enterprise application logic, the provision of new enterprise application logic, connectivity to distributed enterprise applications and embedded devices, and business-to-business connectivity with commerce partners. Part VI I , " Ent erprise Applicat ions Enabling," is dedicated to an applications enabling discus sion with a focus on Enterprise JavaBeans and Enterprise Application Integration.

Conclusions Enterprises achieve their goals with the use of valued resources and assets, information, knowledge, and people. In an effort to preserve, protect, grow, make accessible, make efficient, and be sensitive to change of such enterprise components, modern enterprises pursue the use of information technology to build enterprise systems that help them effectively foster their goals and objectives. Information technology is used to build enterprise systems that provide user interfacing, data enabling, communications enabling, communications services, assurance services, Web enabling, and applications enabling. Java enterprise technologies with the J2EE provide standard means for covering all such bases of an enterprise system architecture's needs.

Chapter 2. Object-Oriented Software Development for the Enterprise IN THIS CHAPTER • • •

Ent erprise Obj ect s The Obj ect - Orient ed Developm ent Process Unified Modeling Language

This chapter presents an overview of the object-oriented concepts, software-development process, and modeling notation that serve as foundations for the practical construction of enterprise systems. Object-oriented software development represents a paradigm of development that offers many advantages when used to create enterprise software, including the facilitation of reusability, scalability, maintainability, and rapid development. Although this material may serve as simply a refresher for some readers, we encourage you to at least examine this chapter's section on the basic Unified Modeling Language (UML) notation that we use throughout the rest of the book. In this chapter, you will learn:

- 16 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • •

The basic concepts behind the object-oriented paradigm and how they enable practical enterprise software development. The concepts and methods behind employing a practical object-oriented software development process when building enterprise systems. A basic subset of the Unified Modeling Language notation used throughout this book to convey software analysis and design notions.

Enterprise Objects The most common circumstances under which the earliest computer programs of the 1950s and early 1960s were created yielded programs that tended to be monolithic collections of computing instructions perhaps designed, developed, and maintained by an individual programmer or by fairly small groups of programmers. Such was the case even as assemblylanguage programming evolved into the use of higher-level language programming as depicted in Figure 2.1. Assembly-language programming (stage 1) was often necessarily monolithic in nature, with data being exposed for direct access by assembly-language instructions. Although higher-level programming languages (stage 2) permitted the construction of programs in a more natural and human-readable fashion, the structure and nature of programs in terms of monolithic behavior and exposed state still remained. Code could be modularized (stage 3) by partitioning software into separately compilable modules with the help of compiler and linkage technology, but the advent of more-advanced software engineering practices further helped encapsulate such modules into functional units (stage 4). Figure 2.1. Evolving programming paradigms.

Functional programming fosters modularity but still exposes the state for manipulation by each module. Thus, separate functional modules aid in functional decomposition, but it wasn't until the birth of object-oriented programming (stage 5) that both modularity of behavior and encapsulation of state would become the new programming paradigm. By encapsulating state, clients of your object-oriented (OO) software module could not form undesirable dependencies on your code by directly interacting with exposed state. Thus, any undesired behavior of your software module stemming from a direct manipulation of state could be

- 17 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

avoided by encapsulating that state to prohibit direct external access. The desired behavior of your module can thus be enforced by forcing any clients to interact with your module via a set of exposed interfaces.

Elements of Object-Oriented Software Central to the foundation of OO software is the concept of a "class." You can view the concept of a class from different OO lifecycle perspectives, but the most common view of a class in OO software development is that from an object-oriented programming (OOP) perspective. Programmatically speaking, a class is a discrete module of code that has a set of variables (aka fields) associated with it, as well as a set of function calls (aka methods). Methods define those interfaces to the class that take a set of zero or more input parameters and return a set of zero or more output parameters. During the process of a method call by a client of the class, the values of the class's fields may also change. Note

The various elements of object-oriented software described in this section will be illustrated via a graphical notation in the " Unified Modeling Language" section later in this chapter.

An object represents an instance of a class in memory. The state of the object is defined by the values assumed by the class fields. The behavior of the object is a function of the method implementations, the return values from method calls, and the state change of the object. Objects can also be distributed such that while their instances sit in some process memory on one machine, an object in some process memory on another machine actually references the remote object. The reference to that distributed object (also known as handle) may be some value with embedded network address information and an object ID to refer to the distributed object.

Visibility levels associated with class fields and methods can define what level of access other classes have to those fields and methods. Private visibility refers to the fact that only the containing class and therefore object instances of that class can access such fields and methods. Public visibility means that other classes can access such fields and methods. Protected visibility refers to the concept of inheritance. Inheritance means that a class B, for example, can be defined such that it inherits the behavior of a class A from which it is inherited. Thus, a method defined on the base class A can be inherited by the subclass B. Protected visibility of fields and methods means that subclasses of a class can access the base class's protected fields and methods. Subclasses can also override methods of base classes by defining new methods with the same input and output types as the base class. Thus, instances of the subclass that have overridden base-class methods can have their method definitions called by clients versus their base class's method definitions.

Classes have class names that are scoped according to a class package. A package refers to a collection of one or more classes. Classes in a package have some cohesive logical relation and tend to offer a very specific service. Whenever classes are tightly coupled in some logical sense, they tend to be collected into a package. The fully qualified package name plus the class name represents a fully qualified class name.

Although such is the view of classes and objects from a strictly programmatic perspective, from an overall OO lifecycle and best-practices perspective, a class should be treated with more care. Otherwise, the strictly programmatic view that classes are just collections of fields

- 18 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and methods could lead to use of the OOP paradigm in a functional programming style. Rather, classes should also represent some concept or classification driven from the problem domain such as an entity (for example, User), a control process (for example, UserLogManager), or an interface of some sort (for example, DatabaseLogInterface). An object instance of the class should represent some unique identity of the concept or classification such as an identifier of an entity (for example, joeUser), the identification of a particular control process (for example, theRemoteUserLogManager), or the identity of a particular interface (for example, theBackupDatabaseLogInterface).

Object-Oriented Software's Importance to the Enterprise OO as a software-development paradigm is one of most important foundations and enablers for building successful and expandable large-scale distributed enterprise systems. OO practices foster the development of modular programs with encapsulated state and implementation behavior, as well as facilitate the abstraction of problems. Modularity, encapsulation, abstraction, and reuse are rudimentary programming tenets that help in making large-scale distributed enterprise projects a reality. Reuse of software can be achieved in other programming paradigms (for example, functional programming), but reuse in OO is inherently fostered by the paradigm. Modularity of classes enables one to discretely represent concepts that are used in defining a problem. Thus when the same problem occurs elsewhere on a project, those same concepts and therefore associated classes can be reused. Connecting objects together in OO via the realization of a sequence of method calls on objects actually represents a solution to a problem. That is, when object A calls a method on object B, which calls a method on object C, then that sequence corresponds to a functional solution to some problem using the associated concepts A, B, and C. In a functional programming paradigm, the functions themselves represent the specific solution to a problem. Therefore, unless the same solution to a problem exists, the code is difficult to reuse. OO, on the other hand, encapsulates concepts in classes and therefore facilitates use of the same concepts in different modular fashions to create different solutions. As the size of an enterprise project grows, the payback for reuse becomes more and more significant. Solving a problem is usually most efficiently performed by first partitioning a problem and then addressing smaller pieces of the original problem. Modularity and abstraction in OO allow for the encapsulation of a problem domain into discrete classes and therefore facilitate more efficient problem solving. Efficient problem solving is of course particularly important for enterprise projects with time-to-market criticality. Modularity of classes also leads to smaller and self-contained pieces of code. Smaller and self-contained pieces of code are easier to understand than large monolithic pieces of code. When code is easier to understand, it will be more easily maintained by other developers who may need to use or understand the code. The code will also be more easily maintained by the developer who originally wrote the code. Maintainability of code becomes very important if software bugs need to be resolved quickly, as well as if the code base needs to expand beyond its original functionality. Stumping the maintainability and expandability of enterprise code stumps the growth of your enterprise. Modularity and the composition of one class that has another class as a field member also helps foster a component-based and reuse-oriented view of development. You may, for example, need to define a class Customer who "has" an Address. Odds are that you will be able to reuse another Address class that has been developed for another type of class. For example, someone may have created an Employee class which also utilized an Address class. Of course, abstraction via inheritance can also enhance reuse. You may, for example, have a base class User who has an Address. Then both Customer and Employee as types of users can inherit the interfaces and access to an Address class from the base User class. Thus, a solution for the higher-level concept can be applied to a lower-level concept and enhance reuse. Behavior is partially a function of state. That is, depending on the value of some object's state, it may behave differently when its methods are invoked. By encapsulating state, the implementation (that is, method definitions) of the class can be what dictates and enforces the

- 19 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

class's behavior. Other modules thus cannot adversely affect behavior of an object by directly manipulating its state. Other modules are forced to affect the state of an object by using the exposed method interfaces for that object. In enterprise projects, the need for such state encapsulation grows as the number of other modules that can use your class grows. Finally, dependencies between modules (that is, classes) are reduced by forcing dependencies to be created through interfaces as opposed to allowing dependencies to be created on state and functions that are to be encapsulated. Changes in a class's implementation can thus be made separate from changes to its interface. The tendency for dependencies being formed on your software will grow as the number of software modules that are added to your enterprise software project grows. Enforcing the fact that such dependencies are to be formed through interfaces as opposed to implementation will help enable you to change implementations without breaking dependencies created by other code. Thus you can separately recompile your implementation changes as opposed to requiring that a significant portion of your enterprise code base be recompiled.

The Object-Oriented Development Process Much has been written about the OO process and how OO development should proceed on a project. We won't be expounding on the process topic much here since it is really outside the scope of this book, but we will present a basic process that can be followed with some specific consideration for certain enterprise software development issues. Many processes are defined with an ideal sequence of steps that should be followed by organizations to enable the creation of high-quality, reusable, maintainable, and extendable software. Many particular process recommendations are good, a few are bad, and a few more are completely infeasible. Building enterprise systems can be a daunting task, especially when time-to-market criticality is involved. Furthermore, not everybody involved with a project behaves as nobly, reliably, or knowledgeably as many processes might assume. People, despite popular process belief, are not purely resources built to implement a process. Realistically, we are process participants who have a diverse array of goals, desires, and capabilities that all affect how a process is pursued. Group dynamics in particular becomes an issue when pursuing enterprise projects involving many people. What we will therefore describe here is an OO process that can be followed with enterprise project scale, time-to-market considerations, and human constraints in mind. We will no doubt leave out process details that may also be pursued, but you should leave this section with an understanding of the core and practical steps to be performed.

Development Process Overview Most literature on OO development focuses on object-oriented analysis (OOA), objectoriented development (OOD), and object-oriented programming (OOP). These are, after all, the essential aspects of a development process that distinguish OO from other development paradigms. But the enterprise development process involves much more than just pure OO development. The creation of enterprise software by an enterprise software development team begins with an initial charter and only truly ends when the maintenance of such software is no longer needed. Although many iterations of such an end-to-end process may occur in an overall actual software-development process, the basic flow of OO software development from charter to maintenance can be given: 1. Project Charter: Establish a charter detailing goals and objectives for the effort to be undertaken. 2. Requirements Analysis: Perform analysis of expected system behavior and system interfaces. 3. Preliminary System Design:

- 20 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Perform a preliminary design of a system with consideration for Commercial Off the Shelf (COTS) software, custom software, and reuse. Partition design into smaller problems to solve. 4. Detailed Design: Perform detailed design of core classes and interfaces. 5. Implementation: Implement the software. May involve custom code writing, as well as integrating with COTS. 6. Unit Test: Unit test the implementation. 7. Assembly: Assemble individual elements into discrete elements of behavior. 8. Thread Test: Test threads of behavior on assembled elements. 9. Configuration Specification: Define the assumed COTS and custom software configura tion and versions. 10. System Test: Test a fully assembled and configured system. 11. Deployment: Deploy the system per the configuration specification. 12. Maintenance: Maintain operational software for bug fixes and upgrades.

Project Charter It is very important to either receive or create a project charter. A project charter is a written vision and mission statement for a project that summarizes the key goals and objectives to be accomplished for a particular development effort. The project charter should be brief and shared with the individuals involved with the project so that everybody has a cohesive and collective understanding of what is to be accomplished. Not only is it important to concisely convey what the primary goals and objectives are, but it also is important for people to have genuine belief in the charter's significance. It should become the battle cry for development.

Requirements Analysis Requirements analysis involves creating an understanding and model of what the system to be developed should do. A well-understood scope and boundary for the software to be

- 21 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

developed should also be formed at this stage. Requirements analysis can be partitioned into behavioral analysis and interface analysis. Architects or analysis gurus should perform an initial analysis of the system and collect analysis models into packages that can eventually be handed off to developers. Although analysis is very important for getting architects and developers to understand what the system is supposed to do, analysis paralysis should be avoided. Analysis paralysis occurs when a system is being overly analyzed and the process is hampered from further progression. This usually occurs when too many or non-interoperable people are involved with the initial analysis phase. Because the products of analysis (that is, models or conceptual diagrams) are necessarily abstract and imperfect, there is a tendency to spend too much time perfecting models that only vaguely define what the system is to do. The focus of initial analysis should always be to create an understanding of the overall system and then group smaller analysis packages for eventual handoff to developers for more detailed understanding. It is very important that you convey the fact that conceptual-analysis models are imperfect and only serve the purpose of requirements understanding. System Behavioral Analysis Regardless of whether you are actually given well-written requirements describing what is to be produced from your project, some form of requirements-analysis effort must be pursued. If you are given requirements, you should read through each requirement and build a picture of what concepts are involved, how the concepts relate, and what actions are being performed by and to each concept. If written requirements have not been provided or have been very loosely defined, it is at least important to create a conceptual-analysis model based on any interactions you have had with a customer or perhaps based on any ideas that have been conceived. If possible, such models should be run by the prospective customer for feedback. Use-case analysis represents one popular technique for performing behavioral analysis and generating conceptual-analysis models. Use-case analysis involves the identification of primarily user-driven behavioral scenarios (that is, a "use case") to analyze. Each use case is defined by describing a sequence of steps that are involved with each behavior. Actors in a use case are those entities involved with realizing the outcome of a use case. A precondition specifies the initial state of the system before beginning a use case, whereas postconditions specify the state of a system after the use case. We will also describe scenario diagrams in the next section as conceptual-analysis models that are closely related to use cases and are used to describe system behavior. System Interface Analysis Interfaces to your system and to software that lie outside of the system boundary should also be analyzed and modeled. Interfaces to external software tend to be one piece of information that is particularly important for development to proceed. An analysis model of your understanding of such interfaces should also be developed. Interfaces between your system and other entities include external system interfaces, legacy system interfaces, database models, and user interfaces.

Preliminary System Design Preliminary system design involves taking your conceptual-analysis model and transforming it into something that can be realized using COTS or custom software. Many times during analysis and the creation of a conceptual-analysis model, you will start to inject actual design constructs into the model. Regardless, concepts created during an analysis transform into more concrete design constructs during preliminary system design and can be used to create conceptual design models. Conceptual design models may be high-level views of the system to be developed and refer only to core design entities, controller classes, or system interface classes of a design. The details of which helper classes are needed to support such core elements are usually not included in a conceptual design model. Furthermore, only core interfaces (that is, operations) on the core classes themselves may be defined. Such interfaces scope the responsibility of a class and may not yet define each input and output parameter exactly. Input and output parameters can be defined to convey

- 22 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

semantic meaning behind a particular interface, but no strict interface definition applies at this stage. The purpose of preliminary system design is to capture those primary design components that are to be involved with a design. Decisions for use of particular COTS, development of custom software components, or identified reusable components should be defined here. COTS evaluation and custom software prototyping should be pursued here to help aid in the decision- making process. The product of preliminary design should be packages of conceptual design models accompanied by any relevant conceptual-analysis models. These preliminary design packages can be given to individual designers and developers to flesh out more detailed designs and implementations. The preliminary system design team, though larger than an analysis team, should also be relatively small. Architects with design experience should lead such efforts and solicit assistance from lead developers with particular COTS or development experiences. Conceptual design models that describe logical relations between concepts and design constructs can actually be defined in terms of what are traditionally viewed as class diagrams. We will describe class diagrams in the next section for modeling class relations in a system, as well as for modeling conceptual designs. Conceptual design models that describe the behavior of a proposed design can also utilize the scenario diagrams that are described in the next section.

Detailed Design The model packages handed to the designer/developer should correspond to individual software packages. This enables designers and developers to focus on a cohesive component of the system to be developed. Once a package of conceptual design and analysis models is handed off to a software designer/developer, he or she may opt to provide models which define any helper classes that support the conceptual model and define detailed interfaces on the core design constructs that were identified during preliminary system design. Detailed designs should, at the very least, define package names, class names, and the core public method names and input/output parameter types (that is, operation signatures) that need to be defined for the core design elements identified by the conceptual design model. Other classes and interfaces used to support the core classes and methods defined here should also be described. Detailed designs that attempt to define every single class, method, and attribute before proceeding to implementation may be overkill in many situations and will significantly slow the development process. Detailed designs can use the modeling approach described in the next section by using class diagrams to describe detailed logical structure, and scenario diagrams to describe detailed behavioral semantics.

Implementation After the core classes and their operation signatures have been defined, the developer can begin implementation using an OOP technique and language. Of course, OOP in this book advocates the use of Java as an OO language to implement the desired interfaces and behavior required of each class. Very often, time-to-market competition among developers may push them to begin implementation of code before a design has even been defined. Although the push for rapid development is actually a healthy desire, the need to understand what the code should do via analysis and design models is key for ensuring that the right functionality will be provided. Furthermore, the need to understand how code development should be approached via design models is key for ensuring that such code will interoperate with code developed by other developers on a project. This understanding will also ensure that such code is making use of the right COTS products already selected for use on the project. Some developers may indeed understand exactly what should be done without analysis and design models. But it is particularly key on enterprise development projects involving multiple people that a cohesive and coordinated view of development be maintained. The analysis and design models are the key tools to ensure that implementation will yield interoperable code as well as the desired code. Furthermore, if reuse can indeed be defined in analysis and design

- 23 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

models, implementation may proceed much faster if developers make use of such models to identify other components to use with their own implementation efforts.

Unit Test Unit testing involves testing software at the class and package level. Many times such tests are performed during implementation of a particular class and collection of classes. Although a debugger is often used to unit test classes during development, it is also important to create standalone test utilities to help test your code. Such unit test software can then be used to quickly regression test code when bugs are fixed and when functionality is added.

Assembly Assembly involves getting a small group of developers together and assembling individually developed software classes into groups of classes that perform some specific service. A subset of the entire system behavior needs to be identified, along with the code that has been targeted to implement that behavior. The responsible developers must then integrate their code preferably with a target platform and environment in mind.

Thread Test Thread test involves demonstrating that any assembled classes can interoperate. Threads of behavior are then demonstrated during thread test. Such behavioral threads can provide incremental assurance that the total system will yield the desired behavior when fully assembled and integrated. Very often assembly and thread test can occur among developers and should be coordinated by a software lead who is aware of the schedule for integrating the total system.

Configuration Specification Although sometimes overlooked, the means by which enterprise software is to be configured should be specified. This includes any assumed versions of COTS software used, software platforms used, and custom software configuration. Custom software configuration should include instructions for how to build as well as deploy the software that was developed.

System Test System test involves the functional/behavioral test of a fully assembled set of software that is to be deployed. System test should be performed using the assumed configuration that will be deployed. Other types of testing orthogonal to functional testing, such as load testing, system security testing, and performance testing, should also be performed at this stage on the system that most closely mimics what will be fielded.

Deployment Deployment involves packaging the system that was tested and deploying it onto the machines that will host it for actual enterprise operation. The configuration specification should resemble what the deployment environment can support. The deployment environment should therefore closely resemble the system test environment.

Maintenance Maintenance involves repairing defects while the system is deployed and in operation. Maintenance also involves providing upgrades to a fielded and operational system. Time to repair defects should be minimized and the ease with which upgrades can be installed should be maximized to enhance the availability of an enterprise system to its enterprise user base.

- 24 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Iteration and Phases of Development Although the general development-process flow just described must occur for some unit of work to be completed, iteration within the process will very often also occur. For example, if requirements have not been fully established at the start of a project, a subset can be analyzed and perhaps some preliminary design may begin. It may be apparent from the subset of requirements that some general design approaches may be pursued that involve evaluation and purchase of a particular COTS product. Thus, evaluation of such a product could be pursued while more requirements are obtained and analyzed. The same case for iteration may be made for all the development-process steps listed above. If a particular project is large enough, it is also usually wise to partition the project into phases of development. Each subsequent phase represents an incremental enhancement over the previous phase. Figure 2.2 depicts this process. Here we see an example of three phases of an actual development process. Each phase focuses on the development of some particular functionality, with phase 2, for example, building on the efforts of phase 1. Figure 2.2. Phased project development.

Such a phased approach to development provides numerous benefits. The first key benefit is that after the first phase completes, the users of your enterprise system can begin to experience incremental upgrades in system features earlier, as opposed to waiting for the entire development process to complete for all functionality. The second key benefit is that engineering personnel who happen to have skills more catered to a specific set of steps in a development process can be gainfully employed throughout the software lifecycle. For example, developers who largely participate in detailed design, implementation, and unit test can begin work sooner rather than waiting for the entire analysis and preliminary design process to complete for a larger set of requirements. They can also work more consistently by moving on to subsequent phases rather than waiting for system test and deployment to complete and then waiting for the next large project to be analyzed and designed.

Unified Modeling Language We talked a lot about generating models throughout an OO development process in the preceding section. Technically speaking, we use the term model here to mean an abstract

- 25 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and structured description of some system. A view of these system models is used to present such system descriptions to an end user in some form that they understand. Preferably, such views will have a graphical nature to facilitate ease of understanding. On large development teams, models and their views are essential to convey engineering analysis concepts and design ideas. A standard notation for such model views is also important so that people can better understand each other's analyses and designs. The Unified Modeling Language (UML) represents such a standard modeling notation. UML represents a compromise and unification of primarily three major notation techniques. The Booch technique, Object Modeling Technique (OMT), and Object-Oriented Software Engineering technique (OOSE) represent the three techniques that have formed the core of UML. Other techniques have also been employed to model OO analyses and designs, such as Fusion and Coad/Yourdon. Nevertheless, we use UML throughout this book largely because of its currently large and growing industry-wide adoption. Although UML has many features, we employ only a subset of UML in this book to keep our diagrams simple and focused on the topic at hand. Furthermore, UML is extensive, but it does have some drawbacks such as being overly complex in some regards and overly simplified in other regards. Thus we occasionally take some minor liberties in deviating from a purely standard notation. However, we point out such minor deviations when necessary.

Static Logical Structure Diagrams A class diagram is primarily used as a design modeling view to depict classes, their relations, their attributes (aka fields), their operations (aka methods), and packages. Class diagrams can be used as both a preliminary design modeling tool and a detailed design modeling tool. When used as a detailed design modeling tool, the elements of a class diagram closely correspond to code. When used as a preliminary design modeling tool, the elements of a class diagram are less strictly defined and represent more of a conceptual design model to express ideas about a design. Class diagrams can also be used as a conceptual-analysis tool to model higher-level concepts and their relations. Thus class diagrams model some static logical structure that describes a conceptual analysis, conceptual design, or detailed design view. Figure 2.3 presents, via example, the notation used in the various elements of a class diagram. The following bullet items describe each feature of this diagram and how such conventions will be used throughout the book for design models: Figure 2.3. Class diagram notation.

- 26 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Classes: Rectangular boxes represent classes.



Class Names: Class names are indicated at the top of a class box, such as ClassName.



Class Packages: Packages to which classes belong are optionally indicated beneath the class name, such as (from PackageName).



Packages: Packages are shown as a rectangle with a small box in the upper-left corner and have a package name displayed, such as PackageName.



Class Attributes: One or more attributes may be optionally shown below the class name and package name. Some diagrams may choose to display only a select set of attributes.



Class Operations:

- 27 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

One or more operations may optionally be shown below the attributes in a class. Some diagrams may choose to display only a select set of operations. •

Visibility: Visibility of an attribute or operation is indicated as a solid rectangle (or plus symbol +) for public, a rectangle with a key (or pound symbol #) for protected, or a rectangle with a lock (or minus symbol -) for private. A rectangle with a hammer is also sometimes used to indicate implementation that simply corresponds to reverseengineered or package private methods in our models. As a general practice in this book, if visibility is not shown, public visibility may be assumed.



Stereotypes: A stereotype enclosed by > simply corresponds to a specialization of a class, attribute, or operation that it is associated with. We most often use to designate a static attribute or method and to indicate that a class is actually an interface.



Attribute Syntax: Attribute descriptions follow a syntax whereby a visibility level may be optionally shown, followed by an optionally displayed stereotype, followed by an attribute name, followed by an attribute type, and followed by an optional initialization value. Attributes within a class tend to be listed in an order that represents a logical grouping of attributes.



Static Attributes: Static attributes may be designated with a stereotype label or a $ stereotype icon.



Operation Syntax: Operation descriptions follow a syntax whereby a visibility level may be optionally shown, followed by an optionally displayed stereotype, followed by a method name, optionally followed by zero or more parameter name and type pairs, and followed by an optional return type. Operations are listed in an order within a class that represents a logical grouping of operations.



Pseudo-Operations: Certain design diagrams, especially conceptual design diagrams, may display method names that are pseudonames displayed for informational purposes only. For example, we might use the name setXXX() to indicate that a method name has some pattern, such as setThis(), setThat(), setSomethingElse(), and so on.



Associations: A class such as ClassName that has an association with another class such as NamedAssociationClass depicts the association as a straight line. An association can have a name, and each end of an association can have role names indicating what role the class closest to it plays in the association.



Navigability:

- 28 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

When one class such as ClassName can access another class such as AssociatedClass via a particular association, but not the other way around, an arrow displays navigability. •

Multiplicity: When a class such as ClassName has a relationship with another class such as AssociatedClass, multiplicity of such relations can be displayed. Multiplicity can have many forms, such as a one-to-zero-or-one relation, a one-to-zero-or-more (many) relation, and a one-to-one-or-more relation. If no multiplicity is shown, the default of one is generally assumed.



Qualified Association: When a class such as ClassName has a special X-to-many relation with another class such as KeyedClass and that relation is "keyed," we designate this with a box displaying a key name and type at the end of the keyed relation. A keyed relation means that each element on the "many" end of a relation can be uniquely identified by a key name of a particular key type. Once a keyed relation is indicated, the multiplicity of the relation at the KeyedClass end goes to one.



Aggregation: Aggregation is shown with a line and diamond on the end of the containing class when the one class such as ClassName contains another class such as ContainedClass. Aggregation implies that the lifetime of the relation to the ContainedClass is tied to the lifetime of the containing class ClassName.



Uses Relations: When a class such as ClassName has a general dependency on another class such as UsedClass, a dashed-line arrow depicting the dependency is shown.



Inheritance: When a SubClass inherits from a BaseClass, a solid line with a triangle at the end of the BaseClass is shown.



Inherited Operations: Note that we often don't display certain methods on subclasses when the base class displays such a method. If the subclass overrides such a method, we may on occasion display that method on the subclass.



Abstract Classes: An AbstractClass has an italicized class name.



Interfaces: When an InterfaceImplementation implements a particular InterfaceType, a dashed line with a triangle at the end of the InterfaceType is shown.



Implemented Operations:

- 29 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Note that we often don't display certain methods on interface implementations when the interface displays such a method. •

Or-Association: An or-association is indicated with the word {or} on a dashed line spanning two relations. Or-associations provide a means for indicating whether a particular ClassA has a relation to one class such as ClassB or another class such as ClassC, but not to both.



Notes: Notes can also be displayed in a diagram and attached to various diagram elements.

Class diagrams can also be used with conceptual-analysis models. In such models, a concept correlates to a class, and relations between concepts are defined in the same way that they are defined for class diagrams. Attributes of a concept can also be displayed, but they will not have the rigid programmatic meaning that attributes on a design class will tend to convey. Operations can also be associated with a concept to convey what responsibilities and activities are to be associated with the concept. Operations of course also do not have the rigid programming semantics associated with operations on a design class. The loosely defined nature of conceptual-design model diagrams in fact may also adhere to the loosely interpreted semantic conventions of analysis models with the exception that concepts should correspond to elements of a design solution in conceptual design models.

Dynamic Behavior Diagrams A scenario diagram is primarily used as a design modeling view to indicate dynamic behavior between object instances. Object instances of particular classes are the primary actors in scenario diagrams. Sequences of method calls between objects are also shown in scenario diagrams with parameter instances being passed between objects during calls. When used as a detailed design modeling tool, scenario diagrams actually correspond to an illustration of how object instances communicate with the use of actual method names and object parameters in the diagram. Conceptual design models have objects that may simply represent an instance of a design construct and may not necessarily correspond to real objects. Methods in the diagram may also simply correspond to a general type of behavior that can be performed on such design objects. Finally, objects in conceptual-analysis models represent some concept identity in the problem domain, and methods between such identities correspond to high-level responsibilities that are associated with concepts and messages passed between conceptual identities. Figure 2.4 presents, via example, the notation used to represent the various elements of a particular type of scenario diagram that we use in this book called a sequence diagram. The following bullet items describe each feature of this diagram and how such conventions will be used throughout the book for analysis and design models: Figure 2.4. Scenario diagram notation.

- 30 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Time: Sequences in time proceed from top to bottom.



Objects: Object instances are represented by boxes at the top of the diagram.



Object Names: An object-instance name can be followed by a class name inside of an object box.



Methods: Method calls are shown as arrows from the invoking object onto the invoked object. Method calls may also be made by an object onto itself.



Method Names: Method names are displayed on method-call arrows, but may simply be more descriptive words designating an action to invoke on some concept or design entity in conceptual model diagrams.



Method Parameters: Object parameters to such methods may also be optionally displayed in method calls. Although it's not standard UML, we also optionally show a return value from a method call.



Method Scope:

- 31 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Scope of a method call is designated by a long rectangle on the dashed line under an object. Thus, a method call that calls an object which itself calls another object before it returns from the original call can be designated with scope.

Conclusions The object-oriented software-development paradigm is an approach and a set of technologies that provide a foundation for enabling practical enterprise-system development. The principles of modularity, abstraction, and encapsulation inherent to OO enable reuse, scalability, maintainability, and rapid development, which serve as key enablers for enterprise-system development. Although OO is an enabler and makes enterprise software development practical, it is also a paradigm that must be used within the context of a practical development process. An iterative and phased process of analysis, design, implementation, assembly, deployment, and testing must complement the use of OO in the enterprise and follow a few important guidelines to account for practical issues of time-to-market and human dynamics. An OO process that generates conceptual-analysis models, design models, and detailed design models using standard modeling notations such as UML are also key ingredients for making an enterprise software-development effort a success. As we'll see in the next chapter, practical scalability of enterprise application development is further enabled by employing a component-based development paradigm that fundamentally builds on the object-oriented development paradigm.

Chapter 3. Component-Based Software Development for the Enterprise IN THIS CHAPTER • • • •

Ent erprise Com ponent s Com ponent Models Com ponent - Based Developm ent St andards

Component-based software development has blossomed in recent years due to its capability to enable enterprise software to be developed more rapidly and with a higher degree of reliability. Although component-based development builds on object-oriented development, components encapsulate a problem and solution domain at a higher level of abstraction than strict object-oriented methods provide. Because enterprise applications and the enterprise development approaches described in this book rely on component-based development concepts, we provide an overview of components, component models, component-based development processes, and component model standards in this chapter. In this chapter, you will learn: • • • •

The motivation behind the usage and creation of components to develop enterprise applications. The generic architecture and elements of a component model. The process used during a component-based development process. About the standard component models employed by this book.

Enterprise Components The fundamental units of object-oriented (OO) software are classes and objects. Classes encapsulate fine-grained concepts of a problem and solution, whereas objects represent instances of classes created during the runtime operation of a system. The OO development process helps enable reuse at the class level, which is a level of encapsulation that is usually too low to be of immediate use on an enterprise project. Although it is possible to generate

- 32 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

OO design models that closely map to classes, the jump from analysis to design on enterprise-scale development projects can often be a big one. Components offer a coarser-grained means to encapsulate problems. As depicted in Figure 3.1, whereas a class having object state and a set of operations can encapsulate a singular concept, a component represents a particular service as a function of one or more such concepts. Components thus expose multiple interfaces as a service to component users. The interfaces encapsulate what the component offers as a service and shields any visibility into the implementation details. Because components represent a logical collection of one or more finer-grained classes and are defined at a higher and coarser-grained level, a component may directly encapsulate a partitioned problem that more directly can be produced from analyses and design models. Figure 3.1. Classes/objects and components.

Thus, a problem, as shown in Figure 3.2, may be composed of a number of concepts that map to classes during design. If the problem is partitioned during analysis and preliminary design into higher-level services, also shown in Figure 3.2, then a more rapid enterprise development process can be enabled with the more direct mapping of services to coarsegrained components. Folks who are closer to the problem domain can also better understand the design of the system as it is described in terms of higher-level components. Figure 3.2. Problems, classes, and components.

- 33 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Components thus offer many benefits to enterprise development. Components build on object-oriented software and development concepts to provide a higher-level model of development and enable the faster construction of enterprise applications. Furthermore, the quality of a system can be enhanced because it will most likely be in the interest of commercial component vendors to focus on enhancing the quality of a component and providing well-documented interfaces. The requirements for in-house personnel to have knowledge of a particular underlying implementation technology, as well as less service implementation–specific knowledge, will also be minimized. As the availability of reusable components increases, the use of components in the enterprise will grow. Time-to-market factors have driven organizations to pursue use of components in enterprise systems. Furthermore, the growth and practicality of component models, development approaches, and standards have also enabled the popularity of component usage in the enterprise. As you'll see in this chapter, the shift in enterprise development has evolved to require that development staff spend less time on programming and dedicate more time to component assembly.

Component Models A component model is a set of requirements to which components and their environments adhere. Component models are primarily concerned with constraining the nature of interfaces that a software component makes publicly available. By constraining a component's interface to adhere to some "knowable" nature, a component model can guarantee a certain level of interoperability between components, for application software using those components, and for application environments on top of which the components operate. Many different views are held as to what exactly the term component model means. As you'll see, various criteria may be used to distinguish between different component models. To some people, component models are patterns of design to which software adheres. More generically, component models involve specifying interfaces on components, component environment assumptions, and inter-component contracts. We briefly explore these various facets of component models in this section.

- 34 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Generic Component Model Figure 3.3 depicts the basic elements of a component model. First and foremost in a component model is, of course, the component itself. The component is an encapsulation of the code utilized in an application. Although the component may itself be application-specific code, we separately diagram the fact that other application-specific code may rest on top of a component and utilize the services it provides. Finally, the container represents an environment in which a component operates. The container itself may offer a set of services that components from the same component model may tap in a standard fashion. Figure 3.3. A generic component model.

A component also has various facets to it. The most important facet is the set of interfaces that it exposes and assumes. In addition to interfaces to a component, the interfaces to a container utilized by a component may also be defined in a component model. Standard events that can be generated by a component, as well as events to which a component can subscribe, may also be defined in a component model. Component models may also specify a standard means by which a component exposes descriptive state attributes. Finally, many component models allow for a means to customize a component's behavior and attributes.

Component Model Interfaces Interfaces in a component model define the primary contract between other code entities and components. Other code entities may be containers, application code, other components, other component models, and providers of some proprietary service. Certain component

- 35 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

models may attempt to rigidly define each type of interface, whereas others may be concerned only with the application interface to a component. Figure 3.4 depicts some of the more common interface styles that can be defined by a particular component model. These various interface classifications are defined here: Figure 3.4. Component interface types.



Component APIs: A component Application Programming Interface (API) defines a set of standard interfaces that applications can use to tap the services of a component. We represent this type of direct interface usage in the figure by showing a generalized interface symbol depicting the component's exposed interface.



Design Patterns: A design pattern is set of classes and interfaces and their relationships that provide a common design solution to a common problem classification. Application code specializes a design pattern by providing a more concrete and application-specific design behavior based on the design pattern. We represent this specialization nature in the figure with a UML inheritance arrowhead and solid line.



Component SPIs: A component Service Provider Interface (SPI) defines a set of standard interfaces that the provider of some service adheres to and implements. Different underlying services can thus be plugged in and out without modification to the application or container code. We represent this exclusive interface implementation nature in the figure with a UML inheritance arrow and dashed line.



Component-to-Container Interfaces: A component-to-container interface defines the interface to a container environment assumed by a component. We represent this type of direct interface usage in the figure by showing a generalized interface symbol depicting the container's exposed interface.

- 36 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Container-to-Component Interfaces: A container-to-component interface defines the interface to a component as assumed by a container. We represent this type of direct interface usage in the figure by showing a generalized interface symbol depicting the component's exposed interface.

Component model interfaces also may be defined in different manners. Some component model interfaces are defined in a language-independent fashion, whereas others are language-dependent. Language dependence, platform dependence, and communications protocol dependence are just a few examples of some of the component model interface specification styles. A few key ways in which component models can be defined are listed here: •

Language Dependence: Some component models define interfaces in a language- independent fashion. Other component models are defined in terms of a specific language. Languageindependent component models use an interface definition language which serves as an intermediate language that can be mapped to a specific computing language.



Platform Dependence: Some component models actually depend on a particular operating system or hardware platform, whereas most component models examined in this book are platform-independent.



Distributed Communications Protocol Dependence: Component models may assume a particular underlying distributed communications protocol among components and applications. Other component models may be protocol-independent and defined at a higher level of abstraction.



Data Representation Dependence: In addition to a communications protocol, some component model interfaces also define a standard data representation format for messages passed to and from component interfaces.



Communications Synchronicity: Some component models may assume a synchronous model of component interfacing in which a caller of a component may block until it receives a result. Asynchronous communications may assume that a caller of a component passes a standard message/event to a component and allows an underlying message/eventhandling service to deliver the message/event to the component.



Interface Definition Rigidity: Some component models specify particular interface operation signatures. Userdefined interface operation signatures will also typically be allowed. Some component models may instead permit and define a particular operation signature pattern that components should follow.



Behavior Customization:

- 37 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Some components may expose their behavior completely by opening their implementation for access and modification by the component user (white box components). Other components may completely restrict the user to the defined interface with no behavior and implementation visibility (black box components). Still other components may enable modification of behavior via customization features (gray box components).

Component-Based Development Along with the growth of component usage in the enterprise came the need for a new look at how enterprise software development should proceed using components. Component-Based Development (CBD) is the process by which organizations develop software using compo nents. Components may be premade and purchased as commercial off the shelf (COTS) entities, they may be modified versions of COTS components, or they may be made from scratch by in-house staff. Although components are ideally purchased as COTS components, it will often be necessary to at least customize COTS components or perhaps create your own application-specific components. So how does one proceed with a development process assuming such a new model of software development? A few approaches to CBD have been proposed by key OO and CBD players, such as the Rational Software Corporation and Sterling Software, Incorporated. Many approaches rely on UML as the notation from which components are described and related. We will not present a specific organization's CBD process here but will highlight some of the salient features involved in most CBD processes. Although the general process flow presented in Chapt er 2, " Obj ect - Orient ed Soft ware Developm ent for t he Ent erprise," and illustrated in Figure 2.2 still applies to CBD, the process focus shifts for CBD, and the details behind a few steps are modified. With CBD the focus of the development process shifts away from time spent in implementation. More importance in CBD is ascribed to analysis, preliminary design, and assembly. A recommended CBD process that builds on the OO process recommended in Chapt er 2 is described here: •

Project Charter: A CBD process benefits from a project charter as does an OO process.



Analysis Pattern Identification (During Requirements Analysis): Analysis patterns may be identified that are common problems described as system behaviors that can be used to map to design patterns. After an analysis pattern is identified, the specific system behavior requirements can be used to customize the analysis pattern.



External Component Interface Analysis (During Requirements Analysis): The component models, standard component interfaces, and specific component interfaces to external system components should also be identified at this stage.



System Component Interface Analysis (During Requirements Analysis): Any standard component model interfaces to the system under development should also be identified.



Component Model Technology Identification (During Preliminary System Design): The assumed component model interface to the system under development may indeed drive the technology and tools used to design the system.

- 38 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Component Identification (During Preliminary System Design): Components of the system should be defined in terms of the interfaces and technology they must support.



Component Selection (During Preliminary System Design): COTS components should be evaluated for fitness and applicability of use. Components developed on other projects should also be evaluated for use. The component should be qualified in terms of functional support, quality, technology support, and degree of customization required and supported. The components should then be acquired for use.



Component Design Adaptation (During Detailed Design): A component's behavior will ideally be altered using an easy-to-use customization interface. This may involve specifying a component's behavior using a descriptor file or perhaps via a set of design-time attributes.



Component Implementation Specialization (During Implementation): A component may also need to be modified in code, perhaps extending the existing component code via subclassing. Design patterns in particular will need to have a concrete implementation.



Component Test (During Unit Test): After a component is selected, adapted, and perhaps specialized, it should be unit tested. The component test should proceed much quicker than the unit test of code created from scratch.



Component Assembly (During Assembly): Components should be assembled into individual modules that can be separately tested. Modules may also have their own customization descriptors.



Module Test (During Thread Test): The behavior of an individual module, serving as an assembly of components, should be tested and verified.



Component Configuration Specification (During Configuration Specification): The specification of a configuration is even more important with CBD. Because more COTS components will presumably be utilized, more component versioning needs to be tracked. Furthermore, any assumptions for custom components should be detailed, including their presumed deployment environment and constraints. Many CBD approaches even allow for the specification of a configuration using component descriptors themselves. The component modules are then configured into a cohesive application.



System Test: System test with CBD involves testing a cohesive application per a particular component configuration.

- 39 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Deployment: Deployment of a component-based system should have a deployed configuration that matches a configuration in which it was validated. The flexibility with which a system can be deployed via customization of component, module, and application properties can actually be a pitfall of CBD. The particular configuration of a deployed system thus needs to have gone through some level of system test to qualify such a configuration.



Maintenance: Lastly, the maintenance phase of a system will ideally be more efficient due to the component-based nature of the system. Components may ideally be swapped out for replacement with other component implementations with less time spent on repair. This, of course, enhances system availability for the user base.

With a CBD approach, less time needs to be spent on implementation, and more time can be dedicated to more careful analyses, design, planning, and integration. Tools for CBD have blossomed in the marketplace, including tools for the custom development of components, the operational management of components, and the assembly and deployment of components. This book and the J2EE, in fact, rely on the fundamental underlying principles of CBD.

Standards Thus far in this chapter, we have discussed in detail the benefits of components, component models, and CBD. In all of this discussion, we have neglected to mention specific standards. Standard component models provide standard interface methodologies and technologies not only between applications and components, but also between components and their container environments. Standards define contracts between components and applications, other components, service providers, and container environments. In this section, we briefly define a few of the key standards that affect Java enterprise system development. We also describe a few common design patterns that can be utilized during Java enterprise system development.

Standard Component Models Many standard component models exist in the market today. In this book, we aim to focus on those models that can be used to build Java enterprise systems. Although many independent Java-based components could be used in enterprise applications before the J2EE, the J2EE does offer an integrated and simplified means to access such components from applications, as well as to build new enterprise components. We define some of the pure Java-based component models here, as well as a few other key models, most of which can also be used in Java enterprise environments. The Object Management Group (OMG) and Microsoft Corporation have also defined enterprise component models. The OMG model has even been partially incorporated by the J2EE model. The various enterprise component models that are described or referenced throughout this book include the following: •

Applets: Java applets define simple container-to-component and component-to-container interfaces enabling Java code to run inside of an applet container that is embedded in a Web browser.



JavaBeans:

- 40 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The JavaBeans component model defines a standard model for writing Java code that can be customized at design-time, and exposes its attributes, events, and interfaces to JavaBean containers. Containers are typically embedded into an integrated development environment such that JavaBean components can be customized during design-time using GUI-based tools. A standard JavaBeans container context interface and standard component-to-component interface model known as the InfoBus have also been defined for the JavaBeans component model. •

CORBA: The Common Object Request Broker Architecture (CORBA) defines a standard model for enabling distributed access to components implemented in any language. A standard communications container environment, known as the ORB, handles transforming calls from distributed clients into data sent via a standard communications protocol to server-side container code that invokes the distributed object method. In addition to a standard component communications and invocation infrastructure, a standard set of higher-level distributed component services and facilities is also defined within the CORBA model.



RMI: The Remote Method Invocation (RMI) framework defines a Java-specific interface model for enabling distributed access to components. The RMI container environment is equipped with the Java platform and has been extended to support communication using the same underlying communications protocol as CORBA's standard protocol.



COM: Microsoft's Component Object Model (COM) defines a standard model for interfacing with components implemented on Microsoft platforms. The Distributed Component Object Model (DCOM) is a distributed communications version of the COM model. ActiveX and OLE are also Microsoft-centric models that predate the COM and DCOM models.



Java APIs/SPIs: Java is much more than just a language. Various Java APIs actually define a standard set of component services that can be used by applications to access services such as databases (JDBC), naming and directory services (JNDI), transaction services (JTA and JTS), messaging services (JMS), and trading/discovery services (Jini). Furthermore, many of these API models allow one to plug in different underlying service providers using an SPI.



J2EE Web Components: Java Servlets and JavaServer Pages represent server-side components for handling Web requests and generating Web presentation content. Such Web components operate and run inside of J2EE-based Web container environments.



J2EE Enterprise JavaBeans: Enterprise JavaBeans (EJBs) are server-side application components adhering to a standard model; they operate inside of EJB containers and servers. Such servers can provide a standard set of infrastructure services to EJBs, such as transactions, security, and scalability.



CORBAcomponents:

- 41 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CORBAcomponents is a CORBA-based application serving model. CORBAcomponents was not a final standard at the time of this writing, but preliminary specification documentation indicates that the CORBAcomponent model will bear a close resemblance to the EJB model. •

Microsoft DNA: The Microsoft Distributed Network Architecture (DNA) is Microsoft's integrated distributed application serving architecture environment for Microsoft platforms. DNA incorporates many of Microsoft's standard components for enterprise applications running on the Microsoft platform.

Design Patterns As a final note, we briefly describe a few common design patterns in this section. A design pattern is a set of classes, interfaces, and their relationships that provide a common design solu tion to a common problem classification. A design pattern is defined in terms of an intended use, the common problem that it attempts to solve, a design structure of classes/interfaces and their relationships, participant and collaborating objects, expected solution results, and implementation considerations. By identifying patterns that recur when solving problems, a developer can quickly recognize and select a solution to a problem given a suite of design pattern solutions. As we alluded to earlier, patterns of analysis can also be identified during requirements analysis. Analysis patterns can generate common analysis models, which can then be related to common design patterns. Some authors have even postulated the use of anti-patterns during development which identify those common design patterns that should be avoided when developing systems. Identified design patterns are often expressed in terms of more abstract design models as opposed to concrete implementation solutions. Application designs can specialize a design pattern by providing the concrete and application-specific design features that make the design pattern useful. Nevertheless, many design patterns can be modeled in code and can provide a common component and interface framework that can be inherited and implemented by concrete application solutions. Following are some of the more common design patterns that we have found to be the most useful and to which we sometimes refer throughout the book: •

Adapter Pattern: An adapter is used to adapt the implementation of one class's interface to support a new underlying implementation. The client interface of the adapter remains constant. Java APIs can often be classified as satisfying the adapter pattern. APIs such as JDBC, JNDI, and JMS provide a standard interface to application clients while allowing for different underlying service providers.



Factory Pattern: A factory is a general framework for creating new object instances. Some generic factory frameworks can create instances of objects of specific types given a type name and initialization parameters for the construction of that type. Factories can be used to create objects that are nondistributed or distributed.



Singleton Pattern: A singleton provides a means to ensure that only one object instance of a class is created and referenced by clients accessing that class. Most often, singletons are defined for a particular process. However, means for defining singletons within a certain distributed processing domain can also be defined.

- 42 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



MVC Pattern: The Model-View-Controller pattern defines a standard way to design systems such that the model, view, and control aspects are separately encapsulated. Model encapsulations represent system state and the relations between system states. View encapsulations represent means to present the same underlying model to different client views of that model. The controller encapsulation provides the means by which a model is manipulated by a client and stimulates updates to a client view.



Strategy Pattern: Strategy patterns encapsulate interchangeable underlying algorithms and provide the same interface for accessing such algorithms. A strategy pattern is similar to an adapter pattern, but it is mainly used to provide pluggable policies and algorithmic processing modules in a design.



Command Pattern: Command patterns encapsulate a command for performing some operation. Generic command handlers may also be defined to take a command and funnel it to a specific command handler that has been associated with the command.



Subject-Observer Pattern: Subject-observer patterns encapsulate the subject of some event that should be observed. Subjects have many encapsulated observer objects that are interested in such events. Standard interfaces for registering, deregistering, and notifying observers can exist on subjects, whereas standard interfaces for being notified can exist on observers. Standard subject-observer event encapsulations may also be implemented.



Proxy Pattern: Proxy patterns provide an intermediate object that is used to make a request to an endpoint object. Clients use the proxy, which, depending on certain configurable parameters, contacts the endpoint object.



Composite Pattern: Composite patterns define entities which represent a component that can be contained by one or more composite objects. Composite objects themselves are components and can be contained by other composite objects.

Many other design patterns exist and can be used to create component frameworks within which you can define other application-specific components. We encourage you to explore Appendix B, " Addit ional Resources," to learn where you can find more design pattern information.

Conclusions A component can help you encapsulate a collection of interfaces more directly useful to an enterprise as a particular service in a much broader sense than can classes and objects. Components have a coarse-grained nature that facilitates more rapid application development and reuse at a higher level. A component-based development process differs from a pure object-oriented development process in that the focus shifts to component identification, evaluation, and assembly and away from lower-level class identification and development.

- 43 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Component models define interface contracts between components and containers, between components and their applications, and among components themselves. Although software reuse has been somewhat of a pipe dream for many organizations, standard component models help stimulate more widespread reuse in the software industry by defining standard software interfaces. Standard software interface models facilitate exchange between software component producers and consumers. Enterprise systems development in particular has benefited from the use of components with components serving as one of the core underpinnings of Java enterprise development and the J2EE.

Chapter 4. Java Foundations for Enterprise Development IN THIS CHAPTER • • • • • • • • • •

Java Feat ures and Versions Java Plat form Archit ect ure Java Files and Tools Java Language Core Java Language API s Collect ion API s I nput / Out put and St at e Persist ence API s Threading API s Dat e and Tim e API s Java Applet s

The Java technologies to be described throughout this book can be directly applied to specific aspects of problems that plague an enterprise. All of these technologies rest on a bedrock of Java language, Java platform, and Java API features. This chapter provides a brief overview of these foundational Java concepts and technologies on which the technologies throughout the remainder of this book depend. This chapter may serve as a refresher for some readers, or some may decide to skip this chapter altogether if they are already familiar with such content. Only a subset of the total Java 2 Standard Edition platform features are discussed in this chapter. The remaining chapters in this book fill in the blanks and cover all other Java 2 Platform Standard Edition and Enterprise Edition packages and features. In this chapter, you will learn: • • • • • • • • • •

Some of Java's features that make it useful to the enterprise development process, as well as a brief history of Java's evolution from the research labs into the enterprise. The architecture of the standard Java development and runtime environments. The basic Java file types involved in development, the environment and tools used for building Java code, and the basic structure of common Java file types. The basic elements of the Java language. The basic elements of Java 2 that extend the Java language with encapsulated OO APIs. The basic elements of Java 2 collections for managing collections of objects. The basic elements of Java 2 input/output mechanisms for transferring data between the Java environment and an external environment. The concepts behind thread synchronization and basic Java 2 elements for creating threads. The basic Java 2 elements for manipulating dates and time. The basic Java 2 elements and steps for creating applets.

Java Features and Versions Java is an object-oriented language with many APIs and standard frameworks enabling it to be used as an enterprise component model platform as well. Java has a lot of built-in features

- 44 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and a simplicity about it that has rendered it very popular with all types of developers. In particular, enterprise developers have gravitated to Java due to its features that enable the faster construction of more reliable enterprise applications. The applicability of Java to the enterprise didn't occur overnight, however. Java's initial conception, in fact, was spawned from embedded application research efforts. This section highlights some of Java's features that make it useful to the enterprise development process, as well as provides a brief history of Java's evolution from the research labs and into the enterprise.

Java's Attractive Enterprise Features Java provides a simple and extremely rich set of programmatic features to facilitate rapid application development in an operating-system and hardware-platform–independent manner. Java also provides an object-oriented as well as a component-based platform for building sophisticated applications. Although Java was originally touted as the language for the Internet by enabling mobile Java code to be run inside of Web browsers, because of its features, it has fast become one of the most widely used languages and platforms for building enterprise systems. The reason for Java's growth as a tool to build enterprise systems lies within its features, including these: •

Object-Oriented: The Java language has a fairly pure and intuitive OO structure that provides all the benefits for using OO without the pitfalls present in other OO languages (for example, C++) that have more loosely defined OO structures.



Component-Based: The Java platform has an enormous number of standard component APIs and a container-component model of programming that provides all the benefits for building enterprise applications using a CBD process.



Platform-Independent Architecture: The architecture of the Java platform is operating-system and hardware-platform independent. The heterogeneous nature of enterprise environments can thus be accommodated by Java's support for "write once and run anywhere."



Rich Tool Suite: Most of the development tools one needs to build applications come free with the Java development kits. Furthermore, the Java development kits also include tools for deploying component-based applications.



Many Language Features: The Java language is a simple and easy language for developing applications faster. Garbage collection for automatic cleanup of resources and a pointer-free language also enable the programmer to worry less about language semantics and help in building more reliable applications faster.



Many Core APIs: Most common programming tasks and abstractions are provided out of the box with a core set of standard APIs. No longer will a programmer spend time sweating over which vendor's collection classes to use.

- 45 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Built-In I/O and Serialization: Built-in facilities for streaming Java objects to and from a common underlying serialization format allow for a standard way to externalize Java objects and transfer Java object state between Java applications, thus enabling mobile code.



Threading: A standard means for providing thread safety and building threaded applications is embedded into Java.



Dynamic Web-Based Applications: Perhaps one of the most popular early aspects of Java was its capability to run as an application inside of Web browsers with Java applet code dynamically downloaded from a Web server.

Java's Version History Java was born out of a 1991 research initiative at Sun when Patrick Naughton, Mike Sheridan, and James Gosling formed the "Green Project" to determine what would be the next new wave of computing. Their early conclusion was that consumer electronics devices and more sophisticated computing would converge. In the summer of 1992, the Green Project members (fully staffed at 13) unveiled their "*7" (pronounced "Star Seven") device, demonstrating a handheld home-entertainment controller having an animated touch-screen interface. Given the need for heterogeneity in device controllers, the team had created a platform-independent language called "Oak," which is now known to be the forerunner of Java. In 1994, the market focus for this new Java platform became the Internet when executable Java code was embedded inside of Web browsers in the form of Java applets. In March of 1995, an alpha Java version 1.0a2 was released to the public. Within a few months, the Java platform was being downloaded by a growing number of developers, Netscape announced the integration of Java into its browser, and the official first release of Java was made public in May of 1995. The Java Development Kit (JDK) v1.0 was released in January 1996, and a final release of the JDK v1.1 was made public in February of 1997. With the release of the JDK v1.1 and a faster runtime environment, Java began to see a growth in applicability to enterprise environments. Sun released the Java 2 platform in December of 1998. The Java 2 platform corresponds to the JDK v1.2. In June of 1999, Sun announced plans for a comprehensive reorganization of the means by which it released Java platforms. Although Sun previously encapsulated a collection of Java enterprise technologies and APIs under the marketing labels of "Java Technologies for the Enterprise" and the "Java Platform for the Enterprise," it wasn't until the June 1999 announcement that Sun would pursue a distinct and integrated Java enterprise platform. The major Java platform distinctions are partitioned along these lines: •

J2ME: The Java 2 Micro Edition (J2ME) is a Java platform catered for embedded and consumer-electronics platforms. It has a smaller footprint and embodies only those Java APIs needed for embedded applications.



J2SE: The Java 2 Standard Edition (J2SE) is a Java platform catered for typical desktop and workstation environments. The J2SE is essentially what was once referred to as the Java 2 platform or JDK v1.2. The J2SE was distributed either as version 1.2 or as version 1.3 at the time of this writing.

- 46 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



J2EE: The Java 2 Enterprise Edition (J2EE) is a Java platform catered for scalable enterprise applications. Web-enabling and application-enabling component-based environments and APIs are equipped with a J2EE platform. The J2EE is separate and dependent on the J2SE, but we often refer to the J2EE throughout this book as a platform to mean both the J2SE and the J2EE physical distributions combined.

Java Platform Architecture Java specifications define standards that affect both the development of Java code and the runtime execution of Java code. All of these standards help provide a level of assurance that your Java applications written and developed for one Java platform implementation and operating system can also run on another Java platform implementation and operating system. Such standards decouple dependence of enterprise applications from specific operating-system platforms, hardware platforms, and Java platform implementations. This section provides an overview of the standard Java development and runtime environments.

Java Development and Runtime Environments The Java architecture is standardized by a series of specifications defining both development and runtime environment standards as depicted in Figure 4.1. Java source code utilizes a standard Java development environment expressed in terms of a standard Java language syntax and semantics, standard Java APIs, and a compilation process that produces executable code adhering to a standard Java class file format. The Java runtime environment specifies standards that guarantee that the same executable Java application class files can execute on a standard Java runtime platform. This Java runtime platform presents the same execution environment to a Java application independent of an underlying operating environment. Figure 4.1. Java development and runtime environments.

Java Runtime Platform Architecture

- 47 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The runtime environment architecture for the Java 2 platform is shown in Figure 4.2 in the context of both the executable Java application code and the underlying operating environment. The Java application class file format is actually expressed in terms of byte codes. Byte codes are similar to assembly-language instructions. As previously mentioned, one of the most attractive features of Java is its operating-system and hardware-platform independence. Byte code instructions are executed within the context of a virtual machine (that is, the Java Virtual Machine, or "JVM") that operates above an operating-system level. The main components illustrated in Figure 4.2 help provide such platform independence and are briefly described here: Figure 4.2. The Java 2 runtime platform architecture.



Byte Code Verifier: The byte code verifier analyzes a byte code stream corresponding to a Java class and verifies that this byte stream adheres to the Java language rules defined for classes. We discuss byte code verification in a bit more detail in the context of Java security in Chapt er 26, " Basic Java Securit y."



Class Loader: The class loader is responsible for loading Java class byte codes from an input stream (for example, file or network), inducing a byte code verifier to verify these byte codes, inducing security checks via the Java security interfaces, and then handing the classes off to the Java runtime execution engine. We have more to say about the class loader in the context of Java security in Chapt er 26.

- 48 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Java Runtime Execution Engine: The runtime execution engine is the workhorse that actually executes the byte codes that have been loaded by the class loader and verified by the byte code verifier. The runtime engine maps abstract byte code instructions to platform-specific library calls and instructions. The runtime engine is the core of the Java Virtual Machine. The JVM also includes the class loader and byte code verifier.



Java API Class Files: The Java API class files are the executable Java code implementing the standard Java platform APIs. Many of the standard Java APIs, such as networking and threading libraries, make native platform calls via a set of native platform interface libraries.



Native Platform Interface Libraries: The native platform interface libraries make native calls to underlying platform libraries and resources on behalf of the Java APIs.

Java Runtime Optimizations Optimizations for a Java runtime environment generally focus on optimizing the Java runtime execution engine. Some implementations simply interpret byte codes into platform-specific instructions and calls as they are encountered during the normal sequence of execution. Many optimizations come in the form of implementations that use certain platform-specific features (for example, IBM's JVM is optimized for Windows NT platforms). If an execution engine utilizes a just-in-time compiler, its byte codes are interpreted and compiled into native calls as they are encountered and subsequently cached. In this way, the native calls can be used without recompilation when the same byte codes are encountered later during processing. Sun's Java HotSpot VM optimizes native code execution for most recently used code. As a final note, in addition to runtime execution engine optimizations, some tools actually precompile

Java Files and Tools The development of Java code involves the specification of Java source code and its compilation into executable Java class files. The Java class files then execute atop the JVM inside of a JVM runtime process. This section describes the basic types of files used to develop, deploy, and execute Java applications. The basic structure of Java source code developed using a standard Java coding and documentation convention is then briefly highlighted. Finally, we describe the basic set of development, deployment, and runtime tools that come freely equipped with the J2SE's Software Development Kit (SDK).

Java File Types Various file types are utilized by the Java platform. Files exist to contain source code, executable code, object state, and archived code. The basic Java platform file types and any standard file naming extensions/conventions are listed here: •

Source Code Files (.java): Contains Java source code. One file corresponds to one public class.



Class Files (.class):

- 49 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Contains the compiled Java source code and is described as a series of byte codes per standard Java specification. One class file corresponds to one Java class. •

Java Serialization Files (.ser): Contains a serialized representation of a Java object's state and class description.



Java ARchive Files (.jar): Contains an optionally compressed collection of files according to the ZIP file archive format. A JAR file will typically hold files such as Java class files, serialization files, a manifest file, and multimedia files such as sound and image files. The Java 2 platform also enables Java code to be directly executed from the JAR file.



Java Manifest Files (MANIFEST.MF): Is used to describe the contents of an archive file.

Basic Java Source File Structure The basic Java source file format consists of declaring the package of a class or interface, importing other classes and interfaces, declaring the class, declaring class and instance variables, and declaring/defining constructors and methods. Sun's Code Conventions for the Java Programming Language defines a simple standard for organizing and creating Java source code (ht t p: / / j ava.sun.com / docs/ codeconv/ index.ht m l). If code is documented in a particular format known as the JavaDoc convention, HTML documentation for that code can be automatically generated from the source code (ht t p: / / j ava.sun.com / product s/ j dk/ j avadoc/ index.ht m l). The basic structure of a Java source code file that adheres to the standard JavaDoc and Java coding conventions is listed here with descriptive comments: /* * Class/interface code documentation here */ // Package declaration package ejava.foo; // Import statements import ejava.bar.*; // Import all elements of ejava.bar package import ejava.bar.drinks.Martini; // Import a specific Martini class /** * Class description here * * @version Version Number and Date here * @author Author Name here */ // Class declaration, optional single inheritance extension, // and optional multiple interface implementations public class ClassName extends BaseClass implements SomeInterface { // List static class variables first in order of decreasing // visibility: public, protected, package, private /** class variable documentation comment */ public static VariableType publicClassVariableName; /** class variable documentation comment */

- 50 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

private static VariableType privateClassVariableName = InitValue; // List instance variables in order of decreasing // visibility: public, protected, package, private /** instance variable documentation comment */ public VariableType publicVariableName; /** instance variable documentation comment */ protected VariableType protectedVariableName; /** instance variable documentation comment */ VariableType packageVariableName; /** instance variable documentation comment */ private VariableType privateVariableName; // // // //

List constructors before methods. Group constructors and methods according to logical groupings. No preference for ordering between class and object methods and visibility such as public, protected, package, or private is assumed.

/** * Constructor comment here */ public ClassName() { // Implementation here } /** * Method comment here * @param aParameterName parameter description */ public ReturnType methodCall(ParameterType aParameterName) { // Implementation here } } // List any non-public classes here class NonPublicClassName { … }

Basic JAR and Manifest File Structure JAR files are optionally compressed collections of files that adhere to the ZIP file archive format. JAR files contain entries that include Java class files, serialization files, a manifest file, and multimedia files such as sound and image files. Manifest files can optionally be placed inside of a JAR file to describe special handling procedures for certain JAR file entries. Manifest files are placed in a JAR file with a path of META-INF and a filename of MANIFEST.MF. Files requiring associated security signatures are placed in a JAR file with a path of META-INF and have a file extension of .SF. The manifest file contains a list of file entries that are placed in the JAR file. Only those files that have special handling instructions need to be designated in the manifest file. At the top of a manifest file, the manifest file standard version needs to be designated via this: Manifest-Version: A manifest file standard version that is required for use may optionally be specified this way: Required-Version: Each entry to be defined in a manifest file begins with a Name: header and is followed by a pathname and filename of the archived file. An entry description has one or more associated attribute values that can be used as special handling information for that entry. Each entry is defined using the following format, in which signature algorithm attributes and other attribute name/value pairs are optional:

- 51 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Name: / -Digest: : Executable JAR files can be built if a manifest file has a Main-Class: attribute name associated with a Java class that has a main() method to be called when executing the JAR file. For example: Manifest-Version: 1.0 Main-Class: com.assuredtech.b2b.server.B2Bserver.class

Java Software Development Kit Tools One of the nice features of Java that has made it very popular with developers is the fact that you can quickly begin programming in Java with a simple text editor and via use of the free Java SDK. The SDK distribution comes equipped with several tools for developing, deploying, and running Java applications (ht t p: / / www.j avasoft .com / product s/ j dk/ 1.2/ docs/ t ooldocs/ t ools.ht m l). Although the J2SE SDK is free for commercial use, it cannot be freely distributed with commercial applications. Rather, the runtime environment component of the J2SE SDK can be separately downloaded and is free for commercial distribution with your Java applications. These are the most commonly used basic command tools from the J2SE SDK: •







• •

javac: Compiles Java source code into Java class files. The command javac [options] [source files] [file list] is used to compile a set of source files given a set of options and optionally using a separate file list to indicate the source files to be compiled. Although the CLASSPATH environment variable can define where to look when compiling Java files, the -classpath classpath option can also specify a class path. Other options exist as well, such as the -d directory option to specify an output directory for class files. jar: Creates and manipulates JAR files. The jar [options] [manifest] destination [one or more input files] command's behavior depends on the associated options. The c option creates a JAR file, the x option extracts the contents of a JAR file, and the u option updates an existing JAR file. The f option specifies a target destination JAR file. A directory or set of input files should be specified for JAR file creation. If the m option is used, a manifest file can be used to build the JAR file. java: Launches a JVM process using Java class files. The java [options] ClassName [zero or more arguments] form of the command initiates a JVM process using the main() method of the ClassName class and passing it a set of arguments. The java [options] -jar JARfile.jar [zero or more arguments] version of the command can initiate a JVM using the main() method of the executable class that is associated with the executable JAR file. If a CLASSPATH environment variable is not used to define the search location for Java classes, the -classpath classpath option may be used. Properties of the runtime system environment can be set using the DpropertyName=propertyValue option. Various nonstandard options beginning with the prefix -X are also often used to specify such options as JVM process heap size and stack size. A -jit option can be used to execute the JVM with a just-in-time compilation optimization. javadoc: Creates a set of HTML files with documentation extracted from your Java source code if your code documentation adheres to the JavaDoc format. jdb: Is a Java debugger. appletviewer: Is a tool for running and debugging Java applets.

Java Language

- 52 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Java language has a fairly simple syntax that has helped it achieve popularity in the developer community. Simpler syntax means more rapid application development. If you're familiar with C/C++ syntax, you'll note the similarity to Java syntax. However, there are some subtle semantic differences. In this section, we briefly cover some of the most often-used Java types, operators, and language constructs.

Java Fundamental Types Java has a set of fundamental types used to define basic data elements. Most of the fundamental Java types have a similarity in naming to C/C++ types but do not vary per platform as do C/C++ types. The fundamental Java types are listed and defined in Table 4.1. Table 4.1. Fundamental Java Types Type Size Description void N/A Represents no type boolean 1 bit A Boolean true or false value char A 2-byte uni-code character whose first byte is an ASCII character using an 16 English locale bits byte 8 bits A 1-byte signed integer short 16 A 2-byte signed integer bits int 32 A 4-byte signed integer bits long An 8-byte signed integer 64 bits float 32 A 4-byte floating-point number bits double 64 An 8-byte floating-point number bits

Java Operators Java also supports a set of standard operators used for operating on both fundamental Java types and Java objects. Table 4.2 lists some of these Java operations. The first column of the table lists the general classification of operator, and the second column indicates how many operands are involved per operator. Operators may be formulated in terms of two operands or one operand. Additionally, a special operator may also operate on three operands. The third column lists each operator and the fourth column describes the operator. Table 4.2. Java Operators Operator Operands Operator Description Type + Arithmetic Two Addition Subtraction * Multiplication / Division % Modulus + Plus One Negative ++ Increment -Decrement > Greater than Relational Two >= Greater than or equal < Less than

- 53 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Bitwise

Two

Logical

One Two

Assignment

One Two

Miscellaneous Three Two

One

>>> & | ^ ~ & | ^ ! = op=

Less than or equal Equal Not equal AND OR Left shift Right shift Right shift with zeroes shifted in from left AND OR XOR Complement AND OR XOR Complement Assignment Perform op and then assign value (for example, += means add then assign)

exp?A:B

If exp is true then do A else do B + Concatenate strings instanceof Determines if an object is an instance of a particular type (TYPE)A Cast object A to TYPE

Java Language Constructs Java has a fairly simple syntax for defining classes, interfaces, objects, variables, and methods. Control structures are also fairly simplistic and have a familiar C/C++ structure. Although much of the syntax for Java bears a striking C/C++ resemblance, some key semantic differences, such as object passing by reference and lack of pointer semantics, make Java a significantly different and simpler language. The most commonly used Java language constructs are presented in Table 4.3. The table lists a construct, an example of use of the construct, and a brief description of the construct. Table 4.3. Java Language Constructs Construct Example Description Comments // Comment here Used to add comments to code.

Identifiers

/* Comment here */ myValue Howdy4 _Egads $yikes

package A.B; Package Declaration import import A.B.Foo; Statements import A.B.C.*;

Identifiers are names for Java constructs such as variables, classes, and interfaces. Identifiers uniquely identify these Java constructs within a particular scope. Identifiers begin with letters, an underscore, or a dollar sign and can subsequently contain these characters and numbers. Declares that the class/interface in this file belongs to a package such as A.B. This class/interface refers to a class named Foo in package A.B or refers to classes in package A.B.C.

- 54 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

interface Interface Declaration MyInterfaceName extends AnotherInterface { public static final int a = 2; public void bla(); }

Declare an interface that can optionally extend zero or more other interfaces. Interfaces only define constants and declare methods with noimplementations.Interfaces that define no methods ("marker interfaces") are created to enable classes that implement them to designate that they have some behavior not definable via methods.

// marker interface interface MyMarkerInterface{ } class MyClassName Class extends BaseClass Declaration implements Interface1,

Declare a class named MyClassName. A class can optionally extend one other class (single inheritance) and implement zero or more interfaces.

Interface2 { } VariableType Field Declaration variableName = InitValue; Object obj = new Objects Object(); MyClass myObj = new MyClass(); Object[]array1 = new Arrays Object[5]; int[]array2 = new int[20]; int[]array3 = {3, 5, 20}; public Visibility protected

private Methods

static

A variable of type VariableType with the name variableName and initialized to an InitValue. An object is an instantiation of a particular class type. Objects are passed around by reference.

Arrays of Java types can be declared for objects and fundamental types. Arrays can be constructed in a pre- initialized state using curly braces.

Some Construct can be accessed by other classes in public, subclasses if protected, classes in the same package if no visibility is defined, and only by the associated class if private.

A method named methName returning a type ReturnType and accepting zero or more parameters of type Param and named public ReturnType paramName. A return statement is used within methName(Param a method to return some value. Objects are paramName){ passed by reference to and from method calls. return someValue; The underlying references themselves are } passed by value. Methods that simply retrieve attribute data from a class are called "getters," // getter whereas data that simply sets attribute data are public Type getData() called "setters." {…} class MyClassName{

// setter public void setData(Type data) {…} } static static Object myObject;

Some Construct, such as a method or variable, can be associated with a class. All objects of that class share the same static construct variable

- 55 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

class share the same static construct variable. A static method can be called on the class directly without an instance being created. final final Some Construct, such as a method or variable, final int val = 4; can be declared final such that it is not able to final void method(){…} be overridden. Objects that are final are constant. Methods that are final cannot be overridden. main class MyClassName{ The main method is the method that is called public static void Method from the command line with an array of main(String command- line arguments. args[]){ } } { Block Can nest blocks of code within code using curly // Code here braces. { // More code here } } public void myMethod() An exception is thrown when error or warning Throwing throws SomeException scenarios are encountered in code. A method Exceptions { declares that it throws an exception of some // bla bla… class type and throws the new exception in code. throw new SomeException(); } try{ An exception is handled by code that uses a Handling obj.myMethod(); Exceptions method that throws an exception using try} catch-finally blocks. The try block catch(SomeException encapsulates the code that can throw the e){ exception. The catch block is used to catch // handle exception specific or base class exceptions that can be } thrown by the try block. An optional finally finally{ // optional block is used to always execute a block of code // always execute even if an exception is thrown or not thrown. this stuff Exception handling can be nested as well. } Because exception- handling code can be lengthy and can clutter up a sample description, we sometimes leave out exception-handling // Nested Exception snippets in the book where indicated. Of course, Handling the code on the CD always contains the proper try{ exception- handling code. obj.myMethod(); static void method(){…}

} catch(SomeException e1){ try{ obj.close(); }

if Statement

catch(AnotherException e2){ // handle nested exception } } if(expression){ Create if statements and if-then-else // Do this statements.

- 56 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

switch Statement

for Statement

while Statement do/while Statement

}

statements.

if(expression){ // Do this } else if(bla){ // Else if bla, do this } else{ // Otherwise do this } switch(value){ case val1: data = val1; break; case val2: data = val2*2; break; default: data = 300; } for(bla=val; bla < max; ++bla){ // do this loop }

A switch statement takes a value and executes a particular case statement based on that value; otherwise, any default statements are executed.

while(expression){ } do{ }while(expression);

Execute a loop given some initial value such as bla=val and executing a clause at the end of each loop such as ++bla. Execute the loop for some while conditional such as bla < max. Execute a loop while some expression is true. Execute a loop while some expression is true, but execute the loop at least once first.

Core Java Language APIs In addition to the language of Java, a set of OO types defined in terms of Java classes and interfaces serves to extend the Java language beyond its fundamental type and identifier support. Appropriately enough, most of these language extensions are contained in the packages beginning with java.lang. However, a few entities in the java.math package also serve as core Java language types. This section of the chapter provides an overview of these core language APIs. Although not strictly part of a Java language extension, the base means for handling events provided in the java.util package is also described in this section. The packages that define the core Java language extended API are shown here: • • • •

java.lang: Contains constructs that extend the Java programming language with basic object encapsulations (ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ j ava/ lang/ packagesum m ary.ht m l). java.lang.reflect: Contains constructs for tapping reflection capabilities of Java constructs (ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ j ava/ lang/ reflect / packagesum m ary.ht m l). java.lang.ref: Contains constructs for reference-objects allowing for some visibility into garbage collection (ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ j ava/ lang/ ref/ packagesum m ary.ht m l). java.math: Contains constructs for performing arithmetic operations using decimal and integer operands of arbitrary precision

- 57 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



(ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ j ava/ m at h/ packagesum m ary.ht m l). java.util: Contains constructs for managing object collections, events, dates, time, locale-dependent data, and a few helper utilities (ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ j ava/ ut il/ packagesum m ary.ht m l).

Base Language and System APIs The java.lang package provides a set of classes that provide a few hooks into the internals of objects, classes, the JVM, processes, and the operating system. Figure 4.3 depicts some of these classes and their relationships. The various classes and interfaces shown in Figure 4.3 are described here: Figure 4.3. Core language and system classes.

• •

Object: Serves as the root class for all classes in Java. Basic operations on all objects are therefore supported by this class. Class: Encapsulates a description of a particular class. We discuss this class more when we describe reflection later in this section. Because every class inherits from

- 58 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •



• • •



Object, the Object.getClass() method can be used to return an instance of this object for a particular object. Cloneable: Utilized by classes that implement this marker interface to designate that the class provides an implementation of the clone() method inherited from Object. The class thus designates that it can return a copy of itself. ClassLoader: Encapsulates an interface to a JVM class loader used to load Java class files from a particular input stream. Methods such as getResource() return an object identifying a resource location given a resource name. Other methods like loadClass() can be used to return a Class instance from the class loader's input stream given the class name. SecurityManager: Encapsulates an interface to a security manager used to check for permissions to access system resources. System: Provides a hook for interfacing with the operating system on top of which a JVM runs. Operations are provided for accessing standard input, output, and error streams; mechanisms for loading libraries and files; and helper methods such as for com puting system time and array copying. Runtime: Provides a hook for interfacing with the JVM process environment. Is also used to spawn a new process external to the JVM process. Process: Encapsulates an interface to a process spawned by the Runtime.exec() call. Compiler: Provides a hook for compiling Java source code into Java byte codes. JVM providers must implement this class, which is disabled by default.

Errors and Exceptions Abnormal program execution conditions are thrown as exceptions or errors in Java code. Figure 4.4 depicts the base hierarchy for such throwable abnormal statuses. The entities of Figure 4.4 are defined here: Figure 4.4. Base exception and error abstractions.

- 59 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •



Throwable: The base class for all errors and exceptions that can be thrown by Java code. Only this class and its subclasses can be thrown by a throw statement and can be caught in a try-catch-finally block. Exception: All exceptions that can be thrown inherit from this class. Exceptions should be caught by applications. Error: An error is thrown when a serious problem has occurred and should not be caught. Classes do not need to declare when they will throw an error.

Type and Mathematical APIs The java.lang and java.math packages provide a collection of object abstractions that can be used to encapsulate fundamental Java types and perform mathematical operations using method calls. Figure 4.5 depicts these fundamental type abstractions and mathematical operation classes. The various classes and interfaces depicted in Figure 4.5 are defined here: Figure 4.5. Fundamental type abstractions and mathematical operations.

- 60 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •



• • • • •

• • • • • • • •

Comparable: Defines an interface for comparing the natural ordering of objects. Math: Defines a set of methods for performing mathematical operations such as exponential, logarithmic, and trigonometric operations. Number: Serves as an abstract base class for numbers that can convert between different fundamental data numeric types. Byte: Encapsulates an object wrapper for the Java byte type. Short: Encapsulates an object wrapper for the Java short type. Integer: Encapsulates an object wrapper for the Java int type. BigDecimal: Encapsulates an object representing an arbitrary precision integer. BigInteger: Encapsulates an object representing an arbitrary precision signed decimal number. Long: Encapsulates an object wrapper for the Java long type. Float: Encapsulates an object wrapper for the Java float type. Double: Encapsulates an object wrapper for the Java double type. Void: Encapsulates an object wrapper for the Java void type. Boolean: Encapsulates an object wrapper for the Java boolean type. Character: Encapsulates an object wrapper for the Java char type. String: Encapsulates a sequence of characters ending with a string terminator. String literals, such as "HelloWorld", are implemented as String objects by the JVM. String objects cannot be changed after they are created. StringBuffer: Represents a modifiable String object.

Reflection Java provides the capability to dynamically investigate the description of a class during runtime. A description of a class includes its members such as fields, constructors, and methods. Java reflection also provides a means for constructing new instances of objects and invoking methods on objects via generic reflection APIs. The java.lang package provides interfaces to Class and Package objects, but the java.lang.reflect package provides the framework for manipulating classes via the Java reflection capabilities. Here we describe each element in Figure 4.6 depicting the major classes and interfaces involved in reflection:

- 61 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figure 4.6. The Java reflection API.





• •

• • • • •

Class: Provides a hook into the powerful features of Java's reflection support. After a Class object representing a description of a Java class is obtained, a series of getter methods can retrieve descriptive information about the construction of that class. The static Class.forName() methods can be used to obtain a handle to a Class object given a class name. An instance of a class having an empty constructor can even be created using the newInstance() call. Package: Encapsulates descriptive information about a package associated with a particular class. Modifier: Encapsulates a modifier and provides methods for decoding whether certain descriptive information obtained from class elements is a particular modifier type. Member: Defines an interface of common operations on a member of a class such as fields, constructors, and methods. AccessibleObject: Serves as a base class for class members that can be used to control accessibility to perform reflective operations on certain classes. Constructor: Encapsulates a class constructor and access to its parameters and exceptions. A means to instantiate an object instance is also provided via Constructor.newInstance(). Method: Encapsulates a class method and access to its parameters, return type, and exceptions. A means to invoke the method is also provided via Method.invoke(). Field: Encapsulates a class field variable and access to its type and value. Array: Encapsulates a Java array with access to its elements, as well as the capability to create a new array.

Garbage Collection

- 62 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

One of the most attractive features of Java is its support for the automatic cleanup of objects that are no longer referenced. Such a feature is known as garbage collection. Programmers thus don't have to worry about memory leaks and deleting objects. The java.lang.ref package defines a set of classes that provides limited support for interfacing with the garbage collector. The classes that compose this Java garbage collector interaction are shown in Figure 4.7. We briefly describe the role of each class here: Figure 4.7. The Java garbage collection API.

• •

• • •

Reference: Serves as an abstract base class for all reference objects. The term reference object is used to mean an object that encapsulates a reference to an object. Thus, if object A has a reference to object B, a reference object would be created to represent the reference A has to B. ReferenceQueue: Encapsulates an interface to a queue where reference objects are appended by a garbage collector. SoftReference: Encapsulates a type of reference object that is cleared by the garbage collector when a demand for more memory is made. WeakReference: Encapsulates a type of reference object which does not allow objects that refer to them to be made finalized and subsequently reclaimed. PhantomReference: Encapsulates a type of reference object that is added to the reference queue when the garbage collector determines that the objects which refer to them can be reclaimed.

Events Java supports a simple standard event model for encapsulating events and their listeners. All other event-handling mechanisms in Java inherit from this base event model. Java also defines a standard subject-observer design pattern framework for notifying observers of changes in observable subject objects. Figure 4.8 depicts the simple and standard event model frameworks that we describe here: Figure 4.8. Java event models.

- 63 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •





EventObject: An abstract base class for all event classes that adhere to the Java event model. The source of an event is associated with an event and can be obtained using EventObject.getSource(). EventListener: A marker interface that must be implemented by all classes that listen for events using the Java event model. Observer: A standard interface implemented by classes that want to be notified of changes made to observable objects using Java's standard subject-observer design pattern. Observable: A class for adding, deleting, and counting observers that want to be notified of changes in an observable class using the Java subject-observer design pattern. Also supports an interface for notifying observers of such changes.

Collection APIs Collections encapsulate a collection of one or more objects. Collections provide a useful means for grouping objects such that a single object reference can refer to the entire collection of objects. Collections have been a part of the Java platform since its inception, but the Java 2 platform introduced a much richer and more sophisticated suite of collection entities. Figure 4.9 presents the top-level classifications of collection types and interfaces used to traverse such collections. A few interfaces and an abstract base class are used to distinguish between collections of objects that have an associated key name and those that do not have a key name. Two specialized classes for manipulating arrays and bits are also defined. A set

- 64 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

of interfaces is defined for iterating over collections. The classes and interfaces illustrated in Figure 4.9 are described here: Figure 4.9. Top-level collection objects.

• • • • • •

Collection: The root interface for collections of objects. Map: The root interface for collections that map key names to objects in the collection. Dictionary: An abstract base class for collections that map key names to objects in a collection. Is obsolete as of the J2SE in favor of objects that implement the Map interface. Arrays: A class used for manipulating collections of objects contained in arrays. BitSet: A class used for manipulating collections of bits in the form of a vector that can automatically grow in size. Iterator: An interface implemented by objects that enable the incremental traversal and removal of objects in a collection.

- 65 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •

Enumeration: An interface implemented by objects that enable the traversal of a collection of objects one at a time. Is obsolete as of the J2SE in favor of objects that implement the Iterator interface. Comparator: An interface implemented by objects that can compare two objects assuming some underlying order on a collection of objects.

Non-Keyed Collection Framework Figure 4.10 presents the hierarchy of the non-keyed collections framework. Abstractions exist for generic lists, lists that require access in sequential order, sets without duplicate objects, and sorted sets of objects. Many new collection abstractions have been added in the J2SE with older JDK-style collections being integrated with this framework. The newer J2SEstyle collections do not provide thread-safe access to collection elements and are consequently more efficient, whereas older JDK-style collections do provide thread synchronization. The various elements of Figure 4.10 are defined here: Figure 4.10. The non-keyed collection architecture .









Collection: A top-level Collection interface that defines basic operations for manipulating collections of objects. AbstractCollection: An abstract class with a partial implementation of generic Collection interface functions. List: An interface with methods for manipulating an ordered collection of objects with next and previous elements in a sequence. ListIterator: A special type of iterator for traversing a collection in a reverse direction as well as forward direction.

- 66 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



• •

• •

• •







AbstractList: An abstract class with a partial implementation of generic List interface functions. Can support random access of list elements. AbstractSequentialList: An abstract class that expands on the AbstractList implementation with a partial implementation that enforces sequential access of list elements. LinkedList: A concrete implementation of the List interface with support for sequential access to list elements. Vector: A concrete implementation of the List interface with support for sequential access to list elements and a growable vector of elements. The Vector class provides multiple thread synchronization support for its elements unlike its LinkedList counterpart. Stack: A type of vector that enforces last-in first-out (LIFO) behavior of elements in its collection. Also provides thread-safe synchronization of its elements. Set: An interface to a collection whose elements have no duplicates. AbstractSet: An abstract class with a partial implementation of generic Set interface functions. HashSet: A concrete implementation of a Set interface that enforces set-like behavior. SortedSet: An interface to a collection whose elements have no duplicates and are traversed in some natural order. TreeSet: A concrete implementation of a SortedSet interface that enforces sorted set-like behavior.

Mapped Collection Framework Figure 4.11 presents the hierarchy of the keyed collections framework. Abstractions exist for generic mapping collections, mapped collections with a sortable order, and collections whose elements can be garbage collected when their keys are no longer referenced. Many new mapping abstractions have been added in the J2SE with older JDK-style mapping abstractions being integrated with this framework. J2SE-style map collections do not provide synchronized access to collection elements and are thus more efficient, whereas older JDKstyle map collections do provide thread synchronization. The various elements of Figure 4.11 are defined here: Figure 4.11. The map collection architecture.

- 67 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE











• • • •

Map: An interface that defines a set of operations that provide a means to access objects in a collection using a key name. AbstractMap: An abstract class with a partial implementation of generic Map interface functions. HashMap: A concrete implementation of a Map interface enforcing the behavior of map ping key names to objects in a collection. SortedMap: A type of Map interface that provides operations to enforce a natural ordering of elements in the map. TreeMap: A concrete implementation of a SortedMap interface enforcing the behavior of an ordered collection of mapped objects. Dictionary: An obsolete base class for providing map-like behavior. Hashtable: A concrete implementation of a Map interface enforcing the behavior of mapping key names to objects in a collection. The Hashtable class provides multiple thread synchronization support for its elements, unlike its HashMap counterpart. Properties: A type of Hashtable whose elements are properties of a system. That is, the element types are String objects that define some property of the system. WeakHashMap: A type of Map whose elements may be removed by the garbage collector when its keys are no longer referenced by other objects in the JVM process.

Input/Output and State Persistence APIs Input serialization is the process of reading data external to an application into data used within an application. Output serialization is the process of writing some data within an application to data external to the application. Input/Output (I/O) serialization is a common enough operation that the Java platform defines a framework and standard set of classes for

- 68 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

serialization in the java.io package. The java.io package provides a basic set of abstractions for serializing objects, mapping bytes to and from I/O streams, mapping character data to and from I/O streams, and manipulating files. Figure 4.12 presents this base I/O architecture. A description of each entity in Figure 4.12 is provided here: Figure 4.12. The base I/O architecture.



• •

• • • • •

• • •

• •

Serializable: A marker interface implemented by classes whose state is serializable to an I/O stream. Externalizable: An interface implemented by classes that assume responsibility for writing and reading its context to and from an I/O stream. InputStream: A base abstract class for classes that read bytes from an input stream. OutputStream: A base abstract class for classes that write bytes to an input stream. Reader: A base abstract class for classes that read characters from an input stream. Writer: A base abstract class for classes that write characters to an output stream. ObjectStreamClass: A class which encapsulates a description of the object information contained in an I/O stream. ObjectStreamField: A class which encapsulates a description of a field within an object I/O stream. ObjectInputValidation: A callback interface permitting an object to be validated. File: A class which encapsulates a file and directory path. FileDescriptor: A class which encapsulates an interface to a system's file descriptor. FileFilter: An interface defining a filter for pathnames. FilenameFilter: An interface defining a filter for filenames.

Byte I/O Streams Byte I/O streams represent those streams that inherit from the InputStream and OutputStream classes to support reading and writing bytes from and to an I/O stream. The byte I/O stream classes and interfaces provide mechanisms for converting data from I/O stream bytes into more manageable Java objects and data types, as well as providing a

- 69 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

means for filtering and redirecting I/O data. Figure 4.13 depicts the entities involved in the byte I/O stream APIs. Each entity in Figure 4.13 is described here: Figure 4.13. Byte I/O streams.











• • •

• •



• • •

ByteArrayInputStream/ByteArrayOutputStream: Used for reading/writing a sequence of bytes from/to an I/O stream. FilterInputStream/FilterOutputStream: Used for reading/writing data from/to an I/O stream by first passing the data through a filter that modifies the data in some way. BufferedInputStream/BufferedOutputStream: Used for reading/writing data from/to an I/O stream with a buffer in place to hold the data. DataInput/DataOutput: Defines interfaces for reading/writing bytes from/to an I/O stream with conversions to/from Java primitive types. DataInputStream/DataOutputStream: Encapsulates concrete implementations of the DataInput/DataOutput interfaces. RandomAccessFile: Provides interfaces to read and write from a file. PushbackInputStream: Used for reading data from an I/O stream with the capability to push data back to the input stream after it has been read. FileInputStream/FileOutputStream: Used for reading/writing data from/to a file I/O stream. ObjectInput/ObjectOutput: Defines interfaces for reading/writing Java objects from/to an I/O stream. ObjectStreamConstants: Defines constants used for writing objects to an I/O stream. ObjectInputStream/ObjectOutputStream: Encapsulates concrete implementations of ObjectInput/ObjectOutput interfaces. PrintStream: Provides a mechanism for printing formatted data to an I/O stream. PipedInputStream/PipedOutputStream: Enables one to create streams that are connected to one another such that data can be piped from a PipedInputStream directly into a PipedOutputStream. SequenceInputStream: Facilitates the concatenation of input streams.

Character I/O Readers and Writers Character I/O streams represent those streams that inherit from the Reader and Writer classes to support reading and writing characters from and to an I/O stream. The character

- 70 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

I/O stream classes and interfaces provide a means for filtering and redirecting character I/O data. Figure 4.14 depicts the entities involved in the character I/O stream APIs. Each entity in Figure 4.14 is described here: Figure 4.14. Character I/O readers and writers.

• • •











• •

InputStreamReader/OutputStreamWriter: Encapsulates concrete implementations of a Reader/Writer to support mapping bytes on an I/O stream from/to character data. FileReader/FileWriter: Used for reading/writing files of character data. BufferedReader/BufferedWriter: Used for reading/writing character data with an underlying buffer to manage data flow. LineNumberReader: Encapsulates a buffered character input stream that maintains a count of line numbers read. CharArrayReader/CharArrayWriter: Used to read/write data from/to a character array buffer. FilterReader/FilterWriter: Used for reading/writing character data by passing it through a filtering mechanism first. PushbackReader: Encapsulates a character stream reader enabling characters to be pushed back onto the character stream after they have been read. PipedReader/PipedWriter: Enables one to create character streams that are connected to one another such that character data can be piped from a PipedReader directly into a PipedWriter. StringReader/StringWriter: Used to read/write character data whose source is a String I/O stream. PrintWriter: Used to print formatted character data to a character stream.

Archive File APIs The Java platform also contains APIs for programmatic manipulation of JAR, ZIP, and GZIP files. JAR file manipulation is accomplished via the java.util.jar package APIs. ZIP and GZIP file manipulation is accomplished via the java.util.zip package APIs. Because JAR files and their manifest files are the most common archive file format that we deal with throughout this book, we only briefly highlight the main features of JAR manipulation and

- 71 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

manifest files in this section. The java.util.jar package is dependent on the java.util.zip package, and thus we necessarily describe some of the ZIP manipulation abstractions as well. Figure 14.15 presents the architecture of the APIs used to manipulate JAR files programmatically. Each class in Figure 14.15 is defined here: Figure 4.15. JAR I/O classes.

• • • • •

• • •

ZipEntry: Encapsulates a file entry in a ZIP file. JarEntry: Encapsulates a file entry, such as a Java class file, in a JAR file. ZipInputStream: Encapsulates an input stream from which ZIP files are read. JarInputStream: Encapsulates an input stream from which JAR files are read. Manifest: Encapsulates a manifest file and operations that can be performed to manipulate its attributes. Attributes: Encapsulates a mapping of Manifest file entry values. ZipOutputStream: Encapsulates an output stream to which ZIP files are written. JarOutputStream: Encapsulates an output stream to which JAR files can be written.

Properties Files

- 72 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Throughout the book, we often utilize the inherent capability of the java.util.Properties class to initialize itself with properties read in from a file with support from the I/O serialization libraries. Although any type of InputStream can be passed into the Properties.load(InputStream) method to load in a set of properties from an input stream, we often create a FileInputStream associated with a properties file as input. Each property is a name/value pair occupying one line of the properties file. Whitespace and lines beginning with # or ! are ignored. A property on a line is defined with a key name, followed by = or :, and then followed by the String value for the property. A backslash (\) may be used to continue the definition of a property value throughout multiple lines. As an example, suppose we have a file named Telecomm.properties with the following contents: # Server ID Name ServerID = TelecommServerB2B # B2C E-Commerce Web Site B2Csite = http://www.assuredtech.com/demos/TelecommStore.html # B2B Init Data B2Bpartners = NetworksInc, PhonesGaloreCorp, EcommAdsInc, } SallysUsedPartsInc, MrAnnoyingTelemarketingCorp, } HappyTelcoContractorsLLC We can then read in the three properties named ServerID, B2Csite, and B2Bpartners using this: Properties properties = new Properties(); try{ FileInputStream fin = new FileInputStream("Telecomm.properties"); properties.load(fin); // Loads properties from file into object fin.close(); } catch(IOException ioException){ System.out.println("Error :"+ioException); } The properties object will then be loaded and can be accessed as Properties objects can normally be accessed. For example: String serverID = properties.getProperty("ServerID"); String b2cSite = properties.getProperty("B2Csite"); String b2bPartners = properties.getProperty("B2Bpartners");

Threading APIs Multiple threads of execution supported by an operating system generally provide a more efficient concurrent processing model than multiple processes of execution. Each thread has its own stack memory (for example, for parameters and method local variables pushed on the stack during method calls) but can share heap memory (for example, a class's instance variables) across all other threads. Multiple processes, on the other hand, must use interprocess communication mechanisms to share data. Although data sharing can provide advantages in terms of performance and reduced hand-coding, care must be taken to guarantee the "thread safety" of such shared data. If multiple threads attempt to access the same data at roughly equivalent times, concurrency issues can arise and induce unpredictable behavior for your application. As an example, suppose a Printer object has an instance variable named jobsCount that is used by the Printer object to determine whether some maximum number of submitted print jobs has been exceeded before it submits a print job: public class Printer{

- 73 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

private static MAX_JOBS = 5; private int jobsCount = 0; public void printJob(PrintJob printJob) throws PrintException{ if(jobsCount > MAX_JOBS){ throw new PrintException("Max Jobs Exceeded"); } else{ // send printJob to printer device ++jobsCount; } } … } Now suppose that multiple threads of execution can manipulate an instance of the same Printer object named hallwayPrinter. Then suppose that the following sequence occurs: 1. At one instant, the hallwayPrinter object's jobsCount value equals 5. 2. Thread A calls hallwayPrinter.submitJob(myJob) at one instant. Thread A calls the if(jobsCount > MAX_JOBS) statement during the next instant, which evaluates to false, and Thread A enters the else block above. 3. Now suppose that Thread B's execution context is swapped in before Thread A can proceed. 4. Thread B calls hallwayPrinter.submitJob(myJob) at one instant. Thread B calls if(jobsCount > MAX_JOBS) the next instant, which evaluates to false, and Thread B also enters the else block above. 5. Both Thread A and Thread B complete their else block with jobsCount being incremented to 7, which exceeds the maximum job count. 6. The printer now jams because it has six jobs in its queue, which exceeds the maximum load it may be capable of handling. Note that we're assuming a rather pitiful printer here for simplicity of describing our problem. This issue can be avoided by making the Printer class thread-safe. One solution would be to use the synchronized Java keyword to declare that the submitJob() method must be executed completely before any other thread can access the Printer object. For example: public synchronized void printJob(PrintJob printJob) throws PrintException{ … } The synchronized keyword can actually be used in Java in the following most common ways to provide thread safety: •

Synchronized Instance Methods: Adding synchronized in front of an instance method definition requires that the invoking thread obtain a "lock" on the object associated with that object instance before it can execute the method. If another thread already has the object's lock, the invoking thread will block. For example:

public synchronized void printJob(PrintJob printJob) throws PrintException {…} •

Synchronized Class Methods:

- 74 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Adding synchronized in front of a static class method definition requires that the invoking thread obtain a "lock" on the associated class before it can execute the method. If another thread already has the class's lock, the invoking thread will block. For example:

public static synchronized void printJob(PrintJob printJob) throws PrintException {…} •

Synchronized Objects in Methods: Finer-grained synchronization can be provided by adding the synchronized keyword with parentheses encapsulating an object that needs to be protected before the block of code within a method that needs to be guarded. For example:

public void printJob(PrintJob printJob) throws PrintException{ synchronized(jobsCount){ if(jobsCount > MAX_JOBS){ // Bla bla bla } else{ // Bla bla bla ++jobsCount; } } // Execute other code here } •

Synchronized Object Blocking and Notification: The Object.wait() method can be used in one synchronized block of code to cause the invoking thread to release its lock and block. The Object.notifyAll() or Object.notify() method can then be used elsewhere within a synchronized block of code to notify blocking objects that they should go ahead and try to obtain the lock and proceed with processing. For example:

// This method call obtains lock on object // Assume application code to use printer calls this method public synchronized void printJob(PrintJob printJob){ // This while loop will loop until jobsCount MAX_JOBS){ wait(); // if jobsCount > MAX_JOBS, then release lock and block } // Only gets to this point in code if jobsCount

. . . some_alternate_HTML_to_display_if_applet_can't_load

Thus, using our earlier MyApplet example, we might define an HTML Web page to reference our applet stored in a MyApplet.jar file and pass it two applet parameters as shown here:

- 81 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



HTML Applet Test Page

SampleApplet will appear below in a Java enabled browser.






Conclusions Java provides a simple and very rich suite of platform features, tools, language features, and common APIs that have enabled developers to rapidly develop and deploy more reliable applications. Such features of Java made it particularly attractive for use in building enterprise applications. We have provided a quick overview and refresher here for the reader to understand those foundations of the Java language and platform that have been so fundamental to enabling Java to be used in the enterprise. Java enterprise systems and the remainder of this book build on these core features of Java to make the rapid development of enterprise systems a practical proposition. We not only describe the specific Java enterprise packages and features of the J2EE throughout this book, but also cover many of the packages and features of the J2SE that have a common enterprise application. Thus, although this chapter provided only a summary of J2SE features such as those provided in the java.lang, java.util, java.io, and java.text packages, future chapters delve deeper into the J2SE features heavily utilized by enterprise applications, including a discussion of the java.net, java.rmi, java.security, and java.sql packages. Of course, throughout the remainder of the book, we also describe all of the Java packages used for standard Java enterprise development and with the J2EE. The next chapter provides an overview of such technologies.

Chapter 5. Java Enterprise System Architecture with the J2EE IN THIS CHAPTER • • • • • • •

The J2EE Model Ent erprise Java and J2EE Archit ect ure Dat a Connect ivit y Com m unicat ion Mechanism s Assurance Mechanism s Client Connect ivit y Web Connect ivit y

- 82 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •

Applicat ion Connect ivit y The J2EE Fut ure

This chapter describes the J2EE in the context of an overall enterprise systems environment. We discussed the needs of an enterprise system in Chapt er 1, "Ent erprise Archit ect ural Overview." Chapt er 2, " Obj ect - Orient ed Soft ware Developm ent for t he Ent erprise," and Chapt er 3, " Com ponent - Based Soft ware Developm ent for t he Ent erprise," presented arguments for the use of object-oriented technologies and component-based technologies in building such systems. Chapt er 4, " Java Foundat ions for Ent erprise Developm ent ," presented the basic features of Java that make it such an excellent language and platform for use in building enterprise systems. This chapter describes those object-oriented and component-based technologies that can be used to build enterprise systems using Java enterprise technologies and the J2EE. The J2EE model and Java enterprise technologies, means for data connectivity, client and user interfacing, communications enabling, systems assurance, Web enabling, and application enabling are considered part of an overall enterprise architecture. In addition to describing what the J2EE currently provides for developing Java enterprise systems, we highlight those key components used for building Java enterprise systems that fall outside the realm of J2EE environments. In this chapter, you will learn: • • • •

The model for developing enterprise applications using the J2EE. The top-level architecture for building Java enterprise applications with the J2EE as advocated by this book. The Java enterprise technology solutions for database connectivity, client and user interfacing, distributed communications and communication services, systems assurance, enterprise Web enabling, and enterprise application enabling. The future extensions targeted for J2EE-based development.

The J2EE Model Before there was a formal Java enterprise model of development, the Java Development Kit (JDK) versions 1.0 and 1.1 were the original standard platforms defined by Sun to create standalone Java-based applications and Web-based Java applets. The JDK did indeed offer many advantages for use in enterprise development projects by providing an easy-to-use and platform-independent approach to rapidly building enterprise systems. In addition to the core JDK platform support, a collection of enterprise APIs emerged, some of which were part of the JDK and others of which were offered as standard extensions to the Java platform. Java APIs useful to enterprise applications such as those for database connectivity and distributed communications were all employed by developers wanting to rapidly build enterprise applications with Java. The use of Java to build enterprise systems was catching on. In addition to the standard Java platform and standard Java extension APIs, many third-party Java-based APIs began to enter the market. In particular, Java-based COTS implementations of the CORBA distributed computing platform further stimulated interest in developing enterprise applications with Java. While Sun was originally touting Java as the platform for the World Wide Web and focusing on Java applets, the explosion in back-end server-side enterprise usage of Java by industry soon aligned Sun's marketing efforts to consider the enterprise application of Java more formally and seriously. Marketers originally coined the terms Java Technologies for the Enterprise (JTE) and Java Platform for the Enterprise (JPE) to refer to a collection of APIs that were extensions to the Java platform and had direct relevance to enterprise applications. However, the APIs were often developed by different groups and at times grew apart from one another. Furthermore, it was not always clear to developers just how these APIs could relate to one another and how they could be used to keep their systems open for use with different underlying vendor implementations of the various enterprise services. This is where the Java 2 Platform, Enterprise Edition (J2EE) entered the picture and attempted to address these needs. The

- 83 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

J2EE was introduced by Sun Microsystems in June 1999 as a standard platform and environment for building enterprise systems using Java.

J2EE Features The J2EE is defined as an umbrella platform and programming model for building Java enterprise systems for use with different underlying vendor implementations of an enterprise system infrastructure. The J2EE (ht t p: / / www.j ava.sun.com / j 2ee) is most accurately defined and scoped according to five standard documents and software libraries: •

Specification: The J2EE specification defines the requirements that a J2EE vendor product implementation must satisfy.



Programming Model: The programming model is cast in the form of a developer's guide explaining how application developers might use various aspects of the J2EE. The guide is primarily described at a conceptual and very high level with a sample application at the end of the guide.



Platform: The J2EE platform is the set of integrated enterprise API library software and development tools. The J2EE platform depends on installation of the J2SE v1.2 platform.



Reference Implementation: The J2EE reference implementation is a sample implementation of the underlying services utilized by the J2EE platform APIs. It is primarily meant to be used in early development and prototyping environments.



Compatibility Test Suite: The compatibility test suite is used by vendors to determine whether their implementation of the J2EE services satisfies the J2EE specification requirements.

J2EE Component-Container Architecture The J2EE model for enterprise application development involves a component-container approach to development as discussed in Chapt er 3. A J2EE container environment essentially offers the following: •

J2SE Platform: The standard J2SE v1.2 Java runtime environment atop of which the J2EE operates.



Java Enterprise APIs: A collection of standard Java enterprise API versions.



Java Enterprise Implementations:

- 84 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Any Java enterprise service provider implementations of the Java enterprise APIs. •

Deployment Services: An environment for configurably deploying J2EE components.



Management Services: Management services offered by the container for providing an efficient, scalable, and dependable computing environment.

J2SE v1.2 versus J2SE v1.3 It is important to highlight the fact that the J2EE v1.2 based architecture assumed by this book depends upon the J2SE v1.2 and not the J2SE v1.3. Indeed this choice of versioning by Sun may be confusing. That is, many folks wonder why "v1.1" still refers to the Java 1.1 platform, and "v1.2" applies to the Java 2 or J2SE platform, but "v1.3" also refers to the Java 2 or J2SE platform. In terms of what this all means to enterprise developers, the J2SE v1.3 platform is essentially the J2SE v1.2 platform with JNDI and RMI/IIOP included with the platform, whereas JNDI and RMI/IIOP are considered standard extensions to J2SE v1.2 platform users. The J2SE v1.3 also provides numerous performance, security, and GUI enhancements as well as bug fixes. Specifically, four major classes of components and their containers are defined within the J2EE specification. These four component-container classifications, depicted in Figure 5.1, can be classified according to whether they are client-oriented or server-oriented and whether they are Web-oriented or purely application-oriented. The four J2EE component-container models are described here: Figure 5.1. J2EE components and containers.

- 85 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



EJB Application Servers: Enterprise JavaBean components represent application-specific components built by a developer or third party to operate inside of an EJB application container environment. EJB container environments are implemented by third-party vendors to offer scalable application services to EJB component developers.



Web Application Servers: Web components come in two flavors: Java Servlets and JavaServer Pages (JSPs). Web components represent application-specific handling of requests received by a Web server and generate Web responses.



Applet Clients: Applets are Java applications that can run inside of a Web browser and offer a GUI inside of a Web browser. The J2EE specification outlines a methodology for hosting applets inside of a standardized applet container environment with added support for acting as J2EE-based clients to J2EE-based servers.



Application Clients: Application clients are Java-based clients that typically run on a user desktop or workstation and offer a GUI. The J2EE specification outlines a method ology for hosting application clients inside of a standardized application client container environment with added API support for acting as J2EE-based clients to J2EE-based servers.

In addition to the four classes of components and containers, Figure 5.1 also illustrates the basic component assembly model assumed by the J2EE. At the finest level of granularity,

- 86 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

both Web and EJB components can be grouped into a module that has its own componentlevel deployment descriptor (DD). A deployment descriptor describes configurable properties of container services and components utilized by a particular deployed instance of its associated components (for example, security levels, transactions semantics, initialization parameters). Modules and an application DD are assembled into concrete applications that run inside of a particular container environment. Application DDs are actually defined in such a way that multiple types of modules can be assembled into a cohesive application if a J2EE provider so chooses (for example, combining a Web module with one or more EJB modules to create an integrated Web-enabled enterprise application). Modules, applications, and their associated DDs are also deployed in their own type of JAR files. A Web module is deployed in a Web application archive (WAR) file with a .war extension. An EJB module is deployed in an EJB JAR file with a .jar extension. Enterprise applications composed of one or more J2EE modules are deployed in an enterprise archive (EAR) file with a .ear extension.

J2EE Restrictions Because J2EE container environments include an underlying J2SE platform and Java enterprise APIs, without further restrictions, J2EE components could simply perform all the operations that an application in a standalone J2SE environment could perform. However, this would violate the fundamental component-container model of the J2EE and affect a container's capability to provide management services for its components. This is why the J2EE specification defines a minimum set of permissions that scope which operations a J2EE-based component can invoke on its underlying J2SE and Java enterprise API environment. Although certain J2EE product service providers may allow for a wider set of permissions, J2EE-based component application developers are at a minimum restricted to the following set of permissions: •

EJB Application Servers: EJB application components can queue print jobs, create socket connections as a client (but not server connections), and read system properties.



Web Application Servers: Web components can also queue print jobs, create socket connections as a client, and read system properties. Additionally, Web components can load external libraries and can read and write files.



Applet Clients: Applet components can only connect to the server defined within its CODEBASE and can read a limited set of properties.



Application Clients: Application client components have the most freedom out of all J2EE-component types. Application clients can create socket connections as a client and accept and listen for socket connections as a server on a local machine's ports above and including port 1024. Application clients can also read system properties, queue print jobs, exit a JVM process, and load external libraries. Application clients can also perform various security-sensitive GUI operations such as accessing a clipboard, accessing an event queue, and displaying a window without a warning banner.

Enterprise Java and J2EE Architecture

- 87 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Although the J2EE is a centerpiece of Java enterprise development and a fundamental aspect of this book, this book focuses on more than just the development of components that operate inside of J2EE-based environments. We also describe many of the Java enterprise APIs that are part of the J2EE in general such that they can also be used in standalone Java environments and not necessarily used from within the context of a J2EE container. In addition to the standard Java enterprise APIs that are incorporated by the J2EE, we describe a host of other Java-based technologies that can be used to facilitate the practical construction of enterprise systems. Although such auxiliary technologies are currently outside of the J2EE scope, we suspect, and in certain cases are already aware of the fact, that in due time such technologies will become integrated with the J2EE platform. We comment on the future of the J2EE at the end of this chapter. There are many advantages to the approach taken by this book. For one, immediate widespread vendor availability of fully integrated J2EE-based container environments will be limited for some time as opposed to the availability of individually mature Java enterprise component API implementations on the market. Furthermore, many real-world enterprise system applications still have widely distributed and disparate legacy system and application needs that make it difficult to invest in J2EE-based environments for all distributed enterprise server scenarios. Rather, a standalone Java enterprise application may be just fine for certain enterprise system deployment scenarios. It will certainly be the case for many near-term legacy enterprise application integration (EAI) solutions to consider use of standalone Java application environments until EAI connector technologies can be integrated with the J2EE. For all of these reasons, we describe many of the Java enterprise APIs that can be used in standalone Java applications in a largely J2EE-independent and unrestricted fashion early in the book. We then focus on Web-enabling and application-enabling technologies later in the book in the context of using J2EE containers. Furthermore, we also describe how use of such J2EE environments can simplify usage of the Java enterprise APIs that were described in earlier chapters. After all, the aim of this book is to turn you into a well-rounded and wellinformed enterprise systems engineer.

Java Enterprise System Architecture Overview Figure 1.3 of Chapt er 1 presented a broad classification of the various enabling and service technologies used to create enterprise systems. Figure 5.2 shows the more concrete architecture solution components advocated by this book for building enterprise systems using Java enterprise technologies. The diagram in Figure 5.2 is primarily logical by nature and is not meant to depict a physical architecture for enterprise systems. Rather, the diagram depicts the various logical needs for construction of an enterprise system and the various Java enterprise technologies that are used to support such needs. The logical architecture defined within Figure 5.2 actually has many physical architecture permutations. Figure 5.2. The Java enterprise system logical architecture.

- 88 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

As you'll see in subsequent sections of this chapter, all the enterprise APIs specified within the J2EE are represented in Figure 5.2. Figure 5.2 also identifies a few technologies that we describe in this book that currently fall outside of the J2EE scope. Each logical enterprise component depicted in Figure 5.2 has a corresponding enterprise technology solution provided in the following fashion: •

Enterprise User Interfacing: Web-based Java applets and desktop Java application clients can be built using Java-based GUI techniques and can be hosted in standalone J2SE environments or inside J2EE container environments. Traditional non-Java–oriented Web browsing applications can also be used with J2EE-based Web servers. Additionally, non-Java– based clients can also interface with server-side components using distributed communication technologies such as CORBA, DCOM, and TCP/IP.



Enterprise Data Enabling: The Java Database Connectivity (JDBC) solution is used to communicate with databases. J2EE Web, EJB application, and application client containers all utilize the JDBC API. Standalone Java enterprise applications running outside of a J2EE environment can also be used with JDBC.



Distributed Enterprise Communications Enabling: Technologies for distributed communications such as CORBA, RMI, DCOM, TCP/IP, and Web-based HTTP are all possible within Java enterprise environments, whether they're embedded in Web servers, application servers, standalone Java applications, or enterprise user interface clients.



Common Services for Distributed Enterprise Communications: A host of communication services are possible within Java enterprise environments. Naming services enable the lookup of named objects across a network. Directory services allow for more sophisticated searching of objects via attribute descriptions of those network objects. Trading services offer a more dynamic means to connect with services on a network. Messaging services allow for the asynchronous communication of messages. Activation services are underlying services that activate

- 89 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

objects based on client requests. Transaction services allow for the management of atomic and dependable operations across distributed resources and clients. •

Enterprise Systems Assurance: Various properties of systems assurance such as reliability, availability, maintainability, safety, and security are more inherent properties of a system as opposed to a distinct service. However, Java-based enterprise environments encapsulate many security services with distinct APIs. CORBA has also defined security services within a CORBA Security Service Specification and is primarily useful for security interoperability across application environments.



Enterprise Web Enabling: Although HTML has been the most traditional format for creating Web pages, XML is a more flexible and extensible mechanism for describing data and controls such as those needed within Web pages. Java Servlets and Java Server Pages are the standard J2EE-based mechanisms for receiving Web-based requests and for generating HTML- or XML-based responses. Web-enabled applications can also take advantage of the various global services for distributed communications, communication services, and assurance services.



Enterprise Applications Enabling: XML can also be used to enable enterprise applica tions to communicate with other applications within and outside of a particular enterprise. EJBs are the primary means defined within the J2EE to create server-side application business logic. Various enterprise application integration technologies are also a part of application enabling. Enterprise-enabled applications can also take advantage of the various global services for distributed communications, communication services, and assurance services. Finally, when J2EE-based application enabling is not possible, a standalone Java enterprise application environment composed of a Java 2 platform and standard Java enterprise API extensions can be used.

Data Connectivity Enterprise information and knowledge are most often managed inside of a database management system (DBMS). Such data is often accumulated over many years and also is often heavily depended on by legacy applications. It should come as no surprise that such data is thus highly valued by an enterprise. Enterprises also end up creating strong dependencies and ties to particular vendor DBMS implementations. For all of these reasons, it is important to have a DBMS-independent solution for accessing enterprise data in a fashion that enables enterprise applications to remain stable despite changes in DBMS vendor product selections. The Java Database Connectivity API is an enterprise API that provides a means for accessing and managing enterprise data stored in a DBMS. The JDBC API is defined in a fashion that permits DBMS-independent construction of commands to access the database using a DBMS command language known as the Structured Query Language (SQL). As with most Java enterprise APIs, an underlying Service Provider Interface (SPI) allows a particular DBMS vendor interface to be adapted for use with the JDBC libraries and permit enterprise applications to use the same JDBC API. The JDBC API can be divided into three categories: •

JDBC 1.0 Core API: Defines most of the basic JDBC functionality.

- 90 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



JDBC 2.0 Core API: Includes all the functionality contained in the JDBC 1.0 version plus a host of new features for managing query results and manipulating new data types. The JDBC 2.0 core API is included with the J2SE, and with the J2EE by virtue of its inclusion with the J2SE.



JDBC 2.0 Standard Extension API: Offers a range of more sophisticated enterprise features useful in middle-tier servers for managing scalable database access.

There are two primary scenarios in which Java enterprise applications can utilize JDBC to access a DBMS. In a standalone J2SE application environment scenario, an enterprise application has unrestricted access to the JDBC API. In a J2EE application environment scenario, a J2EE container provides a set of management services that manage JDBC-based resources. The J2EE environment restricts some of the JDBC API operations allowed to be performed by J2EE components. J2EE application client, Web, and EJB container environments must support the JDBC 2.0 core API. Inclusion of JDBC with J2EE applet containers is optional. Inclusion of the JDBC 2.0 standard extension API is required for J2EE containers, but an underlying implementation is optional (although it is recommended for J2EE EJB container environments).

Communication Mechanisms Enabling applications for distributed communications is a fundamental necessity when building an enterprise system. An enterprise application may need to offer its services in a distributed server mode, or it may need to tap the services of a distributed server and act as a distributed client. Both modes of operation require an interface to some distributed communications code for enabling an application to communicate over a network. This book describes two main approaches for enabling an enterprise application to utilize distributed communications. One approach advocates use of a standalone Java enterprise environment that uses an underlying distributed communications API and implementation. Another approach advocates use of an underlying communications infrastructure embedded into a J2EE container environment that offers distributed communication services transparently to J2EE components. Regardless of the approach, a particular methodology of communications and underlying protocol must be selected to enable clients and servers to communicate with one another. These are the primary approaches adopted in this book: •

TCP/IP: The Transmission Control Protocol/Internet Protocol (TCP/IP), a standard protocol suite used on the Internet, serves as the underlying protocol for all distributed computing paradigms discussed in this book. Java provides a set of libraries that allow an application to communicate directly via TCP/IP and is thus equipped with the J2EE by virtue of its inclusion with the J2SE.



Web/HTTP: The Hypertext Transfer Protocol (HTTP) v1.0 is the protocol over TCP/IP used for communicating between Web browsers and servers. APIs for communicating directly via HTTP are provided by the J2SE. Furthermore, HTTP requests and responses are encapsulated by higher-level abstractions for use by programmers in J2EE Webcontainer environments. The use of a Secure Socket Layer (SSL) v3.0 protocol must also be available for use with HTTP to enable secure Web communications.

- 91 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



CORBA/IIOP: The Common Object Request Broker Architecture (CORBA) is an industry-standard and language-independent distributed object communications paradigm that transparently handles the mapping of object method calls to and from an underlying communications message data representation. The Internet Inter-ORB Protocol (IIOP), which is the underlying communications protocol used by CORBA, operates above TCP/IP. Although the term IIOP is frequently used, a higher-level protocol known as the General Inter-Orb Protocol (GIOP) is actually used above IIOP. Java IDL is a Java-based API and implementation of the CORBA communications paradigm, and it is equipped with the J2EE by virtue of its inclusion with the J2SE. However, although creating CORBA clients in a J2EE environment is possible for EJB, Web, and application client containers, only application client components can create their own CORBA server instances. There is no requirement for J2EE EJB containers to offer their services as CORBA servers transparent to the component developer, either.



RMI/JRMP: Remote Method Invocation (RMI) is the distributed object communications paradigm that was developed for use with Java. Java Remote Method Protocol (JRMP) is the original protocol used by RMI for communications under the RMI interface and also operates above TCP/IP. RMI/JRMP is equipped with the J2EE by virtue of its inclusion with the J2SE.



RMI/IIOP: RMI has also been adapted to operate over IIOP. With RMI/IIOP, Java-based applications that use the RMI distributed object communications interface can communicate with CORBA-based applications. RMI/IIOP v1.0 adds a few API features to RMI that must be included by J2EE EJB, Web, and application client environment vendors. However, the actual implementation of RMI/IIOP to enable RMI/IIOP-based clients and servers using the IIOP protocol is not a current requirement for the J2EE. Standalone J2SE v1.2 environments can use RMI/IIOP as a standard Java extension, whereas JDK v1.3 environments include RMI/IIOP.



DCOM: The Distributed Component Object Model (DCOM) is a Microsoft platform–specific distributed object communications paradigm. Java applications can also act as DCOM clients and DCOM servers. However, a Microsoft platform–specific Java environment is needed.

Use of the distributed communications paradigms alone enables one to build distributed application clients and servers. However, a set of common services hosted atop a distributed communications paradigm makes creating distributed enterprise applications an easier task. The core common services for distributed enterprise communications discussed in this book are listed here: •

Naming Services: Naming services are used to reference and look up distributed objects on a network in terms of a human-readable name. The Java Naming and Directory Interface (JNDI) is used to provide a common Java API to various underlying naming service implementations and types. A file system, an RMI registry, and a CORBA Naming Service are all examples of specific naming services accessible via JNDI. Additionally, naming services without current JNDI SPI mappings such as DNS and a means for mapping DCOM names to objects are also important to the Java enterprise developer.

- 92 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

J2EE EJB, Web, and application client environment vendors must include the JNDI v1.2 API with their products. Standalone J2SE v1.2 environments must use JNDI as a standard Java extension, whereas JDK v1.3 environments include the JNDI API. •

Directory Services: Directory services are a type of naming service that adds the capability to reference and search for distributed objects on a network in terms of descriptive attributes about the object. JNDI is also used to provide a common Java API to various underlying directory service implementations and types. NIS, NDS, and LDAP are all examples of directory services with JNDI-based interfaces. Additionally, the Microsoft Active Directory Service is also important for DCOM-based directory service lookups.



Trading Services: Trading services are a type of directory service that adds support for a more dynamic means to locate objects on a network and join communities of distributed services on a network. Trading services can also look up objects based on descriptive attributes, as well as based on object type. The CORBA Trading Service and Jini are both examples of trading services discussed in this book.



Activation Services: Activation services provide an important underlying mechanism for distributed communication paradigms to transparently bring a persisted object into active memory based on a client request. RMI, CORBA, and DCOM all have an underlying activation service framework. Additionally, the CORBA LifeCycle Service provides a means to create, copy, and move active objects in a distributed network. The Java Activation Framework (JAF) v1.0 provides a means to activate an object handler proxy based on received data and is used by J2EE EJB and Web environments to support the use of JavaMail.



Messaging Services: Messaging services provide an asynchronous means for sending and receiving messages on a network. The Java Message Service (JMS) v1.0 API is part of J2EE EJB, Web, and application client environments, but no underlying implementation is mandatory. The JavaMail v1.1 API for sending and receiving email messages is also part of J2EE EJB and Web environments, but only requires email sending implementation support. The CORBA Event Service, CORBA Notification Service, and CORBA Messaging specification are also types of messaging services important to Java enterprise applications and are discussed in this book.



Transaction Services: A transaction service provides a mechanism for encapsulating inseparable operations performed over a distributed network into an atomic operation. The CORBA Object Transaction Service (OTS) is mapped to Java by virtue of the Java Transaction Service (JTS). The Java Transaction API (JTA) is a higher-level framework for managing transactions and resources from Java enterprise applications. JTA v1.0 is required by J2EE EJB and Web environments with implementation support only required for API client demarcation of transactions.

Assurance Mechanisms Needless to say, there is not much demand in industry for enterprise applications that fail, are not available, cannot be maintained for upgrades and bugs, have security holes, or perhaps

- 93 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

cause safety hazards. Assurance involves providing software that can be depended on. Assurance may be defined according to one or more of the following qualities: •

Security: The likelihood that your system will operate in a secure and security breach–free fashion.



Reliability: The likelihood that your system will operate correctly and as intended.



Availability: The likelihood that your system will actually be operational and offering service. Scalability of your system to support growth in usage is one aspect of availability.



Maintainability: The likelihood that your system will be capable of being maintained, upgraded, and extended for future growth.



Safety: The likelihood that your system will operate in a safe and accident-free manner.

Many such qualities of assurance are more inherent properties of software rather than discretely definable components of software. In fact, process and techniques, such as the object-oriented and component-based software development techniques employed throughout this book, are very important to enable the creation of higher assurance software. Nevertheless, because security is a sensitive and important aspect of enterprise assurance, certain discrete aspects of security have been independently encapsulated in terms of software components. The CORBA Security Service Specification defines a set of specifications used in distributed CORBA environments to provide security. Security is also built into the Java 2 platform. Security in J2EE-based environments is inherited from the underlying J2SE platform's security features. Java security features can be tapped programmatically in standalone J2SEbased applications by use of the various Java security APIs. J2EE-based applications can take advantage of declarative security in addition to programmatic security. Declarative security refers to the specification of security features in the deployment descriptor associated with a J2EE-based component. The J2EE container environment then handles the management of security on behalf of the component. Java-based security helps provide identity and authentication, as well as authorization for your enterprise application environments. Identity and authentication involves the secure identification of a user associated with an object that is making a request of the system on behalf of that user (for example, a password-based login). Authorization involves the association of an authenticated user's identity with permission to access or use a particular system resource. Enterprise Java environments also have the capability to provide for the integrity and confidentiality of data exchanged and stored via a security-critical medium. Standard facilities for auditing security-critical events and providing nonrepudiation evidence of data transmissions and receptions are currently not inherent APIs of the J2SE or its standard extensions.

Client Connectivity Various types of clients can talk to Java enterprise server environments. As mentioned earlier, we can generally classify Java clients according to the categories of Java applet clients, Java

- 94 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

application clients, general Web browser–based clients, and non-Java clients. Clients implemented in Java, such as Java applets and Java application clients, can take advantage of the numerous Java-based GUI components, such as from the AWT and Swing libraries, to rapidly build user interfaces. However, use of Java-based clients will not always be possible in all situations for enterprise user interfacing. J2EE-based client containers will also not always be possible or practical. This is why we assume a much broader range of client interfacing techniques using open and standard distributed communication paradigms. Java applets are essentially Java applications embedded into Web browsers. Java applets can run inside of J2EE-based applet containers as well. J2EE applet containers assume a J2SE platform and thus may require the Java Plug-in product for Web browsers that do not come equipped with the J2SE and need to automatically download Java platform upgrades. Applets can use distributed communication paradigms such as RMI/JRMP, Web/HTTP, and CORBA/IIOP. A standard Web browser can also be used with J2EE-based Web-enabling applications. J2EE Web components can generate HTML and XML documents viewable inside of Web browsers. The J2EE container environment handles translating HTTP requests and responses to and from standard Java object abstractions. Java-based application clients can talk to Java-based servers using the various distributed computing paradigms described earlier. Whereas DCOM clients need to run inside of a Microsoft Java environment, all other Java application client types can operate inside of a standard J2SE-based environment. The J2EE also defines an application client container that has many of the standard Java extension APIs needed to communicate with J2EE-based servers. Various non-Java clients can communicate with Java enterprise servers. TCP/IP, CORBA/IIOP, and DCOM-based clients are the most significant examples of distributed computing paradigms usable by various non-Java clients. The type of client you can connect to your server will, of course, be dependent on the protocol supported by your particular Java enterprise application. J2EE-based EJB environments are currently required to support only RMI/JRMP implementations and thus are required to support only Java-based clients by consequence. Future versions of the specification open up J2EE-based EJB applications to support RMI/IIOP and CORBA/IIOP implementations.

Web Connectivity Enterprise Web connectivity involves providing a solution for handling Web requests and generating Web responses via a Web server. A Web server tier is often best thought of as a middle-tier layer whose responsibility is to handle Web-based client interface requests and to generate a new Web presentation interface for the Web client. Web server tiers often delegate to an enterprise application serving tier for any significant business logic processing that must be performed. The most popular need in Web browser data generation support requires Web presentation pages to be generated in the form of HTML documents. HTML is used to display content within a Web browser and also present user-interface controls that can be used to capture data and actions from a user. The eXtensible Markup Language (XML) is a more flexible and extendible type of language being integrated into Web environments as an extension to HTML. XML documents can represent data in a hierarchical form and can be accompanied by Document Type Definitions (DTDs), which describe the structure and semantics of a particular class of documents. Although XML has grown out of the World Wide Web, it also has a much broader application to the generic representation of data in general. Thus, data exchanged or stored via a particular medium can be described using the standard syntax of XML. In fact, J2EE deployment descriptors are described and stored in a standard XML format. This is why XML document parsing libraries are currently shipped with J2EE-based products. A standard XML API will be required of J2EE-based products in the future for general data exchange usage by J2EE applications. The Java API for XML Parsing (JAXP) is a standard Java extension that can be used in the meantime. Java Servlets is a Java API that encapsulates HTTP requests, HTTP responses, and HTTP session management interfaces. The J2EE allows Java Servlet components to operate inside of a J2EE Java Servlet Web container. The Web container handles the mapping of requests

- 95 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

to specific servlet instances and handles transforming request and response objects to and from the underlying HTTP I/O stream. The approach to Web connectivity advocated by this book recommends use of J2EE Java Servlet Web container environments as a key approach for enterprise Web enabling. JavaServer Pages are documents written in a scripting-based language. JSPs can interact with Java code and actually are described using a syntax considered to be familiar and easily comprehended by Web developers. JSPs are constructed to manage Web requests and responses as are servlets. JSPs are actually converted into Java Servlets by a J2EE JSP Web container environment when the JSP is first loaded or referenced. The approach to Web connectivity advocated by this book recommends use of J2EE JSP Web container environments as another key approach for enterprise Web enabling.

Application Connectivity Writing server-side enterprise applications can be significantly more difficult than writing client-side applications. Enterprise applications must be scalable, be secure, handle a large number of client requests, manage server-side resources, and manage external resources, among many other multiple client/application/resource management duties. This book describes two main approaches to accomplishing this task: standalone Java enterprise applications and J2EE-based EJB applications. Standalone Java enterprise applications are applications written on top of the Java platform that take advantage of standard Java enterprise API extensions. Standalone Java applications offer maximum flexibility in terms of choices for COTS and the capability to support many types of client connectivity paradigms. J2EE-based EJB container environments are also used to build enterprise applications. The container environment offers a vendor-independent interface to a host of enterprise services for building scalable enterprise applications. J2EE EJB container services reduce the amount of infrastructure hand-coding required of the developer and allow developers to concentrate on the development of business logic embedded within EJB components. However, the direct instantiation of distributed communication server instances (for example, RMI and CORBA) by application components in J2EE EJB application servers is not permitted by the container environment. You thus have to rely on those distributed communications server types that can be created by the J2EE container environment. J2EE EJB container environments are required only to support RMI/JRMP-based implementations. RMI/IIOP and full CORBA/IIOP mappings will be required in a future specification release. Some vendors do provide IIOP-based connectivity, however. Thus, enabling your J2EE-based servers to support connectivity from different distributed communication paradigm clients is currently a function of your particular J2EE vendor's offering. Standalone Java enterprise applications can, of course, support many types of client connectivity. Although creating and managing distributed server instances in standalone environments can require more hand-coding, it may be your only choice for certain client connectivity solutions in some cases. Furthermore, the scalability requirements and complexity of a particular enterprise application may not warrant the investment in a J2EEbased COTS EJB application server. For many other large-scale and complex enterprise application cases, however, use of a J2EE-based EJB application server may be your only option given your time-to-market needs, cost limitations, and human-resource availability. In addition to building J2EE-based EJBs or standalone Java enterprise applications, the enabling of legacy and embedded applications for access by the enterprise will also be a key consideration in enterprise application enabling. Enterprise application integration techniques require the provision of a means to integrate a legacy or embedded application into your Java enterprise application environment. Technologies such as CORBA, JMS, XML, the Java Native Interface (JNI), and J2EE Connectors are all examples of technologies used for EAI in some fashion. JMS, XML, and CORBA are particularly important for enterprise applications to interoperate with other enterprise applications in business-to-business (B2B) integration scenarios. B2B integration may occur between separately managed business units within an enterprise or with partner businesses external to an enterprise.

The J2EE Future

- 96 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The J2EE v1.2 specification defines a minimal set of requirements to be provided by service providers of J2EE-based containers in order to satisfy the J2EE compatibility test. Such minimal requirements more rapidly enable vendors to provide J2EE-compliant products. However, many enhancements above and beyond the J2EE v1.2 specification requirements are expected in the future. We can only hope that future versions of the J2EE specification will be defined in terms of compliance levels and packages such that more vendor implementation options may enter the marketplace. Nevertheless, Sun has made it clear that these are some potential future J2EE specification requirements: •

Application Client Service Enhancements: A future specification may define more deployment service and management service support for J2EE application clients.



Service Provider Interfaces: A future specification may define standard interfaces to be implemented by J2EE vendor service providers.



JDBC 2.0 Extension Implementation: A future specification may require J2EE EJB containers to implement the JDBC 2.0 Extension API.



RMI/IIOP Implementation: A future specification may require the implementation of the RMI/IIOP API.



IIOP Communication: A future specification may define a requirement for J2EE EJB containers to support IIOP-based communication with an EJB.



JMS Implementations: A future specification may define a requirement to provide implementation of the JMS messaging APIs.



Asynchronous EJB Messages: A future specification may define a means for JMS to direct asynchronous messages to EJBs.



JTA Implementations: A future specification may require the implementation of many APIs in the JTA.



Security Authentication and Authorization: A future specification may define a standard authentication and authorization interface to a J2EE environment via the Java Authentication and Authorization Service (JAAS) API standard Java extension.



Security Auditing:

- 97 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A future specification may define standard interfaces to audit security-critical–related events. •

Security Permission Extensions: A future specification may define a means for applications to specify their own types of security permissions that fall outside of the standard types provided by Java security.



Security Interoperability: A future specification may define standards for EJB environments operating in different domains to share security identification context information. This security interoperability will be based on CORBA/IIOP.



Transaction Interoperability: A future specification may define standards for EJB environments to share transaction context information. This security interoperability will be based on CORBA/IIOP.



EAI Connectors: A future specification may define standards for extending J2EE services to external non-J2EE applications.



XML APIs: A future specification may require XML APIs to be provided by J2EE containers. This API will most likely be the JAXP.



Administration Tools: A future specification may define standard interfaces for deployment, management, and system monitoring tools.

Conclusions This chapter presented an overview of the J2EE model for building enterprise systems using Java in the context of a more general Java enterprise system architecture. Given the set of enterprise-system needs outlined in Chapt er 1, this chapter demonstrated how Java enterprise technologies can satisfy those needs. You learned that although J2EE container environments provide many advantages for Web and application enabling, certain application scenarios and needs may not warrant use of a J2EE container environment. In such cases, many of the Java enterprise APIs that form the core of J2EE will indeed still be of use. They may, however, be useful only in certain standalone Java application configurations. Additionally, many other non-J2EE but Java-based enterprise APIs are also useful in building enterprise systems. Nevertheless, the J2EE is a centerpiece of current and future Java enterprise development. This chapter presented a Java enterprise system architecture useful in many different enterprise system scenarios. Solutions for enterprise database connectivity, client and user interfacing, distributed communications, communication services, systems assurance, Web enabling, and application enabling were all discussed in this chapter. Lo and behold…all enterprise system problems have solutions that can use Java enterprise technologies.

- 98 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Chapter 6. Enterprise User Interfacing IN THIS CHAPTER • • • • • •

The Dist ribut ed Ent erprise User I nt erface Java AWT Com ponent s Java Swing Com ponent s Ut ilit y and Accessibilit y Com ponent s Graphics and Mult im edia Com ponent s Web Page I nt erfaces

The user interface provides the presentation of your enterprise system to the enterprise user base. Although this book largely revolves around server-side and middle-tier enterprise systems development, it is important to possess a basic knowledge of which frontline userinterface methodologies will be available to connect to the enterprise systems you build. A knowledge of which user-interface techniques will be used to communicate with your enterprise system and their constraints will enable you to make more informed enterprise interface-enabling design decisions. This chapter provides an overview of the mechanisms available for presenting enterprise system information to users of an enterprise system. We provide only an overview of the various Web-based and Java-based GUI components and APIs that will typically be used to interface with a server-side and middle-tier enterprise system in this chapter. Because userinterface design is an extensive topic in and of itself, we do not cover the details of userinterface design here. Rather, we outline the technologies that can be used, as well as the specific technologies that should ideally be used, to interface with your enterprise system. In this chapter, we present: • • • • • •

An overview of the various technologies used for enterprise user-interface development that will need to interface with server-side and middle-tier enterprise systems. An overview of the Java Abstract Windowing Toolkit (AWT) GUI components, AWT architecture features, and deployment considerations. An overview of the Java Swing GUI components, Swing architecture features, and deployment considerations. An overview of extended and standard Java GUI components for providing drag-anddrop, printing, online JavaHelp documentation, and accessibility support. An overview of the extended and standard Java-based support available for providing graphics and multimedia to Java applications. An overview of the techniques available for providing Web-based user interfaces.

The Distributed Enterprise User Interface A user interface (UI) provides a means by which people interact with a system. Computerbased UIs are, of course, key for making computers useful to people. Graphical user interfaces (GUIs) are the most popular types of computer UIs. They present a graphical interface for people to interact with a system in a more user-friendly fashion. UIs connected to an enterprise system are very often distributed across many types of users and thus offer varied levels of access to the enterprise system and different styles of presentation. Figure 6.1 illustrates various enterprise users and the networks from which they access an enterprise system. The user type and network from which they interface with the system drives the style of interface offered to a particular user. For example, you may develop an enterprise user interface for prospective customers to shop via a Web-based enterprise store front. You may also provide a special interface to access certain enterprise information to be used exclusively by a business partner. Access to enterprise information via a corporate intranet or local area network (LAN) may also be provided to employees and contractors. Such networks may be used to conduct actual business for the enterprise or perhaps access information pertinent to a user's personal relation with the enterprise.

- 99 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figure 6.1. Enterprise users and networks.

Although enterprise user interfaces are extremely important additions to an enterprise system, the topic of interface design does lay outside of the scope of this book. This book focuses on how an enterprise system can be built, whereas the design of endpoint UIs is a broad topic in and of itself with a large variety of techniques existing to realize interface designs. Thus, in a Model-View-Controller (MVC) approach to describing a system, you might say that our interest in describing the "View" component of a system is in describing how an enterprise system can be designed to best enable such views, as well as describing what techniques exist to connect your enterprise from system infrastructure to end user. Thus, in this chapter we cover only the basic techniques that can be employed by you and your enterprise development team to provide a user interface for your enterprise Java applications. As an enterprise systems developer, you'll find that an understanding of enterprise user-interface design needs will help you develop a system that can most effectively enable it to be connected with various enterprise user interfaces. Figure 6.2 depicts the major enterprise user-interface classes that will be supported by the enterprise system development techniques employed by this book. Figure 6.2. Enterprise user interfaces.

- 100 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Note

We only describe the basic techniques and technologies that are used to build enterprise user interfaces in this chapter. Be sure to check out Appendix B, " Addit ional Resources," for more information. In Appendix B we provide references and Web links for many of the technologies discussed in this chapter.

CORBA-based client applications utilize a technology described in Chapt er 14, " Modeling Com ponent s wit h CORBA," and Chapt er 15, " CORBA Com m unicat ions," which enables a client written in any language to communicate with an enterprise using a standard protocol and interface technology. Thus any UI technique supported by the client language and platform can be used. Similarly, Chapt er 12, " Net work Com m unicat ions," describes a technique that uses lower-level standard communications protocol connectivity for bridging clients and servers via a protocol known as TCP/IP. Thus, clients that can communicate with an enterprise using this standard protocol can also be implemented in any language and can utilize any UI technique.

Client applications that are written for the Windows platform can talk with enterprise Java applications using a Windows-specific technology known as DCOM. We describe DCOM in Chapt er 17, " Modeling Com ponent s wit h COM/ DCOM," and Chapt er 18, " DCOM Com m unicat ions." Thus, Windows-based UIs may be easily customized to access your enterprise by exposing some of your enterprise's services using DCOM interfacing technology.

Web-based clients can utilize interface technologies communicated over a Web-based protocol known as HTTP. Java applets embedded into Web browsers can be implemented using Java-based UI technologies known as AWT and Swing. HTML-based, scripting language–based, and XML-based Web interfaces may also be utilized. We describe some of these techniques in more detail throughout this chapter. Specific details behind server-side Web enabling are discussed in Part VI , " Ent erprise Web Enabling."

Java-based application clients represent those desktop applications built using Java technology such as that offered by the J2SE or via J2EE application clients. Java UI

- 101 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

technologies such as AWT and Swing can be effectively utilized by Java applications. Other Java UI technologies have also been developed to enable the creation of more sophisticated Java user interfaces. We present some of these UI technologies in this chapter. As you'll see in Part I I I , " Dist ribut ed Ent erprise Com m unicat ions Enabling," Java clients can also act as TCP/IP, CORBA, and DCOM clients. Java also uses a distributed communications technology known as RMI that's described in Chapt er 16, " RMI Com m unicat ions."

Enabling your applications to speak HTTP, CORBA, TCP/IP, or DCOM may open your client base to a wider variety of legacy and newly created user interfaces. However, Java-based interface applications and applets themselves offer the capability to interface with enterprise systems using these and other enterprise connectivity solutions. Use of Java on the client also enables reuse of common development tools, processes, and application code shared between your enterprise user-interface and enterprise system design teams.

Part VI of this book describes how to Web-enable an enterprise system such that Web interface design techniques, including HTML, XML, and scripting languages, can be used in addition to Java applets. Web enabling an enterprise system represents one of the more important technical challenges for an enterprise systems developer to consider. The Webenabling solutions pursued by this book offer the most flexibility in enterprise user-interface design. Thus your solutions as an enterprise systems developer will not preclude certain enterprise user-interface solutions.

In summary, the enterprise system design practices of this book enable the use of a wide range of enterprise user-interface design approaches such as those depicted in Figure 6.2.

Java AWT Components The Abstract Windowing Toolkit is a set of Java packages that are used to create graphical user interfaces. The AWT has been equipped with the Java platform since Java 1.0. The AWT API follows a component-container model for GUI development in which GUI components are displayed inside of GUI containers according to particular layout policies. GUI-related events and interfaces for receiving these events are also defined by the AWT API. We describe the core support for GUI-based components, containers, and event handling by the AWT in this section. Indeed, many other classes and interfaces are strewn throughout various java.awt.XXX packages, and those also are covered in subsequent sections throughout this chapter.

AWT Components, Containers, and Layouts An AWT componentis a GUI-based component that will have some graphical presentation display presence and perhaps be capable of receiving events input from a user. AWT components may be, for example, buttons, check boxes, drop-down lists, scrollbars, and text fields. The java.awt package contains many of the core interfaces and classes used to create AWT-based user interfaces and graphics and images. The java.awt.Component abstract class is the superclass for most of the AWT GUI components. Such components in the AWT package actually use native platform UI libraries and are thus considered heavyweight components. AWT components can also extend directly from the Component class to support lightweight interfaces not bound to native-platform UI libraries. Finally, AWT components may also be menu-related, such as menu bars and menu items. The java.awt.MenuComponent abstract class is a superclass for such GUI-related menu components. An AWT container is itself a GUI-based component that contains one or more other GUI components. A window frame, a pop-up dialog window, a panel embedded in a window, and a scroll panel are all examples of containers that contain various GUI components. Because

- 102 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

containers are components, they can contain instances of one another. For example, a window frame may contain one panel to display a set of button components and another panel to display a canvas component that responds to button events by displaying information in some graphical fashion. The java.awt.Container class encapsulates a container of components. Containers are associated with layout managers that describe a policy for the placement of components within a container. The java.awt.LayoutManager interface defines a base set of container layout operations. The java.awt.LayoutManager2 sub-interface of LayoutManager adds the capability to specify constraints to be considered during the layout of components in a container. Various implementations of these interfaces are provided out of the box in the java.awt package to support various types of layout policies.

AWT Events A java.awt.AWTEvent abstract class encapsulates events that can be generated by GUIrelated events. Various types of AWT events that extend AWTEvent are defined in the java.awt.event package to deal with events such as actions on components, mousegenerated events, and keyboard-generated events. Events that are generated are received by registered listeners such as classes that implement one of the java.awt.event.XXXListener interfaces. A collection of java.awt.event.XXXAdapter abstract helper classes implement XXXListener interfaces with empty methods as a way to allow for classes to subclass these XXXAdapter classes and implement only relevant methods instead of every method defined on an XXXListener.

Deployment Considerations Because the AWT libraries have been a part of Java for some time now, many Web browsers that support the dynamic execution of Java programs as Java applets will be able to execute purely AWT-based Java programs without a need to download any extra GUI libraries. That is, the AWT libraries equipped with the Web browser software can be used without the overhead of downloading these libraries to a Web browser. Although newer browsers can support use of the Java Plug-in product for updating your Web browser with more current Java runtime libraries, requiring your enterprise user base to make use of browsers that support the Java Plug-in may not be feasible. Furthermore, those browsers that do support the Java Plug-in will still have to download updated large JVM libraries to handle code that supports Java GUI library updates. Chapt er 29, "Web Browsers and Servers in t he Ent erprise," describes the Java Plug-in in more detail. Many extensions to the AWT libraries also exist and are made available as third-party products. However, these libraries will impose additional overhead needed to download such libraries when used in Java applets. If your application needs to implement such functionality offered by the third-party product, it may make more sense to use the third-party product. Of course, Java applications installed on a client machine don't have application download time concerns, nor do they have GUI library compatibility concerns because updated GUI libraries can be installed along with the Java application.

Java Swing Components The Java Swing libraries offer an alternative means for developing Java-based GUIs. Swing was introduced to remedy many of the shortcomings of AWT. Swing's implementation is a lightweight GUI framework without the native platform dependence that is present in the AWT implementation. That is, Swing GUI elements don't depend on platform-specific GUI components as do AWT components, and thus they can offer the same look and feel when run on different platforms. Furthermore, Swing even encapsulates look and feel by providing a framework that allows one to plug in different look-and-feel styles to be used when displaying Swing GUI components. Aside from being part of the Java 2 platform, Swing is part of the JFC v1.1 that can be used with Java 1.1.

- 103 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Swing Components, Containers, Layouts, and Events The javax.swing library contains the core set of Swing elements used to implement GUIs using pure Java classes and interfaces. A new set of classes in this package beginning with the letter J represents lightweight components and containers without the level of native platform dependence required by AWT components and containers. The javax.swing.JComponent class is the base class for all Swing components. Various Swing components and containers extend from this base class. Most top-level containers use the JFrame, JDialog, or JApplet containers. Intermediate containers such as a JPanel, JScrollPane, and JTabbedPane are typically used inside top-level containers to hold Swing GUI components. Finally, although Swing containers can use the same layout mechanisms available with the AWT packages, a different suite of events and event handlers can be used by the Swing components. The javax.swing.event package encapsulates Swing-specific events that can be generated by Swing components. Event types and listeners particular to the Swing components are contained in this package.

Swing Models Many of the Swing components that are not containers can be associated with underlying models. Models encapsulate underlying representations of data and state. Such distinguishing encapsulation of models stems from Swing's goal of adhering to a Model-ViewController architecture. Models expose data and state used by GUI components as a separate entity that can be managed apart from the GUI component. As an example of a model, the JList component represents a GUI list whose contents are contained in a ListModel object and whose current selection is contained in a ListSelectionModel object.

Swing Look and Feel The javax.swing.plaf package provides an interface and a host of abstract classes used to define a pluggable look-and-feel framework. Different look-and-feel styles subclass the abstract classes in this javax.swing.plaf package. A default look and feel is implemented by classes in the javax.swing.plaf.basic package. A slightly more stylish look and feel known as the "metal" look and feel is implemented in the javax.swing.plaf.metal package. Finally, different look and feels can be combined with the default look and feel using entities in the javax.swing.plaf.multi package.

Swing Component Helpers In addition to the core Java Swing libraries, various packages are implemented in Swing to support the core Swing components. These helper libraries are listed here: • • • • •

The javax.swing.border package contains classes and interfaces used to draw borders around Swing components. A javax.swing.JColorChooser GUI Swing component offers a set of controls used to select colors to be used for various GUI operations and uses additional helper classes from the javax.swing.colorchooser package. A javax.swing.JFileChooser GUI Swing component provides a set of controls for selecting a file and uses additional helper classes from the javax.swing.filechooser package. A javax.swing.JTable GUI Swing component is used to display and manipulate data in a visual grid and makes use of additional helper classes from the javax.swing.table package. A javax.swing.JTree GUI Swing component enables the hierarchical display of data with additional helper classes implemented in the javax.swing.tree package.

- 104 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • •

The javax.swing.text package contains classes for managing GUI components such as javax.swing.JTextField and javax.swing.JTextArea that manipulate text on the screen. Such helper classes for text manipulation include text selection, highlighting, editing, and key map behaviors. The javax.swing.text.html and javax.swing.text.html.parser packages contain classes for allowing GUI-based editing of HTML text. A javax.swing.text.rtf.RTFEditorKit package offers minimal support for enabling Rich Text Format (RTF) editing capabilities. The javax.swing.undo package provides classes for implementing undo and redo capabilities in editors such as text editors.

Deployment Considerations Swing offers many advantages over AWT in terms of lighter-weight components, a consistent look and feel, and a richer set of APIs. Swing is thus a better solution for GUI-based Java applications than AWT. However, using Swing for Java applets that get downloaded to Web browsers is a bit more problematic. Older browser versions do not support Swing. Although newer browsers can support Swing via the Java Plug-in, the upgrade to a browser with new JVM libraries may still be an undesirable solution for some deployment scenarios. Furthermore, requiring your entire enterprise user base to utilize the latest browser upgrade to support Java Plug-ins may also be unfeasible. Chapt er 29 describes the Java Plug-in in more detail.

Utility and Accessibility Components Building enterprise user interfaces is not all about designing standalone and self-contained Java UI applications and applets. UIs often must interact with other UIs. Furthermore, common utilities such as printing and providing online help are embedded in almost every commercial-ready UI application. The Java platform, JFC, and standard Java extensions provide such utilities and accessibility packages for you to use in building commercial-ready enterprise UIs. We'll briefly describe some of the core utility and accessibility packages here, including data transfer between and within applications, drag-and-drop support, printing support, assistive technology interfacing, and online help support.

Data Transfer The java.awt.datatransfer package contains classes and interfaces for transferring data between applications, as well as within an application. A Transferable interface is implemented by those classes that support being transferred between and within applications. A Clipboard class encapsulates a means for transferring data to a Clipboard via copy, cut, and paste operations.

Drag and Drop The java.awt.dnd package contains classes and interfaces for more sophisticated dragand-drop capability between applications. A DragSource object encapsulates a source from which information is to be dragged. A DropTarget object encapsulates a sink into which information is to be dropped from a dragged source. DropTarget objects are associated with GUI components when they want to receive objects dropped onto them. Support is also provided by the Drag-and-Drop package to display visual cues from source to target during drag-and-drop operations.

Printing Built-in support for printing in Java was very minimal before Java 2. The java.awt.print package added in Java 2 contains a set of classes and interfaces to support general-purpose

- 105 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

printing. A PrinterJob class in this package serves as the primary class for configuring print jobs, spawning print dialogs, and actually submitting the job to a printer. Classes also exist to specify paper type and page formats.

Accessibility The JFC also has support for interacting with assistive UI technologies such as screen magnifiers, screen readers, Braille terminals, and speech-recognition systems. Such UI technologies open access to your enterprise system for users with physical disabilities. Classes and interfaces in the javax.accessibility package define an interface to which Java-based GUI applications adhere in order to enable connectivity to assistive UI technologies. GUI components must implement an Accessible interface, which returns an AccessibleContext object. The AccessibleContext object contains information useful for assistive technologies to interact with a Java-based GUI.

JavaHelp JavaHelp is a standard extension to the Java platform used for creating online documentation as a standalone window or a window that is embedded inside of another Java application or applet. JavaHelp comes with a default help viewer window offering toolbar controls, a navigation pane, and a document-content display window. The navigation pane includes builtin support for displaying a hierarchical table of contents, a document index, and a full-text document search interface. Although HTML-based documents are the default standard used for content viewing, JavaHelp can be extended to view various other types of help document formats.

Graphics and Multimedia Components Enterprise information can be conveyed and input in many forms other than those forms encapsulated by the GUI components of AWT and Swing. Images, sophisticated 2D graphics, and 3D graphics provide ways in which enterprise information can be conveyed in a more easily understood and digestible fashion. Furthermore, sound, video, and speech also offer important techniques for conveying enterprise information, as well as perhaps inputting information (for example, speech recognition). Finally, enabling input from various types of devices is also important for international acceptance of Java, as well as for providing efficient means to input data from devices such as pens and drawing pads. This section briefly highlights some of the built-in and extended standard graphical and multimedia APIs available for use with your enterprise Java UI applications.

AWT Images The Java 2 platform's built-in java.awt.Image class and java.awt.image package can be used for creating and manipulating images. Images can be rendered even while they are being read from an underlying stream. Image producers that implement the ImageProducer interface are responsible for creating a particular image. Image consumers that implement the ImageConsumer interface are endpoints interested in receiving a produced image. Various image filters that subclass the ImageFilter class can filter image data according to some algorithm as it passes from producer to consumer.

2D Graphics Java 2D is an API that enables a more sophisticated two-dimensional rendering of objects and images. For example, to create images (perhaps even animated images) that display the distribution of sales for a product over the years via a graph using gradients of colors along each graph, you might consider utilizing the 2D graphics APIs. APIs that have been created for Java 2D support are actually strewn throughout the Java AWT packages. The java.awt

- 106 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

package contains some of the base classes used to create 2D graphics and images. The java.awt.color package contains classes used to add various colors to 2D images. The 2D classes that relate to creating and transforming 2D geometrical shapes are contained in the java.awt.geom package. Image-rendering operations are contained in both the java.awt.image and the java.awt.image.renderable packages.

3D Graphics The Java 3D API is a collection of classes and interfaces used to create and manipulate three-dimensional graphics. Java 3D provides interfaces for creating and manipulating 3D shapes, as well as adding animation, texture, lighting, and shading to these objects. 3D charts, graphs, and displays can be useful to convey depth to information not readily apparent by examining 2D images. For example, a graphical depiction of a stock portfolio may choose an x-axis to depict time, a y-axis to depict value, and a z-axis to convey price/earning ratio.

Java Advanced Imaging The Java Advanced Imaging API is used for creating and rendering images according to sophisticated and perhaps application-specific algorithms. The Advanced Imaging API is extensible in that different algorithms and imaging techniques can be used with the framework. Advanced imaging is primarily useful for those applications that have either very specific or very advanced types of imaging requirements such as geological, astrophysical, and photographic applications.

Java Media APIs In addition to some of the packages described already, a Java Media API collection provides a Java Media Framework API for building applications whose media varies over time. Media in this case may include audio and video. For example, manipulation of audio WAV files falls under the auspices of the Java Media Framework API, as do MPEG and Quicktime video data. The Java Media Framework can be used as a building block for other time-based Java Media APIs. The Java Sound, Speech, Shared Data Toolkit, and Telephony APIs are all part of the Java Media API collection with a few of the APIs having or expected to have dependence on the Java Media Framework. The Java Sound API provides support for audio data manipulation, including the mixing and capture of MIDI-formatted data. The Java Speech API provides support for speech recognition, speech-based command control, and speech synthesis. The Java Shared Data Toolkit provides support for collaborative media-based interactions among users over a network, including collaborative whiteboards and chat rooms. The Java Telephony API is provided to enable telephone-based communications over a network.

Input Method Framework The Input Method Framework is part of the Java 2 platform and enables Java GUI text components to receive information from alternative input methods. Alternative input methods include different keyboard types, speech input devices, and pen-based input devices. International character sets input through different keyboard types can thus can be used to input text into Java-based GUI components. The java.awt.im package contains the core classes and interfaces used to support the Input Method Framework.

Web Page Interfaces Given the growth of the Internet and World Wide Web (WWW), many enterprises realize the importance of having a Web-based interface to their enterprise systems. Web pages displayed in a Web browser represent an important marketing brochure or perhaps employee work-flow interface for the enterprise. The exact type of interface depends on the end enterprise user. Customers, for example, may have an Internet Web interface to an enterprise

- 107 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

that allows them to purchase products from the company's "e-store." Employees may have an intranet Web interface that enables them to access and perhaps modify their benefits options, or even to interactively participate in conducting the very business of the enterprise. A key facet of this book, in fact, is to describe how enterprises can Web-enable their enterprise information systems such that prospective clients, customers, employees, contractors, and business partners can access these enterprise systems via a Web interface. Part VI describes how to connect an enterprise system to the Web in a rapid development fashion such that a scalable Web user base can be supported. Although we do focus on the engineering tasks involved with creating that connectivity in Part VI , we do not focus on the art of Web user-interface design. Such user-interface design topics are outside the scope of this book. However, in this section we briefly highlight those technologies involved with building Web interfaces using Java technology. After such a discussion, you will hopefully walk away from this chapter with a more cohesive view of the options available to you in providing a user interface for your enterprise system.

Web Interface Content Most of us are familiar with the use of a Web browser as the tool by which we access information over the WWW. Web browsers display Web pages, which display information to users in the form of text, hyperlinks, images, audio, and video. The Web user interacts with such Web pages using various GUI input techniques that depend on the Web interface technology being used. User input from a Web page is sent as a request to a Web server, which is then responsible for handling the request. Regardless of the technique for handling the request by the Web server, the result received from the Web server is one or more Web pages with which the user can continue to interact. Following are the primary techniques by which users interface with an enterprise via the Web and to which we refer throughout this book: •

HTML-Based Interfaces: HTML stands for Hypertext Markup Language. HTML is a text-based data format used by Web browsers to interpret how embedded text, hyperlinks, images, audio, and video should be displayed. HTML also contains GUI elements that can be used for input from the user. Chapt er 30, " Tradit ional Web Program m ing and Java," discusses HTML in more detail.



Client-Side Script-Based Interfaces: Client-side scripting languages are embedded into HTML documents and interpreted by a Web browser that can support such a language. Scripting languages offer more control and programmatic flexibility than do HTML pages for implementing dynamic behavior inside of a Web browser. We talk about scripting languages in Chapt er 30 in more detail.



Applet-Based Interfaces: Java applets are executable Java programs that can run inside of a Web browser. The power of Java's programmatic flexibility, richness of API, and GUI-based support make applets an attractive Web interface solution. Applets are downloaded to a Web browser by inserting specific tags into an HTML document. Running Java applets inside of Web browsers, however, has seen widespread application only for smaller programs due to a perceived performance issue in both code download and browser execution times.



XML-Based Interfaces:

- 108 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

XML stands for the eXtensible Markup Language. XML is an extension of HTML that supports a more flexible framework for describing information contained within a data stream. XML information is self-describing and is becoming the de facto standard for data interchange, including Web-based data interchange. Chapt er 31, " XML," is dedicated to our XML discussion.

Web Interface Generators Although Web browsers represent the end consumer of Web-based information such as HTML, client-side scripts, applets, and XML, this information must be generated in some fashion by the server side of an enterprise. Web servers are the frontline platforms responsible for performing or inducing the generation of such Web-based information. The techniques for performing such tasks are the focus of Part VI . Some common techniques used to generate Web-based information and the techniques we refer to and discuss throughout this book are listed here: •

File-Based Interface Generators: Web servers most commonly store HTML files on disk and serve them to Web browsers requesting such information. Other data referenced by such HTML files including images, scripting files, and audio files will also be retrieved from a serverside disk and served to the Web browser. We discuss Web servers more generically in Chapt er 29.



CGI-Based Interface Generators: The Common Gateway Interface (CGI) represents one of the oldest techniques for dynamically generating content for the Web browser. CGI applications are spawned as separate processes by a Web server and return information to the Web server that can be packaged up as a response to the Web browser. We provide an overview of CGI-based generation in Chapt er 30.



Script-Based Interface Generators: Scripting languages can also be executed on the server side inside of a Web server to dynamically generate Web page content. Server-side scripting requires that a server-side runtime engine process Web requests and generate responses to be sent to a Web browser. We provide an overview of Web server scripting approaches in Chapt er 30.



Servlet-Based Interface Generators: Java Servlets are Java-based code that executes inside of a Web server process to handle Web requests. Servlets can also dynamically generate and handle Web content and are one of two Web-enabling techniques that form the core of this book. Chapt er 32, " Java Servlet s," is dedicated to our servlet discussion.



JSP-Based Interface Generators: JavaServer Pages (JSPs) represent another approach for dynamically generating and handling Web content. JSPs are scripting language like elements having a Java syntax. Chapt er 33, " JavaServer Pages," is dedicated to our JSP discussion.

Conclusions

- 109 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Enterprise user interfaces built in other languages can be connected to your server-side enterprise Java system using distributed communications technologies such as TCP/IP, CORBA, and DCOM. Enterprise user interfaces can also be built using a large suite of standard Java-based libraries. User interfaces built as Java applications or applets can make use of two GUI component technologies built into the Java platform known as AWT and Swing. Whereas Swing is a lighter-weight GUI component model, AWT offers some Web browser deployment advantages when used inside of Java applets. Various extended Java-based UI utilities and accessibility APIs also make Java-based UIs more feature rich by supporting connectivity to printers, drag and drop between applications, online help, and connectivity to assistive technologies. A suite of extended Java-based graphics APIs for 2D, 3D, and high-resolution graphics as well as multimedia APIs for sound, speech, and video also enhance the capabilities of Java-based UIs. Web-based interfaces employ various technologies, including HTML, scripting languages, Java applets, and XML. Generators of Web-based content include file-based, CGI, scripting-language, Java Servlet, and JavaServer Page Web-enabling techniques.

Chapter 7. Modeling Components with JavaBeans IN THIS CHAPTER • • • • • • • •

JavaBeans Overview JavaBeans Cont ainers JavaBeans Event s JavaBeans Propert ies JavaBeans I nt rospect ion JavaBeans Persist ence JavaBeans Cust om izat ion The I nfoBus

JavaBeans provide a way to define methods, events, and properties for Java classes such that they can allow external manipulation and customization during design-time. Component event registration and delivery, recognition and utilization of properties, customization, and state persistence are all built into this model. This chapter describes usage of the JavaBeans component model in the context of how a user may create components for enterprise applications. This chapter provides a simple introduction to the JavaBean component model and is not meant to serve as an in-depth coverage of JavaBeans. It is simply meant to introduce the basic elements of one of the original Java-based component models and serve as a premise for understanding the other more enterprise-relevant component models described throughout the rest of the book. We particularly want the reader to be able to distinguish between the JavaBeans component model discussed here and the Enterprise JavaBeans component model discussed later in the book. JavaBeans and Enterprise JavaBeans are often mistakenly thought to be similar, and this chapter should help make clear the precise nature and application of regular JavaBeans. Furthermore, the JavaBeans component model is also relevant to understanding how JavaServer Pages can interact with server-side JavaBean objects as described in Chapt er 33, " JavaServer Pages." In this chapter, you will learn: • • •

The basic architecture and concepts behind the JavaBeans component model. The means by which JavaBeans are embedded in applications for design-time manipulation and the basic requirements of a JavaBeans component. The JavaBeans event model.

- 110 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • •

The means by which JavaBeans expose controllability and visibility of their internal nature and structure. The means by which JavaBeans allow the persistence of their state. The means by which JavaBeans enhance their design-time customizability via GUI property editors and arbitrary GUI customizers. The mechanisms by which JavaBeans can better communicate with one another via the InfoBus architecture.

JavaBeans Overview The JavaBeans architecture was one of the first comprehensive standard component-based models to grace the Java platform. JavaBean components are Java classes that adhere to an interface format such that method names, underlying behavior, and inherited or implemented behavior are structured in such a way that the class can be treated as a standard JavaBean component. Containers of these components can then interact with the JavaBean in a standard fashion. This facilitates the JavaBean's capability for being deployed in various design tools and runtime environments where the JavaBean's standard design-time and runtime interface behavior can be relied on. So how is all of this accomplished? Figure 7.1 depicts a top-level architecture of the JavaBeans component model. At the top of this diagram is shown a JavaBean container, which provides the context and environment in which a JavaBean operates. The Java 2 platform has begun to more rigidly standardize this container environment for JavaBeans. The JavaBean component represents the JavaBean that you as an applications developer create or that you perhaps use. Figure 7.1. The JavaBeans architecture.

JavaBeans can generate events in a standard way according to the JavaBean event model and expose standard event interfaces. JavaBeans can also expose standard accessor methods for getting and setting properties of a JavaBean in a standard fashion. Property manipulation also includes standard interfaces for changes in property values, as well as the generation of property change events by JavaBeans in a standard fashion. Beans may also be analyzed by a container using JavaBean introspection facilities. Furthermore, if the generic means by which manipulating a JavaBean as provided by a container implementation is not sufficient, then interfaces for JavaBean customization may also be utilized. The persistence of a JavaBean component's state may also come in handy with particular consideration for deployment in a JAR file. Finally, a standard extension to the JavaBean's platform known as the InfoBus pro vides a standard mechanism for JavaBean components to pass information among themselves. Integrated Development Environments (IDEs) such as Symantec's Visual Café and Inprise/Borland's JBuilder tools provide container implementations within which your JavaBean can be manipulated during design-time. Design-time manipulation of a JavaBean's

- 111 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

events, properties, and customization features is a key feature of the JavaBean component model. The JavaBeans Development Kit (BDK), downloadable from the Sun Web site at ht t p: / / j ava.sun.com / beans/ soft ware/ bdk_download.ht m l, provides a minimalist environment for creating JavaBean components and includes a reference JavaBean container known as the "BeanBox." The basic JavaBean component APIs are contained in the java.beans package equipped with the Java 1.1 and 1.2/2.0 platforms. The newer java.beans.beancontext package provides standard interfaces to JavaBean container environments and is equipped with the Java 1.2/2.0 platform. The InfoBus standard extension to Java can be retrieved from ht t p: / / j ava.sun.com / beans/ infobus/ and used with the Java 1.2/2.0 platform. Throughout the chapter, we introduce the basic elements of the JavaBean component architecture with a few examples. We first describe a very basic container/component infrastructure and incrementally build on a core example with additional JavaBean capabilities throughout the rest of the chapter. Because an in-depth discussion of JavaBeans development is beyond the scope of this book, we have omitted some sample code from the chapter and instead refer you to the sample code on the CD. Note

All the sample code that we incrementally build on and to which we refer throughout this chapter can be found on the CD in the examples\src\ejava\beansch7 directory. Furthermore, in the interest of keeping this chapter short and simple, we often exclude exception handling and other code elements from the snippets that we incorporate throughout the chapter. The complete collection of source code can be found on the CD in the examples\src\ejava\beansch7 directory.

Note that a run.bat file is also included with this code as a sample Windows script file for building the code example. This run.bat file compiles the sample code and creates a JAR file that can be loaded by a JavaBeans container environment. Refer to Appendix A, " Soft ware Configurat ion," for general build and execution instructions for all sample code on the CD.

Although many JavaBeans examples found in literature are created with an illustration of a GUI-based JavaBean, our sample code demonstrates a more enterprise business logic– oriented example of a JavaBean. A basic auditing bean is created that can be used in a nonvisual fashion to implement a basic service for auditing events that can occur in an enterprise system.

JavaBeans Containers JavaBean components operate inside of a JavaBean container environment. In the Java 1.1 model for JavaBeans, the container environments were loosely defined environments provided by IDEs or other environment implementations to host JavaBean components. It was the JavaBean component model that was standard and well-defined. The Java 2 platform extends the container model to support more standard JavaBean container interfaces. We explore the JavaBean container model in this section, along with the most basic JavaBean component requirements needed for a JavaBean to operate inside of a JavaBean container. Subsequent sections build on the basic JavaBean component model. Finally, we briefly explore the more standard JavaBean container model provided in the Java 2 platform. Figure 7.2 depicts the basic architecture and relationship between JavaBean components and their containers. JavaBean containers instantiate one or more JavaBean component

- 112 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

instances using one of the java.beans.Beans.instantiate() methods. JavaBean components can then be manipulated via the JavaBean container according to the standard component model rules to which the JavaBean components adhere. JavaBean containers are most often implemented inside of an IDE or another JavaBean environment. JavaBean components are implemented by applications developers. Figure 7.2. JavaBeans containers and components.

JavaBean Containers When creating JavaBeans, you will most likely not need to create a JavaBean container because you, as an applications developer, will often use an IDE or another JavaBean container environment into which you'll plug your standard JavaBean components. Nevertheless, we will talk about JavaBean containers here and even develop a simple sample container to enhance our capability to manipulate the JavaBean component that we create in this chapter. A basic JavaBean container must inherit from the java.awt.Container class or one of its subclasses. Both AWT- and Swing-based components have containers that extend this class or one of its subclasses, but purely Swing-based JavaBean components may also have containers that directly extend the javax.swing.JComponent class or one of its Swing container subclasses. As an example of a JavaBean container, the ejava.beansch7.AuditBeanContainer extends the javax.swing.JPanel class (which extends the javax.swing.JComponent). The AuditBeanContainer holds a reference to an ejava.beancsh7.AuditBean JavaBean instance, which we will discuss shortly. The AuditBeanContainer's constructor instantiates an instance of an AuditBean by calling the static instantiate() method on the java.beans.Beans class with a null ClassLoader and fully qualified AuditBean classname as parameters. The null ClassLoader designates the fact that the system class loader is to be used. Additionally, getter and setter methods for the AuditBean have also been added to the AuditBeanContainer as convenience methods. Only a portion of the

- 113 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

AuditBeanContainer code on the CD is shown here, with exception handling and other features excluded for simplicity: public class AuditBeanContainer extends JPanel { private AuditBean auditBean; public AuditBeanContainer() { ClassLoader useClassLoader = null; auditBean = (AuditBean)Beans.instantiate(useClassLoader, "ejava.beansch7.AuditBean"); // Exception handling and other code excluded here… } public AuditBean getBean(){

return auditBean; }

public void setBean(AuditBean newBean) {

auditBean = newBean; }

// More code to show later in the chapter… }

JavaBean Components JavaBean components must adhere to a few simple rules to satisfy the JavaBean component model and be callable from a JavaBean container. We'll introduce only the most basic rules in this section and discuss additional rules of JavaBean component modeling in subsequent sections on JavaBean component events, properties, methods and introspection, persistence, and customizers. The most basic rules of JavaBean component standard modeling are that the JavaBean be a public class, have a default public constructor with no parameters, and implement the java.io.Serializable interface. If the JavaBean component is to be a visual bean, it should also extend the javax.swing.JComponent class if it is a purely Swing-based bean, and the java.awt.Component class if it is AWT-based. As an example of a JavaBean component, the public ejava.beansch7.AuditBean class implements an empty default constructor. The AuditBean class also implements an auditMessage(String) method that logs a message String and current date to a log file via a PrintStream. Although a default log filename is assumed for now, a subsequent section demonstrates how such a file can be configured via JavaBean properties. Only a portion of the AuditBean code on the CD is shown here, with exception handling and other features excluded for simplicity: public class AuditBean implements Serializable { private transient PrintStream streamToWrite; private final String DEFAULT_FILE_NAME = "default.txt"; private File file = new File(DEFAULT_FILE_NAME); // More variable definitions to show later in the chapter… public AuditBean() { // default constructor, it should be implemented for a bean } public void auditMessage(String message) { Date nonCreditAuditDate = null; if(streamToWrite == null ){

- 114 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

FileOutputStream foutStream = new FileOutputStream(file); boolean flushOut = true; streamToWrite = new PrintStream(foutStream,flushOut); // Exception handling excluded… } Date currentTime = new Date(); String auditMessage = message + " : " + currentTime; streamToWrite.println(auditMessage); } // More method definitions to show later in the chapter… }

JavaBean Context In addition to the loosely defined Java 1.1 means for providing a JavaBean container environ ment, the java.beans.beancontext package now equipped with the Java 2 platform provides a more standard means for implementing an environment for JavaBean components. JavaBean contexts define an environment in which a bean's lifecycle can be managed in a standard fashion in addition to providing a standard interface for beans to interrogate their environment, access standard container services, and receive container environment information. Figure 7.3 depicts this newer JavaBean context architecture. Figure 7.3. JavaBean context.

The BeanContext interface is the root of all JavaBean container environments using this newer JavaBean context model. The BeanContext extends the java.util.Collection interface and thus defines add, remove, and other operations for manipulating collections of objects. In the case of a BeanContext, it can contain JavaBean components and other BeanContext objects. The BeanContext interface also extends the BeanContextChild

- 115 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

interface, which adds the capability for a BeanContext to obtain a handle to its containing BeanContext environment if it has one. JavaBean components also wanting access to their BeanContext environment can implement the BeanContextChild interface. JavaBean containers that want to provide services to their JavaBean components can implement the BeanContextServices interface. Services are added to the container environment using the BeanContextServices.add() method. Those services may then be retrieved by the JavaBean component after it obtains a handle to its JavaBean container environment and then via a call to getService() on the container implementing the BeanContextServices interface. Although we do not expand on the use of the BeanContext in our sample JavaBean here, you can think of our AuditBeanContainer as a JavaBean container that could implement the BeanContext or BeanContextServices interface. The AuditBeanContainer could then create an AuditBean JavaBean component instance using the Beans.instantiate(ClassLoader, String, BeanContext) interface in which the AuditBean instance could be created with a reference to the AuditBeanContainer object itself. The AuditBean operating inside of the AuditBeanContainer could then utilize the standard interfaces defined by the BeanContext or BeanContextServices interface to interact with its JavaBean container environment.

JavaBeans Events JavaBean container environments can receive notification of JavaBean component events and allow for the design-time selection of which events a JavaBean component will respond to if the JavaBean component adheres to a few simple rules. Public add and remove methods on a JavaBean component must be defined in a standard fashion to add and remove event listeners, respectively. JavaBean containers can then add and remove references to event listeners with the JavaBean components that allow for the container to interact with a component's events. Events on JavaBean components can be registered with a bean if it implements a method of the form addXXXListener(XXXListener), where XXX is the name of some event type. Similarly, events can be unregistered if the bean implements a method of the form removeXXXListener(XXXListener). As a final note, if your JavaBean component allows only one listener to be registered for events at a time, the addXXXListener(XXXListener) method should declare that it throws a java.util.TooManyListenersException. These rules for a JavaBean component and the relationship between it and a listener (for example, XXXListener) and an event type (for example, XXX) are shown in Figure 7.4. The XXXListener extends the java.util.EventListener class or one of its subclasses. Figure 7.4. JavaBean events.

- 116 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A JavaBean container may utilize one of the standard Java listeners or an application-specific listener. The JavaBean container may simply hold references to a listener or implement a listener interface itself. Events generated from a JavaBean component extend the java.util.EventObject class or one of its subclasses. As an example of a simple audit event that can be generated from our AuditBean class, we create an ejava.beansch7.AuditEvent class. It has two constructors, one of which can receive an AuditBean instance and another of which can receive an AuditBean instance and audit message String. A getMessage() method returns a handle to the associated audit message String. The AuditEvent class is rather simple and is shown in its entirety here: package ejava.beansch7; import java.util.EventObject; public class AuditEvent extends EventObject { private String auditMessage; public AuditEvent(AuditBean source){

super(source); }

public AuditEvent(AuditBean source, String message) { this(source); auditMessage = message; } public String getMessage(){ return auditMessage; } } An ejava.beanch7.AuditListener interface is implemented by objects that want to obtain notification of generated AuditEvent objects from a JavaBean component. The AuditListener is defined as follows in its entirety: package ejava.beansch7; import java.util.EventListener; public interface AuditListener extends EventListener { public void auditEvent(AuditEvent e); } Our AuditBean component can then be made to work with events in a standard fashion for use by containers. We extend our AuditBean class defined previously to first include a Vector collection of audit listeners. A notifyAuditEvent() method has also been added

- 117 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

to the AuditBean class to notify each listener in the Vector of listeners of a generated AuditEvent containing both the AuditBean source reference and an audit event message String. This notifyAuditEvent() method is called at the very end of the auditMessage() method. Finally, we also implement addAuditListener() and removeAuditListener() methods so that our AuditBean can satisfy the requirements of the JavaBean component model for enabling events to be received by JavaBean containers. Only the addition of code for our JavaBean component to support events is illustrated here: public class AuditBean implements Serializable { // List of Listeners to be notified of an event private Vector auditListeners = new Vector(); // Other member variables defined not shown… public void auditMessage(String message) { Date nonCreditAuditDate = null; if(streamToWrite == null ){ FileOutputStream foutStream = new FileOutputStream(file); boolean flushOut = true; streamToWrite = new PrintStream(foutStream,flushOut); // Exception handling excluded… } Date currentTime = new Date(); String auditMessage = message + " : " + currentTime; streamToWrite.println(auditMessage); notifyAuditEvent(auditMessage); } protected void notifyAuditEvent(String auditMessage) { Vector listeners = null; AuditEvent auditEvent = new AuditEvent(this, auditMessage); synchronized(this) { listeners = (Vector) auditListeners.clone(); } for (int i = 0; i < listeners.size(); i++) { AuditListener auditListener = (AuditListener)listeners.elementAt(i); auditListener.auditEvent(auditEvent); } } public synchronized void addAuditListener(AuditListener auditListener) { auditListeners.add(auditListener); } public synchronized void removeAuditListener(AuditListener auditListener) { auditListeners.remove(auditListener); } // Additional methods not shown… }

JavaBeans Properties

- 118 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Properties defined on a JavaBean are those attributes of the component defined in a standard way such that the values can be set during design-time. Thus, for example, a property on some generic Printer JavaBean component may define whether a printer supports color printing. JavaBean properties must have public getter and setter methods defined on the JavaBean component according to a particular standard pattern in order for JavaBean container environments to recognize JavaBean properties. JavaBean properties come in various flavors, as illustrated in Figure 7.5. Simple properties and Boolean properties simply rely on a standard naming convention for getter and setter methods on a JavaBean. Array properties allow for the getting and setting of entire arrays, whereas indexed properties allow for the individual getting and setting of array elements by using an array index number. Bound properties are those properties whose changes in value must be broadcast to property change listeners. Vetoable properties are those properties whose changes in value must be validated by vetoable property change listeners before the changes are effected. We expand on these various property types below. Figure 7.5. JavaBean properties.

Simple Properties As illustrated in Figure 7.5, simple properties adhere to a few simple rules for general properties and Boolean properties. Objects defined as properties must be Serializable as a first rule. Getters for simple properties are defined according to

- 119 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

getSimplePropertyName(), returning the property type in which the SimplePropertyName in the getter name is the name of the simple property and must be preceded by the word get. Setters for simple properties are defined according to setSimplePropertyName(), taking a property type as an input parameter and requiring that SimplePropertyName in the setter name correspond to the simple property name and be preceded by the word set. The exception to this rule is for boolean values where the getter differs in that instead of get, the word is precedes the property name. As an example, our AuditBean may now be extended to support two simple properties. A getFile() getter and a setFile(File) setter are first added for our Serializable File object. Additionally, a setFile(String) method is also added as a helper to first create a File object from a filename String and then call setFile(File). As an example of a calculated simple property with no underlying attribute for the property, we also define the getFileName() and setFileName(String) methods, which are recognized as simple fileName properties. For example: public class AuditBean implements Serializable { private final String DEFAULT_FILE_NAME = "default.txt"; private File file = new File(DEFAULT_FILE_NAME); // Other member variables defined not shown… public File getFile(){

return file; }

public void setFile(File newFile){ file = newFile;} public void setFile(String newFileName) { File file = new File(newFileName); setFile(file); } public String getFileName(){

return file.getName(); }

public void setFileName(String fileName){

setFile(fileName); }

// Other method definitions not shown… }

Array and Indexed Properties Arrays of properties are treated similarly to the way in which simple properties are treated. Figure 7.5 illustrates the convention for array properties. A getArrayPropertyName() method returns an array of property types with ArrayPropertyName corresponding to the name of the array property. A setArrayPropertyName() takes an array property as a parameter with ArrayPropertyName also corresponding to the name of the array property. For example, an underlying array of user group names may be retrieved and set using this: private String[] userGroups = new String[100]; public String[] getUserGroups(){ return userGroups; } public void setUserGroups(String[] groups){ userGroups = groups; } You can also set and get indexed properties as shown in Figure 7.5. A getIndexedPropertyName(int) method returns an element of a property collection given

- 120 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

an index number into that collection with IndexedPropertyName corresponding to the name of the indexed property. A setIndexedPropertyName(int, IndexedPropertyType) takes an index and a property element as parameters with IndexedPropertyName also corresponding to the name of the indexed property. For example, underlying indexed user group names may be retrieved and set using this: private String[] userGroups = new String[100]; public String getUserGroup(int idx){ return userGroups[idx]; } public void setUserGroup(int idx, String group){ userGroups[idx] = group; }

Bound Properties Bound properties provide a mechanism for notifying listeners of changes in a JavaBean component's property value. As shown in Figure 7.5, listeners implement the PropertyChangeListener interface and receive PropertyChangeEvent objects that have been generated by JavaBean components. PropertyChangeEvent objects contain a property name, an old property value, and a new property value to which the listener may want access. The JavaBean component can use the PropertyChangeSupport helper class to fire the actual event to be received by the listeners. A PropertyChangeSupport object is constructed with a reference to the JavaBean component instance, and it relies on the fact that the JavaBean implements addPropertyChangeListener() and removePropertyChangeListener() methods to add and remove property change listeners, respectively. One of the PropertyChangeSupport.firePropertyChange() methods can be used, passing in such information as the property name, old value, and new value. As an example, our AuditBean may be extended to support bound properties indicating when an audit file changes as shown here: public class AuditBean { private PropertyChangeSupport propertyChange new PropertyChangeSupport(this); // Not all variable definitions shown here…

=

public void setFile(File newFile) { File oldFile = file; file = newFile; propertyChanage.firePropertyChange("file", oldFile, newFile); fileChanged(file); } public void fileChanged() { FileOutputStream foutStream = new FileOutputStream(file); boolean flushOut = true; streamToWrite = new PrintStream(foutStream,flushOut); // Exception handling excluded… } public void addPropertyChangeListener( PropertyChangeListener propertyChangeListener)

- 121 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

{ propertyChange.addPropertyChangeListener(propertyChangeListener); } public void removePropertyChangeListener( PropertyChangeListener propertyChangeListener) { propertyChange.removePropertyChangeListener( propertyChangeListener); } // Not all methods shown here… } An AuditPropertyChangeAdapter class acts as a simple PropertyChangeListener implementation: public class AuditPropertyChangeAdapter implements PropertyChangeListener { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { System.out.println("Property Name :"+ propertyChangeEvent.getPropertyName()); System.out.println("Old Value :" + propertyChangeEvent.getOldValue()); System.out.println("New Value :" + propertyChangeEvent.getNewValue()); } } A JavaBean container can then create an instance of our custom AuditPropertyChangeAdapter property change listener and register it with the AuditBean for bound property change events, as we do here in the constructor of our AuditBeanContainer: public class AuditBeanContainer extends JPanel { private AuditBean auditBean; public AuditBeanContainer() { auditBean = // instantiate bean AuditPropertyChangeAdapter auditPropertyChangeAdapter = new AuditPropertyChangeAdapter(); auditBean.addPropertyChangeListener( auditPropertyChangeAdapter); // Exception handling excluded here… } }

Constrained Properties Constrained properties are similar to bound properties, but the change in value of a property must first be validated by all listeners before the value change can be effected by the JavaBean component. Any listener may veto the property change, and the JavaBean component then agrees to not effect the change. As shown in Figure 7.5, listeners implement the VetoableChangeListener interface and receive PropertyChangeEvent objects that have been generated by JavaBean components. The JavaBean component can use the VetoableChangeSupport helper class to fire the actual event to be received by the listeners. A VetoableChangeSupport object is constructed with a reference to the JavaBean component instance and relies on the

- 122 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

fact that the JavaBean implements addVetoableChangeListener() and removeVetoableChangeListener() methods to add and remove vetoable property change listeners, respectively. One of the VetoableChangeSupport.fireVetoableChange() methods can be used by passing in such information as the property name, old value, and new value. If any of the listeners veto the change from being made, a PropertyVetoException will be thrown. As an example, our AuditBean may be extended to support vetoable properties indicating when an audit file changes as shown here: public class AuditBean { private VetoableChangeSupport vetoableChange = new VetoableChangeSupport(this); // Not all variables shown here… public void setFile(File newFile) { File oldFile = file; try { vetoableChange.fireVetoableChange("file", oldFile, newFile); file = newFile; fileChanged(); } catch(PropertyVetoException propertyVetoException) { // Some of the listeners does not like to change the file file = oldFile; } } public void addVetoableChangeListener(VetoableChangeListener vetoableChangeListener) { vetoableChange.addVetoableChangeListener(vetoableChangeListener); } public void removeVetoableChangeListener( VetoableChangeListener vetoableChangeListener) { vetoableChange.removeVetoableChangeListener(vetoableChangeListener); } // Not all methods shown here… } A simple AuditVetoPropertyChangeAdapter serving as a VetoableChangeListener vetoes a change if the audit filenames are the same: public class AuditVetoPropertyChangeAdapter implements VetoableChangeListener { public void vetoableChange(PropertyChangeEvent propertyChangeEvent) throws PropertyVetoException { String propertyName = propertyChangeEvent.getPropertyName(); Object oldValue = propertyChangeEvent.getOldValue(); Object newValue = propertyChangeEvent.getNewValue(); String newFileName = newValue.toString();

- 123 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

String oldFileName = oldValue.toString(); if(oldFileName.equalsIgnoreCase(newFileName)){ throw new PropertyVetoException("NotReady to change", propertyChangeEvent); } } } A JavaBean container can then create an instance of our custom AuditVetoPropertyChangeAdapter vetoable property change listener and register it with the AuditBean for bound property change events, as we do here in the constructor of our AuditBeanContainer: public class AuditBeanContainer extends JPanel { private AuditBean auditBean; public AuditBeanContainer() { auditBean = // instantiate bean AuditVetoPropertyChangeAdapter auditVetoPropertyChangeAdapter = new AuditVetoPropertyChangeAdapter(); auditBean.addVetoableChangeListener( auditVetoPropertyChangeAdapter); // Exception handling excluded here… } }

JavaBeans Introspection Introspection involves the analysis of a JavaBean component at runtime. JavaBean containers and JavaBean-capable IDEs can discover properties and behavior of a JavaBean by using introspection. The Java reflection API supported by the java.lang.Class method and the java.lang.reflect package provides a low-level means for analyzing Java code that is utilized by JavaBeans introspection. Figure 7.6 depicts some of the core interfaces and classes used for JavaBeans introspection. A container and an IDE use these classes to dynamically discover information about JavaBean components that adhere to the JavaBean component model. Figure 7.6. JavaBean introspection.

- 124 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Introspector class is the frontline interface to JavaBeans introspection. In particular, the Introspector.getBeanInfo() methods are used to return a BeanInfo object that is used to describe the methods, properties, events, and other features of a JavaBean component. Features of a JavaBean are described via subclasses of the FeatureDescriptor class. These subclasses and the information that they convey about a JavaBean component are listed here: • • • • • •

BeanDescriptor: Describes general information about a JavaBean. EventSetDescriptor: Describes the type of events that can be generated by a JavaBean. MethodDescriptor: Describes the methods that are supported by the JavaBean. ParameterDescriptor: Describes the parameters of a JavaBean method. PropertyDescriptor: Describes the properties exported by a JavaBean. IndexedPropertyDescriptor: Describes the indexed properties exported by a JavaBean.

The SimpleBeanInfo class is a default helper class implementation of the BeanInfo interface. "No-op" values are returned from the various interface implementations. JavaBean components that want to present more information about themselves can then subclass the SimpleBeanInfo class without implementing every method in the BeanInfo interface. As an example, we provide an AuditBeanBeanInfo class on the CD in the ejava.beansch7 sample package that extends the SimpleBeanInfo class. We also provide a BeanIntrospectorExample class on the CD that demonstrates how the introspection APIs can be used by a container and an IDE to dynamically use the information

- 125 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

provided by the AuditBeanBeanInfo class. We show BeanInfo method implementations here by the AuditBeanBeanInfo class for getBeanDescriptor(), getPropertyDescriptors(), getMethodDescriptors(), and getEventDescriptors() with exceptions and other extraneous code excluded for simplicity (the complete implementations can be found on the CD): public BeanDescriptor getBeanDescriptor() { BeanDescriptor beanDescriptor = new BeanDescriptor(ejava.beansch7.AuditBean.class); beanDescriptor.setDisplayName("AuditBean"); return beanDescriptor; } public PropertyDescriptor[] getPropertyDescriptors () { PropertyDescriptor fileP = new PropertyDescriptor("file", AuditBean.class, "getFile", "setFile"); PropertyDescriptor fileNameP = new PropertyDescriptor("fileName", AuditBean.class, "getFileName", "setFileName"); fileNameP.setDisplayName("File Name"); fileNameP.setBound(true); PropertyDescriptor auditTypeP = new PropertyDescriptor("AuditType", AuditBean.class); auditTypeP.setPropertyEditorClass(AuditPropertyEditor.class); PropertyDescriptor[] descriptors = new PropertyDescriptor[] { fileP, fileNameP, auditTypeP} ; return descriptors; } public MethodDescriptor[] getMethodDescriptors () { MethodDescriptor[] descriptors = { new MethodDescriptor ( AuditBean.class.getMethod ("auditMessage", new Class[0]))} ; return descriptors; } public EventSetDescriptor[] getEventSetDescriptors () { EventSetDescriptor[] events = { new EventSetDescriptor (AuditBean.class, "audit", AuditListener.class, "notifyAuditEvent")} ; return events; } As a final note, you'll notice that the BeanInfo interface has a getIcon(int) method and four static ICON_XXX values. When a container calls your getIcon() on your JavaBean component's BeanInfo class using one of the ICON_XXX values, your BeanInfo class may optionally return a java.awt.Image object that encapsulates a reference to a JavaBean's icon image. Color and monochrome images at sizes of 16´16 or 32´32 pixels can be returned from this getIcon() call.

JavaBeans Persistence - 126 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Persistence of JavaBean components allows for a JavaBean component to save its state to be retrieved later. The most basic form of JavaBean persistence uses the Java serialization interfaces to transform a bean to and from a JavaBean object's instance values and a serializable stream (for example, file stream). JavaBean containers and IDEs may invoke the actual serialization and deserialization process, but you may also want to serialize your JavaBean for deployment inside of a JAR file. The first thing that must be accomplished to permit serialization is to make a JavaBean component implement the Serializable interface. A JavaBean component must then follow any necessary semantics for persisting or not persisting fields of your component based on the rules for object serialization, such as designating transient fields if necessary. Our AuditBean, for example, follows these simple rules and is thus a persistable JavaBean component. A JavaBean container and IDE must persist and restore the state of a JavaBean to and from its serialized representation. However, you may also want to deploy your JavaBean inside of a JAR file with some initial serialized state. Serialization of a JavaBean involves the creation of a serialization file with a .ser extension, as shown here: String serializedFileName = "AuditBean.ser"; FileOutputStream fileOutputStream = new FileOutputStream(serializedFileName); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); AuditBean beanToBeSerialized = // get handle to bean objectOutputStream.writeObject(beanToBeSerialized); objectOutputStream.flush(); objectOutputStream.close(); To package your JavaBean inside of a JAR file, you must create a manifest file indicating those Java classes inside of the JAR file that correspond to JavaBeans. This is accomplished by adding the property Java-Bean: True to a manifest entry for a JavaBean class. Those classes that are not JavaBeans but are used for design-time introspection of JavaBeans add a Design-Time-Only: True property to the manifest. As an example for our audit bean code, we have this: Name: ejava/beansch7/AuditBean.class Java-Bean: True Name: ejava/beansch7/AuditBeanBeanInfo.class Java-Bean: False Design-Time-Only: True Although incorporation of serialized JavaBean state and JavaBean icon images is optional, the JavaBean class itself is, of course, necessary. You may then create a JAR file with the jar utility using the -m option to specify a manifest file to use. You should, of course, create your JAR file with all of your JavaBean's class files, serialization files, and any images in the directory corresponding to your JavaBean's package. For example, if you want to create an audit bean JAR file with a manifest file named manifest.mf and a set of icons that are to be read from the ejava\beansch7 directory, you might use this command: jar -cmf manifest.mf audit.jar ejava\beansch7\AuditBean.class ejava\beansch7\AuditBean.ser ejava\beansch7\AuditBean_color16.gif ejava\beansch7\AuditBean_color32.gif ejava\beansch7\AuditBean_mono16.gif ejava\beansch7\AuditBean_mono32.gif

JavaBeans Customization

- 127 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

When you adhere to the JavaBean component model standards for defining events, properties, introspective beans, and persistable beans, your JavaBean will be manipulable by most JavaBean containers and IDEs using their built-in property sheet editors and other bean manipulation features. However, you may also want to extend the standard property sheet editing capabilities provided by your IDE using custom property editors. Furthermore, more advanced GUI-based tools for customizing a JavaBean may also be provided using JavaBean customizers. We only briefly describe what is involved here with JavaBean property sheet editors and JavaBean customizers.

Property Editors Figure 7.7 presents the basic architecture involved in using JavaBean property editors to create custom property sheets. The PropertyEditor interface is a base interface that must be implemented to provide a custom property editor. The PropertyEditorSupport class provides a default implementation of the PropertyEditor interface that may be inherited by or directly referenced by custom property editors. For example, a custom property editor such as the MyPropertyEditor class in Figure 7.7 extends the PropertyEditorSupport class. A PropertyEditorManager class is used to register and retrieve custom PropertyEditor classes. A property can also be associated with a custom PropertyEditor using the PropertyDescriptor.setPropertyEditorClass() method from within a BeanInfo implementation. Figure 7.7. JavaBean property editors.

We include a simple example of a custom property editor on the CD in the AuditProperty Editor.java file for our AuditBean that can work inside of the BDK's BeanBox. The AuditBean is extended to support a new int property called auditType. An interface defining static constants for audit type int values and corresponding displayable String values is defined in an AuditTypes interface. Finally, the AuditPropertyEditor class extends PropertyEditorSupport to implement a custom property editor mapping audit type values to displayable String values. The custom AuditPropertyEditor is then

- 128 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

associated with the auditType property owned by the AuditBean from within the AuditBean class's getPropertyDescriptor() method as shown here: PropertyDescriptor auditTypeP = new PropertyDescriptor("AuditType", AuditBean.class); auditTypeP.setPropertyEditorClass(AuditPropertyEditor.class);

Customizers Figure 7.8 presents the basic architecture behind JavaBean customizers. A JavaBean customizer (for example, MyBeanCustomer) must implement the Customizer interface and provide a GUI to solicit input from a user that can be used to manipulate a JavaBean component. Although no requirements are imposed on the nature of the GUI, it will either be AWT-based requiring inheritance from a subclass of Component, or Swing-based requiring inheritance from a subclass of JComponent. The Customizer.setObject() method is implemented to associate the JavaBean component instance with the customizer. The addPropertyChangeListener()and removePropertyChangeListener() methods on the Customizer interface signify the fact that a Customizer implementation must generate PropertyChangeEvent objects when it updates a JavaBean's properties. Figure 7.8. JavaBean customizers.

We also include a simple example of a JavaBean customizer on the CD in the AuditBeanCustomizer.java file for our AuditBean. The AuditBeanCustomizer class extends the Swing JPanel class and implements a Customizer interface. A dropdown box displays and allows the selection of audit type property values, and a text field displays and allows the user to enter filename values. Whenever the audit type or filename values are changed, the AuditBeanCustomizer generates property change events. The JavaBean container is notified of these events by a PropertyChangeListener interface that it registered with the customizer by calling addPropertyChangeListener() defined by the Customizer interface. The AuditBeanCustomizer is registered with the JavaBean container environment by modifying the AuditBeanBeanInfo class's getBeanDescriptor() method to return a BeanDescriptor constructed with the customizer's class, as shown here: public BeanDescriptor getBeanDescriptor() { BeanDescriptor beanDescriptor =

- 129 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

new BeanDescriptor(ejava.beansch7.AuditBean.class, ejava.beansch7.AuditBeanCustomizer.class); beanDescriptor.setDisplayName("AuditBean"); return beanDescriptor; }

The InfoBus The InfoBus is an extension to the Java platform for JavaBean components to exchange information in a dynamic and standard fashion. JavaBean components that want to receive data from other JavaBean components implement standard InfoBus consumer interfaces. JavaBean components that want to make data available to other JavaBean components implement InfoBus producer interfaces. Both consumers and producers implement standard InfoBus interfaces to become a member of the InfoBus community. Data that is exchanged between members of the InfoBus is also encapsulated in a standard way by JavaBean component producers such that JavaBean component consumers can receive this data in standard form. The basic InfoBus architecture is shown in Figure 7.9. The classes and interfaces from the javax.infobus package that compose this architecture are listed here: Figure 7.9. The JavaBean InfoBus architecture



InfoBus: InfoBus is a standard JavaBeans service class that can be retrieved from a bean context's getService() method. An InfoBus holds a list of InfoBusMember objects representing components that have joined the InfoBus for

- 130 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



• • • •

communication. The InfoBus is used by members to request, make available, and revoke data items of interest to other members on the InfoBus. InfoBusMember: The InfoBusMember interface must be implemented by all producers and consumers on the InfoBus. InfoBusDataProducer: The InfoBusDataProducer interface is implemented by those components that provide data to the InfoBus. Data is made available and revoked by imple menters of this interface. Implementers of this interface also register with the InfoBus to receive requests for data. InfoBusDataConsumer: The InfoBusDataConsumer interface is implemented by those components that receive data from the InfoBus. Data is requested by implementers of this interface. Implementers of this interface are also notified of data availability and revocation by producers. InfoBusEvent: The InfoBusEvent class and its subclasses encapsulate events on the InfoBus such as data requests, availability announcements, and revocations. DataItem: The DataItem interface is implemented by classes that encapsulate data passed via the InfoBus in events. DataItem objects may also implement a DataItemChangeManager interface for consumers implementing a DataItemChangeListener interface to subscribe for changes in the state of some DataItem.

Conclusions The JavaBeans component model provides a standard way for developers to define Java classes such that their components can operate inside of JavaBean container environments. JavaBean components expose their attribute properties according to various property definition models, expose their events, expose introspective information about themselves, and allow for the customization of design tools that allow the beans themselves to be customized at design-time. By developing classes that adhere to the JavaBeans component model, you help foster the reusability of your components by virtue of the advanced level of design-time customization that you permit for your component. Aside from design-time customization, the persistence of your component's state can also be used when deploying and initializing a component's state for runtime usage. Use of the JavaBean component model has gained particular popularity among GUI-based development efforts. Developers often customize JavaBean components that implement GUI components using an IDE that understands the JavaBean component model. JavaBean components can, however, also have a nonvisual nature, but the utility of such components is often limited in scope. The primary services offered by JavaBean containers are the designtime customization of properties and events as well as a GUI-based means for easily interconnecting JavaBean components. Enterprise class features needed by the container, such as middle-tier security, transaction, and database connectivity services, are provided by a server-side cousin to the JavaBean component model known as the Enterprise JavaBean component model. We discuss the Enterprise JavaBean component model in Chapt er 36, " Modeling Com ponent s wit h Ent erprise JavaBeans," and Chapt er 37, " Advanced Ent erprise JavaBeans Serving."

- 131 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Part II: Enterprise Data Enabling I N TH I S PART 8 Ent erprise Dat a 9 Base JDBC 10 Advance JDBC

- 132 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Chapter 8. Enterprise Data IN THIS CHAPTER • • • • • • • • •

Dat abase Basics Relat ional Dat abases Obj ect Dat abases RDBMSs Versus ODBMSs Relat ional/ Obj ect Translat ions CLI s Em bedded SQL ODBC JDBC

Interfacing with enterprise data is one of the most important steps involved in building an enterprise system. General database concepts and issues, as well as concepts and issues specific to relational and object database management systems, are very important for the enterprise systems developer to understand. Knowing basic architectural constructs for such database systems helps one more easily grasp how to interface with enterprise data. Most significant to this book, understanding how to interface with enterprise data from Java is important. The options available to the enterprise Java developer and having knowledge of which of these options is most important help one to focus on more rapidly assembling an enterprise data-enabling solution. This chapter describes the basic concepts involved in enterprise databases and the options for interfacing to databases from within the enterprise Java programming paradigm. In this chapter, you will learn: • • • • • • •

The concepts and architecture of most database management systems. The concepts and architecture of relational database management systems. The basics of SQL as the standard language interface to RDBMSs. The concepts and architecture of object database management systems. The pros and cons of object versus relational database management systems. The basic steps behind using object/relational mapping products. A description of CLIs, Embedded SQL, ODBC, and JDBC.

Database Basics Information is one of the most significant assets of any enterprise. Information must flow in and out of an enterprise, flow through an enterprise, and be manipulated by an enterprise. Information must be easily disseminated to the right people at the right time. Information also has security constraints that mandate access control based on the type and content of the information. Information is plentiful and tends to grow exponentially in time and with the growth of an enterprise. Many different people in an enterprise often must concurrently access the same information at a given time. Clearly, information is extremely important to an enterprise; it must be persisted in such a way that it is not lost and must be efficiently and easily retrieved and updated. A database management system (DBMS) is precisely the information-technology component used by enterprises to efficiently retrieve, update, and generally solve the problem of managing enterprise data. The collection of data managed by a DBMS is often referred to as a database. However, the term database also is often used to refer to the DBMS itself.

Data Model Abstraction Levels When one is referring to databases, it is important to understand the different levels of abstraction at which people think about databases. Database designers sometimes think of databases at the lowest level of abstraction in terms of a physical data model used to

- 133 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

represent storage of data on physical media, including how the data is structurally related. A higher level of abstraction describes a logical data model (aka a conceptual data model) wherein logical-data-model entities correspond to one or more underlying physical-datamodel entities and their relationships. Logical data models describe data in terms of what is stored in the database, such as "customer information" or "order information." The logical data model typically relates to an object model and is largely used to describe specific database designs to an enterprise programmer. The logical data model is thus the level of modeling employed by this book. The highest level of data abstraction is referred to as a view and corresponds to a specific customization of a logical data model for use by a particular enterprise user class. Data from the logical model is eliminated from the view level, and new information is derived from the logical level for the view level. Many different views can exist above the logical-data-model level. A different way to describe the database generally exists at all three levels of database abstraction. The description of the database structure at each abstraction level is called the database scheme. At the physical level of abstraction, the database is described in terms of an internal scheme. At the logical level, a database is described in terms of a conceptual scheme. Views of the database are described in terms of an external scheme or subscheme. Although a database scheme at each level describes the structure of the database, the term database instance is typically used to describe a particular instantiation of a database scheme. Thus database A on a host machine X and database B on a host machine Y may adhere to the same database scheme but represent two separate database instances.

General DBMS Architecture The diagram in Figure 8.1 depicts a generic architecture for DBMSs and databases. The DBMS is broken out separately from the database in this diagram. The database represents the physical storage of actual allocated file space for all data and structures being managed by the DBMS. While we have made a distinction between the database and DBMS, we should note that the terms DBMS and database are sometimes individually used to mean both the DBMS and database. Figure 8.1. Generic DBMS and database architectural diagram.

The database itself contains the physical manifestation of all data files, data dictionaries, indices, and stored procedures. Data files are used for storing the actual enterprise information values (for example, credit-card numbers, employee names, and so on). A data dictionary stores all meta-data about the enterprise data, including data attribute names, relationships between data, and data value constraints. Indices are used to provide indexing of information stored in the data dictionary for faster access of the associated data. Stored procedures are predefined and user-defined functional code stored in the database to operate directly on the data stored in the database.

- 134 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Technically speaking, the term DBMS encompasses all the software that rests atop the physical database layer. A DBMS will make use of a physical storage manager to allocate and deallocate physical file space for data, meta-data, indices, and procedures to be stored. The higher-level database manager provides a layer of abstraction for manipulating data, meta-data, and stored procedures related to a way that higher-level DBMS components desire to view the database. DDL compilers map database schemes described in a database definition language (DDL) into lower-level calls that create and delete new structures and data types in the database. A query manager maps high-level statements described in some query language into lower-level calls that can retrieve data from the database. DML compilers use a data manipulation language (DML) to map high-level database access and update calls into lower-level calls according to a particular data model. Although a query language technically corresponds to a subset of DML pertaining to data retrieval, the term query language is very often used to refer to functionality provided by a DML as well.

Transactions The inherent distributed nature of DBMSs and databases is not apparent from the generic logical architecture of DBMSs and databases depicted in Figure 8.1. Not only are databases and DBMSs often physically distributed, but client applications to these DBMS are typically plentiful, especially in enterprise environments. These inherent distribution facets of DBMSs and databases raise a set of concurrent access issues around which a whole science has developed, known as transaction management. Whenever a sequence of processing steps that either must all take place or must have no individual step takes place at all, we say that such a sequence of steps represents a transaction. When all steps occur as an inseparable operation, we say that the transaction may be committed. When no steps are allowed to occur because one or more steps failed, we say that the transaction must be rolled back (to the original system state). The classic example illustrating a transaction is the example involving a withdrawal from one bank account that must be followed by a deposit to another account. If both steps occur, the transaction can be committed. If one step fails, neither must be allowed to occur and the transaction is rolled back (aborted). Transactions must be managed such that they are governed by what the ISO/IEC calls ACID principles. ACID is an acronym standing for atomicity, consistency, isolation, and durability. Atomicity of a transaction means that any failure occurring during a transaction will result in an undoing of all changes made during the transaction. Consistency means that all data affected by a transaction is restored to its original state before the transaction in the event of a failure during the transaction. Isolation means that any data changes made during a transaction are not visible to other transactions until the transaction is complete. Durability means that all committed data is saved such that, in the event of a failure, the state of the data will be correct. A distributed transaction is a transaction that involves operations being performed by multiple distributed applications, as well as perhaps involving multiple distributed databases. Guaranteeing that transactions can adhere to the ACID principles in a distributed transaction processing environment can be difficult, by and large due to the heterogeneous nature of both distributed applications invoking the transactions and the distributed databases involved with the transactions. Such complexity affecting heterogeneous environments has led to some key standards that have been developed to handle distributed transaction processing (DTP). One such DTP standard has been developed by the Open Group (aka X/Open). The X/Open DTP standard defines the DTP model utilized by the J2EE. Figure 8.2 depicts the most basic view of the X/Open DTP model. The X/Open DTP model is composed of transaction managers (TM), resource managers (RM), communication resource managers (CRM), and application programs (AP). The DTP standard specifies standard roles for these components and standard interfaces between the components. In addition to these components, we depict a resource adapter between APs and RMs to be described shortly. Figure 8.2. X/Open distributed transaction processing model.

- 135 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The X/Open term resource manager is used to describe a management process for any shared resource, but it is most often used to mean a DBMS. Although the interface between application programs and resource managers is RM-specific under the X/Open DTP model, a resource adapter can be used as an interface to provide a common means for communicating with various resource manager types. Thus, as we'll see, database interfaces such as ODBC and JDBC can be thought of as resource adapters following the "Adapter Pattern" mentioned in Chapt er 3, " Com ponent - Based Soft ware Developm ent for t he Ent erprise." Transaction managers represent the heart of the X/Open DTP model and are the modules responsible for coordinating transactions among the various distributed entities. Resource managers participate in distributed transactions by implementing a transaction resource interface (XA) to communicate information needed by transaction managers for coordinating transactions. Using information from the distributed resource managers, the transaction manager can ensure that all steps in a transaction are atomically completed. A commit protocol (that is, two-phase commit) implemented by transaction managers helps guarantee ACID principles by ensuring that all resource managers commit to transaction completion or rollback to an original state in the event of a failure. The TX interface between application programs and transaction managers enables applications to initiate the begin, commit, and rollback of transactions, as well as to obtain the status of transactions. As we'll see in Chapt er 34, " Ent erprise Applicat ion Plat form s," a middle-tier server, sometimes referred to as a transaction monitor, can help provide support for communicating with transaction managers, as well as resource managers. Use of transaction monitors can help reduce the amount of knowledge needed by applications programmers for managing transactions. Transaction managers are often configured to manage a particular domain of distributed resource managers and applications. Communication resource managers provide a standard means for connecting distributed transaction managers to propagate transaction information between different transaction domains for more widely distributed transactions. The standard interface between transaction managers and communication resource managers is defined by an XA+ interface, while communication-resource-manager to application-program interfaces are defined by three different interfaces known as TxRPC, XATMI, and CPI-C.

Relational Databases R&D and commercial developments have produced a few general architectural approaches for DBMSs over the years. Nevertheless, the relational database management system (RDBMS) architecture has clearly been the most successful architecture used in the most popular of DBMS products on the commercial market today. As a result, much of today's legacy enterprise data is hosted inside of RDBMSs. This fact alone makes a basic understanding of RDBMS principles key for any serious enterprise systems developer. The fact that RDBMSs are also the assumed underlying DBMS model for J2EE data connectivity makes understanding RDBMSs even more critical for the Java enterprise systems developer.

RDBMS Architecture Figure 8.3 depicts the general architecture for an RDBMS in terms of its primary logical components. A table in an RDBMS serves to group a collection of attribute values for a type

- 136 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

of logical entity. A table actually contains the collection of element attributes in what are called rows of a database. Each row corresponds to one instance of a particular entity. The columns of a table correspond to particular attributes of the entity that the table represents. Thus, for example, Figure 8.4 shows a database table called Customer that has one row per customer instance in the table. Each column of the table corresponds to an attribute of a particular customer. Figure 8.3. RDBMS architecture.

Figure 8.4. Table entries in an RDBMS.

- 137 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

One or more columns per table can be used to uniquely identify a row entry in a table. These one or more columns taken together form what is called the table's primary key. No two rows in a table can have the same primary key value. Some tables can also have columns containing foreign keys, which are primary key values from other tables. Foreign keys are used to explicitly relate one table to another. For example, if a Customer table uses the Account Number as a primary key, then an Order table used to capture the details for a particular customer order may have a foreign key containing the Account Number column value for the customer associated with a particular order. Tables are organized into schemas, whereby a schema encapsulates a collection of tables. Catalogs can also be used to group schemas. Catalogs and schemas help organize tables as well as other entities such as views into groups such that access control and maintenance policies can be defined at the group level. With catalogs and schemas, data can also be scoped by referring to data such as in the format ..

.. Not all RDBMSs support grouping of tables into catalogs and schemas, and the separator used to delimit the scope of data can also vary between DBMS vendors.

SQL Structured Query Language (SQL) is the most widely used query language for RDBMSs. Even though it is called a query language, SQL is used for much more than just data retrieval. SQL is also used to create and define database structures like a DDL and to update data like a DML. SQL was created by IBM in the 1970s and became standardized in the 1980s. Although a few standard versions of SQL exist, the version of SQL used by the J2EE database connectivity solution is the American National Standards Institute's (ANSI) SQL-92, as well as some extensions to SQL via the SQL3 standard. Within such standards, different levels of compliance are defined. Although we will discuss mappings between SQL data types and Java types in subsequent chapters, we present brief descriptions of some of the more core SQL types here in Table 8.1 to better explain how SQL statements are created. Table 8.1. Core SQL Types SQL Type Description CHAR Fixed-length string VARCHAR Variable-length string LONGVARCHAR Large variable-length string BIT Binary digit BINARY Fixed-length binary array VARBINARY Variable-length binary array LONGVARBINARY Large variable-length binary array TINYINT 8-bit integer SMALLINT 16-bit integer

- 138 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

INTEGER BIGINT REAL FLOAT DOUBLE NUMERIC DECIMAL DATE TIME TIMESTAMP

32-bit integer 64-bit integer Small floating-point number Regular floating-point number Large floating-point number Variable base fixed-point number Base 10 fixed-point number The date The time A date and time instant

Creating and Deleting Tables Databases, catalogs, and schemas can be created using statements such as CREATE DATABASE, CREATE CATALOG, and CREATE SCHEMA. However, the precise command syntax often varies from vendor to vendor. Creating tables is a more common operation and fortunately is fairly standard across SQL-compliant DBMSs. This is the syntax for creating a table: CREATE TABLE ( ); Each column definition is sometimes expressed in one of various forms:

NOT NULL For example, to create a table to store customer information including two-character state codes, we might have this: CREATE TABLE state ( state_code CHAR(2) NOT NULL, state_name VARCHAR(50) ); CREATE TABLE customer ( customer_id INTEGER NOT NULL PRIMARY KEY, first_name VARCHAR(32) NOT NULL, last_name VARCHAR(32) NOT NULL, middle_initial VARCHAR(10), address_1 VARCHAR(32) , address_2 VARCHAR(32), city VARCHAR(50), state CHAR(2), zip CHAR(5), phone CHAR(10) ); You can also delete tables from a database using the DROP TABLE command, as in this example: DROP TABLE customer; Modifying Tables The standard syntax for modifying a table is ALTER TABLE ;

- 139 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

in which alter_table_action may be one of following:

\ For example, if you want to add a new column called Email to the Customer table, you can do so as shown here: ALTER TABLE customer ADD email VARCHAR(70); If you were to modify the column definition of a previously defined column Email in the Customer table, you might have this: ALTER TABLE customer MODIFY email VARCHAR(100); You can also remove the Email column from the Customer table as shown here: ALTER TABLE customer DROP email; Inserting and Deleting Rows from a Table Rows are inserted into a table according to the general syntax INSERT INTO VALUES (, …, ); if all columns are being newly inserted, or INSERT INTO (, …, ) VALUES (, …, ); if only a select number of columns are being inserted. For example, to insert data into a selected set of columns, use this: INSERT INTO customer(customer_id, first_name, last_name, address_1, city, state, zip, phone) VALUES(1,'Sam','Sung','Oracle Rd.','Reston','VA','20191','7035551212'); To insert data into all the columns, you might have the following: INSERT INTO customer VALUES ('2', 'Sam', 'Mellone', 'R','123 Drive.', 'Suite 5', 'Fairfax', 'VA', '22222', '7034567899'); You can delete a row from a table via the following general syntax: DELETE FROM ; DELETE FROM WHERE ; The WHERE clause may be added if a set of search criteria is to be added to limit the criteria by which a row is to be deleted. Otherwise, all rows from the table are deleted. For example: DELETE FROM customer WHERE customer_id=1; Modifying Rows in a Table The UPDATE statement is used to modify rows already present in a table according to the syntax UPDATE SET ; UPDATE SET WHERE ; in which is of the following form: =, …, =

- 140 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

When a WHERE clause is not used, all rows of the table are updated. As an example of an UPDATE, we have this: UPDATE customer SET address_1 = '1901 Bay Dr.'WHERE customer_id = '1'; Queries Queries are the most common form of SQL statement submitted to a database. SQL queries typically adhere to the following general form: SELECT FROM [WHERE ] [ORDER BY ]; The SELECT portion of a SQL query can take a * value to indicate that all column values are to be returned, a DISTINCT value indicating only those column values that are unique, or a comma-separated column list of column names identifying those column values to return. The FROM portion of a SQL query indicates which tables to query given a comma-separated list of table names. The optional ORDER BY clause takes a comma-separated list of columns specifying the order in which column values are returned from a query. The optional WHERE clause in a SQL query is expressed in terms of column names, column values, and various operators that define a search criteria. Aside from a fairly intuitive set of logical operators that may be used in a WHERE clause, the IS qualifier can be used to test whether a column adheres to a particular criterion (for example, myColumn IS NULL). The IN qualifier in a WHERE can be used to check whether a value is in a set of values defined after the IN qualifier (for example, myColumn IN ('VA', 'MD')). All the following statements are valid SQL queries (with embedded comments preceded by #): #select all individual states to which customers belong SELECT DISTINCT state FROM customer; #select all columns and rows in the customer tables SELECT * FROM customer; #get all customer_id, first_name, last_name, and state from customer table SELECT customer_id, first_name, last_name, state FROM customer; #select distinct states of the customers whose phone is not null SELECT DISTINCT state FROM customer WHERE phone IS NOT NULL; #select first_name and last_name of customers whose phone number value is null SELECT first_name, last_name FROM customer WHERE phone IS NULL; # select first_name, last_name of customers in state of VA, MD, or DC SELECT first_name, last_name FROM customer ×WHERE state IN('VA','MD','DC'); #select the customers'first_name and last_name who live in VA, MD or DC SELECT first_name, last_name FROM customer WHERE ( state = 'VA'OR state = 'MD'OR state ='DC'); #select the customers'first_name, last_name who don't live in VA, MD or DC SELECT first_name , last_name FROM customer WHERE STATE NOT IN('VA','MD','DC'); #select customer state, first_name, and last_name in order of state

- 141 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

SELECT state,first_name, last_name FROM customer ORDER BY state; # This query selects all customers whose first_name has FR in it. SELECT first_name, last_name FROM customer WHERE phone is not null AND first_name LIKE '%FR%'; # This query selects all customers whose first_name starts with FR. SELECT first_name, last_name FROM customer WHERE phone is not null AND first_name LIKE 'FR%'; If a query fruitfully proves to yield data, one or more results will be returned in the form of a result set. Each result set is composed of one or more "rows." Because queries return only selected column data from one or more tables, these rows don't necessarily correspond to regular table rows. One scrolls through result set rows to pluck data results from each row for use. A result set cursor maintains a pointer to the current result set row being accessed. Because result sets may be distributed, cursors may be pointing to result set row data that could exist somewhere on a remote server. Of course, result set data may also be cached locally.

Data Model Diagram Conventions Because the data model abstraction pursued here is at a logical/conceptual level, the data model diagramming convention used in this book closely resembles the object-oriented model diagramming convention described in Chapt er 2, " Obj ect - Orient ed Soft ware Developm ent for t he Ent erprise." The modeling convention also employs some features that closely follow typical data modeling conventions. The data model used here can actually be thought of as a subset of a general object model. Nonetheless, we take a few liberties in describing data models in this book to bridge the gap between traditional data modeling and object modeling without resorting to explaining a completely new modeling paradigm. The simple set of conventions used for data model diagrams in this book and their UML object model diagram analogues are described here: • •

• • • • • • • • • • •

Tables are represented by squares much like classes are represented in object diagrams. Columns are represented as elements of the table much like attributes in classes are represented in object diagrams. Columns are defined according to the following general form: [] column_name : column_type // column_description Primary keys and foreign keys appear as stereotypes for a particular column. Column types are defined in terms of SQL types. Two forward slashes are used after a column_type to delineate the beginning of a column description. Table relations are represented by lines much like lines are used to represent relationships in object diagrams. The same multiplicity notation at the end of a relationship is used for data models here as is used for object models. Directionality of a relationship indicates how one table explicitly references another table via a foreign key (this is different from object modeling conventions). Roles are used at each end of a directional relation to indicate which primary or foreign keys are involved in the explicit relationship. No directionality of a relationship indicates how one table implicitly relates to another table.

Object Databases

- 142 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Relational data models are used to describe an RDBMS design for storing and relating data. Because storing and relating data is precisely the problem that RDBMSs attempt to solve, relational data models are well suited for their intended purpose. However, the types of systems that evolve from using relational data models are much more limited than the types of systems that evolve from object-oriented and component-based models. Wouldn't it be nice if we could continue to model our scalable enterprise systems using the object-oriented and component-based models that we've grown to love and then simply be able to indicate what elements of state in those models should be persisted? Enter the object database management system (ODBMS). Object database management systems are DBMSs that allow one to directly store and retrieve objects to and from a database. An ODBMS stores class attributes and relations in such a way that database operations can be accomplished in a manner that is most natural to the object- oriented programmer. Thus, in the case of Java, Java objects can be saved to an ODBMS by one JVM and later retrieved by another JVM.

ODBMS Architecture ODBMS architectures for Java typically include a tool to map Java class references to database calls. This mapping tool is usually either baked into a modified JVM or external to a JVM and used as a post-compiler. Although using a modified JVM is undesirable for some applications, post-compilation tools can normally be used only on user-defined classes. Userdefined persistable Java objects can automatically store and retrieve any persistable Java objects they reference during database operations. The Object Data Management Group (ODMG) is a standards body that has defined a standard model for ODBMSs. The basic model consists of an Object Definition Language (ODL) for defining object databases and an Object Query Language (OQL) for ODBMS querying. Language-specific APIs are used for manipulating objects. An Object Interchange Format (OIF) is used for importing and exporting objects between different ODBMSs. The basic class architecture for the ODMG's ODBMS Java language binding is shown in Figure 8.5. Note that none of the standard classes defined by the ODMG belong to a standard package because package naming is up to the vendor. A Database class is used to open and close database connections, bind objects to names, and look up objects'given names. The Java 2.0 collection types are extended by the standard's DCollection, DList, DArray, DSet, and DBag interfaces to allow persistable versions of a collection of objects. The classes ListOfObject, SetOfObject, and BagOfObject implement these extended persistable interfaces. One typically must bind a collection to a name so that it can be used to query, update, insert, and delete objects from such collections using a name. The creation of a Transaction object creates a transaction that the current thread joins. You can also call join() on a Transaction object passed in from another thread to join the current thread to that transaction. Standard transaction begin(), commit(), and abort() methods also exist on a Transaction object. Finally, a few exception types not shown in the diagram are also defined by the ODMG. Figure 8.5. ODMG's ODBMS architecture.

- 143 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The OQL is to ODBMSs as SQL is to RDBMSs. Calls to select(), selectElement(), and query() on DCollection objects can be used to issue queries in a manner much like SQL SELECT clauses are formulated. An Iterator.next() call can then be used to obtain query results in the form of objects by executing such OQL calls. For example: Database d = Database.open("MyDataBase"); Transaction t = new Transaction(); DList customerList = (DList) d.lookup("Customers"); Iterator i = customerList.query("ZIP = 11111"); while(i.hasNext()){ Customer c = (Customer) i.next(); c.setZip("20177"); } t.commit();

RDBMSs Versus ODBMSs For most enterprise development situations, the question of whether you should use an ODBMS or a RDBMS is usually moot. For one, the database to which you must provide connectivity may be a legacy database for which exists many configuration scripts or perhaps much in-house knowledge, or most certainly the product has already been purchased and you have a maintenance/upgrade contract established with the vendor. If a legacy database is not already in place, the question of purchasing a new database may still be skewed by political or business factors such as pre-established vendor relationships, previous engineering staff and management product familiarity, or flat-out blind dislike of "new"ODBMS technologies or "old" RDBMS technologies. Regardless of such business, political, or personal realities, it is important to compare and contrast RDBMS and ODBMS technologies from a pure and

- 144 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

unbiased technical and economical perspective. In what follows, we offer some pros and cons of RDBMSs and ODBMSs. RDBMS pros: • • •

More mainstream solution means that more support and experience will be available. More mainstream nature also means that more tools will be available for use. More mainstream nature also means more comfort and assurance in security, scalability, and overall enterprise-class nature of the product.

RDBMS cons: • • •

Developers must hand-code the mapping of data retrieved from or stored to an RDBMS from a relational model to attributes and objects in a Java object-oriented model. Developers must understand the SQL language above and beyond understanding Java, which can be a significant investment in time. Performance degrades as object model complexity increases when creating, traversing, and querying for objects that are mapped to an RDBMS.

ODBMS pros: • •

Object-oriented software solutions more easily map to and from ODBMS persistence solutions without as much hand-coding. Performance does not degrade significantly when object model complexity increases for object creation, traversal, and queries.

ODBMS cons: • • • •

Developers using the ODMG model still must understand OQL. ODMG standards don't specify packages for standard classes and leave out other specifics like constructors on collection classes. Thus, portability of ODBMS-based Java code is an issue. A lack of certain key features in the ODMG standard also leads to vendor tie-in because vendors will often supply these features. Because ODBMSs tend to be newer than many RDBMSs, product maturity for enterprise-class applications is a risk item. Integrated solutions to enterprise-class issues dealing with remote access, concurrency, scalability, and security are always questionable in newer products.

ODBMSs indeed do provide a database platform that more closely maps to the types of object models the Java developer uses. However, replacement of long-lived RDBMSs can be a futile endeavor. Enterprise data is typically plentiful, and converting legacy RDBMS data into a form exportable by ODBMSs can be time-consuming and can possibly require more effort than would be required by developers'RDBMS-to-OO hand-coding. Furthermore, the enterprise-class capabilities of certain ODBMSs over RDBMSs are still questionable for certain application demands. Projects defining new databases may be in a position to consider ODBMSs but should evaluate vendor offerings very carefully to ensure enterpriseclass applicability. Given the relative youth of the current ODBMS standards, such standards will need to be evolved to help ensure vendor portability. We believe that ODBMSs will be the DBMS of choice in the future when vendor offerings become more suitable to handle the full gamut of enterprise-class applications, as well as when the standards mature enough to the point of helping ensure true cross-platform portability. Most RDBMS vendors have seen this as a potential direction of industry as well and thus have been evolving their back-end architectures appropriately toward supporting the needs of object-oriented (and in particular Java) programming paradigms. A new breed of object/relational hybrid databases and data-mapping products now on the market clearly highlights the trend from relational to object-oriented data modeling.

- 145 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Relational/Object Translations Because many enterprises already make use of RDBMSs hosting legacy enterprise data, object-oriented developers are usually stuck with more programming overhead than they care to have. Mapping object-oriented classes and relationships to RDBMS tables and relations can be a tedious and complex task. However, tools now exist to facilitate relational/object translations. Many RDBMS vendors are now providing hybrid object/relational back-end database architecture solutions. Additionally, a host of object/relational mapping solutions is now on the market to provide an OO layer above an RDBMS. Object/relational mapping products usually either generate object models from relational schemas or create relational models for you from pre-existing object models. Object/relational mapping products can be purchased separately or are sometimes found integrated with other enterprise products. Data-aware GUI JavaBeans, for example, implicitly map GUI components to RDBMS database calls according to GUI-based customizers used by the developer to define such mappings. More sophisticated and general-purpose object/relational mapping products are also now being integrated into middle-tier products with particular applicability in Enterprise JavaBeans, as we'll see in later chapters. Mapping Java objects to RDBMS tables involves an object/relational mapping tool analyzing Java class relationships and then generating an associated relational model. Each class will often map to a table. Class attributes that correspond to fundamental SQL types map to table columns. Classes having references to other class objects map to a table with a foreign key to another table that represents the referenced class. However, given the prevalence of legacy RDBMSs in the world, the most common object/relational mapping scenario encountered by the enterprise developer is to map an existing RDBMS schema into an object model. An example process for mapping an RDBMS schema into an object model is as shown here: •

Step 1: Open your object/relational mapping tool.



Step 2: Provide your tool with the schema name for which the object-relational mapping must be performed.



Step 3: The tool will display all the tables contained by that schema.



Step 4: Now select the tables from which you want to create Java classes.



Step 5: Select each table name and provide a class name to which you want it to be mapped. Many tools will use the table name as the default name for the class but in a Java language format. For example, the Customer table will by default map to a public class named Customer in a Customer.java source file.



Step 6: Depending on the particular mapping tool, the generated Java class might be extended from some sort of persistable class or perhaps implement some persistable interface. For example, a mapped object may be produced in this way:

- 146 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public class Customer extends Persistable { int customerId; String firstName; String lastName; String middleInitial; String address1; String address2; String city; State state; String zip; String phone; .. .. // Generated getter/setter methods for the columns public void setXXX() { } public XXX getXX() { } // For one to one relationship with other tables, we have… public XXX getXXX() { } // For one to many relationship with other tables, we have… public Enumeration getXXX() { } // To select a particular Customer from the database, we might have… public static Customer selectElement(String predicate) { } // To select one or more Customers from the database, we might have… public static Enumeration select(String predicate) { } •

Step 7: Use the generated classes as regular Java objects by your Java application code. The underlying RDBMS queries, inserts, deletes, and updates are transparent to the Java application programmer. For example:

Customer c = Customer.selectElement("customerID=1"); String firstName = c.getFirstName(); String lastName = c.getLastName(); State state = c.getState(); String stateCode = c.getStateCode(); String stateName = c.getStateName(); … c.setState("VA"); c.updateCustomer(); // Updates the state of customer to VA … Enumeration customers = Customer.select("state = VA");

- 147 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Step 8: Compile code and run your application.

CLIs A Call Level Interface (CLI) represents a functional call API to a database. CLIs provided for the various RDBMS vendor solutions are often proprietary and have a native SQL API implementation. Typically, C language–based APIs are provided, but bindings for Cobol and FORTRAN are also common. CLI calls can be made directly to an underlying database driver or can be remotely invoked over a network. The Open Group has specified the X/Open SQL CLI standard for interfacing to databases via a CLI. The X/Open SQL CLI interfaces define function calls at the level of allocating and deallocating system resources, controlling database connections, obtaining database status informa tion, executing dynamic SQL statements, and controlling transactions. The X/Open SQL CLI specification was published as an addendum to the SQL-92 standard and is now also part of the ISO standard. X/Open SQL CLI support for SQL3 features is also being considered.

Embedded SQL We have talked about the prevalence of RDBMSs and SQL a lot so far. So how does one use SQL to talk with an RDBMS from Java? SQLJ offers one standard created by key DBMS industry players such as Oracle, Sybase, and IBM for embedding SQL directly into Java applications. Java source code containing embedded SQL commands is run through a SQLJ preprocessor to generate new Java source code with the appropriate database calls (mainly JDBC calls). During the precompilation process, the SQLJ runtime engine can access the database to determine whether all the tables, columns, and SQL statements are syntactically correct with respect to the database. Certain security restrictions can also be checked at this time. The main utility of SQLJ is that a significant set of SQL errors can be caught at compiletime rather than during runtime as with other Java database connectivity solutions such as JDBC. By embedding SQL directly into a Java program, SQLJ extends the Java API with a whole new set of programming interfaces. Each embedded SQL command in the Java code begins with a #sql token. A colon in an embedded SQL statement is placed before a Java variable used as either input or output in a SQL command. A database connection can be created using the expression #sql context ContextName;. The context is compiled into a Java class having a set of constructors with arguments used to create database connections. Some vendor solutions also read Java properties files to obtain connection-related information. Iterators are used to map SQL results from queries into Java objects. Iterators can be defined using the command #sql [modifiers] iterator IteratorType (colType1, …, colTypeN);. Such a form is used to retrieve query result values by an index number in the result set and subsequently map these result values to an associated Java object. Optional Java modifiers such as static and public can be used to modify the visibility and semantics of the iterator. An iterator of the preceding type is declared using the regular Java variable declaration syntax IteratorType myIterator. The command #sql myIterator = { SQL_Command } ; is used to populate myIterator with the result of a query. The mapping of iterator results to a Java object is then accomplished using #sql { FETCH : myIterator INTO :JavaVar1, … , :JavaVarN} ;. Here, the JavaVarX values refer to regular Java attributes in a Java class. Iterators can also be defined to retrieve database values by name such as this: #sql [modifiers] iterator IteratorType (colType1 JavaVar1, …, colTypeN JavaVarN);. After declaring your iterator instance and querying the database as before, you can then use regular Java calls such as myIterator.JavaVarX() to obtain values from the query result by name. As an example of using SQLJ with an Oracle database, we first make the proper imports, declare a SQL context, and declare a Java class as shown here:

- 148 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

import java.sql.*; import sqlj.runtime.ref.DefaultContext; import oracle.sqlj.runtime.Oracle; #sql context ExampleContext; public class Customer{ …} A Customer class and set of connection properties are used by Oracle to configure a database connection. A SQL context can then be instantiated using the connection created by Oracle: Oracle.connect(Customer.class, "connect.properties"); Connection conn = DefaultContext.getDefaultContext().getConnection(); ExampleContext context = new ExampleContext(conn); An iterator can then be defined inside the Customer class like this: #sql public static iterator Customers (String first_name, String last_name) ; A customer retrieval can be achieved by embedding a SQL SELECT statement into a Java method as shown here: public static Customers selectCustomers(String whereClause, ExampleContext ctx) throws SQLException { Customers myCustomers; #sql [ctx] myCustomers = { SELECT first_name, last_name FROM customer WHERE :whereClause} ; return myCustomers; } The returned set of customer values might be accessed like this: while (myCustomers.next()) { System.out.println( myCustomers.firstName() + " : " + myCustomers.lastName()); } A customer update may be achieved by simply embedding a SQL UPDATE statement into a method that uses a customer's attributes and SQL context: public static void updateCustomer(String fname,String lname, int id, ExampleContext ctx) throws SQLException { #sql [ctx] { UPDATE CUSTOMER SET first_name = :fname , last_name = :lname WHERE customer_id = :id } ; } Similarly, a customer insert may be achieved by embedding a SQL INSERT statement into a method taking a customer's attributes and SQL context: public static void insertIntoCustomer(String fname, String int id, ExampleContext ctx) throws SQLException { #sql [ctx] { INSERT INTO CUSTOMER(first_name, last_name, customer_id) VALUES(:fname, :lname, :id ) ; }

lname,

- 149 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ODBC In addition to embedding SQL directly into programs, a more common solution for standard database connectivity involves use of a standard API for making database calls. In an effort to alleviate developers from database vendor dependence and use of vendor-specific database protocols to communicate with databases, Microsoft defined the open database connectivity (ODBC) solution. ODBC is based on SQL/CLI standards and has been widely supported since its introduction. ODBC applications depend only on the ODBC API and the SQL standard. SQL statements are submitted to ODBC API calls, and results are retrieved using standard ODBC API constructs. The ODBC API is defined in terms of the C programming language. Given the C language dependence, ODBC requires that API libraries be pre-installed on client machines. The ODBC API communicates with an underlying ODBC driver manager that loads an appropriate ODBC driver as specified by the ODBC API client application. ODBC drivers are code libraries that adhere to a standard ODBC service-provider interface. The ODBC serviceprovider interface is implemented by ODBC driver vendors to map standard ODBC calls to database-vendor–specific calls. ODBC drivers may call the database directly via a CLI or via some networking protocol.

JDBC Providing a Java binding for the ODBC API would have required some modifications to the ODBC API because not all C-based constructs (for example, pointers) have decent corresponding Java analogues. Thus, Sun has created the Java Database Connectivity (JDBC) solution as Java's answer to database-vendor interface independence. JDBC provides a database connectivity solution for Java applications just as ODBC provides for C and Microsoft applications. As we'll see in Chapt er 9, " Basic JDBC," JDBC has a basic architecture philosophy similar to the ODBC architecture. That is, JDBC has a standard JDBC API which communicates with a JDBC driver manager that loads JDBC drivers. JDBC drivers implement a JDBC service-provider interface and map standard JDBC calls into databasevendor–specific calls. To better understand why Sun created a Java-specific database connectivity solution, consider the fact that client-side installs of ODBC API libraries would have made it difficult to run Java anywhere (that is, such as within Web-based applets). Regardless, ODBC was still an attractive database-connectivity solution when JDBC was created, largely due to widespread ODBC driver implementations. To make JDBC a viable Java-based database connectivity solution, Sun created a JDBC-ODBC bridge to solve the temporary problem of JDBC driver unavailability while enabling Java applications to capitalize on use of ODBC driver availability. Of all methods for data-enabling your enterprise using Java technologies, JDBC is the preferred solution utilized by the J2EE. For one, in light of the widespread RDBMS database vendor solutions available, JDBC's gearing for RDBMSs makes it a commercial-ready solution. ODBMS databases and Java binding standards are still in their relative enterpriseclass infancy. Furthermore, some of the ODMG ODBMS mappings may require modified JVMs and package naming, which affects portability. Because ODBC cannot map directly to Java, Java bindings for ODBC are not possible. Because embedded SQL for Java requires a post-compiler and clutters Java code, it is also not as desirable a solution for database connectivity. Object/relational mapping tools are a very good idea and can off-load much of the model mapping hand-coding work for you. Nevertheless, some object/relational mapping tools are not yet suitable for use in many enterprise-class applications. Thus, knowledge of JDBC as a solution for interacting with databases is key for any serious enterprise developer and architect. JDBC is by far the most common way to interact with databases, and JDBC drivers now exist for most database vendor solutions. Finally, if you are still wondering why understanding JDBC is important, consider the fact that JDBC provides a very rich set of database connectivity features available to Java enterprise applications and is an integral part of the J2EE.

- 150 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Conclusions Clearly, the development of an enterprise system will involve connecting to enterprise data from within your enterprise applications. RDBMSs currently have the most significant market presence of any database architecture. Even though ODBMSs have less presence now, RDBMS vendors are evolving their architectures toward the more object-oriented interfacing needs of enterprise developers. Capitalizing on this shortcoming, object/relational mapping products bridge the gap from relational data models of RDBMS demand to object-oriented models of enterprise applications development demand. Many database connectivity solutions for RDBMSs have been around for some time. SQL CLIs and ODBC represent two approaches and standards for interfacing with RDBMSs from non-Java applications. SQLJ offers one means to interface with RDBMSs from Java programs, but it requires more overhead in terms of development. The Java Database Connectivity solution is the J2EE-recommended means for enterprise Java data connectivity. Just about every object/relational mapping tool available for Java maps Java objects to JDBC calls. Whether you are using JDBC directly, using an object/relational mapping tool, or creating object/relational mappings yourself, an understanding of JDBC is key for the enterprise Java architect and developer. The next two chapters cover JDBC from the basics to fairly advanced topics to arm you with the knowledge you need to successfully connect your enterprise data to your enterprise Java applications.

Chapter 9. Basic JDBC In This Chapter • • • • • • • •

JDBC Archit ect ure JDBC Drivers and t heir Types JDBC Driver Configurat ion JDBC Connect ions JDBC St at em ent s JDBC Result Set s SQL and Java Mappings JDBC Met aDat a

This chapter presents the architecture of JDBC, JDBC driver configuration, and the most commonly used API features of JDBC. A detailed example supports the material throughout this chapter and introduces an example e-commerce enterprise application's data model for use throughout the remainder of the book. Database connectivity represents one of the most fundamental problems for which any enterprise system must have a solution. Because enterprise data is often plentiful, must be archived, and must be shared among many distributed users, it is key for distributed enterprise systems to provide a scalable, reliable, and highly available means for accessing and updating data. Furthermore, the complexity inherent with communicating to a wide variety of DBMS vendor solutions and legacy data models presents a time-to-market impediment that also often hampers the enterprise system solutions provider. The creators of the Java platform have realized these problems and have provided the Java Database Connectivity (JDBC) solution now incorporated as part of both the J2SE and the J2EE platforms. JDBC represents the standard means for connecting to DBMSs from Java applications in a fashion that is largely DBMS-independent and enables connectivity to both legacy and newly defined enterprise data. In this chapter, you will learn: • • • •

The architecture of JDBC as the standard means for connecting to databases from Java applications A classification of JDBC driver types and their pros and cons for usage The steps involved in configuring various JDBC driver types The mechanisms for establishing database connections via JDBC

- 151 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • •

The creation and execution of regular and prepared SQL statements in JDBC The handling of query results and obtaining information about query results in JDBC The mappings between SQL data types and Java types Obtaining information about databases and database drivers via JDBC

JDBC Architecture The Java Database Connectivity architecture represents the de facto standard means for connecting to databases from Java applications. JDBC is both an API for Java programmers and an interface model for service providers who implement connectivity to databases. As an API, JDBC provides a standard interface for Java applications to interact with multiple types of databases. As an interface model for service providers, JDBC provides a standard way for database vendors and third-party middleware vendors to implement connectivity to databases. JDBC leverages off of existing SQL standards and provides support for bridging to other database connectivity standards such as ODBC. JDBC accomplishes all of these standardsoriented goals with an interface that is simple, strongly typed, and capable of highperformance implementation. JDBC version 1.0 was initially offered separately from the JDK 1.0 platform but was integrated with the JDK 1.1 platform in the java.sql package. The JDBC 1.0 version contains most of the core and commonly used features of JDBC. The material in this chapter almost exclusively focuses on JDBC 1.0 version functionality. Sun has also introduced the JDBC 2.0 version, which is partitioned into two separate categories: the JDBC 2.0 Core API and the JDBC 2.0 Standard Extension API. The JDBC 2.0 Core API includes all the functionality contained in the JDBC 1.0 version plus a host of new features that includes query result enhancements, enhancements for updating batches of data, persistence of Java objects, and support for a whole slew of new SQL types. The JDBC 2.0 Core API is contained in the J2SE/J2EE java.sql packages. The JDBC 2.0 Standard Extension API offers a range of more sophisticated enterprise features such as a new and simpler paradigm for connecting to databases in a three-tier architecture, support for connection pooling, distributed transactions, and enhanced management of query result sets. The JDBC 2.0 Standard Extension API is incorporated into the J2EE in the javax.sql package. The next chapter focuses on some of the more sophisticated aspects of the JDBC 1.0 API, as well as the JDBC 2.0 APIs. Because the JDBC 1.0 API specification has been around longer, support for this API by driver vendors is more prevalent than support for the JDBC 2.0 API. Sun maintains a fairly thorough list of JDBC driver-compliant vendors for all JDBC versions on its Web site at ht t p: / / j ava.sun.com / product s/ j dbc/ drivers.ht m l. The conceptual diagram in Figure 9.1 depicts a high-level view of the JDBC architecture. Here we see a Java application using the JDBC API via usage of the java.sql package. The interfaces in the java.sql package are implemented by a JDBC driver vendor. JDBC driver implementations provide Java-based wrappers to one or more DBMS interfaces. We will go into the various types of DBMS interfaces shortly, but suffice it to say that a DBMS interface represents an existing method for connecting to a database provided either in a vendor-specific way or via some vendor-independent means for interfacing with the database. Many JDBC driver implementations will connect only to a single type of database, but some middleware vendor driver implementations actually allow for connectivity to various database types. Figure 9.1. A JDBC architecture conceptual diagram.

- 152 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A Java application must first load a JDBC driver into memory. JDBC API database commands from the Java application are then delegated to the loaded JDBC driver implementation. The JDBC driver implementation talks to the vendor-specific or vendor-independent DBMS interface, and calls to this DBMS interface are then routed to the specific DBMS in use. The class diagram in Figure 9.2 depicts a set of classes, interfaces, exceptions, and key relations for the most basic subset of the java.sql package. The diagram is partitioned into three groupings showing the core JDBC 1.0 classes and interfaces, the basic exceptions, and a set of key helper classes used to wrap and identify SQL types. The additional classes, interfaces, and exceptions added to the JDBC 2.0 API are not shown in this diagram because the next chapter more completely presents the advanced functionality inherent in the JDBC 2.0 API. Figure 9.2. A basic JDBC class diagram.

- 153 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

You can see from the diagram that the DriverManager is at the top of the JDBC API composition serving as the basic class for managing zero or more JDBC drivers. Such JDBC drivers must implement the Driver interface, which is obligated to return a DriverPropertyInfo instance to allow an IDE or application to discover information about the driver. The DriverManager is also used to manage and return Connection objects to the Java application that represent connection sessions with the database. The Connection object may then be consulted to obtain meta-data information about the particular database via the DatabaseMetaData interface. The Connection object's main usage involves creating statements to execute commands against the associated database. Static SQL statements (Statement interface), precompiled SQL statements (PreparedStatement interface), and stored SQL procedures (CallableStatement interface) may all be created and used to execute database commands. Database queries issued against such statements will return a ResultSet object reference that corresponds to zero or more query results from the database query. The ResultSet is used to obtain the desired query results and may also be used to obtain ResultSetMetaData to find out information about the properties of the returned result set. A hierarchy of exceptions may be thrown during usage of the various JDBC API calls. SQLExceptions are the basic types of exceptions that return information regarding database access errors. Because more than one exception may be thrown by the database during certain calls, a chain of SQLException objects is returned and the SQLException class enables traversal of such exceptions. SQLException thus has a setNextException() method to chain exceptions and a getNextException() method to traverse chained exceptions. SQLExceptions can also return error-code information via a getErrorCode() call and SQL state information via a getSQLState() call. The SQLWarning exception is a special type of SQLException returning information regarding a database access warning. SQLWarnings also have setNextWarning() and getNextWarning() calls for chaining and traversing SQLWarnings. Finally, the DataTruncation exception returns information regarding a database read or write warning when the JDBC driver truncates a value returned from or sent to the database. The JDBC type helpers of Figure 9.2 will be used throughout this chapter and represent the basic type helpers in JDBC 1.0 for identifying and managing data types submitted to and returned from the database through JDBC. A major enhancement in JDBC 2.0 is its provision of a much richer set of data types. The java.sql.Types class is simply a container of constants used to identify SQL types. The values used by the Types class are taken from the X/Open standard and are used to uniquely identify SQL standard types (for example, VARCHAR, INTEGER, FLOAT, DATE). A mapping between these types and Java types is presented later in this chapter.

- 154 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JDBC Drivers and their Types The basic JDBC architecture presented in the preceding section described two broad categories of DBMS interfaces with which JDBC driver implementations may interact. These interfaces were classified according to interface openness as vendor-specific and vendorindependent DBMS interfaces. Sun has in fact come up with a classification scheme for JDBC drivers that is even more specific. Although the distinction by Sun is still made between JDBC drivers that speak to vendor-specific interfaces and those that speak to vendor-independent interfaces, an additional discriminator is employed to offer four distinct types of drivers. This discriminator indicates whether the JDBC driver talks with an interface that has a native platform implementation or with an interface that has a remote network listener with which the JDBC driver communicates. We refer to this additional classification discriminator as interface locality. Table 9.1 shows each JDBC driver type number and name in the context of how they are classified according to interface openness and interface locality. It should be noted that this classification of the four driver types according to interface openness and interface locality is not a formally defined classification scheme but one presented here for you to more rapidly grasp the fundamental and most common distinctions among the four driver types. Table 9.1. JDBC Driver Types Interface Openness Vendor-Independent Vendor-Specific Client-Side Type 1: JDBC ODBC Bridge Type 2: Native-API Partly Native Java Technology-Enabled Interface Locality Remote Type 3: Net-Protocol Fully Type 4: Native-Protocol Fully Network Listener

Java Technology-Enabled

Java Technology-Enabled

The J2EE and JDBC Driver Type Selection Selection of JDBC drivers per the instructions of this section are only relevant to standalone Java enterprise applications. As we'll see in Part VI , " Ent erprise Web Enabling," and Part VI I , " Ent erprise Applicat ions Enabling," J2EE container environments shift JDBC driver type selection from the application developer's concern to the concern of J2EE container providers. Figure 9.3 illustrates a typical configuration for type 1 JDBC drivers. Type 1 JDBC-ODBC Bridge drivers provide a means for Java applications to make JDBC calls that in turn are mapped to ODBC calls. An ODBC driver thus must be installed on the client side typically as a set of native libraries. Because ODBC is a popular DBMS interface standard for which there exists many ODBC drivers already available to talk with a wide variety of databases, and because JDBC is designed with ODBC in mind, Sun provides a JDBC/ODBC driver implementation with the JDK 1.1 and the J2SE. Sun's implementation of the java.sql.Driver interface for the JDBC-ODBC bridge driver is encapsulated by the sun.jdbc.odbc.JdbcOdbcDriver class. Use of this bridge is typically not recommended in production environments but is useful as a way to perhaps bootstrap your enterprise development efforts. Figure 9.3. Typical Type 1 JDBC driver configuration.

- 155 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figure 9.4 illustrates a typical configuration for type 2 JDBC drivers. Type 2 Native-API Partly Java Technology-Enabled drivers provide a mechanism for Java applications to make JDBC calls that are directly mapped to vendor-specific DBMS native library interface calls. Thus the JDBC driver is specifically designed to call native client libraries provided for DBMSs such as Oracle, Sybase, or Informix. Most database vendors now ship JDBC type 2 drivers with their databases. Such type 2 drivers will most typically offer better performance than using a JDBC/ODBC bridge because they bypass the ODBC intermediate layer. Figure 9.4. Typical Type 2 JDBC driver configuration.

- 156 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figure 9.5 illustrates a typical configuration for type 3 JDBC drivers. Type 3 Net-Protocol Fully Java Technology-Enabled drivers provide a mechanism for Java applications to make JDBC calls that are mapped to calls embodied in some DBMS vendor-independent network protocol. These over-the-wire calls are then mapped to a specific DBMS vendor's interface calls. This vendor-independent remote listener is typically implemented by a middleware vendor offering support for connecting to various back-end database types. Thus the Java client application is freed from any dependence on having a set of native libraries installed on the client and has a very flexible means for communicating with various database types. The configuration of vendor-specific DBMS interfaces is thus localized to the middleware database server. Although the choice of network protocol for communicating to the middleware listener is left up to the middleware listener vendor, many vendors have been implementing fairly open solutions that are usable in Internet and intranet environments. Figure 9.5. Typical Type 3 JDBC driver configuration.

Figure 9.6 illustrates a typical configuration for type 4 JDBC drivers. Type 4 Native-Protocol Fully Java Technology-Enabled drivers provide a mechanism for Java applications to make JDBC calls that are mapped to calls embodied in a DBMS vendor's specific remote network listener protocol, which in turn are used to directly access that vendor's database. As with the type 3 drivers, type 4 drivers also enable a Java client application to be freed from dependence on the loading of a set of native client-side libraries. However, because these

- 157 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

drivers are vendor specific, this driver type solution does make for a less-flexible configuration on the client side because clients can now talk only with that vendor's DBMS. Figure 9.6. Typical type 4 JDBC driver configuration.

Driver Assessment Choosing a driver for your enterprise application is an important step that affects performance, reliability, flexibility, and maintainability. Different drivers will have different performance characteristics, but some general assumptions and trade-offs are typically made when considering the various driver classes: • • • • • • •

Client-side native drivers are usually more appropriate in networks in which clientside native libraries can be easily installed and configured or in situations in which a middle tier is assumed to provide intermediate database access on behalf of the client tier. Client-side native drivers are difficult to configure for Web clients and usually involve trusted applets and client-side library installs. Remote network listener-based drivers result in thinner, pure Java clients. Type 1 drivers offer more database vendor independence at the price of lower performance as compared with type 2 drivers. Type 2 drivers offer higher performance at the price of database vendor-dependence as compared with type 1 drivers. Type 3 drivers offer more database vendor-independence at the potential price of lower performance as compared with type 4 drivers. Type 4 drivers offer potentially higher performance at the price of database vendordependence as compared with type 3 drivers.

Such driver comparisons based on type are indeed gross comparisons. Evaluations of drivers should be performed on an individual basis because drivers will vary in performance according to specific features, databases in use, and other system environment factors. System environment factors such as client usage, client-side platforms, network bandwidth and usage, and server-side platforms all affect the performance of an application. Because driver implementation details are often not known a priori, information about the performance in a particular environment is not always obvious until it's evaluated in a simulated or actual system environment. Other issues such as security and level of JDBC compliance are also worthwhile attributes of a particular JDBC driver vendor to take into consideration. Of course,

- 158 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

as we'll see in Parts VI and VII of this book, the application developer typically does not worry about such issues in J2EE container-based enterprise applications.

JDBC Driver Configuration Now that you know what a JDBC driver is and the various types available, it is important to know how to configure a JDBC driver for use in your enterprise application. Figure 9.7 depicts a class diagram of the key entities involved in configuration of a JDBC driver. Note that although Figure 9.7 shows many of the core JDBC 1.0–style operations, a few newly introduced JDBC 2.0–style operations are also shown. Figure 9.7. Driver management class diagram.

The java.sql.DriverManager class represents the primary interface to the JDBC API user for loading and managing JDBC drivers. The DriverManager can either load the driver classes implicitly by setting the system property jdbc.drivers or load them explicitly with calls to Class.forName(). The DriverManager is also used when creating new connections associated with the pool of loaded drivers.

The J2EE and JDBC Driver Configuration Configuration of JDBC drivers per the instructions of this section are

- 159 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

only relevant to standalone Java enterprise applications. As we'll see in Part VI and Part VI I , J2EE container environments shift JDBC driver configuration from the application developer's concern to the concern of J2EE application assemblers and deployers as well as J2EE container providers. To implicitly load a set of drivers, simply specify the driver class names separated by a colon (:) in the jdbc.drivers system property. Note that the driver class name specified must, of course, be in your CLASSPATH. For example: java -Djdbc.drivers=sun.jdbc.odbc.JdbcOdbcDriver: com.assuredtech.jdbc.JdbcDriver MyProgram To explicitly load a driver, use the Class.forName() method in your Java program as shown here: Class.forName("com.assuredtech.jdbc.JdbcDriver"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); A flexible scheme for configuring a set of drivers for your application may be to provide a set of JDBC driver names in a file adhering to a format readable by a java.util.Properties object and then to load these driver names and call Class.forName() for each driver. The example presented in the next section demonstrates how to accomplish this. As a final note on driver configuration, the constructors of some drivers are occasionally used for driver registration. Although this scheme lacks flexibility because you are now rendered with a hard-wired driver name in your code, it is exemplified here for completeness: com.assuredtech.jdbc.JdbcDriver driver = new com.assuredtech.jdbc.JdbcDriver(); // Note: com.assuredtech.jdbc.JdbcDriver() calls // DriverManager.registerDriver(Driver); Note that the com.assuredtech.jdbc.JdbcDriver shown here would have to implement the java.sql.Driver interface as all JDBC drivers must. The Driver interface specifies the need to return a DriverPropertyInfo object that may be used to get and set properties for a connection associated with the driver. The JDBC API user rarely needs to interact with the Driver interface and the java.sql.DriverPropertyInfo class. Rather, the JDBC API user usually has the DriverManager class as the point of contact with the loaded JDBC drivers.

General Configuration Steps per Driver Type The general steps for configuring type 1 JDBC-ODBC bridge drivers are detailed here: •

• • • • • •

Install the native DBMS interface client libraries and ODBC client driver for the DBMS to which you want to connect according to your DBMS vendor's instructions. It should be noted that Microsoft Windows often comes pre-installed with many Microsoftrelated ODBC drivers ready to connect to Microsoft databases such as MSAccess and SQL Server. Start the Control Panel from your Windows 95/98/NT platform. You can get to the Control Panel by first clicking the Start button, then selecting the Settings menu item, and finally selecting the Control Panel menu item (and the Control Panel window pops up). Find and double-click on the ODBC icon (the Data Source Administrator window pops up). Select the System DSN tab. Click the Add button (the Create New Data Source window pops up). Select the driver for the database with which you want to communicate. Click the Finish button (an ODBC window specific to the selected driver pops up).

- 160 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •

Type the data source name, fill in a description, and select or type the information regarding the database instance to which you want to connect. Load the type 1 JDBC driver class (in your CLASSPATH) from your Java client application according to the instructions described previously in this section.

The general steps for configuring type 2 Native-API Partly Java Technology-Enabled drivers are detailed here: • •

Install the native DBMS interface client libraries for the DBMS to which you want to connect according to your DBMS vendor's instructions. Load the type 2 JDBC driver class (in your CLASSPATH) from your Java client application according to the instructions described previously in this section.

The general steps for configuring type 3 Net-Protocol Fully Java Technology-Enabled drivers are detailed here: • • • •

You may first have to install the native DBMS interface client libraries for the DBMS to which you want to connect according to your DBMS vendor's instructions on your middleware server. Install the middleware component libraries for your middleware remote network listener according to your middleware vendor's instructions. Configure the middleware vendor's remote network listener to use one or more natively installed DBMS interfaces with a JDBC type 1 or JDBC type 2 driver or perhaps a JDBC type 4 driver for connection to a database vendor's remote network listener. Load the middleware vendor's type 3 JDBC driver class (in your CLASSPATH) from your Java client application according to the instructions described previously in this section.

The general step for configuring type 4 Native-Protocol Fully Java Technology-Enabled drivers is detailed here: •

Load the type 4 JDBC driver class (in your CLASSPATH) from your Java client application according to the instructions described previously in this section.

Configuring the BeeShirts.com Example Data Model Of course, configuring a JDBC driver and data enabling an enterprise Java application with JDBC would be pointless without a database hosting useful data. To demonstrate how to data-enable an enterprise application with JDBC, we use an actual database and some sample data. The sample data and associated data model define a commercial retail T-shirt business model that we will continue to communications-enable, Web-enable, applicationenable, and infuse with assurance throughout the remainder of this book. After reading this book, you will have gone through all the key enterprise-enabling steps to be considered in building a distributed Java-based e-commerce enterprise system known as BeeShirts.com. If you don't already have a database available, you can follow the steps outlined in Appendix A, " Soft ware Configurat ion," for installing the underlying database that we have used to create these examples. Appendix A also demonstrates how to configure the database with the BeeShirts.com data model and data used throughout this book. You of course can configure and populate your own database with the BeeShirts.com data. The next section demonstrates how you can connect to this database. Throughout the book, we incrementally introduce parts of the BeeShirts.com data model as its elements become relevant to understanding the example code that utilizes the model. We take this approach so that you are not plagued with attempting to understand a complete data model before parts of it are even utilized or relevant. Appendix A describes the full-blown example data model used in the example BeeShirts.com application for the reader interested in understanding the data model now before proceeding.

- 161 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

As described in Chapt er 8, " Ent erprise Dat a," we use a UML-like type notation and SQL type names from the java.sql.Types class for describing the data models throughout the book. Figure 9.8 depicts the most basic subset of the BeeShirts.com data model relevant to the examples of this chapter. The item table includes the information related to a particular item (that is, a T-shirt) that may be purchased. The item table is related to an actual order via an order number. The orders table contains the order information for a particular set of items. The orders table is related to a customer table via a customer number. The customer table includes all information related to a potential or existing BeeShirts.com customer. An auxiliary state table contains the mapping from a two-character state code to a complete state name. Figure 9.8. BeeShirts.com customer, orders, and items basic data model.

JDBC Connections A database connection represents a communications session in which a communications channel is opened and SQL commands are executed between a database client and the database server. The java.sql.Connection interface represents this database connection. A database connection is closed when the database session between the database client and the database is terminated (that is, via Connection.close()).

The J2EE and JDBC Connections Configuration and creation of JDBC connections per the instructions of this section are only relevant to standalone Java enterprise applications. As we'll see in Part VI and Part VI I , J2EE container environments shift JDBC connection creation from the application developer's concern to the concern of J2EE container providers. Connections are yielded from a connection pool for application code in J2EE container environments. J2EE assembly and deployment providers configure any specific connection information on behalf of the application code. Database URLs

- 162 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A database Uniform Resource Locator (URL) represents a fully qualified database connection name identifying the database and database driver to which you are connecting. To fully describe a connection name, one needs to know information such as the type of database driver, the type of database, the type of database connection, and some connection-instance information like the username, password, and IP address of the database instance. The database URL is represented as a String in the form jdbc:subprotocol:subname in which • • •

jdbc is a database driver type keyword used in the URL for all JDBC database URLs. subprotocol represents the type of database to which one desires connectivity. subname provides additional information needed by the database type for establishing connectivity.

The subprotocol and subname to use for a particular database instance should be described in your JDBC driver vendor's documentation, but some examples are listed here for different driver types: • • • • • • • • • • • • • •

Type 1: JDBC-ODBC Bridge Driver URLs jdbc:odbc:customer;UID:dba;pwd:dba jdbc:odbc:customer;CacheSize=100 jdbc:odbc:;param=value;param=value;…. Type 2: Native-API Partly Java Technology-Enabled Driver URL jdbc:oracle:oci7:@SQLNETinstance Name Type 3: Net-Protocol Fully Java Technology-Enabled Driver URLs jdbc:dbAnywhere:1529 Type 4: Native-Protocol Fully Java Technology-Enabled Driver URLs jdbc:oracle:thin:@::

Creating Connections To create a connection object instance, one of the DriverManager's getConnection() methods must be invoked with the database URL as a parameter. When invoking this method, DriverManager first finds a driver from its pool of loaded drivers that can accept the database URL and then asks the driver to connect to the database with the associated database URL. A Connection object is then returned to the object that invoked DriverManager.getConnection(). Three forms of getConnection() exist on the DriverManager class: •

• •

getConnection(String url) simply attempts to connect given the database URL. getConnection(String url, String user, String password) attempts to connect given the database URL, a database username, and the database user's password. getConnection(String url, java.util.Properties info) attempts to connect given the database URL and a set of properties used as connection arguments. Sometimes, a user and password property are passed in via the Properties object.

- 163 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

As an option, the DriverManager.setLoginTimeout() method may be invoked to specify the timeout in seconds for a driver to wait while attempting to connect to a database.

Example: Connecting to a Database This next example demonstrates how to establish a connection to the database. The example code is contained in the ejava.jdbcch09.ConnectToDatabase class and has the following definition: public class ConnectToDatabase{…} Note

The following complete code example can be found on the CD in the examples\src\ejava\jdbcch09 directory using the ConnectToDatabase.java and the JDBCCH09Properties.txt files. Some exception handling and other handling mechanisms have been left out of the book here for simplicity but can be found in the examples on the CD. A description of the database-relevant properties used in JDBCCH09Properties.txt can be found in Appendix A and a tad later in this chapter.

A runconnecttodb.bat example script file (for Microsoft Windows) is also included in the examples\src\ejava\jdbcch09 directory to demonstrate how to compile and execute the example code. We provide such example scripts throughout the book and describe our general build and execution procedures in Appendix A. Such scripts can be extended to operate on Unix and other platforms utilizing the same core Java commands.

The main() method of ConnectToDatabase is invoked like

java ejava.jdbcch09.ConnectToDatabase where the is the location of a properties filename with the set of properties set as in the JDBCCH09Properties.txt file. The main() method then instantiates a new ConnectToDatabase object and calls setProperties() with a filename and then getConnection() to return the Connection object. A series of exceptions are handled and the status of the connection attempt is returned. The key elements of the main() function are shown here: public static void main(String[] args) { if(args.length == 0){ System.out.println("Error: Run the program as:" + " java ejava.jdbcch09.ConnectToDatabase "); System.exit(0); } String fileName = args[0]; ConnectToDatabase connectionToDatabase = new ConnectToDatabase(); . . . connectionToDatabase.setProperties(fileName);

- 164 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Connection connection = connectionToDatabase.getConnection(); . . . // Catch exceptions here. . . . // Else print results of successful connection attempt. . . . } The following member variables of the ConnectToDatabase class are used to maintain the relevant variables used in this example: private String driverClass; // Driver class name private String dbURL; // Database URL private Properties dbProperties; // Properties read from properties file private Connection connection; // A database connection object The ConnectToDatabase.setProperties() method creates a new java.util.Properties object reference (dbProperties), creates a new FileInputStream object with the propertiesFileName, and calls load() on the Properties object with the newly created FileInputStream object. Any exceptions that may be thrown are simply passed back to the invoking object. The setProperties() method is defined as shown here: public void setProperties(String fileName) throws FileNotFoundException, IOException { dbProperties = new Properties(); FileInputStream propertiesFileStream= new FileInputStream(fileName); dbProperties.load(propertiesFileStream); } As described in Chapt er 4, " Java Foundat ions for Ent erprise Developm ent ," we generally use property files throughout the book for most of our examples to enable you to experiment with the examples via setting properties with different values. In this example, we read properties such as the driver class and database URL, which you will probably have and want to change to run with your particular configuration and database. We will also usually provide you with some variations that may be set for each property that you may comment or uncomment according to your desired experiment. The relevant properties for this example are shown here: # Refer to Appendix A for more info on configuring the JDBC # driver via setting of the DRIVER_CLASS and DATABASE_URL properties #JDBC Driver Class # for ODBC Driver: #DRIVER_CLASS=sun.jdbc.odbc.JdbcOdbcDriver # for Oracle Driver #DRIVER_CLASS=jdbc.oracle.driver.OracleDriver # for CloudScape Driver equipped with J2EE reference implementation #DRIVER_CLASS=RmiJdbc.RJDriver # for CloudScape Driver equipped with BEA Weblogic Server DRIVER_CLASS=COM.cloudscape.core.JDBCDriver #Database URL # for ODBC URL #DATABASE_URL=jdbc:odbc:tShirts # for Oracle URL #DATABASE_URL=jdbc:oracle:thin:@localhost:1521:ORCL # for URL with CloudScape equipped with J2EE reference implementation #DATABASE_URL=jdbc:rmi:jdbc:cloudscape:beeshirtsdb # for URL with CloudScape equipped with BEA Weblogic Server

- 165 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

DATABASE_URL=jdbc:cloudscape:D:\\weblogic\\eval\\cloudscape\\beeshirt s #UserName to connect to database UserName=TSHIRTS #Password to connect to database Password=TSHIRTS #otherParameters SUB_PROPERTIES= The ConnectToDatabase.getConnection() method called from main() first extracts the driver class name (driverClass), database URL (dbURL), username (userName), and password (password) from the dbProperties object. The driver class name is then used to call Class.forName() to load the driver. Finally, the database URL, username, and password are used to create a connection via DriverManager.getConnection(). The ConnectToDatabase class also demonstrates use of the DriverManager.getConnection() call using two of its other overloaded getConnection() methods. Depending on whether or not you include a UserName, Password, or a SUB_PROPERTIES set of values in the JDBCCH09Properties.txt file, you can induce the example code to demonstrate use of the other two DriverManager. getConnection() methods. A convenience method called convertStringToProperties() is used to convert a comma-separated set of NAME=VALUE pairs from the SUB_PROPERTIES string into a Properties object if it is supplied (for example, SUB_PROPERTIES=User=Scott, Password=tiger). The key elements of the getConnection() method are shown here: public Connection getConnection() throws ClassNotFoundException, SQLException, Exception { if(connection != null){ return this.connection; } // Get connection properties from properties file driverClass = (String)dbProperties.get("DRIVER_CLASS"); dbURL = (String)dbProperties.get("DATABASE_URL"); String userName = ((String)dbProperties.get("UserName")).trim(); String password = ((String)dbProperties.get("Password")).trim(); String otherProperties = (String)dbProperties.get("SUB_PROPERTIES"); if(driverClass == null || dbURL == null){ throw new Exception("Driver Class or Driver URL should not be null"); } // Load driver Class.forName(driverClass); // Create connection in one of three ways depending on whether // a user name, password, or sub-properties were in properties file if( (userName.length() == 0) && (password.length() == 0) && (otherProperties.length() == 0) ){ connection = DriverManager.getConnection(dbURL); } else if(otherProperties.length() == 0){ connection = DriverManager.getConnection(dbURL, userName, password); } else if(otherProperties.length() != 0){ Properties subProperties = convertStringToProperties(otherProperties);

- 166 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

connection = DriverManager.getConnection(dbURL, subProperties); } return connection; }

JDBC Statements After a connection to a database is opened, a Java application typically makes actual use of the connection via the creation and execution of a series of SQL commands. These SQL commands are executed as database statements that perform such operations as querying for data, updating data, inserting data, and deleting data. The java.sql.Statement, java.sql.PreparedStatement, and java.sql.CallableStatement interfaces shown in Figure 9.9 encapsulate various forms of database statements that are created by a Connection object and that can be issued to the database. We will not cover use of all the methods on the statement interfaces in this section, but throughout the rest of this chapter and the next chapter, most of the functionality that demonstrates use of these methods will be presented. Figure 9.9. Statements class diagram.

The Statement interface represents a basic SQL statement that can be executed. The PreparedStatement represents a type of Statement that can be precompiled with query information as a performance enhancement. The CallableStatement is a type of PreparedStatement that serves to encapsulate execution of stored procedures in the database. Because stored procedures are a more advanced database processing topic, the discussion on CallableStatement objects is deferred until the next chapter.

- 167 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Using Regular Statements SQL commands are contained in Java String objects passed to JDBC calls. These String objects simply contain SQL commands as described in Chapt er 8. A regular Statement object can be created by invoking createStatement() on a Connection object. Such nonprepared types of statements will be useful for infrequent queries because they are not precompiled for efficiency, as are PreparedStatement objects. You can create a Statement object as shown here: Statement statement = connection.createStatement(); The Statement object is then called upon to execute an actual SQL command using one of three basic methods: • • • • • • •

• • • •

ResultSet executeQuery(String sql) allows one to execute SQL queries and obtain a ResultSet object. For example ResultSet rs = statement.executeQuery("SELECT * FROM CUSTOMER"); int executeUpdate(String sql) allows one to execute SQL inserts, deletes, and updates and then obtain a count of updated rows. For example int nValues = statement.executeUpdate("INSERT INTO CUSTOMER VALUES" + " ('129','Sam','Cheng','s','123 Sam St.', '12','Baltimore','MD'," + "'20222', '(410)444-4444','[email protected]') "); boolean execute(String sql) is the most generic type of execute call allowing one to execute SQL DDL commands and then obtain a boolean value indicating whether a ResultSet was returned. For example boolean returnValue = statement.execute("SELECT * FROM CUSTOMER" );

Querying with Joins, Outer Joins, and LIKE Clauses Aside from queries, inserts, deletes, updates, and DDL commands that operate on a single table as in the code snippets shown previously, joins in queries are used when data from more than a single table needs to be returned with a value in one table equaling a value in another table. As an example join that may be issued on the example database, we have this: String joinStatement = "SELECT CUSTOMER.*, ORDERS.* FROM " + "CUSTOMER, ORDERS WHERE CUSTOMER.CUSTOMER_ID = ORDERS.CUSTOMER_ID_FK"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(joinStatement); Outer joins are used when we are trying to join tables that have data in one table that has no cross-reference in the other table yet we still want to return its value from the resultant query. Joins are executed in JDBC statements like any other SQL command, but outer joins may take a different syntax. One database vendor's syntax for outer joins may differ from another vendor's syntax. For example, an outer join String in MS Access may be formulated this way: String joinStatement= "SELECT C.* , S.* FROM CUSTOMER C OUTER JOIN" + "STATE S on C.STATE = S.CODE"; The same outer join in Oracle may be formulated like this: String joinStatement = "SELECT C.*, S.* FROM CUSTOMER C, STATE S " + "WHERE C.STATE(+) = S.CODE(+)";

- 168 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

There are also differences for issuing SQL statements with an embedded LIKE clause. For example, an MS Access SQL String with a LIKE clause it in may be formulated like this: String sqlString = " SELECT * FROM CUSTOMER WHERE FIRST_NAME like '*R*'"; The same LIKE clause for Oracle is formulated this way: String sqlString = " SELECT * FROM CUSTOMER WHERE FIRST_NAME like '%R%'"; There does exist a standard JDBC escape syntax for handling such outer join and LIKE clause anomalies, but the level of particular support for such features from many driver implementations remains minimal.

Example: Creating and Executing Statements This next example demonstrates how to create and execute a series of simple statements. The example code is contained in the ejava.jdbcch09.SimpleStatementExample class. This example builds off of the previous database-connection example. In fact, the SimpleStatementExample class extends the ConnectToDatabase class: public class SimpleStatementExample extends ConnectToDatabase{…} Note

The following complete code example can be found on the CD in examples\src\ejava\jdbcch09 directory using the SimpleStatementExample.java, ConnectToDatabase.java, and JDBCCH09Properties.txt files. Some exception handling and other handling mechanisms have been left out of the book here for simplicity but can be found in the examples on the CD. Additionally, a runsimplestatement.bat example Windows script file is included in the examples\src\ejava\jdbcch09 directory to demonstrate how to build and execute this example. See Appendix A for more information on general database and example code configuration procedures.

The main() method of SimpleStatementExample is invoked as

java ejava.jdbcch09.SimpleStatementExample where the propertiesFileName is the location of a properties filename with the properties set as in the JDBCCH09Properties.txt file. The main() method then calls setProperties() and getConnection() on the example class as it did in the ConnectToDatabase example to load the properties file and establish the database connection. However, now we also create a Statement object and attempt to execute two regular queries, an update, a join query, an outer join query, and a query with a LIKE clause. We also close the associated Statement object after all the example statements are executed. A series of exceptions are handled and the status of each command executed is reported but left out of the following listing: public static void main(String[] args) { if(args.length == 0){ System.out.println("Error: Run the program as:" + " java ejava.jdbcch09.SimpleStatementExample "

- 169 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

+ " "); System.exit(0); } String fileName = args[0]; SimpleStatementExample simpleStatementExample = new SimpleStatementExample(); . . . // Establish properties from properties file and get connection simpleStatementExample.setProperties(fileName); Connection connection = simpleStatementExample.getConnection(); // Get SQL statements from properties file and execute them… String sqlString = (String)(simpleStatementExample.getProperties()). get("SQL_QUERY_STATEMENT"); boolean executionStatus = simpleStatementExample. execute(sqlString); . . . ResultSet resultSet = simpleStatementExample. executeQuery(sqlString); . . . sqlString = (String)(simpleStatementExample.getProperties()). get("SQL_UPDATE_STATEMENT"); int count = simpleStatementExample.executeUpdate(sqlString); . . . String joinStatement = (String)(simpleStatementExample.getProperties()). get("SQL_QUERY_STATEMENT_JOIN"); resultSet = simpleStatementExample.executeQuery(joinStatement); . . . String outerJoinStatement = (String)(simpleStatementExample.getProperties()). get("SQL_QUERY_STATEMENT_OUTER_JOIN"); resultSet = simpleStatementExample. executeQuery(outerJoinStatement); . . . String likeStatement = (String)(simpleStatementExample.getProperties()). get("SQL_QUERY_STATEMENT_WITH_LIKE"); resultSet = simpleStatementExample.executeQuery(likeStatement); . . . simpleStatementExample.closeStatement(); . . . } In addition to the state implicitly inherited from ConnectToDatabase, we have added another attribute to this class for containing a reference to the Statement object: private Statement statement; // Statement object Each query or update String issued is read from the properties file. You of course can modify this properties file to demonstrate different types of queries. These are the newly introduced properties that are relevant to the preceding example and beyond those properties used in the ConnectToDatabase example: #SQL Query SQL_QUERY_STATEMENT = SELECT * FROM TSHIRTS.CUSTOMER #SQL Update

- 170 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

SQL_UPDATE_STATEMENT = INSERT INTO TSHIRTS.CUSTOMER VALUES ('129','Sam','Cheng','S','123 Sam St.', 'C3', 'Baltimore','MD','20222','4104444444','[email protected]') #Join STATEMENT SQL_QUERY_STATEMENT_JOIN = SELECT TSHIRTS.CUSTOMER.*, TSHIRTS.ORDERS.* FROM TSHIRTS.CUSTOMER, TSHIRTS.ORDERS WHERE CUSTOMER.CUSTOMER_ID = ORDERS.CUSTOMER_ID_FK #OUTER JOIN for ORACLE #SQL_QUERY_STATEMENT_OUTER_JOIN = SELECT CUSTOMER.* FROM TSHIRTS.CUSTOMER,STATE WHERE CUSTOMER.STATE(+) = STATE.CODE(+) #OUTER JOIN for MSACCESS #SQL_QUERY_STATEMENT_OUTER_JOIN = SELECT C.* , S.* FROM CUSTOMER C OUTER JOIN STATE S on C.STATE = S.CODE #OUTER JOIN for MSACCESS and Cloudscape SQL_QUERY_STATEMENT_OUTER_JOIN = SELECT C.* , S.* FROM TSHIRTS.CUSTOMER C LEFT OUTER JOIN TSHIRTS.STATE S on C.STATE = S.CODE #SQL Statement with Like for MSACCESS #SQL_QUERY_STATEMENT_WITH_LIKE = SELECT CUSTOMER.* FROM CUSTOMER WHERE CUSTOMER.FIRST_NAME LIKE \'*R*\' #SQL Statement with Like for ORACLE and Cloudscape SQL_QUERY_STATEMENT_WITH_LIKE = SELECT * FROM TSHIRTS.CUSTOMER WHERE FIRST_NAME LIKE '%R%' When each type of example execute statement is invoked on the SimpleStatementExample object, each method attempts to retrieve the Statement object. Each method does this by calling a createStatement() method that retrieves the connection object from the base class and creates the Statement if it does not already exist. The createStatement() method is defined as shown here: protected void createStatement() throws SQLException, Exception { if(statement == null){ Connection connection = super.getConnection(); statement = connection.createStatement(); } } Each type of execute command on a Statement object is demonstrated from the SimpleStatementExample's main() method by calling one of the following three methods on the SimpleStatementExample object: public boolean execute(String sqlString) throws SQLException, Exception { if(statement == null){ createStatement(); } boolean returnValue = statement.execute(sqlString); return returnValue;

- 171 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

} public ResultSet executeQuery(String sqlString) throws SQLException, Exception { if(statement == null){ createStatement(); } ResultSet rs = statement.executeQuery(sqlString); return rs; } public int executeUpdate(String sqlString) throws SQLException, Exception { if(statement == null){ createStatement(); } int returnValue = statement.executeUpdate(sqlString); return returnValue; } We finally close the statement with this: public void closeStatement() throws SQLException { if(statement != null){ statement.close(); statement = null; } }

Using Prepared Statements Although each Statement object used in the preceding set of examples represents a SQL statement that must be compiled each time it is executed, a prepared statement represents a precompiled SQL statement and is identified by the java.sql.PreparedStatement interface. A PreparedStatement has advantages over a regular Statement in that it is created with a parameterized SQL statement. Each PreparedStatement's SQL command parameter is indicated by a question mark (?) in the SQL String and represents an input (IN) variable that can be dynamically set before the statement is executed. Because only the values of each parameter need to be set after the statement is created, the statement itself can be compiled when the statement is created (assuming that the database or driver or both fully support this feature). This provides an obvious benefit when sending SQL commands to the database that have the same basic command structure but differ only in the IN values used by each submitted command. A PreparedStatement is created with the prepareStatement() method on the Connection object as shown here: PreparedStatement statement = connection. prepareStatement("SELECT * FROM CUSTOMER WHERE CUSTOMER_ID= ?"); After the prepared statement is created, the IN values must be set. This is accomplished via use of the various setXXX() methods that exist on the PreparedStatement object. The basic format for each setXXX() method is void setXXX(int parameterIndex, XXX value);

- 172 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

where XXX is the type of object being inserted into the parameterized prepared statement at the index specified by parameterIndex. The various setXXX() methods available to a PreparedStatement are shown in Figure 9.9. For example, one way to set the parameter for the select clause created in the preceding PreparedStatement object would be as follows: statement.setInt(1, new Integer(129)); After each setXXX() method is called for each IN parameter in the PreparedStatement, the statement may be executed. This is accomplished via a call to one of three parameterless exe cute methods on the PreparedStatement object as defined here: •

• •

ResultSet executeQuery(); to execute SQL queries and obtain a ResultSet object int executeUpdate(); to execute SQL updates and obtain a count of updated rows boolean execute(); to execute SQL DDL commands and obtain a boolean value indicating whether a ResultSet was created

Example: Creating and Executing Prepared Statements This next example demonstrates how to create and execute a series of PreparedStatement objects. The example code is contained in the ejava.jdbcch09. SimplePreparedStatementExample class. This example also builds off of the database connection example with the SimplePreparedStatementExample class extending the ConnectToDatabase class: public class SimplePreparedStatementExample extends ConnectToDatabase{…} Note

The following complete code example can be found on the CD in the examples\src\ejava\jdbcch09 directory using the SimplePreparedStatementExample.java, ConnectToDatabase.java, and JDBCCH09Properties.txt files. Some exception handling and other handling mechanisms have been left out of the book here for simplicity in describing the example. Additionally, we have included an example runsimplepreparedstatement.bat script in the examples\src\ejava\jdbcch09 directory to demonstrate how to build and execute the example code. Appendix A describes general database and example code configuration procedures used by the book.

The main() method of SimplePreparedStatementExample is invoked like

java ejava.jdbcch09.SimplePreparedStatementExample

where the is the location of a properties filename with the properties set as in the JDBCCH09Properties.txt file. The main() method calls setProperties() and getConnection() on the example class as it did in the ConnectToDatabase example to load the properties file and establish the database connection. Here we also create PreparedStatement objects to execute queries and an

- 173 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

update. For each type of execute command, a parameterized prepared SQL String and a Vector of IN parameter values are read from the properties file and submitted to the execution method. A special helper method for converting the IN parameters read from the property files as a String into a Vector object is also provided. A series of exceptions are handled and the status of each attempt is reported but left out of the following code snippet: public static void main(String[] args) { if(args.length == 0){ System.out.println("Error: Run the program as:" + " java ejava.jdbcch09.SimplePreparedStatementExample" + " "); System.exit(0); } String fileName = args[0]; SimplePreparedStatementExample simplePreparedStatementExample = new SimplePreparedStatementExample(); . . . // Establish properties from properties file and get connection simplePreparedStatementExample.setProperties(fileName); Connection connection = simplePreparedStatementExample. getConnection(); . . . // Get SQL statements from properties file and execute them… String sqlString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_QUERY_STATEMENT"); String parameters = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_QUERY_STATEMENT_VALUES"); Vector values = simplePreparedStatementExample. parseStringToVector(parameters); boolean executionStatus = simplePreparedStatementExample. execute(sqlString,values); . . . String insertString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_INSERT_STATEMENT"); String insertValuesString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_INSERT_STATEMENT_VALUES"); values = simplePreparedStatementExample. parseStringToVector(insertValuesString); int nResults = simplePreparedStatementExample. executeUpdate(insertString, values); . . . String updateString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_UPDATE_STATEMENT"); String updateValuesString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_UPDATE_STATEMENT_VALUES"); values = simplePreparedStatementExample. parseStringToVector(updateValuesString);

- 174 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

nResults = simplePreparedStatementExample. executeUpdate(updateString, values); . . . String sqlString = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_QUERY_STATEMENT"); String parameters = (String) (simplePreparedStatementExample.getProperties()). get("PREPARED_SQL_QUERY_STATEMENT_VALUES"); Vector values = simplePreparedStatementExample. parseStringToVector(parameters); ResultSet rs = simplePreparedStatementExample. executeQuery(sqlString,values); simplePreparedStatementExample.closeStatement(); } In addition to the state inherited from ConnectToDatabase, another private variable is used to store a PreparedStatement object: private PreparedStatement statement; // PreparedStatement object In addition to the properties contained in the JDBCCH09Properties.txt property file used for the ConnectToDatabase example, the following properties from the JDBCCH09Properties.txt property file are now used for this example: #Prepared QUERY Statement PREPARED_SQL_QUERY_STATEMENT = SELECT * FROM TSHIRTS.CUSTOMER WHERE FIRST_NAME = ? PREPARED_SQL_QUERY_STATEMENT_VALUES = Roy #Prepared Insert PREPARED_SQL_INSERT_STATEMENT = INSERT INTO TSHIRTS.CUSTOMER VALUES(?,?,?,?,?,?,?,?,?,?,?) PREPARED_SQL_INSERT_STATEMENT_VALUES =130,John,Hiller,Miller, 125 S St.,C6,Baltimore,MD,20100,4104444444,[email protected] #Prepared Update PREPARED_SQL_UPDATE_STATEMENT = UPDATE TSHIRTS.STATE SET STATE_NAME = 'California'WHERE CODE = ? PREPARED_SQL_UPDATE_STATEMENT_VALUES =CA When each prepared statement is executed, a new PreparedStatement object is created and stored locally in this example using the createStatement() method as shown here: protected void createStatement(String sqlString) throws SQLException, Exception { Connection connection = super.getConnection(); statement = connection.prepareStatement(sqlString); } Three types of SQL command executions are performed in the execute(), executeQuery(), and executeUpdate() methods. For each method, a PreparedStatement is created and the SQL String and Vector of IN values passed into the method are used to call setObject() for each prepared statement value. Finally, the appropriate command execution method on the PreparedStatement object is called. These three execute method variations are shown here: public boolean execute(String sqlString, Vector values)

- 175 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

throws SQLException, Exception { createStatement(sqlString); for(int i = 1; i -1){ this.serverPort = port; } this.properties =p; } public void makeConnection() throws IOException { if(this.serverHost.indexOf("local") != -1){ serverHost = null; } InetAddress serverAddress = InetAddress.getByName(this.serverHost); socket = new Socket(serverAddress, this.serverPort); this.outputStream = new ObjectOutputStream(socket.getOutputStream()); } public void queryForCustomersWhoSpendGreaterThan(float value) throws IOException, Exception { // Write customer query to server socket this.outputStream.writeInt(this.CUSTOMERS_QUERY); this.outputStream.writeFloat(value); this.outputStream.flush(); if(remoteInputStream == null){ remoteInputStream = new ObjectInputStream(socket.getInputStream()); } // While still getting results from server boolean received = false; while(!received){ Vector vector = (Vector)this.remoteInputStream.readObject(); for(int i = 0; i< vector.size(); i++){ // For each Vector element result, create a Customer object Customer customer = (Customer)vector.elementAt(i); System.out.println("First Name :"+customer.getFirstName()); System.out.println("Last Name :"+customer.getLastName()); System.out.println("Address1 Name :"+customer.getAddress1()); System.out.println("Address2 Name :"+customer.getAddress2()); System.out.println("City :"+customer.getCity()); System.out.println("State :"+customer.getState()); System.out.println("Zip :"+customer.getZip()); System.out.println("Email Address :"+customer.getEmailAddress()); System.out.println("Phone :"+customer.getPhoneNumber()); } received = true;

- 267 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

} } public void registerReceiverHostAndPort() throws IOException { // Read client socket info from properties file String receiverHost = (String)this. properties.get("CLIENT_RECEIVER_HOST"); String receiverPortString = (String)this. properties.get("CLIENT_RECEIVER_PORT"); int receiverPort = Integer.parseInt(receiverPortString); if(receiverHost == null){ receiverHost = "localhost"; } // Create and start client callback socket if(this.clientReceiver == null){ this.clientReceiver = new ClientReceiverServer(receiverPort); this.clientReceiver.start(); } // Write client callback info to server this.outputStream.writeInt(this.REGISTER_RECEIVER); this.outputStream.writeObject(receiverHost); this.outputStream.writeInt(receiverPort); this.outputStream.flush(); } public void queryForOrderFromState(String state) throws IOException { this.outputStream.writeInt(this.ORDERS_QUERY); this.outputStream.writeObject(state); this.outputStream.flush(); } public void clean() throws IOException { this.remoteInputStream.close(); this.outputStream.close(); this.socket.close(); } public static void main(String[] args) { if(args.length == 0){ System.out.println(" you need to provide the configuration info"); System.out.println(" java ejava.tcpipch12.Client "+ " "); System.exit(0); } Client c = null; try{ // Read info from properties file FileInputStream fin = new FileInputStream(args[0]); Properties p = new Properties(); p.load(fin); fin.close(); String serverHost = (String)p.get("SERVER_HOST"); String serverPortString = (String)p.get("SERVER_PORT"); int serverPort = -1;

- 268 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

if(serverPortString != null && serverPortString.length() != 0){ serverPort = Integer.parseInt(serverPortString); } // Create client, make server connection, issue customer query, // register callback, issue order query to receive callback c = new Client( serverHost, serverPort, p); c.makeConnection(); c.queryForCustomersWhoSpendGreaterThan(100.00f); c.registerReceiverHostAndPort(); c.queryForOrderFromState("VA"); c.clean(); } catch(IOException ioe){ System.out.println(" Error :"+ioe); ioe.printStackTrace(); try{ if(c != null){ c.clean(); } } catch(Exception ex){ } System.exit(0); } catch(Exception e){ System.out.println(e); e.printStackTrace(); try{ c.clean(); } catch(Exception ex){ } System.exit(0); } } } The rather long-winded name of a queryForCustomersWhoSpendGreaterThan() method writes the QueryServiceProtocol marker interface's CUSTOMERS_QUERY value and the desired minimum spending value to the TCP/IP output stream. The resultant Vector of Serializable Customer objects is then read from the stream and displayed. A call to registerReceiverHostAndPort() on the Client object then induces the Client to create and start a new instance of the ClientReceiverServer thread class shown in List ing 12.8. The ClientReceiverServer thread simply creates a ServerSocket and listens on it to receive a Vector of Serializable Orders sent from the ServerHelper in our example. The Client object then registers the ClientReceiverHelper host and port with the ServerHelper object using the QueryServiceProtocol's REGISTER_RECEIVER type message. Finally, the Client object's queryForOrderFromState() call is made to create an ORDERS_QUERY message to send to the ServerHelper. The ServerHelper object then makes the callback onto the ClientReceiverHelper object with the Order results. Listing 12.8 TCP/IP Client Callback Handler (ClientReceiverServer.java) package ejava.tcpipch12; import java.io.IOException; import java.util.Vector; import java.util.Hashtable; import java.io.ObjectInputStream;

- 269 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

import java.io.ObjectOutputStream; import java.net.Socket; import java.net.ServerSocket; public class ClientReceiverServer extends Thread implements QueryServiceProtocol { private Socket socket; private ObjectInputStream remoteInStream; private ObjectOutputStream remoteOutStream; private int portNumber = 5556; ServerSocket serverSocket = null; public ClientReceiverServer(int portNumber) throws IOException { if(portNumber > -1) this.portNumber = portNumber; serverSocket = new ServerSocket(this.portNumber, 1); } public synchronized void run() { boolean listening = true; /** * Until finalize method of this class is called by GC * it waits for the server to write. */ while(listening){ try{ // Block on socket and read data when connection made Socket socket = serverSocket.accept(); this.remoteInStream = new ObjectInputStream( socket.getInputStream()); Vector receivedOrders = (Vector)this.remoteInStream.readObject(); // For each vector received, create an Order object for(int i = 0; i< receivedOrders.size(); i++){ Order order = (Order)receivedOrders.elementAt(i); System.out.println("Received the Orders :"); System.out.println("Order Data :"+ order.getOrderDate()); System.out.println("Order ID :"+order.getOrderID()); System.out.println("Value :"+ order.getOrderValue()); } } catch(IOException ioe){ System.out.println("Error :"+ioe); ioe.printStackTrace(); } catch(Exception e){ System.out.println("Exception :"+e); e.printStackTrace(); } } } } Running the runtcpip.bat file will compile all TCP/IP classes and interfaces described in this section, as well as start your TCP/IP server and TCP/IP client demonstration programs. Aside from the database-specific properties defined in the TCPIPCH12.Properties file equipped with the book, the following key TCP/IP-oriented properties will be of interest and need to be set for your environment:

- 270 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

# TCP-IP Server Name SERVER_HOST=localhost # TCP-IP Server Port SERVER_PORT=9000 # TCP-IP Client Callback Name CLIENT_RECEIVER_HOST=localhost # TCP-IP Client Callback Port CLIENT_RECEIVER_PORTS=9001 The SERVER_HOST and SERVER_PORT properties need to be set to the hostname (or IP address) and port number for wherever you want to run the TCP/IP server in this example. The CLIENT_RECEIVER_HOST and CLIENT_RECEIVER_PORTS properties need to be set to the hostname (or IP address) and port number for wherever you want to run the TCP/IP client in this example. Note that the predefined properties equipped with the TCPIPCH12.Properties file should be fine to run on your localhost machine if the ports 9000 and 9001 are available. UDP Datagrams The preceding section demonstrated how to use the basic java.net socket programming libraries with TCP as the Transport Layer protocol. Java also provides support for using UDP as the Transport Layer protocol for socket programming. Figure 12.3 shows the key UDPrelated classes part of the java.net package. The DatagramSocket class is used to receive and send DatagramPacket objects via UDP. Datagram packets can arrive in any order when sent between endpoints, and the routing of packets always differs between successive transmissions because no TCP-like connection is involved. The MulticastSocket class is a type of UDP DatagramSocket used for receiving and sending multicast datagram packets in which a group of subscribing UDP endpoints can receive packets sent to the entire group. Figure 12.3. UDP datagram entities.

- 271 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

DatagramSocket objects can be created on a particular port for a particular IP address as shown here: DatagramSocket datagramSocketRemote = new DatagramSocket(2020, InetAddress.getByName("206.26.48.100")); Or you can create a DatagramSocket on your local host in this way: DatagramSocket datagramSocket = new DatagramSocket(2020); DatagramPacket objects can then be created to receive packets on a specified UDP socket and perhaps convert it to an object more directly useful, such as a String: byte[] bufferToReceive = new byte[16]; DatagramPacket receivedPacket = new DatagramPacket(bufferToReceive, bufferToReceive.length); datagramSocket.receive(receivedPacket); String stringReceived = new String(receivedPacket.getData()); You can then extract the IP address and UDP port from which the datagram was sent and perhaps send the client a datagram using their IP address and UDP port during the construction of a new DatagramPacket as shown here: String stringToSend = "Hello"; byte [] bufferToSend = stringToSend.getBytes(); InetAddress clientAddress = receivedPacket.getAddress(); int clientPort = receivedPacket.getPort(); DatagramPacket packetToSend = new DatagramPacket(bufferToSend, bufferToSend.length, clientAddress, clientPort); datagramSocket.send(packetToSend); As for multicast sockets, it is a rather straightforward process to join a multicast UDP group using the MulticastSocket class. After that, you can send and receive packets as usual;

- 272 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

now, however, sent packets are broadcast to the group listening on this multicast channel, and you can also receive packets broadcast over this channel. For example: MulticastSocket dgsocket = new MulticastSocket(); dgsocket.joinGroup(InetAddress.getByName("166.0.0.1")); ... // Datagram business as usual ... dgsocket.leaveGroup(InetAddress.getByName("166.0.0.1")); Custom Sockets and Factories The diagram in Figure 12.4 shows some of the remaining entities you can use to customize your TCP/IP-based applications. The SocketImpl class and SocketImplFactory interface can be used to create custom socket implementations that can then be associated with the Socket and ServerSocket classes. The implementation of Berkeley Software Design (BSD) style socket options and use of default TCP and UDP transport implementations are all also provided by the java.net package. Figure 12.4. Customizing sockets and factories.

The SocketImpl abstract class represents the base class for implementing TCP-based sockets. The PlainSocketImpl class extending the SocketImpl class is not a public API class, but it is the underlying default TCP-based socket implementation used by both the ServerSocket and the Socket classes. By extending the SocketImpl class with your own socket implementation, you can provide your own custom transport layer. By creating

- 273 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

your own SocketImplFactory that returns an instance of your custom SocketImpl, you can call the static methods Socket.setSocketImplFactory() and ServerSocket.setSocketFactory() to register your custom socket factory from both the client and the server side of a TCP/IP connection. Both the SocketImpl and the DatagramSocketImpl classes implement the SocketOptions interface. SocketOptions allow you to get and set BSD-style socket options for your socket connection. Options such as TCP_NODELAY (Nagle's algorithm enabling/disabling), SO_LINGER (time for connection to linger on a close), and SO_TIMEOUT (read calls block for this timeout duration) all have type-safe getter and setter methods on the Socket class itself. The ServerSocket has the capability to get and set to the SO_TIMEOUT option.

Communication Streams As you've seen from the TCP/IP examples of the preceding section, I/O streams from the java.io library are used in conjunction with the socket classes from the java.net library to exchange data between TCP/IP clients and servers. On a particular java.net.Socket connection object, one can obtain handles to the java.io.InputStream and java.io.OutputStream over which you can receive or send data, respectively. Many subclasses of InputStream and OutputStream can be constructed with a handle to such stream objects in order to chain I/O streams together. Given many of the built-in java.io stream classes, this gives Java socket programmers the added advantage of implementing a set of fairly clean interfaces to TCP/IP connection streams. For example, as with the example in the preceding section, object streams can offer a fairly type-safe interface to TCP/IP connections, as demonstrated here: outStream = new ObjectOutputStream(socket.getOutputStream()); outStream.writeObject("CustomerAddressQuery"); outStream.writeObject("Heilmann"); inStream = new InputOutputStream(socket.getInputStream()); String lastName = (String) inStream.readObject(); int id = inStream.readInt(); Address addr = (Address) inStream.readObject(); Or perhaps use a BufferedReader to read buffered text from an input stream or send text over an output stream with a BufferedWriter. For example: InputStream inStream = socket.getInputStream(); InputStreamReader isReader = new InputStreamReader(inStream); BufferedReader bufferedReader = new BufferedReader(isReader); String theTime = bufferedReader.readLine(); Aside from these and other java.io streams, you can also implement object-oriented typesafe protocols over TCP/IP of your own ilk by creating your own InputStream and OutputStream types. That is, you might consider encapsulating any proprietary protocol that needs to operate over TCP/IP inside one or more classes which can be constructed with the InputStream or OutputStream objects associated with a Socket. Type-safe calls on such custom protocol classes can then be made and can allow you to handle any socket protocol transparent to users of the custom streaming classes.

Conclusions TCP/IP is an extremely important communications protocol underlying all other higher-level distributed communications schemes examined in this book. TCP/IP is a reliable and connection-oriented protocol acting as the backbone of the Internet. A basic understanding of TCP/IP is of tremendous importance for the serious enterprise Java developer. Socket programming

- 274 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

is a term used to describe how to interface with the TCP/IP protocol suite from your applications. The java.net packages offer a simple and standard means to interact with a platform's underlying socket resources from Java. Socket programming can yield very efficient applications and is sometimes the only choice for solving a particular problem. However, the lack of any application/communications interface layer over TCP/IP causes one to perform a lot of hand-coding. As you could see from the examples in this chapter, a lot of programming effort was expended in just building an interface between the example application and the TCP/IP stacks. Future chapters on communications paradigms like CORBA, RMI, and DCOM help illustrate how such work can be handled for you by auxiliary distributed communications libraries and utilities.

Chapter 13. Web Communications IN THIS CHAPTER • • • • • •

The I nt ernet and t he World Wide Web HTTP CGI Servlet s HTML Docum ent s Dynam ic HTML Generat ion

The Hypertext Transfer Protocol (HTTP) over TCP/IP is the protocol used between Webbrowser– and Web-server–based communications. Common Gateway Interface (CGI) programs have long been the traditional means by which Web servers allowed a programmatic interface to HTTP requests and responses. Servlets offer a simple and more efficient Java-based mechanism for interfacing with HTTP requests and responses from within a Web server process. This chapter is mostly conceptual in nature and describes the Web-based communications model for you in the context of your reading about the other communications models utilized by enterprise Java applications in this part of the book. Part VI of this book, "Enterprise Web Enabling," describes how to practically Web-enable your enterprise in much more detail.

The Internet and the World Wide Web We briefly described the foundations of the Internet's TCP/IP protocol suite in Chapt er 12, " Net work Com m unicat ions." The ARPAnet began using TCP/IP in 1969 where it grew from just four hosts to approximately 200 hosts in 1981, 1,000 hosts in 1984, 300,000 hosts in 1990, and more than 35 million hosts at present. Clearly, the Internet has exploded as a medium to share and exchange information among people. But what is behind this explosion? Most people realize that without the user-friendly face of the World Wide Web (WWW), the market demand for Internet-based information delivery would never have grown so quickly, nor would it have changed our lives so much.

History of the Web In 1980, Tim Berners-Lee wrote a simple program at the European Laboratory for Particle Physics (CERN) that allowed for arbitrary traversal between nodes using hyperlinks. Almost 10 years later, in 1989, Berners-Lee wrote a proposal describing a means for organizing the vast amounts of information shared by many people on many machines at CERN using hypertextual links between such information. Although the concept of hypertextual linking was not new, Berners-Lee put together a very feasible and simple proposal for building a distributed hypertextual document-linking system that was pursued later in 1990. Eventually, the term "World Wide Web" was coined to describe the GUI-based browsing community that tapped into the prototype infrastructure.

- 275 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Over the next few years and with the help of a few co-workers, Berners-Lee and crew deployed working versions of the WWW browsers for CERN and took a demonstration of their WWW on the road to a few key conferences. By that time, various servers of hypertext pages usable by a WWW browser were established around the globe (approximately 50 WWW servers were available by January 1993). Later that year, Marc Andreessen, working at the National Center for Supercomputing Applications (NCSA) at the University of Illinois at Urbana-Champaign, created the Mosaic WWW browser capable of running on various operating-system platforms and enabling true multimedia content delivery via the WWW. CERN announced that the WWW technology would be available free for commercial use, and by the end of 1993 there would be approximately 200 WWW servers. Early in 1994, Marc Andreessen and a few NCSA co-workers left NCSA to form the Mosaic Communications Corporation, which became the Netscape Communications Corporation. Eventually, the W3 Organization was formed by MIT and CERN to help push standardization of the WWW, which has explosively grown to levels supporting more than 4 million WWW servers, more than 35 million Internet hosts, and more than 40 million Internet users. Thus, in just about 10 years of time, the World Wide Web grew from a laboratory concept to the economical, sociological, and political force that it is today. In 1990, most people still had to either physically transplant themselves to a library or bookstore to obtain certain information they were looking for or wait for such information to make its way into their home or business via newspaper or television. The overhead involved with pursuing information usually resulted in never even obtaining such information. Now, you can simply turn on your computer from work or home and locate just about any information you want on any topic in a matter of minutes. This economical and ease-of-information access has penetrated the enterprise and has thus become one of the key ways organizations present information to their employees, customers, and business partners. Enterprise development is thus inextricably intertwined with pushing and pulling information through this WWW-based communications medium. In this chapter, we will pursue understanding the basic concepts and approaches for communicationsenabling such information via the Web so that you can put it in context with other distributed computing paradigms described in this part of the book. Part VI describes in much more detail how to Web-enable your enterprise applications using Java.

URLs Before you can retrieve a Web page via the WWW, or for that matter access any resource on the Internet (an email address, an executable program, and so on), you'll need a way to identify where that resource is. Uniform Resource Identifiers (URIs) represent standard identifiers for any resource accessible via the Internet. A Uniform Resource Name (URN) is a type of URI that identifies a resource via some alias name. A Uniform Resource Locator (URL) is a type of URI that identifies a resource by specifying the exact location of such a resource on the Internet. Because URNs identify where to obtain resources on the Internet via a logical name, the actual location of the resource can change and the URN will still be valid. However, URLs are much more widely employed by Web-based software used on the Internet today. In fact, because URLs were first used by most people when referring to Web sites, some might think that URLs refer exclusively to Web-based resources, but they do not. URLs assume this general form: scheme://user:password@host:port/path/resource#section?parameters The scheme represents the protocol operating over TCP/IP through which the referenced Web resource can be accessed (for example, http, ftp, telnet, file). The optional user and password fields represent part of a standard way to transfer credential information via a URL for authentication that may be required for access to the requested resource. A hostname or IP address must be used in the host portion of the URL to identify the TCP/IP host location of the resource. The port may also be optionally supplied, depending on whether the requested resource has a socket listener on the default port for that scheme (that is, there's no need to add 80 for the scheme http if the WWW server is running on this default port for the Web).

- 276 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

After the protocol, the client identity, and a socket have identified a unique machine and process running somewhere on the Internet, the process resource and set of parameters used by that resource need to be specified. The path identifies the path to that resource on the particular host (that is, a subdirectory from some root context). The resource identifies the actual resource of interest (for example, HTML file), and the section can optionally be used to specify a sublocation within the resource location. Finally, the parameters field is also optionally used to pass a set of parameters that may be used by the resource if it is some sort of executable program requiring such values. Parameters are an ampersandseparated (&) set of name/value pairs of the following form: name1=value1&name2=value2&.... Finally, because URLs have parameters that can contain an arbitrary selection of characters in them, a mechanism for encoding such characters must exist to prevent certain control and nonprintable characters from corrupting processing along their path of delivery. The basic rule is that a control or nonprintable character that is embedded into a URL must be represented in its two-byte hexadecimal ASCII form prepended with a percent sign (%). Space characters, however, are encoded with a plus (+) sign. Generally speaking, any characters used in a URL that are not meant to be interpreted by any Web or network hardware/software and that are not letters, numbers, periods, underscores, or hyphens should be URL-encoded. Thus, to reference an HTML file named Buy Me!.html at www.beeshirts.com, your encoded URL might look as follows: www.beeshirts.com/Buy+Me%21.html. As shown in Figure 13.1, an encapsulation for a URL is provided by the java.net.URL class. In addition to getting and setting the various elements of a URL, a URL object can also be used to obtain a reference to a java.net.URLConnection object. The abstract URLConnection class is a base class encapsulating a connection between a client application and the resource location identified by the URL. Information can be read from and written to the URL via a URLConnection instance. A concrete instance of the abstract java.net.URLStreamHandler class is also associated with a URL to encapsulate a protocol handler for a particular URL protocol connection scheme. The java.net.URLStreamHandlerFactory is used to create a URLStreamHandler object given a particular URL protocol scheme name. Figure 13.1. Basic Java URL abstractions.

- 277 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

HTTP The Hypertext Transfer Protocol (HTTP) is a protocol built atop the TCP/IP protocol. HTTP began as a connectionless and stateless protocol whereby an HTTP client opened a socket connection to an HTTP server, issued an HTTP request stream of data, received an HTTP response stream of data back from the server, and closed the connection. That was it. Since the early days of HTTP, it has evolved only mildly into a protocol that can keep connections open for multiple response and request transactions. Furthermore, common techniques now exist outside of the protocol to provide a stateful nature to HTTP. HTTP/0.9 was first used during the early development stages of the WWW in 1990 as the protocol over which the hypertextual document-linking system created by Berners-Lee would operate. HTTP/1.0, introduced thereafter, made HTTP commercially viable and is currently the most widely implemented version of HTTP. The latest version, HTTP/1.1, improves on HTTP/1.0 by providing more functionality and support for allowing multiple transactions to occur between an HTTP client and server over the same connection.

Basic HTTP Behavior Figure 13.2 depicts a basic collaboration diagram for HTTP client/server behavior. In this figure, we see the HTTP client side on the left and the HTTP server side on the right. The HTTP client software represents the software implementing the HTTP protocol above the client-side TCP/IP stacks. An HTTP client making use of such HTTP client software will typically be a Web browser, for example. The HTTP server software also implements the HTTP protocol above a set of server-side TCP/IP stacks. A typical HTTP server example is a Web server. Figure 13.2. A basic HTTP behavioral diagram.

- 278 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The basic sequence of steps illustrated in Figure 13.2 are described here, with the step numbers in the diagram enclosed in parentheses: •

Server listens for requests (step 1): First, an HTTP server must listen for requests on a particular socket. For Web servers, port 80 is a standard and default port on which to listen for Web requests.



Client creates HTTP URL (step 2): The HTTP client software then submits a URL designating the protocol, hostname, optional port number, and path of the desired Internet resource to retrieve.



Client creates socket connection (step 3): The HTTP client software creates a TCP/IP socket connection given the desired hostname (or IP address) and a port number (default port 80).



Server accepts socket request (step 4): The HTTP server software listening for a request on that port accepts the client socket connection request.



Client creates HTTP request (step 5): Back on the client side, the HTTP client software creates an HTTP request out of the URL. The HTTP client software may also formulate an HTTP request given additional data to send to the HTTP server from the HTTP client.



The HTTP request is sent (steps 6 and 7): The HTTP request is then pushed through the open TCP/IP socket connection and received on the server side.

- 279 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Server parses/handles request (step 8): The HTTP server software then parses the HTTP request and takes whatever action is specified in the request.



Server generates HTTP response (steps 9, 10, and 11): The HTTP server software then generates an HTTP response message, which is sent back over the TCP/IP socket connection.



Client parses/handles HTTP response (step 12): The HTTP client software parses and handles the HTTP response from the server.



Socket connection is closed (steps 13 and 14): The underlying socket connection is closed.



Relay result (step 15): The result from all of this processing is then returned to the HTTP client that triggered this whole sequence of events.

As can be seen from Figure 13.2, a connection is created, a single request is handled with a response being generated, and then the connection is closed. Thus, server-side scalability becomes very practical because an HTTP server won't have to deal with as many open connections at a single time as would be the case if such connections remained open for the life of an HTTP client and server session. Of course, the concept of a "session" from the perspective of the HTTP protocol is meaningless because no such information is baked into the protocol.

MIME The Multipurpose Internet Mail Extensions (MIME) specifications define a standard for encoding binary data into ASCII, as well as a standard for indicating the type of data contained inside a message. Although MIME was originally used by email client software to describe how to interpret mail sent with multiple forms of media types (for example, pictures, text, and audio), MIME is now also used by HTTP to facilitate the exchange of multiple media types between Web servers and Web browsers. Web browsers use MIME types to tell Web servers what types of data they can support, and Web servers use MIME types to indicate the type of data they are sending. MIME types are identified in the following general format: type/subtype. The type classifies the general type of data being sent, such as application, audio, image, text, or video. The subtype defines the specific type of format used within the general class of types, such as gif or jpeg for image types. Thus, for example, the designation of a GIF-format image sent via the Web is formatted as image/gif. Nonstandard subtypes are designated with an x- in front of the subtype, such as image/x-bitmap for Microsoft bitmap images. Table 13.1 defines some typical MIME types and subtypes, along with typical file extensions. Table 13.1. A Few Key MIME Types MIME Type MIME Subtype Description text html HTML files (*.htm, *.html) plain Regular ASCII files (*.txt) image

gif

GIF image (*.gif)

jpeg

JPEG image (*.jpg)

- 280 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

audio video

application

x-bitmap

Microsoft bitmap (*.bmp)

basic

Basic audio files (*.au)

x-wav

Microsoft sound wave files (*.wav)

mpeg

Moving Pictures Experts Group videos (*.mpg)

quicktime

Apple QuickTime videos (*.mov)

x-msvideo

Microsoft Audio Video Interleave (*.avi)

java

Java Class file (*.class)

pdf

Adobe Acrobat file (*.pdf)

postscript

Postscript file (*.ps)

msword

Microsoft Word file (*.doc)

zip

Compressed ZIP file (*.zip)

As shown in Figure 13.3, java.net.ContentHandlerFactory objects can be used to create a special content handler instance that is associated with a particular MIME type. The abstract java.net.ContentHandler class is extended to represent a concrete content handler object associated with a particular MIME type. The ContentHandler returns an object of a particular MIME type read from a URLConnection. The java.net.FileNameMap interface is used to define a mapping between a file name and a MIME type String. Finally, a java.net.URLEncoder utility class encodes a string into a URL encoded MIME type format and the java.net.URLDecoder utility class decodes a MIME type URL encoded string. Figure 13.3. Basic Java MIME type handling utilities.

HTTP Requests

- 281 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

An HTTP request needs to indicate the nature of the request, indicate the resource desired, supply any other information to control the request nature, and supply any other data that may be of use in satisfying the request. HTTP requests tend to be human-readable and of the following general form: •

Request Method: An identifier for the type of HTTP request being made.



Resource ID: An identifier of the particular resource being requested (on same line as request method). The resource is usually the result of a concatenation of the path, resource, and parameters submitted in a URL.



HTTP Version: Specifies the HTTP protocol version to use (on the same line as request method and resource ID). The version is followed by a carriage return and line feed.



Header Name and Value Pairs: Optional sequence of standard header names and associated values are used to control the request-handling behavior. Each header is followed by a carriage return and line feed.



Blank Line: Blank line is followed by a carriage return and line feed.



Request Body: Optional data that can be used as part of a particular request.

HTTP request methods come in the core flavors: •

• •

• • •

GET: The GET request type is the most common type of request and is used to obtain a resource from the HTTP server. A GET request specifies the resource solely in the resource ID portion of the HTTP request and does not include any data in the request body. Because Web servers typically store GET information in environment variables, there is a limit to the amount of data that can be sent in a GET method. POST: Post request types don't have the request data limit that GET requests have. They store auxiliary request data in the request body typically in the form of name value pairs. HEAD: These requests fulfill the same function as GET requests but force the Web server to return only an HTTP header as opposed to any HTTP entity response data. PUT: This HTTP/1.1 type uploads a resource to the HTTP server. DELETE: This HTTP/1.1 type deletes a resource from the HTTP server. OPTIONS: This HTTP/1.1 type requests that the HTTP client be sent a set of HTTP server configuration options.

The complete set of request header types can be found in RFC 1945, but we list a collection of the most common request header types here: •

Accept: Specifies the type of MIME types supported by the HTTP client.

- 282 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • •

Accept-: Specifies other types of data or behavior supported by the client (for example, Accept-Language: en). Content-Length: Specifies the length of data in the request body. Authorization: Authorization information. User-Agent: Specifies browser information. Host: The hostname and port requested. Connection: Client indicates the desire to keep the connection alive (Keep-Alive) for multiple requests.

As an illustration of what an HTTP request looks like, consider the following example of a GET HTTP request generated from a Netscape Web browser when you enter the URL ht t p: / / www.assuredt ech.com : GET /index.html HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.5 – (WinNT; U) Host: www.assuredtech.com Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Here we see that the first line contains the GET request method and the resource /index.html, and uses HTTP version HTTP/1.0. This is followed by a series of header name and value pairs.

HTTP Responses An HTTP response must return the status of the response and information to control the response behavior, as well as perhaps the requested data itself. HTTP responses also tend to be human-readable and of this general form: •

HTTP Version: Identifies the HTTP version used.



HTTP Status Code: A numeric identifier of the status for the response (on the same line as HTTP version).



HTTP Status Description: An optional short description of the HTTP status code (on the same line as HTTP version and status code). It is followed by carriage return and line feed.



Header Name and Value Pairs: Optional sequence of standard header names and associated values are used to control the response-handling behavior. Each header is followed by a carriage return and line feed.



Blank Line: Blank line is followed by a carriage return and line feed.



Response Body:

- 283 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Optional data that can be used as part of a particular response. There are many response codes, but the general classes of codes are as shown here (the complete specification is in RFC 1945): •

100-199: Response is informational in nature only.



200-299: Response was successful.



300-399: Response is a redirection to another location.



400-499: Response designates a client request error.



500-599: Response designates a server-side error.

Furthermore, some common response headers are shown here (the complete specification is in RFC 1945): •

Date: Date and time response was created.



Server: Identifies the server.



Content-Type: Identifies the MIME type of the response body.



Content-Encoding: Indicates MIME encoding scheme.



Connection: Although keeping connections open for multiple client-side requests over a small timeout period is the default for HTTP/1.1, a server may issue a close value response to indicate that it has closed the connection.

As an illustration of what an HTTP response looks like, consider the response to the HTTP request sent earlier: HTTP/1.1 200 OK Date: Sat, 30 Oct 1999 15:36:30 GMT

- 284 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Server: Apache/1.2.5 FrontPage/3.0.4 Connection: close Content-Type: text/html





Assured Technologies, Inc.









Here we see that the first line contains the HTTP version used, HTTP/1.1, the success status code 200, and the success status description OK, followed by a series of header name and value pairs, a blank line, and then the actual response entity data (that is, the HTML page).

Basic HTTP Handling in Java Figure 13.4 shows an extension of the URLConnection class built into Java by way of the java.net.HttpURLConnection abstract class. HttpURLConnection represents a type of URLConnection with support for the HTTP protocol. The HttpURLConnection defines a collection of static HTTP response codes. A request method String and a flag indicating whether or not redirects should be followed can be get or set as part of the HttpURLConnection interface. Furthermore, response messages as well as various error and status information about the connection can be obtained from the HttpURLConnection object. The HttpURLConnection class can thus be used as the basis for building basic web client functionality into your Java applications. Figure 13.4. Basic Java HTTP URL connections.

- 285 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Tracking Sessions outside of HTTP Given that HTTP is a stateless protocol, how do Web sites such as ht t p: / / Am azon.com know that the HTTP request sending your credit-card information at one instant is to be associated with another HTTP request for your book order the next instant? The answer is that the Web servers at ht t p: / / Am azon.com somehow force your subsequent HTTP requests to contain some identifying information that the server side can associate with your user session. But how you ask? Baking Session IDs into the URL and Request Body One way to accomplish the tracking of sessions outside of HTTP is to force your subsequent URL requests to contain some sort of session ID information. On the server side, the server

- 286 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

can then relate all HTTP requests that are received with such a session ID. The server can force your URL requests to be formulated in such a way because the servers are what generate the embedded URL links that you click on after you first enter their Web site. Thus, you may be clicking on a hyperlink that should vector you to some sales.html page, but in actuality, the hyperlink in the Web page might refer to http://bla.com/sales/ID5656/sales.html. Of course, the parameter portion of the URL may also embed session ID information. Another technique is to generate HTML pages on the server side which will cause session identifying information to be embedded into the request body portion of an HTTP request unbeknownst to you. Cookies Cookies are simple additions to the HTTP protocol first used by Netscape to maintain the state of a particular user's session on the Web. Cookies are values that are initially generated by a Web server and contained in one or more HTTP response headers. A cookie-capable Web browser maintains the cookie information so that future requests to a URL that match the information contained in a cookie can be sent back to the server via the HTTP request. The server can then relate such information with the cookie information that it saved in order to make the association that these two requests come from the same user session. The header on the server side that is packed into an HTTP response follows this form: Set-Cookie: name=value; expires=date; domain=domainName; path=pathName; secure If the Web browser is sending an HTTP request to a URL whose domain and path match one or more of the cookies stored, it will send each cookie name and value pair back to the Web server in an HTTP request header of the following form: Cookie: name1=value1; name2=value2; ...

HTTP-NG The "Next Generation" HTTP architecture currently being developed is HTTP-NG. HTTP-NG is a protocol architecture being pursued that not only will be connection oriented, but also will offer the capability to build stateful HTTP-NG–based servers. HTTP-NG will not only be downward-compatible with the existing HTTP protocols, but it will also support an extended application and messaging layer, allowing for the marshaling of types and the capability to group HTTP request methods into objects. HTTP-NG will thus offer the capability for applications built using CORBA, RMI, and DCOM to directly map to the type system supplied by HTTP-NG. Because such other computing paradigms as CORBA, RMI, and DCOM traditionally must "tunnel" through HTTP with a lot of extra overhead, this will further the cause for building truly object-oriented Web-based applications.

CGI The Common Gateway Interface (CGI) provides for a standard way to allow Web servers to pass off HTTP requests to external processes by spawning such processes, passing them the request data, and receiving response data. CGI determines the interface for Web servers to identify the fact that an HTTP request is indeed supposed to result in a CGI call. CGI also defines the way in which Web servers pull data from the HTTP request and set appropriate environment variables for the CGI process, as well as for how the Web server spawns the process passing it the HTTP request's resource parameters. CGI also puts constraints on the CGI programs themselves for determining how to return data to the Web servers (that is, as HTML pages perhaps with HTTP response headers). The basic flow of a CGI request via a Web server works as shown here: •

A Web browser sends an HTTP request formulated from some URL. For example, the URL http://www.bla.com/cgi-

- 287 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • • •

bin/customerQuery.cgi?customer=heilmann may get transformed into an HTTP request with the HTTP request header line POST /cgi-bin/ customerQuery.cgi?customer=heilmann HTTP/1.0. A Web server receives an HTTP request with a resource ID specifying the path to a resource, the resource name, and possibly a set of parameters to pass to this resource. If the Web server supports CGI, either it should have been configured to recognize the fact that the path refers to a directory where CGI programs are stored (for example, cgi-bin) or it will be configured to recognize the fact that the resource name ends with an appropriate extension (for example, cgi). The Web server will set certain environment variables derived from the HTTP request used by the CGI program. It will then spawn the CGI program identified by the pathname and resource name as a separate process, passing it the parameters also sent over to the Web server via the HTTP request. The spawned CGI program uses the environment variables and parameters passed to it to do whatever job it is supposed to do (for example, database query or remote printing). By virtue of being a CGI program, the program either must format the results in the form of an HTML page for the response body or must return the response headers and alleviate the Web server from this duty (that is, is a nonparsed CGI program). The CGI program then returns the results to the Web server via a standard output stream. The Web server then returns the results to the Web client by either first prepending the header values or sending the results back without further modification (if the CGI program is of the nonparsed persuasion).

To infuse state into your CGI programs, they too can implement one of the techniques mentioned earlier for providing state across HTTP session requests. That is, the CGI program could implement a technique forcing the client to send its session ID information via a URL or the request data body, or by using cookies. Of course, a lot of hand coding is required on the part of the CGI programmer to persist such session information so that it can be obtained and used during successive requests. CGI is one of the oldest and still very popular techniques for handling HTTP requests and generating HTTP responses. Part VI comments more on the scalability and actual usage of such techniques in much more depth, but we wanted to highlight here how CGI can really be viewed as one way to create applications that interface with the HTTP protocol.

Servlets The Java Servlet standard provides a way to allow Web servers to pass off HTTP requests to Java-based code by starting such code as a separate thread, passing request data to the servlet, and receiving back response data. Servlets are a sort of Java equivalent to CGI programs, with the major difference being that servlets run inside a thread as opposed to running as a separate process like CGI programs. Servlets are built by adhering to a standard interface defined by the javax.servlet packages. A servlet engine can then be installed inside a Web server to provide a mechanism by which Web servers can map HTTP requests to servlet requests and HTTP responses from servlet responses. The basic flow of a servlet request via a Web server works as shown here: •



A Web browser sends an HTTP request formulated from some URL. For example, the URL http://www.bla.com/servlets/CustomerQuery?customer=heilmann may get transformed into an HTTP request with the HTTP request header line POST /servlets/ CustomerQuery?customer=heilmann HTTP/1.0. A Web server receives an HTTP request with a resource ID specifying the path to a resource, the resource name, and possibly a set of parameters to pass to this resource.

- 288 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • •

If the Web server supports servlets (that is, has a servlet engine), it should have been configured to recognize the fact that the path refers to a directory where servlet programs are stored (for example, servlets). If the requested servlet has not been loaded, it will be loaded. The servlet engine then creates an instance of the servlet

HTML Documents The Hypertext Markup Language (HTML) provides the primary data format used to describe how a document is displayed inside a Web browser, as well as the controls provided by this document. HTML pages are sent in the response body of an HTTP response from the Web server to the Web browser. When inside your Web browser, HTML pages display familiar GUI widgets such as hyperlinks, text boxes, and submit buttons. When a user interfaces with the displayed widgets and submits a request, the Web browser transforms such events into HTTP requests that are sent back to the Web server. HTML has gone through several version upgrades and is now at HTML 4.0 in its versioning lifeline. HTML pages are by and large static constructs that are typically either read locally from a disk on the Web server or generated by some server-side application in a more dynamic fashion. Nonetheless, when the HTML documents leave the Web server in the form of an HTTP response, they end up at the browser and rest there in a fairly static state whereby statically defined text, images, audio, and a whole slew of HTML GUI widgets create the Web-based interface with which we are all familiar. Client-side scripting such as clientside JavaScript can help produce some behavior on the Web browser, but most pages you see today still remain constrained by the nature of their HTML elements identified by the HTML standard's set of tags. An HTML form (that is, ...) is one type of HTML element used to describe a type of HTTP request and an action to take. Some event, of course, must induce this action to occur. An HTML input element (that is, ) defined within a set of HTML form tags is used to designate a GUI element to display, as well as to either capture request data or induce the submission event of the actual HTTP request. HTML input elements can have different types such as text boxes, submission buttons, reset buttons, and check boxes. Of course, it is the submission type of input that is key for inducing the Web browser to collect all the data in between the form tags, create an HTTP request, and send it over to the Web server. Another type of HTML input element is known as a hidden input element. The hidden input element does not result in the display of any actual GUI element. Rather, the hidden element defines a name and value pair that can be set with some data which will then be mapped into the request body of an HTTP request. By sending such data to and from the HTTP server and the HTTP client, we then have the means by which session information can be baked into the HTTP request such that the HTTP server can keep track of which requests are from the same HTTP client.

Dynamic HTML Generation Dynamic HTML generation is a term that some people use to designate the creation of HTML pages dynamically on the server side. Servlets and CGI programs alike are often created to do just this. That is, based on some input from the HTTP request and perhaps any maintained session information, the servlet or CGI program can generate an HTML page with the appropriate tags, controls, and data embedded into the document. Different request data or session data may produce different HTML output for different users. Such Dynamic HTML generation can be expensive because it means a trip back to the Web server from the Web browser every time new HTML content needs to be brought down to the client. Dynamic HTML generation can also occur on the client side using some newly defined features in HTML 4.0. With Dynamic HTML being performed on the client side, trips back to the Web server can be alleviated and thus your Web server environments won't be taxed as much. Of course, the con is that more processing power is required on the client side than for static client-side HTML processing, but most modern desktop environments can handle the load. Of course, your browser version must support such Dynamic HTML extensions, but

- 289 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Netscape Communicator 4.0 and Microsoft Internet Explorer 4.0 both offer such support. However, as is to be expected, there exists a host of nonstandard Dynamic HTML features that one browser supports which the other does not. With Dynamic HTML's object-oriented interface, features now permit the Web browser to perform such activities as dragging and dropping from within the HTML page, moving objects around the page, displaying dynamic fonts, and layering content. So what does Dynamic HTML have to do with the Web communications focus of this chapter? It means that your interface to the HTTP response stream may have gotten a lot more difficult. Although generating simple static HTML pages from the server side may be fairly straightforward, going beyond the simple can become a tedious chore. As you'll see in Part VI , and in Chapt er 33, " JavaServer Pages," in particular, JavaServer Pages can make creating HTML content a lot easier than was the case with using Java Servlets. The programming paradigm for interfacing with the HTTP response stream will thus become a lot more palatable because the Web-enabling framework provided by the J2EE will prove to make your life a lot simpler.

Conclusions Web-based communications focus around the HTTP protocol built atop TCP/IP. The HTTP protocol is an inherently connectionless and stateless protocol. Furthermore, the interface to the HTTP protocol is currently very functionally oriented rather than object-oriented. Although there exists no real application/communications interface layer above HTTP in its current form, HTTP-NG provides a glimmer of hope for providing such an interface in the future. In the meantime, frameworks such as Java servlets can help simplify the interface to the HTTP request and response communications paradigm. Requests from the same user over multiple HTTP transactions can be related as a unique user session via a few hand-coding–based tricks outside of the HTTP protocol. However, the Java Servlet framework can also be used to handle some of the details for managing HTTP sessions for you.

Chapter 14. Modeling Components with CORBA IN THIS CHAPTER • • • • • •

CORBA Overview The ORB GI OP and I I OP Services, Facilit ies, and Business Obj ect s I DL Obj ect s by Value

The Common Object Request Broker Architecture (CORBA) is a language- and platformneutral body of specifications for building distributed object applications. CORBA applications are built in such a way that they are largely isolated from the details of communications code. In fact, CORBA applications are so defined that, from a CORBA client perspective, the distributed nature of a CORBA server can be completely transparent. The Common Object Services Specification (CORBAservices), the Common Facilities Architecture (CORBAfacilities), and CORBA business objects are all standards built atop CORBA to provide an even richer suite of distributed communication services and frameworks. The CORBA Interface Definition Language (IDL) offers up a language-neutral mechanism for defining distributed object interfaces with standards that exist for mapping IDL to Java, as well as for mapping Java to IDL. Finally, CORBA objects now have the capability of being passed either by reference or by value. In this chapter, you will learn: • •

The concept and architecture of the OMG's Common Object Request Broker Architecture (CORBA) The basic structure of the Object Request Broker (ORB)

- 290 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • •

The architecture of the General Inter-Orb Protocol (GIOP) and Internet Inter-Orb Protocol (IIOP) protocols over which CORBA clients and servers communicate The basic subcomponents of CORBAservices, CORBAfacilities, and CORBA Business Objects The basic structure of the CORBA Interface Definition Language (IDL), as well as the basic transformation rules for mapping IDL elements to Java elements The behavior and means by which CORBA objects can now be passed around by value

CORBA Overview As depicted in Figure 14.1, the Common Object Request Broker Architecture represents a standard model for creating objects and components whose services are to be distributable to remote clients. CORBA uses a standard communications model over which clients and servers implemented in a heterogeneous mix of languages and running on a heterogeneous mix of hardware and operating-system platforms can interact. CORBA is described via a collection of standards created by an organization known as the Object Management Group (OMG). Figure 14.1. Heterogeneous CORBA communications.

Note

You'll find the OMG's Web site at ht t p: / / www.om g.org. All CORBA specifications, proposals for specifications, and the latest news on CORBA can be found there.

- 291 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The OMG was founded in 1989 by a collection of largely hardware-oriented companies (including Sun Microsystems) with the mission of making standard and interoperable component-based software a reality. Since then, the OMG has grown to include more than 800 member organizations. The membership of the OMG ranges from large companies like Sun, IBM, Oracle, and even Microsoft to smaller companies and university groups. Aside from CORBA and platform interoperability, now the OMG also oversees standards established for UML. CORBA has become one of the most widely adopted standard architectures since the CORBA 1.1 specification was published in 1991. Since that time, the CORBA 2.X series of specifications has been the standard that has enabled CORBA to become more viable for the marketplace. CORBA 2.3.1 (ht t p: / / www.om g.org/ library/ c2indx.ht m l) was the latest specification finalized at the time of writing this book and is the standard in which we present most of our material. CORBA 3.0 is scheduled to be released in final form sometime in mid to late 2000 (ht t p: / / www.om g.org/ news/ pr98/ com pnent .ht m l). Nevertheless, we will comment on enhancements to expect in CORBA 3.0–based products throughout this book as well.

The Object Management Architecture Figure 14.2 depicts the Object Management Architecture (OMA). This high-level diagram provides scope and context for the CORBA specifications. At the highest level, we have application objects—perhaps created by you or purchased off the shelf—to offer businessspecific services in a distributed fashion via CORBA. Application objects are specific to an application and are not governed by any CORBA specification standard. However, the application-level CORBA Domain Interfaces are defined in actual OMG specifications to deal with application-specific services for a particular domain such as the Telecommunications, Manufacturing, and Finance application domains. At the lowest level, specifications that deal with the Object Request Broker (ORB) define exactly how distributed clients can remotely utilize the services of distributed servers in a language- and platform-independent fashion, as well as describing the underlying communications protocol in which such service utilization occurs. Interfacing with an ORB is by far the most commonly accessed layer by CORBA application developers. Above the layer of the ORB, we have CORBAservices (aka Common Object Services) specifications to define those distributable CORBA services that CORBAbased applications commonly rely upon, such as providing human-readable object names to object reference mappings and querying for objects using some search criteria. At a higher level than CORBAservices, we have CORBAfacilities to provide frameworks for building directly useful distributed services such as printing, email, and document-management facilities. Distributable application objects may use one or more of the services provided by any one of these OMA levels. Figure 14.2. The Object Management Architecture (OMA).

- 292 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CORBA 3.0 CORBA 3.0 will enhance the basic OMA with two fundamental additions: minimumCORBA and CORBAcomponents. The ORB layer of CORBA most suited for enterprise applications will now also come in an embedded flavor known as minimumCORBA. Thus minimumCORBA will result in a new ORB profile with features removed from the typical enterprise-style ORB to better enable usage of CORBA from within embedded applications. Of more relevance to the enterprise developer, the CORBAcomponents specification will define a standard set of interfaces to which CORBA components can be programmed to automatically inherit the services offered by a component container environment. The CORBAscripting specification will define how CORBAcomponents can be assembled in a standard way using whatever scripting language is defined for such component assembly. As we'll see in later chapters, the CORBAcomponents specification closely relates to the Enterprise JavaBeans specification. Because CORBA 3 was still under development at the time of this book's writing, Figure 14.3 is a sort of speculative view of what the new OMA model may look like when CORBA 3.0 comes to fruition in mid to late 2000. Figure 14.3. The OMA after CORBA 3.0?

- 293 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CORBA's Java Enterprise System Role Based on this short blurb of CORBA, you can see that the OMA offers much more than distributed object communications enabling capabilities. Rather, although the ORB will help communications-enable your distributed objects, the CORBAservices, CORBAfacilities, CORBA Domain Interfaces, and CORBA 3.0's CORBAcomponents all provide higher-level services and frameworks that help build entire enterprise applications. This chapter continues to describe the CORBA computing model in general, but the next chapter focuses on communications-enabling your enterprise applications with the CORBA ORB. Part I V, " Com m on Services for Dist ribut ed Ent erprise Com m unicat ions," and Part V, "Ent erprise Syst em s Assurance," discuss some of the CORBAservices in the context of distributed object security services. Part VI I , " Ent erprise Applicat ions Enabling," describes applications-enabling technologies that have relevance to CORBAfacilities and CORBA Domain Interfaces, as well as the new CORBAcomponents specifications.

The ORB The CORBA ORB is the key component of the OMA with which most CORBA developers and architects will come into contact. The reasons for this are fairly straightforward. For any technology to be useful in the practical world, it must be built from the ground up. That is, you might as well forget about building a CORBAservice unless you have an ORB to use it with. Furthermore, the robustness of any architecture greatly depends on the robustness of its lower layers. If the lower layers are unreliable, the higher-level layers will topple down or simply will not be very evolvable. At this stage of CORBA's evolution, CORBA developers are at a point where most will purchase relatively robust and interoperable ORB software off the shelf and spend their time interfacing with such products. As time goes on, implementations of higher-level OMA specifications will become more and more dependable, and more developers will have time to become familiar with use of such products. Interfacing with the ORB itself will be as low-level a consideration as directly interfacing with the Ethernet is now.

The ORB Concept The ORB is really just a set of CORBA specifications. The ORB specifications are implemented by CORBA vendors to produce what we also sometimes refer to as "an ORB." In such context, the term ORB actually refers to a collection of software libraries used either by CORBA clients to access distributed services or by CORBA servers to make their services

- 294 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

distributed. The architecture of an ORB and the types of components involved in its use are shown in Figure 14.4. Figure 14.4. The ORB architecture.

The two most important players in distributed object communications via an ORB are the CORBA client and the CORBA server. The CORBA server is simply a distributed object offering up some of its method calls for remote access. CORBA clients are those objects that make remote method calls on CORBA servers.

Client Side ORB Components Interface Definition Language (IDL) interfaces are language-independent descriptions of interfaces to CORBA server objects. Think of IDL as a language used for describing the methods you want to make distributed on your CORBA server classes. Most ORB vendors or other third-party vendors provide IDL compilers that map IDL interface specifications (typically stored in IDL files) into CORBA static interfaces and CORBA client stubs. CORBA static interfaces are the language-specific analogues of the IDL interfaces from which they were mapped. The CORBA client stubs handle the transformation of calls made on the CORBA static interfaces into calls that can be made over the wire on a distributed CORBA server. Client stubs handle packing (that is, marshaling) method-call parameters and unpacking (that is, unmarshaling) method-call return values to and from CORBA communications protocol message formats. Stubs also handle identifying which method on a particular CORBA server is being invoked by packing such identifying information into the marshaled data stream to be sent to the server. In addition to the static interfaces that can be generated from IDL, CORBA provides support for CORBA clients being able to invoke a remote method by dynamically providing information identifying the remote object and method to call, as well as providing the parameters to be used in the remote method to be invoked. This Dynamic Invocation Interface (DII) technique essentially bypasses use of any static interface definitions to directly talk with an ORB's remote method invocation mechanisms. Conceptually, you can think of DII being to CORBA programming as the Java reflection API is to Java programming. Interface Repositories are small databases used in some ORB implementations to hold the metadata descriptions of CORBA server interfaces in a machine-readable version of the CORBA Interface Definition Language. Interface Repositories have a standard API callable by CORBA clients and are also used by DII implementations.

ORB Protocols The ORB interface provides programmatic interfaces to the actual underlying ORB core. The ORB core libraries are those libraries needed on the client side for implementing the CORBA communications protocol. The higher-level CORBA communications protocol is the General Inter-ORB Protocol (GIOP), which maps messages created by stubs into message-transport

- 295 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

formats capable of being communicated between ORB implementations. The lower-level protocol used by CORBA is called the Internet Inter-ORB Protocol (IIOP); it is a transport layer for handling how GIOP messages are communicated over TCP/IP. Although other transports besides IIOP can be used, IIOP is by far the most popular protocol used in CORBA applications today.

Server-Side ORB Components On the server side, we have CORBA server skeletons, which are also generated by IDL compilers. Server skeletons are the server-side analogue of client stubs in that they unmarshal method parameter data into language-dependent types from the marshaled data sent over from the client. When a server skeleton method is invoked, it will unpack the marshaled data and call the appropriate server-side method with the expected parameter types. Likewise, any return data from the CORBA server implementation will be marshaled by the GIOP message data that can be sent back over the wire to the CORBA client. The Dynamic Skeleton Interface (DSI) is basically an API your CORBA implementations can utilize, allowing your servers to avoid generating any static skeletons and instead supporting a generic interface that your server implementation object must implement. This generic interface implementation must handle determining the type of call being made and extract the parameters passed over from the client. DSI essentially requires your server implementation to handle many of the steps that a server static skeleton would provide you, but it allows your server implementation to be implemented in a flexible fashion and handle calls dynamically. The Implementation Repository is a small database on the server side containing a runtime description of available object implementations, as well as information on how such objects should be activated upon client request. Such activation information in the Implementation Repository is used by the Object Adapter. The Object Adapter takes requests from the ORB core communications libraries and determines how to activate (that is, bring into memory) server implementations and funnel such requests to their static or dynamic skeletons. Both the Object Adapter and the core ORB libraries have interface APIs that CORBA servers can use.

GIOP and IIOP The General Inter-Orb Protocol (GIOP) and Internet Inter-Orb Protocol (IIOP) represent the communications layer above TCP/IP for CORBA-based applications. Both protocols are fairly simple in nature and offer the capability to build scalable CORBA servers. GIOP defines a means for mapping marshaled IDL data into a common way to represent data over the wire and a set of message formats encapsulating the request and reply semantics of distributed calls. IIOP maps GIOP message data into TCP/IP connection behavior.

GIOP Overview GIOP maps marshaled IDL data types into binary data streams to be sent over the wire. GIOP accomplishes this using a Common Data Representation (CDR) syntax for efficiently mapping between IDL data types and binary data streams. The binary data streams are formatted in one of eight simple inter-ORB message formats. Although not discussed here, certain Environment Specific Inter-Orb Protocols (ESIOPs) serve to replace GIOP for particular communications environments and tend to use their own transport layers as well (that is, not IIOP). Note

GIOP versions are defined according to the format major.minor. GIOP version 1.0 specified only seven message types, whereas GIOP versions 1.1 and 1.2 use an eighth message type.

- 296 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

GIOP messages also allow for object instance representations to dynamically relocate among ORBs. GIOP messages support all of CORBA's necessary functionality, as well as some fundamental CORBAservice-specific features. GIOP v1.0 and v1.1 permit only client-to-server connection establishment whereby only clients can initiate connections and send requests. GIOP v1.2 relaxes this restriction. Finally, in GIOP, multiple clients may share a connection via multiplexing.

GIOP messages sent between CORBA clients and servers contain a message header and message data. The header format simply consists of these elements: • • • • • •

Four bytes of characters always of the form: GIOP. Two GIOP protocol version numbers. A Boolean value indicating the byte order of the message (used in GIOP v1.0 messages only). A byte of bit flags used to indicate things like byte ordering, as well as whether this message is fragmented into multiple subsequent messages (used in GIOP v1.1 and v1.2 messages). A single byte message type identifier. The size of the message following the header.

These are the eight GIOP message types: •





• • •





Request (type 0): Encapsulate CORBA server object invocations from a client to a server. Reply (type 1): Encapsulate replies sent from CORBA server objects based on CORBA client requests. Exception data may be included in such messages. CancelRequest (type 2): Encapsulate notifications from clients to servers that it is no longer interested in receiving a reply from a previous request. LocateRequest (type 3): Encapsulate requests from a client to a server that attempt to resolve whether a server reference is valid and determine the address to which requests should be sent. LocateReply (type 4): Encapsulate responses from servers to clients from LocateRequest messages. CloseConnection (type 5): Encapsulate notifications from servers to clients about an impending connection closing. MessageError (type 6): Encapsulate notifications from either server or client in the event of an erroneously received message. Fragment (type 7): This message type was introduced in GIOP v1.1 and is sent following a previous message that has more fragments (that is, more messages) to send.

IIOP Overview IIOP maps GIOP message data into TCP/IP connection behavior and input/output stream reading/writing. When a CORBA server object is to be distributed, the ORB will make information uniquely identifying that object on the network available via an Interoperable Object Reference (IOR). IORs contain the IP address and TCP port of the CORBA server object's process. CORBA servers listen on those sockets for incoming client connection requests. CORBA clients obtain IOR handles and open connections to the associated socket. Depending on the ORB policy, the server will either accept or reject the connection requested by the client. Clients and servers then communicate GIOP messages over this connection. After a CloseConnection message is received, the ORB must close the TCP/IP connection. Note

- 297 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

IIOP versions are also defined according to the format major.minor. IIOP v1.0 is used with GIOP v1.0, whereas IIOP v1.1 can be used with GIOP v1.0 or v1.1, and IIOP v1.2 can be used with GIOP v1.0, v1.1, or v1.2.

Interoperable Object References An Interoperable Object Reference (IOR) is an address identifying a particular CORBA server object on a particular machine. Different transport protocols of CORBA have different IOR profiles. The standard part of an IOR and the profile of an IIOP-IOR contains such key information as this: • • • • • • •

Identifier of byte ordering (standard part of IOR). A repository ID identifying the object type (standard part of IOR). Two bytes designating the major and minor versions of IIOP supported (IIOP-IOR profile). A host or IP address string identifying where the CORBA server object resides (IIOPIOR profile). A TCP port number on which the CORBA server object listens (IIOP-IOR profile). A sequence of bytes representing the object key to which requests are directed. This value is proprietary to an ORB implementation but is not interpreted in any way by the client (IIOP-IOR profile). As of GIOP v1.1, a sequence of tagged components is also included in an IOR. Tagged components contain additional information used during object invocations (IIOP-IOR profile).

Services, Facilities, and Business Objects CORBA provides a number of specifications for defining standard interfaces to higher-level enterprise services. Above the ORB level, a set of common services utilized by most distributed enterprise objects are defined within the CORBAservices. Above the CORBAservices level, a set of common application interfaces and standard set of interfaces for specific applica tion markets are defined within the CORBAfacilities. Finally, CORBA also has specifications particular to certain market domains as well as a more generic business object framework. This section will briefly explore these various higher level CORBA specifications that rest above the ORB infrastructure.

CORBAservices The specification of the set of common CORBA object services is referred to as CORBAservices. CORBAservices are a collection of component specifications, each of which provides a service that can be used by distributed objects in general. That is, there is no application- or domain-specific nature to a CORBAservice. They represent truly modular components designed to solve one discrete and particular problem. We discuss a few of the key CORBAservices in more detail in the context of general distributed enterprise services in later chapters, but the following list of CORBAservices at least summarizes the distributedsystem issues that each CORBAservice attempts to address: •

Naming Service (aka CosNaming):Naming is the principal mechanism for locating objects (primarily in a distributed paradigm) via a human-readable name. The Naming Service maps these human-readable names to object references. Resolving a name means obtaining an

- 298 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

object reference associated with the name. Binding a name means to create a nameto-object relation. A name binding is always defined in terms of some naming context. •

Trading Object Service (aka CosTrading):The role of a Trader Service is to let your applications discover and obtain object references based on the services they provide. Exporters advertise services with the Trader, whereas importers discover services. An exporter gives the trader its object reference, a service type name, and a collection of service properties. Traders from various domains can pool their services into a federation. One can search for services via policies, constraints, and preferences. You can also use a policy to identify the set of service offers to examine, constraints to specify the search criteria, and preferences to order the results.



Relationship Service: The Relationship Service allows for the dynamic creation of relationships between objects. Relationships have roles, cardinality, and attributes. The Relationship Service also lets you link roles to relationships, create relationships, create roles, destroy relationships and roles, identify identical objects, navigate relationships, and iterate through relationships. Two base relationships exist for containment and reference.



Life Cycle Service: The Life Cycle Service provides services for creating, deleting, copying, and moving objects. Life Cycle Services provide mechanisms for locating factories that can be used to create objects, and also provide basic interfaces for copying, moving, and removing the object. Compound Life Cycle interfaces provide support for deep copies, moves, and deletes. Compound Life Cycle Services can collaborate with the Relationship Service in maintaining associations.



Externalization Service: Externalization Services provide a mechanism for transforming an object into and out of a stream. A stream factory can create a stream object. The client tells the stream object to externalize the object reference needing to be externalized. The Stream object then notifies the Streamable object to externalize itself. The object then writes its contents to the stream. A client telling the Stream object to internalize itself will go through a reverse process (that is, the Streamable object is told to internalize and the I/O stream is read). Externalization can make use of Relationship and Life Cycle Services.



Persistent Object Service: The Persistent Object Service (POS) provides interfaces for managing persistent objects. The POS is defined to be independent of an underlying storage medium (that is, ODBMS versus RDBMS versus flat files). Persistent Objects (POs) are objects whose state can be persisted. A Persistent Object Manager (POM) provides an interface for persistence operations and is called by POs for storage-independent interfaces to an underlying storage medium. Specific storage medium interfaces are provided with Persistent Data Services (PDSs). PDSs perform the actual work of moving data between storage and memory. Persistence may use Externalization, Life Cycle, and Naming to accomplish its duties.



Query Service:

- 299 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Query Service is a service for finding objects whose attributes adhere to a set of search criteria. Queries are created using SQL or OQL. Query Service operations include search, selection, insertion, and deletion on collections of objects. A query can be either directly executed or delegated to a query evaluator (for example, native RDBMS query facilities). Querying also involves creating collections and iterating over collections. A query evaluator evaluates a query. A query manager allows you to create query objects that encapsulate the preparation, execution, and status retrieval of query results. •

Object Collection Service: The Object Collection Service enables one to manipulate objects in a group (that is, queues, stacks, lists, arrays, sets, trees, and bags). Collections can be ordered or unordered, and key based or non–key based. Ordered collections can be sorted or sequential. Restricted access on collections is possible for collections such as queues and stacks.



Property Service: The Property Service is used for dynamic association of named attributes with components. Properties have a name (a string), a value (any), and a mode of operation (for example, read-only). Properties can be manipulated as a set.



Events Service: The Events Service provides a framework for objects to dynamically register and unregister for specific events. Event suppliers produce event data, and event consumers process event data. Suppliers can push events to consumers. Consumers can also pull event data from suppliers. Multiple suppliers and consumers communicate asynchronously over an event channel.



Licensing Service: Licensing provides services for starting, stopping, and monitoring object service usage, as well as for locating license managers. Licensing can also be used for recording time spent utilizing a particular service, as well as for limiting use.



Time Service: Time Services can be used to perform certain date- and time-related functions such as to obtain a commonly synchronized current time common across distributed systems, determine an ordering for events, and generate timer-based events. The Time Service is thus basically an interface to universal time and timers.



Transaction Service: An Object Transaction Service (OTS) lets multiple distributed objects participate in atomic transactions. Here, transactions involve agreeing on when use of a shared resource begins, when it ends, and the appropriate unit of rollback mechanism after a failure. Nested transactions could also be supported.



Concurrency Control Service: The Concurrency Control Service manages concurrent access to a shared resource by multiple objects. Concurrency prevents multiple users from simultaneously owning locks on objects.

- 300 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Security Service: The rather-lengthy Security Service specification provides a set of services for minimizing the probability of a malicious attack on the system to be secured. Authentication of trusted objects, object privileges, access control, audit trails, object accountability and certification, encryption, federated security domains, and security administration are all part of the CORBA security service model.

CORBAfacilities CORBAfacilities represent higher-level and more application-specific services and frameworks used in building distributed systems than is the case with CORBAservices. CORBAfacilities can provide component services such as email, printing, and globalpositioning information. CORBAfacilities are further broken down into two categories: Horizontal Common Facilities and Vertical Market Facilities. Horizontal Common Facilities Horizontal Common Facilities are those component service frameworks that are used by many distributed systems such as the following working specifications: •

User Interface Common Facility: Provide frameworks for building user interfaces with interfaces for user-interface styles, user-interface hardware, application enablers, user working-environment management, and user task management



Information Management Common Facility: Provide frameworks for building general information management systems with interfaces for modeling information, information storage and retrieval, information interchange, and information encoding and represen-tation



System Management Common Facility: Provide frameworks for building system- administration functionality with interfaces such as policy management, quality-of- service management, instrumentation, data collection, security, and event management



Task Management Common Facility: Provide frameworks for building user task-management functionality with interfaces such as workflow management, static and mobile agents, rule management, and automation

Vertical Market Facilities Vertical Market Facilities are those component service frameworks that are used to achieve interoperability in specialty distributed-system markets such as the following working specifications: •

Imagery Facility: Provide interfaces for the exchange and access of imagery data retrieved from sensors or artificially generated

- 301 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



International Information Superhighway (IIS) Facility: Provide interfaces for the management of wide-area networks



Manufacturing Facility: Provide interfaces to systems used in the manufacturing of products



Distributed Simulation Facility: Provide interfaces to distributed system components used for computer simulation



Oil and Gas Industry Exploration and Production Facility: Provide interfaces to systems used in the production and exploration of natural resources such as oil and gas



Accounting Facility: Provide interfaces for accounting software used in an enterprise



Application Development Facility: Provide interfaces for systems used in the development of software applications



Mapping Facility: Provide interfaces for systems used to create geospatial maps

CORBA Domain Interfaces and Business Objects CORBA Domain Interfaces represent collaboration between vendors and customers of systems being used in a particular industry to create CORBA standard interfaces to such systems, allowing for interoperability between the various system implementations. CORBA Domain Interfaces have been defined already for four key industries: • • • •

Manufacturing System Domain Interfaces Telecommunication System Domain Interfaces Financial System Domain Interfaces Healthcare/Medical System Domain Interfaces

Regardless of the domain-specific nature of such specifications, the OMG has created a Business Object Task Force in order to create a generic framework for creating such domainspecific objects based on a common Business Object Facility (BOF). The BOF specifies a generic business-object component from which all domain-specific business objects inherit. The BOF also specifies ways to assemble such business objects and how to mix-in use of particular CORBAservices. At the time of this book's writing, the BOF specification was still under development.

IDL The Interface Definition Language (IDL) in CORBA provides a way to describe interfaces to distributed CORBA servers in a language-independent fashion. An IDL description in an IDL file may be run through an IDL compiler to generate the language-specific stubs and skeletons to be used in a distributed CORBA application. CORBA clients use the generated

- 302 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

stubs, whereas CORBA servers make use of the CORBA skeletons. Actually, CORBA skeletons call your CORBA server implementations. Thus, in situations whereby you already have a class implemented in which you want to make its methods callable as a CORBA server object, you may then have to generate the IDL definition from the class definition manually or perhaps by using a tool if it is available. Various specifications describing mappings from IDL to particular languages exist, including mappings for Java, C++, C, Ada, Smalltalk, and COBOL. Additionally, a Java-to-IDL specification mapping also exists (to be described later).

Generic CORBA IDL File Format IDL is not terribly foreign looking. In fact, many syntax conventions may look familiar to you. A rough general format of an IDL file is defined as shown here: [#include ReferencedIDLFileName] module ModuleName { /* An IDL Comment */ Module's Type Declarations here: e.g. typedef type name; e.g. struct StructName {StructDeclaration} ; e.g. enum EnumType {EnumValues}; Module's Constant Declarations here: Module's Exception Declarations here: e.g. exception ExceptionName { [AttributeType name,…]}; Module's Interface Declarations here: e.g. interface InterfaceName [:InheritedInterfaceName] { Interface's Type Declarations here Interface's Constant Declarations here Interface's Exception Declarations here Interface's Attribute Declarations here e.g. [readonly] attribute AttributeType name; Interface's Method Declarations here e.g. [ReturnType] MethodName ([in|out|inout ParamType ParamName, …]) [raises (ExceptionName, …)]; } ; } ;

CORBA IDL-to-Java Mappings Table 14.1 defines many of the key IDL entities referred to in the basic IDL file previously outlined and provides examples for how IDL maps to Java code. On the left-hand side of the table, we present example snippets from an IDL file for the most significant types of IDL entities. On the right-hand side of the table, we present the main elements of Java code that are generated from the example IDL. Note that the mappings in the right-hand column reflect the most recent IDL-to-Java mappings assumed by the J2SE v1.3. Table 14.1. OMG IDL to Java Mappings

- 303 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

OMG IDL Entity Core Constructs Module module ejava { module corbach14 { … }; }; interface module ejava { module corbach14 { interface Customer { … }; }; };

exception exception FailedToGetCustomerInfo { string reason; long reasonCode; };

Java Mapping Java package package ejava.corbach14;

Operations interface containing all defined methods of interface: public interface CustomerOperations {…} and a signature interface implemented by stub and skeleton: public interface Customer extends CustomerOperations, org.omg.CORBA.Object, org.omg.CORBA.portable.IDLEntity {} and helper class: abstract public class CustomerHelper {…} and holder class: public final class CustomerHolder implements org.omg.CORBA.portable.Streamable {…} and stub class: public class _CustomerStub extends org.omg.CORBA.portable.ObjectImpl implements ejava.corbach14.Customer {…} and skeleton class (see "Other Constructs"). See note below for differences between this J2SE v1.3 style of Java generation from IDL versus the J2SE v1.2 style. Java Exception: public final class FailedToGetCustomerInfo extends org.omg.CORBA.UserException implements org.omg.CORBA.portable.IDLEntity { public String reason = null; public int reasonCode = (int) 0; … }

Get and set methods on the associated interfaces and classes: attribute boolean hasEmail; boolean hasEmail(); void hasEmail(boolean newHasEmail); read-only attribute Get method on associated interfaces and classes: readonly attribute boolean hasEmail(); boolean hasEmail; Java methods:void login(in string methods with in parameters void login(String userName, userName, String password) in string throws .failedToLogin; password) raises attribute

- 304 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

(failedToLogin); methods with out andinout parameters Void getLatestOrderByCustomer( in string customerID, out Order o ); void addNewOrder(inout Order o); Primitive Types void boolean char, wchar octet short, unsigned short long, unsigned long long long, unsigned long long float double fixed string, wstring FALSE TRUE Extended Constructs const any enum enum ShirtColor { RED, GREEN};

Holder class for out and inout parameters and methods:void getLatestOrderByCustomer( String customerID, .OrderHolder o); void addNewOrder( .OrderHolder o);

void boolean char byte short int long float double java.math.BigDecimal java.lang.String false true public static final org.omg.CORBA.Any Java class version of enum: public class ShirtColor implements org.omg.CORBA.portable.IDLEntity { public static final int RED = 0; public static final int GREEN = 1; public static .ShirtColor from_int(int value) { …} … }

struct struct Order{ long orderID; long customerID; string orderDescription; };

Java class with public members: public final class Order implements org.omg.CORBA.portable.IDLEntity { public int orderID = (int) 0; public int customerID = (int) 0; public String orderDescription = null; … }

An array: typedef Order listOfOrders[30];

Array helper: abstract public class listOfOrdersHelper{…} and Array holder: public final class listOfOrdersHolder implements org.omg.CORBA.portable.Streamable {…}

- 305 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Unbounded or Bounded sequence: Sequence helper: abstract public class OrdersHelper{…} typedef sequence Orders; Sequence holder: public final class OrdersHolder typedef sequence implements Orders; org.omg.CORBA.portable.Streamable {…} union Java class: union DataStoreUnion public final class DataStoreUnion switch(DataStore){ implements case ORACLE: string org.omg.CORBA.portable.IDLEntity { oracleValue; case SYBASE: string public String oracleValue() sybaseValue; {…} default : long public void oracleValue(String value) defaultValue; {…} }; public String sybaseValue() {…} public void sybaseValue(String value) {…} public int defaultValue() {…} public void defaultValue(int value) {…} … } and helper: abstract public class DataStoreUnionHelper{…} and holder: public final class DataStoreUnionHolder implements org.omg.CORBA.portable.Streamable {…} Other Constructs CORBA::ORB org.omg.CORBA.ORB CORBA::Object org.omg.CORBA.Object CORBA:: pseudo-objects in general

Pseudo-object definition in CORBA IDL maps to a particular type in Java such as: org.omg.CORBA.

Server implementation using inheritance (sometimes confusingly referred to as the "BOA approach").

Java CORBA server implementation must extend the IDL-generated _ImplBase skeleton class. The IDL-generated _tie_ skeleton class will delegate calls to your Java CORBA server implementation. Your Java server must implement the IDL-Generated Operations interface.

Server implementation using delegation ("TIE approach").

Note

Note that the Java mappings presented in Table 14.1 are with respect to the most recent standard mappings for IDL to Java ( ht t p: / / www.om g.org/ corba/ clchpt er.ht m l# ij lm ) and integration of RMI/IIOP with CORBA. The J2SE v1.3 IDL-to-Java compiler utilities assume such a mapping standard. The J2SE v1.2 IDL-to-Java compiler utilities differ slightly and do not assume as complete of an integration between RMI/IIOP and CORBA. In particular, IDL interface entities using J2SE v1.2 style mappings do not generate

- 306 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Java operations interfaces by default and such interfaces are therefore not extended by the signature interfaces. Furthermore, helper classes are not declared abstract when generated using the J2SE v1.2 compiler utilities.

IDL Compilation Compiling IDL into Java code requires use of an IDL-to-Java compiler. An IDL-to-Java compiler utility is used with the Java IDL CORBA component that comes equipped with the J2SE. The Java IDL IDL-to-Java compiler is a command line utility that is used to generate Java stubs and skeletons given an IDL file. The Java IDL component IDL-to-Java tool comes pack aged with the J2SE v1.3 distribution and is referred to as idlj. A special Java IDL IDLto-Java tool must be separately downloaded if you are using the J2SE v1.2 (the version used with the J2EE) and is referred to as idltojava. Note

The J2SE v1.3 idlj compiler utility is located beneath the bin directory of your root J2SE v1.3 installation. The J2SE v1.2 compatible idltojava compiler utility can be downloaded from ht t p: / / developer.j ava.sun.com / developer/ earlyAccess/ j dk12/ idlt oj ava.ht m l. Note that you will need to use the -fno-cpp flag when using idltojava to tell the compiler not to attempt any C/C++ preprocessing before compiling the IDL.

To generate Java code from an Example.idl file, simply type the following for idlj:

idlj Example.idl …and similarly for idltojavawe have the following: idltojava –fno-cpp Example.idl Note that we use the -fno-cpp flag to tell the compiler not to attempt any C/C++ preprocessing before compiling the IDL. To generate client-side Java bindings from an Example.idl file, simply type the following for idlj: idlj -fclient Example.idl …and similarly for idltojava we have the following: idltojava –fno-cpp –fclient Example.idl To generate server-side Java bindings from an Example.idl file, simply type the following for idlj: idlj -fserver Example.idl …and similarly for idltojava we have the following: idltojava –fno-cpp –fserver Example.idl By default, the IDL-to-Java compiler will generate server-side skeletons which will require you to implement a CORBA server that inherits from a base class in order to be CORBA-enabled (to be discussed in more detail in the next chapter). You can flag the compiler to generate

- 307 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

skeletons that will enable your server implementation to use delegation (the "TIE" approach) versus inheritance if you so desire, by using the following for idlj: idlj -fserverTIE Example.idl …and similarly for idltojavawe have the following: idltojava –fno-cpp –ftie Example.idl IDL files can include other IDL files for definitions of types. When compiling an IDL file that includes another IDL file as reference, you may want to generate Java code for every included IDL file as follows for idlj: idlj -emitAll Example.idl …and similarly for idltojavawe have the following: idltojava –fno-cpp –fmap-included-files Example.idl Although you can nest modules inside of modules to produce a desired package naming for your Java classes, it may be desirable to keep your IDL files fairly clean by eliminating any unnecessary outer-level modules such as this: module com { module BeeShirts { module Example { … }; }; }; You may rather prepend the package prefixes that would be generated from such module definitions and avoid adding these definitions to your IDL file by using this command for idlj: idlj -pkgPrefix Example com.BeeShirts Example.idl This will prepend the com.BeeShirts package prefix to a module named Example in your Example.idl file. Similarly for idltojava, a package may be directly prepended to the modules defined in an IDL file as in the following case: idltojava –fno-cpp –p com.BeeShirts Example.idl

Java-to-IDL Mappings In addition to mapping IDL to Java, you can map your Java code to IDL. Tools such as Inprise's Caffeine perform just such a task. Caffeine provides the Java2IIOP utility for generating CORBA stubs and skeletons and Java2idl for generating actual IDL according to a set of rules thought up by the folks at Inprise. However, more recently, with the help of Inprise, the CORBA 2.3 specification has outlined a standard way to map Java classes to IDL. We will discuss this procedure in more detail in Chapt er 16, " RMI Com m unicat ions." Caffeine and the OMG standard Java-to-IDL mappings allow you to take servers defined in Java using Java's built-in distributed object communications paradigm known as RMI and convert them into CORBA-enabled servers. This paves the way for enabling your Java-based servers to be accessed by non-Java clients via the CORBA communications paradigm. This provides the benefit to Java developers of being able to create Java programs using the programming language that they are already familiar with and alleviate their having to know and understand the semantics and syntax of IDL.

Objects by Value

- 308 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Most of the distributed computing performed by CORBA-based programs involves a CORBA client invoking methods on a CORBA server sitting somewhere on the network. As discussed previously, the CORBA client by and large accomplishes this by communicating with a clientside stub that packs up the request and ships it over the wire. A server-side skeleton takes the request and calls the CORBA server, retrieves the results, and ships them back over the wire. The client-side stub then unpacks the results for the CORBA client. The client thus only communicates with a reference to the server. The actual work is performed somewhere else on the network. Inprise's Caffeine extension was one of the first products to introduce the idea of passing around CORBA objects by value instead of exclusively by reference. With objects by value, a CORBA object is passed by value as a method parameter. The OMG later came up with a standard CORBA objects-by-value specification that happens to be part of the CORBA 2.3 specification. However, the standard as it exists right now is somewhat overly complicated and even has a few holes. CORBA product vendors have been thus somewhat slow to implement the specification as it currently stands. Some of the objects-by-value specification's current shortcomings may be addressed in CORBA 3.0.

Value Types The valuetype keyword is a new core construct in CORBA identifying an object that is to be passed by value. The valuetype keyword is used inside of a module to tag such objects much in the same way that the interface keyword tags objects to be passed by reference. For example module ejava { module corbach15 { valuetype Order { … }; }; }; The identified valuetype can then be used as a parameter inside of a method call on a regular CORBA interface: module ejava { module corbach15 { interface Customer { void setOrder(in Order myOrder); … }; }; };

Objects by Value Behavioral Sequence As an example behavioral sequence involving passing objects by value, the following general sequence of events occurs between an object (SEND) that sends a value type (VT) to a receiving object (RECEIVE): • •

SEND makes a call onRECEIVE: An object named SEND calls a distributed method on an object named RECEIVE, which takes a valuetype object VT as a parameter. VT

- 309 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

is marshaled on the sending side:The ORB being used by SEND marshals the state of VT and packs this information and a Repository ID associated with the VT type into the GIOP message sent to the ORB used by RECEIVE. •

VT is unmarshaled on the receiving side:The ORB being used by RECEIVE unmarshals the state description sent by SEND's ORB.



Attempt reconstitution of VT with local implementation: The ORB being used by RECEIVE then uses the Repository ID associated with this type and attempts to map this ID to a locally available implementation. This step is language dependent, but a factory is generally used for this step and reconstitutes a new instance of the VT object on the receiving side.



Else, attempt reconstitution of VT with downloadable ( CODEBASE) implementation:If the implementation could not be found locally, the ORB for RECEIVE will attempt to load the object from a location defined in a CODEBASE parameter sent along in the GIOP message with the VT object by SEND's ORB. This CODEBASE may refer to a downloadable implementation. This step is also language dependent.



Else, attempt reconstitution of VT with base class implementation: If the implementation could not be downloaded, a base type of the VT object will be used if the keyword truncatable was used in the IDL specification for any base type used by the VT valuetype.



Else, throw exception: If VT could not be reconstituted, the exception NO_IMPLEMENT is raised.



If VT is available, use it: If an implementation of VT was available locally or was downloadable, the RECEIVE object can make calls onto the VT instance. Such calls will not be delegated to a remote server instance as is the case with passing objects by reference, but rather will be made on the local copy of the VT object.

Objects by Value Marshaling Objects being passed by value can opt either to use the built-in ORB marshaling features for packing and unpacking the state of an object being passed by value or to customize how the state of an object being passed by value is packed and unpacked for over-the-wire transmission. If you want to use the built-in state marshaling, you simply use the valuetype keyword to identify the CORBA type as usual. Otherwise, you must prepend the keyword custom in front of the valuetype keyword to designate the desire to customize the marshaling of the state. For example module ejava { module corbach15 {

- 310 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

custom valuetype Order { … }; }; }; The org.omg.CORBA.portable.ValueBase Java interface is mapped from the CORBA::ValueBase pseudo-object used to identify a CORBA value type. Two types of subinterfaces to ValueBase exist: StreamableValue and CustomValue. If a value type is to use the ORB's underlying state marshaling mechanisms, the mapped Java value type will generate a class that extends the org.omg.CORBA.portable.StreamableValue Java interface. If you desire to customize state marshaling for your object, the org.omg.CORBA.portable.CustomValue Java interface is used. On the receiving side in Java, when the ORB attempts to reconstitute an object instance with a particular implementation class, it attempts to strip off leading data in the RepositoryID field passed over the wire in the IIOP message and append DefaultFactory to the data retrieved. If the data in the middle was a valid Java class name, a factory can be reconstituted (if that factory class name is in the CLASSPATH). Otherwise, an exception is thrown. By declaring a method as returning a factory type, you can explicitly generate a factory interface to be used by the ORB on the receiving side to reconstitute an instance of the passed-by-value object implementation.

Objects by Value Code Example As an example, let's define a type Order as a valuetype in IDL as follows: module ejava { module corbach15 { valuetype Order { private long orderID; private string orderDate; private double orderValue; void setCustomerID(in string customerID); string getCustomerID(); factory createOrder(in long id, in string date, in double value); }; }; }; This IDL will generate a collection of interfaces and classes that can be used to implement pass-by-value semantics in your Java programs. For example, the abstract class Order implementing the StreamableValue interface will handle all basic state marshaling and unmarshaling functionality: public abstract class Order implements org.omg.CORBA.portable.StreamableValue { protected int orderID = (int)0; protected String orderDate = null; protected double orderValue = (double)0; private static String[] _truncatable_ids = { ejava.corbach15.OrderHelper.id () };

- 311 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public String[] _truncatable_ids() { return _truncatable_ids; } public abstract void setCustomerID (String customerID); public abstract String getCustomerID (); public void _read (org.omg.CORBA.portable.InputStream istream) { this.orderID = istream.read_long (); this.orderDate = istream.read_string (); this.orderValue = istream.read_double (); } public void _write (org.omg.CORBA.portable.OutputStream ostream) { ostream.write_long (this.orderID); ostream.write_string (this.orderDate); ostream.write_double (this.orderValue); } public org.omg.CORBA.TypeCode _type () { return ejava.corbach15.OrderHelper.type (); } } An OrderHelper and an OrderHolder are also generated as usual with most Java mappings: public final class OrderHolder implements org.omg.CORBA.portable.Streamable { public ejava.corbach15.Order value = null; public OrderHolder (){ } public OrderHolder (ejava.corbach15.Order initialValue){…} public void _read (org.omg.CORBA.portable.InputStream i){…} public void _write (org.omg.CORBA.portable.OutputStream o){…} public org.omg.CORBA.TypeCode _type (){…} } abstract public class OrderHelper { public static void insert (org.omg.CORBA.Any a, ejava.corbach15.Order that){…} public static ejava.corbach15.Order extract (org.omg.CORBA.Any a){…} synchronized public static org.omg.CORBA.TypeCode type (){…} public static String id (){…} public static ejava.corbach15.Order read( org.omg.CORBA.portable.InputStream istream){…} public static void write (org.omg.CORBA.portable.OutputStream ostream, ejava.corbach15.Order value){…} public static ejava.corbach15.Order createOrder(org.omg.CORBA.ORB orb, int id, String date, double value){…} } The valuetype factory defined within the Order valuetype and associated with the createOrder() method is used to generate and define factory objects for the Order. An

- 312 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

OrderValueFactory interface extends the ValueFactory with the specific creation method defined in the interface and returning the Order value object: public interface OrderValueFactory extends org.omg.CORBA.portable.ValueFactory { Order createOrder (int id, String date, double value); } Finally, an OrderDefaultFactory class can provide a default implementation of the value type factory: public class OrderDefaultFactory implements OrderValueFactory { public Order createOrder (int id, String date, double value) { return new OrderImpl (id, date, value); } public java.io.Serializable read_value (org.omg.CORBA_2_3.portable.InputStream is) { return is.read_value(new OrderImpl ()); } }

Conclusions CORBA represents a standard model for creating objects and components whose services are to be distributable to remote clients. CORBA uses a standard communications model over which clients and servers implemented in a heterogeneous mix of languages and running on a heterogeneous mix of hardware and operating-system platforms can interact. The CORBA ORB provides a standard framework for communications via GIOP and IIOP, as well as for implementing an application/communication interface layer to insulate your CORBA clients and servers from communications-specific logic. Thus, CORBA clients and servers are offered a completely transparent interface to the underlying CORBA distributed computing platform. CORBAservices, CORBAfacilities, and CORBA domain and business objects offer higherlevel suites of distributed object communication services and frameworks with which you can more rapidly build distributed applications that also adhere to a common standard. IDL offers you a means to describe your CORBA-based distributed objects in a language-neutral fashion. Standard IDL-to-Java and Java-to-IDL bindings exist that fully enable Java-based CORBA programming. Finally, CORBA now allows one to pass objects around by value as well as by reference. CORBA is perhaps the most comprehensive and standard component model for building distributed applications. CORBA's ORB infrastructure offers a true separation of application code from communications code. The next chapter will provide code snippets and develop a simple client-server example application demonstrating all the concepts discussed in this chapter.

Chapter 15. CORBA Communications IN THIS CHAPTER • • • • •

The Very Dist ribut ed CORBA CORBA Vendors Java I DL CORBA I nt erfaces CORBA Servers and Skelet ons

- 313 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • •

I m plem ent at ion Reposit ory Obj ect Adapt ers I nt erface Reposit ory CORBA Client s and St ubs CORBA Nam ing

Building a CORBA-enabled application involves several considerations and steps that may be new to you. Design for scalability and choosing the right ORB products are key considerations and decisions to be made up front. Beyond ORB product selection and scalable design considerations, you'll need to be cognizant of a few core CORBA server implementation issues. Creating CORBA clients is much easier, but some design options still do exist. Because CORBA represents the collective catchall distributed communications standard from many organizational inputs, a lot of flexibility in design has been introduced into the CORBAapplication enabling process, as you'll see in this chapter. Flexibility in design, of course, means some overhead added to the very process of design, development, and infrastructure configuration. In this chapter, you will learn: • • • • • • • • •

How CORBA's distributed architecture can be used and how it can scale in the enterprise. About the key product vendors in providing CORBA-compliant ORBs and services. About the Java IDL package equipped with the J2SE/J2EE and its limitations. How to create and compile CORBA IDL files. How to create CORBA servers that use static or dynamic invocations and are implemented using either inheritance- or delegation-based approaches. How the implementation repository and object adapters are used by CORBA servers. How the interface repository is used by CORBA clients. How to create CORBA clients that use static or dynamic invocations. How CORBA clients can obtain initial references to CORBA servers.

The Very Distributed CORBA Inherent in the specification of CORBA is its presumed application in distributed enterprise environments. Such environments mean potentially large network client bases, which means that an individual CORBA server may be required to support a large number of CORBA client requests. Designing your CORBA servers to be scalable is thus paramount to good CORBA enterprise development practices. The actual development process you follow also affects how distributable your CORBA servers will be. Development of scalable distributed objectbased applications requires a different mindset than is the case with other development paradigms, such as the development of desktop applications or simple client/server interactions. This section describes which design issues affect the scalability of your CORBA servers and how the development process for building CORBA server applications generally may proceed.

Designing for Scalability From the outset, CORBA has mainly been applied in enterprise computing environments. This is a logical expectation because building enterprise-scale applications often involves connecting heterogeneous platforms, and organizations are very sensitive to the need for building systems that can interoperate. However, the very generic nature involved with creating a CORBA server allows one to essentially make any object distributable. If you were to follow this paradigm to the extreme and indeed make every object distributed, you would also be plagued with an extremely inefficient system due to all the communications and marshaling overhead that would be involved. That is, although you may enhance the parallel processing nature of your distributed application by creating many fine-grained CORBA servers, the effects of increased communications overhead and resource utilization (for example, process and socket creation) will rapidly begin to far outweigh the benefits of parallel processing.

- 314 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

It thus behooves you, the enterprise developer, to follow a few simple guidelines when creating standalone CORBA applications for the enterprise: • • • • •

• •

Create CORBA servers that act as service points that CORBA clients communicate with on a more coarse-grained basis. Create CORBA servers with methods that can process a large batch of similar operations and return a batch of results versus only providing finer-grained methods that must be called successively. Create CORBA servers that avoid offering direct getter and setter methods at the attribute layer on a distributed object. Create CORBA servers that act as service points to communicate with more finegrained objects on the server side behind the wall of its service interface to the client. Where possible, employ a smart proxying design on the CORBA client side. Smart proxying involves a design in which your client can make getter type calls on CORBA proxy objects that retrieve data from a local cache. The proxy defers making a distributed call until cache data is updated via a setter method call. You may be able to utilize an ORB vendor's support for such smart proxying features, or perhaps you can create the smart proxy framework for your CORBA clients if you happen to have a priori knowledge of the client-side implementation language. Become cognizant of the connection allocation policies of your ORB vendor implementation. ORBs that create a new connection for each CORBA client to CORBA server association will not scale very well. ORBs that can intelligently pool connections or use more efficient transports will offer a scalability advantage. Become cognizant of the thread allocation policies of your ORB vendor implementation. Many commercial ORBs will offer you options in terms of how threads are assigned to incoming requests. You might also consider creating your own thread pooling and request handling framework on the back end to support a scalable number of clients.

The J2EE and CORBA CORBA application design for scalability is of particular concern when creating standalone CORBA applications. As we'll see in Part VI I , " Ent erprise Applicat ions Enabling," use of J2EE containers and Enterprise JavaBeans (EJB) does not require as much developer cognizance of scalable application development techniques and principles. Chapt er 37, " Advanced Ent erprise JavaBeans Serving," in particular directly addresses how EJB and CORBA relate. Hosting EJBs as CORBA servers is primarily accomplished by the J2EE EJB container. EJB developers do however utilize CORBA APIs when the EJBs act as CORBA clients. Regardless, as we have stated throughout this book, there will indeed be many instances when implementation of standalone CORBA applications is still needed to solve particular enterprise application problems. CORBA Development Process The steps to take in building a CORBA client and server can seem tedious at first, but at least Java-based CORBA development is easier than CORBA development in other languages. When CORBA-enabling a server, you either may have a predefined application for which you want to provide a distributed interface or may be creating a distributed server from scratch. Regardless, the same basic steps can be followed: •

Define your IDL interface:

- 315 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

You must first create an IDL file with a description of the distributed CORBA server methods to be exposed via a CORBA interface. You may also choose to define types to be passed by value between CORBA clients and servers. •

Compile your IDL file: With an IDL file in hand, you can run such a file through an IDL-to-Java compiler to generate all necessary Java bindings for interfaces, stubs, skeletons, helpers, and holders. Depending on the desired server implementation method, you can generate server skeletons requiring that your server either inherit from or be delegated calls from the generated server skeletons.



Implement the CORBA server: You can then implement a CORBA server either by inheriting from a generated skeleton or by being delegated calls from a generated skeleton. If using a static skeleton is not to your liking, you can also use the Dynamic Skeleton Interface (DSI) to implement your server. After selecting how calls are mapped from either a static skeleton interface or DSI, you can implement the functionality behind your calls if they were not already implemented, and compile your server.



Implement a CORBA server registrar: You should then typically implement a separate class that registers a CORBA server implementation with an object adapter's implementation repository. The registrar will also typically register any "frontline" server object instances with an object adapter. You may also use the CORBA Naming Service to register human-readable names to any newly created object references. Note that only initial references to certain frontline server objects need be registered with a naming service and object adapter from a server registrar. After any initial CORBA server object handles are obtained by CORBA clients, other CORBA server objects will most typically be instantiated and registered by the CORBA servers that were initially or subsequently created.



Possibly register interfaces with an Interface Repository: You may optionally register a description of the CORBA server interfaces with an Interface Repository on the client side. However, for Java-based CORBA clients, access to a CORBA stub is usually available or perhaps remotely downloadable. If the Dynamic Invocation Interface (DII) is used, use of an Interface Repository will be needed.



Implement the CORBA client: A CORBA client can now be created using either the CORBA stubs created in a previous step or DII to make distributed calls on a CORBA server. A CORBA client must obtain a reference (IOR) to the CORBA server. It can do this by using a CORBA Naming Service, by converting an IOR in string form to a concrete IOR, or perhaps by using a vendor-specific approach. The client code can then be compiled and you are ready to begin client/server computing CORBA style.

CORBA Vendors Selecting the right CORBA products to use for your enterprise application can make or break acceptance and the success of CORBA in your projects. Knowing which components of a CORBA standard you need to purchase and which ones you might pursue implementing yourself is also important. In what follows, we first describe the set of tools you'll need in order

- 316 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

to build a CORBA-based application. We then describe which major CORBA product vendors do exist and what they offer in the way of CORBA implementations.

Basic Tools and Configuration Before you dive into developing a CORBA-based application, you'll want to pick up a few tools. Unless you're in the ORB-making business, you'll want to pick up a set of ORB libraries from a third-party vendor. You'll need to identify the target language in which you want to implement your CORBA server or from which you want to make a CORBA client. You should indeed evaluate your ORB vendor's implementation before deploying it into an enterprise application, especially in consideration of the scalability issues highlighted previously. And although you as a reader of this book will presumably be developing your CORBA-based applications in Java, you should still investigate the operating-system platform dependency of your ORB, because many commercial vendors will equip platform-specific util ities with their products. The good news for us enterprise Java developers, however, is that we already know our target language and we already have the J2SE/J2EE's Java IDL ORB reference implementation to use during development while we take time to evaluate an actual commercial ORB implementation to plug into a deployed enterprise environment. We will examine some ORB vendor implementations and Java IDL later in this chapter. In addition to the ORB libraries, you'll need an IDL-to-Java compiler, which usually comes packaged with a development environment from the vendor whose ORB libraries you have selected. Although use of a CORBAservice is not necessary, your particular application's demands may warrant use of one of the services described in Chapt er 14, " Modeling Com ponent s wit h CORBA." At the very least, use of a CORBA Naming Service will help you keep your CORBA applications more portable because without such a service, you will inevitably get locked into using a vendor-specific CORBA Naming Service analogue. CORBA Naming Services are often sold separately, however. With the proper tools in hand, configuring the infrastructure for running CORBA applications may depend largely on the ORB implementation you've selected. In the purest scenario, you will only need to install the ORB libraries on your server and client platforms and then start a CORBA Naming Service process somewhere on your network. The remaining steps to take depend on your particular CORBA application. Particular ORB vendor implementations may also require that you kick off other processes on your network. Although ORBs and CORBAservices have traditionally been key COTS products to purchase when building CORBA-based applications, more and more we are seeing a trend for such products to be integrated with other products. Server-side products such as Web servers, application servers, and even database servers are deploying their products with ORBs and a few CORBAservices built in. Even client-side Web browsers like the Netscape Communicator offer baked-in CORBA libraries that facilitate the capability to create Java applets with CORBA connectivity (aka Orblets). As more and more applications employ CORBA technology under the hood, your need for knowing the details behind creating CORBA-based applications may diminish. Rather, application servers and CORBAcomponents-based frameworks will increasingly make writing distributed CORBA-based applications more transparent.

Vendor Offerings Vendor offerings of products enabling CORBA connectivity currently tend to come in three basic flavors: (1) standalone ORB and CORBAservice products, (2) ORB and CORBAservice product suites, and (3) ORB and CORBAservice products integrated into another framework. Although some products are free, they typically are useful only in prototype and early develop ment environments while you select a more commercial-ready product. Of course, most commercial vendors allow you to download free evaluation copies of their software from their Web site. The vendors in the following list offer ORB and CORBAservice products for Java largely in standalone or product-suite form (with a few exceptions noted): •

Sun Microsystems's JavaSoft Organization (ht t p: / / www.j avasoft .com ): Perhaps you've heard of Sun Microsystems…they have defined this neat new enterprise framework called the J2EE. The Java IDL product equipped with the J2SE (and

- 317 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







• • • • •

therefore used with the J2EE) is a reference implementation of a set of Java-based ORB libraries and a naming service. Iona Technologies, Inc. (ht t p: / / www.iona.com ): OrbixWeb is its Java-based package of ORB libraries and development tools with COM integration (OrbixCOMet) and a CORBA Naming Service (OrbixNames). CORBAservices are also offered by Iona, such as a Trading Service (OrbixTrader), Security Service (OrbixSecurity), and the Events Service (OrbixEvents). CORBA-based application frameworks offer more integrated support such as the OrbixOTM and the Iona iPortal Suite. Inprise Corporation (ht t p: / / www.inprise.com ): The Inprise Corporation is the result of a merger between Borland and Visigenic. This merged Inprise Corporation and the Corel Corporation were also about to merge at the time of this writing. Visigenic created the Visibroker for Java Orb product. CORBAservices are offered by Inprise such as a Naming Service, an Event Service, and a Transactions Service. CORBA-based application frameworks also offer integrated support such as the VisiBroker Integrated Transaction Service (ITS) and Inprise Application Server. PrismTech (ht t p: / / www.prism t echnologies.com ): PrismTech offers many kinds of CORBAservices, such as the Naming Service, Event Service, Trading Service, LifeCycle Service, Property Service, Collection Service, Concurrency Service, Time Service, and Relationship Service. A suite of these services can be purchased via the OpenFusion package. PeerLogic (ht t p: / / www.peerlogic.com ): PeerLogic makes a Java-based ORB called DAIS J2. They also make C++–based CORBAservices such as Naming, Event, Transaction, Trader, LifeCycle, and Security Services. Object Oriented Concepts, Inc. (ht t p: / / www.ooc.com ): OOC makes the ORBacus for Java ORB product and a set of CORBAservices such as a Naming Service (ORBacus Names) and a Trading Service (ORBacus Trader). Expersoft (ht t p: / / www.expersoft .com ): Expersoft makes its CORBAplus ORB product for Java. It also makes a C++ implementation of the Naming and Event Services, as well as a Trading Service. JacORB (ht t p: / / www.inf.fu- berlin.de/ ~ brose/ j acorb): The JacORB is a free Java-based ORB, as well as a free Naming, Event, and Trading Service. Jorba (ht t p: / / j orba.cast le.net .au): Jorba is another Java-based shareware ORB currently in prototype form.

Additionally, as a few key examples, the following vendors offer COTS products and server frameworks that make use of an ORB and CORBAservices: • • •

Oracle (ht t p: / / www.oracle.com ): Although Oracle uses Java and CORBA in a variety of its products, its Oracle8i Database Server's architecture completely revolves around a baked-in Java Virtual Machine and an older version of the Visigenics ORB. Netscape (ht t p: / / www.net scape.com ): Netscape's Web server (the Netscape Enterprise Server) and Web browser (Netscape Communicator) both come equipped with an older version of the Visigenics ORB. BEA WebLogic (ht t p: / / www.beasys.com ): Aside from the J2EE-based WebLogic Server that we discuss in Part VI I , BEA WebLogic Enterprise integrates the J2EE with a CORBA ORB.

Thus, as you can see, there are many vendors out there who have either created the building blocks for building CORBA-based systems or have already begun to integrate CORBA into their server frameworks as the distributed communications enabler of choice. Apart from CORBA vendor solutions, many other more proprietary and application-specific uses of CORBA have been permeating our marketplace. Visit the OMG Web site (ht t p: / / www.om g.org) to keep abreast of where CORBA is being used today.

Java IDL

- 318 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Java IDL is a Java-based set of CORBA 2.0–compliant libraries for Java, including an IDL-toJava compiler and a CORBA Naming Service implementation (tnameserv). Java IDL currently does not implement an Interface Repository, however, and as a result, Java IDLbased CORBA clients cannot use DII. CORBA servers built atop the Java IDL ORB are also limited to being transient by nature, meaning that dormant CORBA objects cannot be stored for activation upon client request given a persistent reference to that object. Other commercial ORBs do support such activation of dormant CORBA objects, however. Java IDL also does not support many of the usual BOA calls in light of the fact that the BOA is deprecated in favor of the POA. However, Java IDL also did not implement the POA at the time of this writing. Instead, a few calls on the org.omg.CORBA.ORB class exist to connect and disconnect servers from the ORB, and run as a transient CORBA server. Similarly, tnameserv also runs only as a transient service, meaning that all registered object information will be lost when it is shut down. Java IDL was first available as a separately downloadable package of Java libraries that could be used with your JRE. The J2EE (by virtue of requiring the J2SE physical distribution) comes equipped with Java IDL for building Java-based CORBA clients and servers. Because Java IDL is packaged with the J2SE, any J2SE-based application can act as a CORBA server or client. Note

As mentioned in the last chapter, the J2SE v1.3 comes with an idlj compiler for IDL-to-Java compilation. A separate idltojava IDL-to-Java compiler can also be separately downloaded for use with the J2SE v1.2. Additionally, a special IDL-toJava compiler used with RMI/IIOP can be downloaded and used with the examples in this chapter. We describe how to obtain and use such a compiler in a subsequent section.

CORBA Interfaces You should now be armed with the conceptual framework and knowledge of which tools you'll need to build CORBA-based applications. Now you can begin the first step in creating an actual CORBA application. Such a first step requires that you define a distributed interface to each CORBA server class via CORBA IDL. The IDL interfaces used in our example application that we will create here are shown in List ing 15.1 (Order.idl), List ing 15.2 (ClientReceiver.idl), List ing 15.3 (Customer.idl), and List ing 15.4 (QueryServer.idl). Note

The CORBA IDL interfaces and all code examples used in this chapter are contained on the CD in or under the examples\src\ejava\corbach15 directory. Four subdirectories also exist under the Chapt er 15 directory, including examples\src\ejava\ corbach15\regular, which contains the basic CORBA example code used here. The examples\src\ejava\corbach15\delegation directory contains example code almost identical in nature to the basic example code with the exception that the CORBA servers use the CORBA delegation (that is, "TIE") implementation technique instead of the inheritance used by the core examples. The directory examples\src\ejava\ corbach15\dynamic contains example code for DII and DSI, and the examples\ src\ejava\corbach15\irquery directory is used to illustrate what gets inserted into an Interface Repository.

- 319 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

List ing 15.1 depicts an Order IDL struct and typedef for a sequence of Orders to encapsulate the minimum information needed to satisfy a simple BeeShirts.com order. Note that the Order object here could also have been appropriately defined as a valuetype if the Orbs you are using support Objects By Value. Chapt er 14 illustrated just such a concept.

Listing 15.1 CORBA IDL Order (Order.idl) module ejava { module corbach15 { struct Order { long orderID; string orderDate; double orderValue; } ; typedef sequence OrdersSeq; } ; } ; The ClientReceiver interface shown in List ing 15.2 will be used to implement a CORBA server on the client side of our application that the server side will call (that is, a callback). Thus the client side's ClientReceiver object will simply take a sequence of Order objects from the server side. Listing 15.2 CORBA IDL Client Callback (ClientReceiver.idl) #include "Order.idl" module ejava { module corbach15 { interface ClientReceiver { void setResultOrders(in OrdersSeq orders); } ; } ; } ; The Customer interface of List ing 15.3 is used to distribute an interface encapsulating a BeeShirts.com customer. Note that in an actual application, you would typically want to avoid defining an interface at this low level of granularity in order to be used in scalable enterprise environments. That is, defining IDL interfaces at the attribute level in particular will mean that a distributed call will result for each client attempt to get or set an attribute value. However, for the sake of simplifying our example and seeing utility in demonstrating a CORBA anti-pattern, we will refrain from the best practices for the time being. Listing 15.3 CORBA IDL for a Customer (Customer.idl) module ejava { module corbach15 { interface Customer { attribute string firstName;

- 320 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

attribute attribute attribute attribute attribute attribute attribute attribute

string string string string string string string string

lastName; address1; address2; city; state; zip; phoneNumber; emailAddress;

} ; typedef sequence RegisterdCustomerNames; } ; } ; The QueryServer interface of List ing 15.4 describes the primary server-side CORBA interface for our application. It is CORBAservices that operate at this level of granularity that are of the kind most appropriate for building scalable applications. The QueryServer offers a very spe cialized set of interfaces to illustrate the CORBA-enabling concepts at work. A call to findCustomersWhoOrderdForMoreThan() finds customers who spend more than a certain amount of money, binds them to a lookup service, and returns a sequence of customer IDs. A method register() takes a ClientReceiver callback interface and client receiver name to register CORBA client callbacks. A method findOrdersWhichAreFrom() finds the orders for a given state and passes the set of associated orders to the registered ClientReceiver objects. Listing 15.4 CORBA IDL for a Query Server (QueryServer.idl) #include "Customer.idl" #include "ClientReceiver.idl" module ejava { module corbach15 { interface QueryServer { RegisterdCustomerNames findCustomersWhoOrderdForMoreThan(in float value); void findOrdersWhichAreFrom(in string state); void register(in string name, in ClientReceiver clientReceiver); } ; } ; } ;

CORBA Servers and Skeletons Whereas IDL defines the distributed interfaces available to a distributed service, a CORBA server and skeleton represent the implementation of that interface. Most of the complex design and implementation decisions associated with building a CORBA-based application are associated with server-side development. Compilation of IDL can generate CORBA skeletons that are then linked to your CORBA server implementations. The remaining discussion in this section describes how to implement CORBA servers using the CORBA skeletons generated by IDL compilation.

Compiling the IDLs and Generating Skeletons After defining your IDL, you'll want to run the IDL through an IDL-to-Java compiler to generate the CORBA skeletons used by your CORBA server implementations. The IDL-to-Java compiler used with Java IDL and RMI/IIOP is called idlj. Before you use idlj, however,

- 321 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

you'll want to determine what type of servers you'll want to create. That is, do you want to implement your CORBA server using skeleton inheritance or delegation (aka the TIE approach)? After this decision is made, the appropriate option can be added to the command line of your idlj invocation to generate the appropriate skeleton types. Note

At the time of this writing, the separately downloadable IDL-to-Java compiler (that worked with Java IDL in the J2SE v1.2) required a separate C++ preprocessor for compiling our IDL files. Even though C++ preprocessing could be turned off with a simple flag, the compiler was then not able to interpret our IDL #include directives. You can use the J2SE v1.3 Java IDL IDL-to-Java compiler with our examples, but we wanted to explain how to use our examples with the J2SE v1.2, since that is the Java runtime used with J2EE v1.2.

Therefore, as an IDL-to-Java compiler choice for use with our examples, we use the compiler that can also be used with RMI/IIOP. You must first download and install the RMI/IIOP standard extension for use with the J2SE v1.2 platform. The RMI/IIOP download package and instructions can be found at ht t p: / / j ava.sun.com / product s/ rm i- iiop/ index.ht m l. You also must set a RMI_IIOP_HOME environment variable to the root directory for your RMI/IIOP installation when running any examples. Note that it is very important to make sure the orb.properties file generated during this installation is copied properly to your [JAVA_HOME]\jre\lib directory. The installation program may attempt to copy this file to another directory that it perceives as the JRE library directory, so step through the installation process carefully.

The IDL-to-Java compiler used with RMI/IIOP can then be downloaded and installed. The RMI/IIOP IDL-to-Java compiler can be downloaded from ht t p: / / developer.j ava.sun.com / developer/ earlyAccess/ idlc/ index.ht m l. A single idlc1_0_1ea.zip file is downloaded which contains a single idlj.jar file that must be copied into the [RMI_IIOP_HOME]\lib directory.

The run.bat file in the examples\src\ejava\corbach15\regular directory generates stubs and skeletons for regular inheritance-based implementations using something akin to this:

idlj -fall Order.idl idlj -fall Customer.idl idlj -fall QueryServer.idl idlj -fall ClientReceiver.idl The run.bat file in the examples\src\ejava\corbach15\delegation directory generates stubs and skeletons for regular inheritance-based implementations using something akin to this: idlj -fallTie Order.idl idlj -fallTie Customer.idl idlj -fallTie QueryServer.idl idlj -fallTie ClientReceiver.idl The inheritance technique involves generating a skeleton from which your CORBA server implementation will inherit. The delegation technique involves generating a skeleton that will

- 322 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

call your CORBA server, which implements a generated Java interface. The con, of course, with the inheritance approach is that your server will be unable to inherit from any other class due to Java's single-inheritance limitation.

Creating the CORBA Servers If you are using the inheritance approach, you should take note that it may be a good general idea to separate your business logic implementation from any CORBA-specific library dependencies by hand-coding the delegation of calls from your CORBA server implementation to a business logic class. This is why we illustrate such an adapter in Figure 15.1's depiction of a CORBA server built using inheritance. Note the similarity to Figure 15.2's illustration of a CORBA server built using delegation. Figure 15.1. A CORBA server built using inheritance.

Figure 15.2. A CORBA server built using delegation.

- 323 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

In both cases of building a MyServer implementation from the MyServer.idl file, a MyServerOperations interface and a MyServer interface are generated. However, in the case of Figure 15.1, the _MyServerImplBase abstract class needs to be inherited from your MyServerImpl object, which can also delegate to your business logic code. Delegation to your business logic code helps keep your logic separate from your distribution paradigm (CORBA here). Of course, in using the delegation model (that is, the TIE approach) of Figure 15.2, the _MyServer_TIE delegation class will be generated for you and will delegate calls to your MyServerImpl implementation, which now must implement the MyServerOperations interface. Listings 15.5, 15.6, and 15.7 show the implementations for our CustomerImplementation, ClientReceiverImplementation, and QueryServerImplementation CORBA servers, respectively. Note

The complete set of code examples for the regular CORBA servers implemented using inheritance can be found on the CD-ROM in the examples\src\ejava\corbach15\ regular directory. We have also included a set of code examples on the CD not shown here that implement the same servers using delegation; this can be found in the examples\src\ejava\corbach15\delegation directory. The run.bat files in both directories will compile your server implementations. These run.bat files actually build and execute all files associated with the example. Pause statements are inserted into these scripts before each process that is spawned. You should wait for each process to start and initialize before allowing the next process to start.

- 324 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

You can ignore the bind() method implemented by the CustomerImplementation class defined in List ing 15.5 for now. But note that all getters and setters needing implementation based on the attributes defined in the IDL List ing 15.3 have been implemented by this class for a distributable Customer object instance.

Listing 15.5 CORBA Customer Implementation (CustomerImplementation.java) package ejava.corbach15.regular; import org.omg.CosNaming.NamingContextPackage.*; import org.omg.CosNaming.*; import ejava.corbach15.*; public class CustomerImplementation extends _CustomerImplBase { private String firstName; private String lastName; private String address1; private String address2; private String city; private String state; private String zip; private String phoneNumber; private String emailAddress;

public void bind(String name) { try{ NamingContext namingContext = NamingContextUtility.getNamingContext(); // bind the Object Reference in Naming NameComponent namingComponent = new NameComponent(name, ""); NameComponent nameComponent[] = { namingComponent} ; namingContext.rebind(nameComponent, this); } catch(Exception e){ System.err.println("Error:"+e); e.printStackTrace(); } } public String firstName () { return firstName; } public void firstName (String newFirstName) { firstName = newFirstName; } public String lastName () { return lastName; } public void lastName (String newLastName) { lastName = newLastName; } public String address1 () {

- 325 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

return address1; } public void address1 (String newAddress1) { address1 = newAddress1; } public String address2 () { return address2; } public void address2 (String newAddress2) { address2 = newAddress2; } public String city () { return city; } public void city (String newCity) { city = newCity; } public String state () { return state; } public void state (String newState) { state = newState; } public String zip () { return zip; } public void zip (String newZip) { zip = newZip; } public String phoneNumber () { return phoneNumber; } public void phoneNumber (String newPhoneNumber) { phoneNumber = newPhoneNumber; } public String emailAddress () { return emailAddress; } public void emailAddress (String newEmailAddress) { emailAddress = newEmailAddress; } } The ClientReceiverImplementation class of List ing 15.6 implements the one remote method declared in the IDL List ing 15.2. The setResultOrders() method simply prints the list of orders received. Listing 15.6 CORBA Client Receiver Implementation (ClientReceiverImplementation. java)

- 326 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

package ejava.corbach15.regular; import ejava.corbach15.*; public class ClientReceiverImplementation extends _ClientReceiverImplBase { public void setResultOrders (ejava.corbach15.Order[] orders) { System.out.println("Received :"+orders.length); for(int i =0; i. Som e t ags st and by t hem selves whereas ot hers have leading and t railing t ags wit h dat a insert ed in bet ween, such as a leading t ag and t railing t ag. The various t ags also m ay have at t ribut es em bedded wit hin t he init ial t ag, usually in t he form of nam e- value pairs, such as . Colors specified using a hexadecim al ident ifier or color nam e and sizes specified in num bers of pixels or percent ages of a displayed page are com m on exam ples of at t ribut es em bedded in various HTML t ags. The general st ruct ure of an HTML docum ent includes a heading and body. As an alt ernat ive t o displaying a single HTML page inside of an HTML body, fram es m ay also be used t o display and cont rol different windows wit hin t he sam e HTML page. We describe each elem ent of t he following sam ple HTML docum ent st ruct ure in t he sect ions t hat follow:

[ [] [ [HTML Document Title] ] ] [ The Body of your HTML Document here… Document display elements:

- 814 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Use formatted text, tables, inline images, and hyperlinks.

- 815 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

H e a dings

The HEAD t ags inform a browser t hat t he inform at ion cont ained wit hin t he and t ags is header inform at ion associat ed wit h an HTML docum ent . Such header inform at ion is used by your browser as nondisplayable cont rol inform at ion:



Meta- Data

Met a t ags indicat ed by t he t ag designat e inform at ion t hat describes som e feat ure of your HTML docum ent . Such inform at ion is not displayed by your Web browser. Rat her, t he inform at ion is associat ed wit h your HTML docum ent and is oft en insert ed t o enable search engines t o learn m ore about t he nat ure of your part icular HTML page. Met a t ags can designat e any nam e- value pair of m et a inform at ion using . Here's an exam ple of a valid generic nam e- value m et a t ag pair:



BEESHIRTS.COM



Body

The BODY t ags inform a browser t hat inform at ion cont ained wit hin t he and t ags designat es t he port ion of an HTML docum ent t hat is t o be displayed in a browser window. You can also set t he background, t ext , and link color default for your docum ent by set t ing nam e- value pairs according t o t he following st andard nam es wit hin t he init ial t ag: •



• • •

t o set t he background color. t o set t he link color. t o set t he link color aft er it has been followed. t o set t he link color when it is clicked. t o set t he t ext color.

For exam ple, t o set t he default background color t o whit e and t he t ext color t o black using hexadecim al not at ion for t hose colors inside of a BODY t ag, we have t his:

- 817 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t o insert unint erpret ed com m ent s int o HTML docum ent t o insert a horizont al line ( aka horizont al rule)

I nline I m a ge s

I m ages are also com m only added t o HTML docum ent s for display wit hin t he HTML page. The IMG t ag designat es such im age insert ion. designat es from where such an im age file can be obt ained relat ive t o t he current HTML page's URL. An ALIGN nam e- value at t ribut e pair can be insert ed wit hin t he IMG t ag t o indicat e whet her t he im age is t o be posit ioned t o t he TOP, BOTTOM, MIDDLE, LEFT, RIGHT, or CENTER of t he screen. For exam ple



- 819 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Ta ble s

The TABLE t ags inform a browser t hat inform at ion cont ained wit hin t he

and
t ags is t o be displayed as a t able of inform at ion in an HTML docum ent . The and t ags block off a row in t he t able. The and t ags block off a t able cell in each row. The and t ags cont ain t able header cells. For exam ple


Small Medium
Tennis Pro Shirt Yes Yes
Millennium Shirt Yes Yes


Fr a m e s

An HTML fram e enables one t o part it ion how HTML inform at ion is displayed wit hin t he sam e browser window. A collect ion of fram es can be indicat ed bet ween and t ags. Each fram e wit hin t he FRAMESET t ags can t hen be indicat ed via a t ag. Ot her FRAMESET t ags can also be nest ed wit hin out er FRAMESET

- 820 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t ags. Various nam e- value pairs defined wit hin fram es and fram e set s are as shown here: • • • • •

• • •

t o designat e t he size in rows of a fram e set eit her in pixels or as a percent age size of a docum ent . t o designat e t he size in colum ns of a fram e set eit her in pixels or as a percent age size of a docum ent . t o define t he URL of t he docum ent t o be read for display in t his fram e. t o ident ify t he fram e wit h a nam e. t o indicat e whet her t he fram e should display scroll bars ( "yes") or not ( "no") . Can also be set t o t he default value of "auto" t o t urn scrollbars on and off depending on screen sizing. t o disable t he capabilit y t o resize t he fram e. t o indicat e t he t op and bot t om fram e m argins. t o indicat e t he left and right fram e m argins.

As an exam ple of using fram es wit h nest ed fram e set s, we have t he following HTML fram e- set snippet wit h a layout as shown in Figure 30.1: Figur e 3 0 .1 . An H TM L fr a m e - se t e x a m ple .

- 821 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







H TM L For m s HTML form s provide a m eans by which user input can be solicit ed from wit hin a Web browser's display of an HTML docum ent and subsequent ly t ransm it t ed t o t he Web server inside of an HTTP request . HTML form s are t hus one of t he m ore im port ant feat ures of HTML for Web- enabling ent erprise developers t o underst and. HTML form s are designat ed bet ween and t ags in a docum ent . FORM t ags can also have at t ribut es em bedded inside of

- 822 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t he leading t ag, such as . The t hree FORM at t ribut es are defined in t his way: •





METHOD=" MethodType " designat es t he HTTP request m et hod. The GET m et hod passes user input via a URL st ring t hat get s added t o t he resource ident ificat ion field of an HTTP request . The POST m et hod passes user input via nam e- value pairs in t he request body of an HTTP request . ACTION=" ActionValue " designat es t he act ion t o be perform ed. A URL as t he act ion value specifies t o what base URL inform at ion is t o be sent . A mailto direct ive can indicat e t o what em ail address inform at ion is t o be sent . ENCTYPE=" EncodingType " designat es t he m et hod in which t he input inform at ion is encoded v ia a MI ME t ype and subt ype. The default encoding form at is application/ x-www-formencoded.

As an exam ple of a basic FORM specificat ion for post ing dat a t o a part icular URL, we have t his:

\n" + "\n" + "\n" + "\n" + "I received following Data from client " ); } /** * To generate HTML Body */ private void generateHTMLBody(String[] data) { System.out.println("
"); // 0th element in data is the input String from the Client Hashtable receivedValues = generateHashtableFromString(data[0]); if(receivedValues == null){ System.out.println("No data Received "); } else{ Enumeration keys = receivedValues.keys(); System.out.println(""); while(keys.hasMoreElements()){ System.out.println(""); String key = (String)keys.nextElement(); String value = (String)receivedValues.get(key); System.out.println(""); System.out.println(""); } System.out.println("
"+key+ " "+value +"
"); } System.out.println("
"); } /** * it converts the input String to a hashtable using delimiters */ private Hashtable generateHashtableFromString(String inString) {

- 827 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

if(inString == null){ return null; } StringTokenizer stringTokens = new StringTokenizer(inString, "&"); Hashtable returnTable = new Hashtable(); while(stringTokens.hasMoreElements()){ String subString = stringTokens.nextToken(); StringTokenizer subTokens = new StringTokenizer(subString, "="); String name = subTokens.nextToken(); String value = ""; if(subTokens.hasMoreElements()){ value = subTokens.nextToken(); } returnTable.put(name, value); } return returnTable; } /** * close html tags */ private void generateHTMLClose() { System.out.println("\n"); } public static void main(String[] args){ SampleCGIExample cgiExample = new SampleCGIExample(args); } } Many Web server environm ent s designat e a part icular direct ory for st oring CGI - based applicat ions. A com m on direct ory nam e used is cgi-bin. You m ight t hus first com pile and st ore your SampleCGIExample Java class file in t he cgi-bin direct ory for a part icular Web server root direct ory using t his:

javac –d /cgi-bin ejava.webch30.SampleCGIExample

Because t he Java class is not direct ly execut able wit hout a JVM inst ance first being invoked from t he com m and line, t he Web server will also need anot her helper script file t hat calls t he applicat ion, such as t he following direct ly execut able UNI X script call also added t o t he cgibin direct ory:

- 828 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

#!/bin/sh java ejava.webch30.SampleCGIExample

I f such a direct ly execut able script or one like it is st ored in a file called CGIShellExample in t he cgi-bin direct ory, as an exam ple, t hen t he following FORM t ag at t ribut es can be used in an HTML docum ent when point ing a browser t o invoke t he dynam ic behavior of a CGI applicat ion:

function checkKeyFields(){ // Read value from INPUT email field var emailField = document.contactForm.email; if(emailField.value == ""){ // Generate a pop-up alert message alert("Email Field Should be filled "); return (false); } // now submit form return(true); }







- 833 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Because m any Web program m ers have com e t o learn JavaScript t hrough t heir client - side Web page developm ent effort s, t he t endency t o use JavaScript on t he server side and em ploy t he sam e knowledge along wit h opport unit ies for code reuse has m ade server- side JavaScript a popular solut ion for som e developers. Server- side JavaScript insert ed int o an HTML file bet ween special SERVER t ags can be read by a server- side JavaScript runt im e engine and dynam ically generat e inform at ion t o be displayed in an HTML docum ent using t he following:

write("Hi There!"); // Write to client document var clientName = Client.name; write("Client is :"+clientName); // Write to client document

Nevert heless, use of JavaScript on t he server side is fraught wit h perils. For one, t he lack of any real OO support for inherit ance and encapsulat ion violat es m uch of t he foundat ional success t hat obj ect orient ed program m ing languages offer in t erm s of scalabilit y, reusabilit y, and m aint ainabilit y ( see Chapt er 2, " Obj ect - Orient ed Soft ware Developm ent for t he Ent erprise" ) . Server- side JavaScript runt im e engines also provide m inim al inherent scalabilit y from a resource m anagem ent and concurrency m anagem ent point of view. JavaScript does support a m eans t o call int erface JavaScript code wit h Java code. Bot h client - side and server- side Java- JavaScript int erfacing adds som e flexibilit y t o JavaScript as a bridging t echnology. However, t he int erface bet ween Java and JavaScript runt im e environm ent s also can add significant and at t im es buggy overhead when dat a t ypes are being t ransferred bet ween runt im e environm ent s.

- 834 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

VBScr ipt A subset of t he Visual Basic program m ing language can also be used as a script ing language via VBScript in bot h t he client and t he server side. VBScript is Microsoft 's preferred script ing approach for Web enabling on t he client and server side. VBScript can be int erpret ed by t he Microsoft I nt ernet Explorer for client - side Web browser processing and using t he Microsoft I nt ernet I nform at ion Server for server- side Web server processing. Server- side VBScript is prim arily used by t he Microsoft Act ive Server Pages t echnology t o be explored in a bit m ore det ail lat er in t his chapt er. On t he client side, em bedded VBScript is ident ified bet ween SCRIPT t ags as shown here:

Because VBScript leverages m uch of t he exist ing developer knowledge of Visual Basic and Basic, it has significant developer support . The sim plicit y of VBScript has also enabled it t o becom e a popular Web- enabling solut ion. Pe r l As a final not e, t he Perl language has also been used for Web enabling on t he server side. Because Perl is considered t o be a sim ple language t o underst and and has a synt ax fam iliar t o m any UNI X script ing gurus, it is oft en used for quick Web- enabling solut ions. Furt herm ore, Perl as a language has also been around since 1987 and has t hus gained considerable developm ent support over t he years. However, t he scalabilit y and ent erprise applicabilit y of Perl on t he server side are ext rem ely lim it ed, as is t he case wit h m any server- side script ing solut ions. Alt hough som e support exist s for calling Perl script s direct ly from wit hin a Web server's process space ( for exam ple, t he Apache Web server) as well as from wit hin an HTML docum ent , m any Web servers use Perl script s wit hin a CGI applicat ion. A Perl script file is placed inside of a CGI direct ory and t hen referenced wit hin a URL like any ot her Web page or CGI applicat ion. Thus a URL, such as http://www.BeeShirts.com/cgi-bin/hello.pl, m ay reference a Perl script like t his:

- 835 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

#

File name : hello.pl

# Main part of Perl script calls write_document subroutine and exits &write_document(); exit(0); # This subroutine calls print_html subroutine sub write_document { @print_html(); } # This subroutine generates HTML to an output stream sub print_html { print "Content-type: text/html" , "\n"; print " "; print " "; print " Hello World "; print " "; print " "; print



D ocum e nt Type D e finit ion H e a de r A DTD, if present , m ust be declared in t he beginning of an XML docum ent aft er t he XML declarat ion. The root - cont aining elem ent nam e for t he XML docum ent is used t o ident ify t he XML docum ent t ype for which t he DTD defines st ruct ure and charact erist ics. The charact ers delim it t he boundaries of t he DTD's definit ion. A DTD and root elem ent nam e are t hus defined using t he following delim it ers:

- 850 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A DTD st ored at som e ext ernal URL m ay also be referenced wit h a syst em ident ifier and ut ilized by t he current DTD using t he following general form :

A public ident ifier m ay also be used wit h a syst em ident ifier t o reference an ext ernal DTD. The public ident ifier m ay be used by an applicat ion t o det erm ine t he alt ernat ive locat ion of t he DTD. Ot herwise, t he applicat ion will use t he syst em ident ifier URL. This is t he general form of use for public ident ifiers wit h syst em ident ifiers:

Ele m e nt D e cla r a t ions An elem ent declarat ion wit hin a DTD defines t he charact erist ics of a nam ed elem ent as it should exist wit hin t he XML docum ent . Elem ent declarat ions are defined wit hin charact ers and have one of t he following general form s: • • • • • • • • •

Em pt y Cont e nt : The nam ed elem ent is defined t o have no cont ent and is t herefore an em pt y elem ent if it has t his form :

Any Cont e nt : The nam ed elem ent is defined t o have any cont ent , and t herefore t he DTD allows any cont ent defined for t he nam ed elem ent if it has t he following form :

Cont e nt M ode l: A part icular cont ent m odel is defined t o const rain t he cont ent s of t he nam ed elem ent wit h an appended quest ion m ark ( ?) designat ing t hat t he m odel is

- 851 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • • • • • •

opt ional, an appended ast erisk ( *) designat ing t hat t he m odel m ay cont ain zero or m ore of t he m odel elem ent s, and an appended plus sym bol ( +) designat ing t hat t he m odel m ay cont ain one or m ore of t he m odel elem ent s. The basic form at for t he cont ent m odel is t his:



- 856 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

- 857 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE











H ype r lin k in g in XM L Hyperlinking in XML involves t he associat ion of URLs t o resources ( for exam ple, im ages and XML docum ent s) , as well as defining t he relat ionship bet ween resources. Linking specificat ions in XML was once referred t o as t he eXt ensible Linking Language ( XLL) and is

- 858 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

now divided int o t wo separat e specificat ions: XLink and XPoint er. The XML Linking Language ( XLink) defines how resources are referenced from wit hin XML docum ent s and is em bodied wit hin an evolving W3C specificat ion ( ht t p: / / www.w3.org/ TR/ xlink/ ) . The XML Point er Language ( XPoint er) defines a m echanism for addressing different port ions of an XML docum ent and is also em bodied wit hin an evolving W3C specificat ion ( ht t p: / / www.w3.org/ TR/ xpt r) . Ca ut ion Bot h t he XLink and t he XPoint er specificat ions are current ly evolving and subj ect t o m uch change. Alt hough a det ailed discussion of XML linking is beyond t he scope of t his book, we at least want t o give you an idea of t he nat ure of XLinks and XPoint ers. You will cert ainly run across such t erm inology in t he course of underst anding how t o use XML in an ent erprise environm ent , and you m ay even run across concret e exam ples of t heir usage. We should not e t hat at t he t im e of t his book's writ ing, support for XLink and XPoint er was very lim it ed. I n part icular, XPoint er support was virt ually non- exist ent due t o it s com plexit y and cert aint y for change.

XLink s Cent ral t o t he t opic of linking in XML is t he concept of a resource. A resource is an addressable piece of inform at ion such as t he t ype of inform at ion addressed by a URL ( for exam ple, files, im ages, and applicat ions) . A link is a relat ionship bet ween resources. A local resource is a resource em bedded inside of an XML link elem ent . A rem ot e resource is t he act ual resource inform at ion point ed t o by an XML link. Linking elem ent s are XML elem ent s t hat include links. A linking elem ent defines a link as an at t ribut e using t he xlink:type at t ribut e nam e. XLink defines several st andard xlink:type at t ribut e values: • • •

simple: Defines an associat ion bet ween a local resource and a rem ot e resource. extended: Defines associat ions am ong m ult iple resources. locator: Defines addresses t o rem ot e resources. An ext ended link m ust have at least one locator elem ent t ype defined.

- 859 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • •

arc: Defines rules for t raversing bet ween t he links cont ained by an ext ended link elem ent . title: Defines a hum an- readable descript ion of an ext ended link. resource: Defines t he local resources for an ext ended link. I f an ext ended link defines a resource elem ent t ype, it is called an inline link.

Sim ple Link s

A sim ple link associat es a local resource wit h a rem ot e resource. Sim ple link inform at ion is em bedded inside of an XML elem ent akin t o t he way an at t ribut e is em bedded inside of an elem ent . The form of t he link ( t hat is, "simple") and URL reference are bot h em bedded int o t he XML elem ent . This is t he general form of a sim ple link:





A source XML docum ent designat es a part icular XSL st yle sheet t o use in t ransform ing it self via a processing inst ruct ion declarat ion t hat resem bles it s XML declarat ion and is of t he following form :



SAX Ar ch it e ct u r e Figure 31.2 depict s t he t op- level archit ect ure of Java- based SAX classes and int erfaces ( excluding except ions) . Most classes and int erfaces com e from t he st andard org.xml.sax package. Two addit ional classes defined in t he javax.xml.parsers package are also ut ilized t o define a provider- independent m eans for creat ing parser handles as well as a non–SAX- st andard parser helper class. A Parser int erface defines a st andard int erface t o a SAX parser for init iat ing t he parsing of XML docum ent s. The SAX Parser int erface can not ify parse event - handler obj ect s during t he parsing of XML docum ent s and t he generat ion of parse event s. St andard SAX abst ract ions also exist for an XML docum ent cont ent input source, XML elem ent at t ribut e list , and XML docum ent event locat ion inform at ion. Figur e 3 1 .2 . The SAX cla ss a r chit e ct ur e .

- 867 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Cor e SAX Obj e ct s Before we delve int o t he prim ary applicat ion int erfaces, let 's look at a few of t he core and m ost basic SAX st andard obj ect s. Figure 31.3 depict s t hese key elem ent s. The m ost basic elem ent s can be part it ioned int o except ion- relat ed classes, a docum ent event locat ion helper, a docum ent elem ent at t ribut e list , and a docum ent cont ent input source abst ract ion. Figur e 3 1 .3 . Cor e SAX obj e ct s.

- 868 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Locator int erface represent s t he locat ion of som e event in an XML docum ent . I nform at ion about t he locat ion of an event in a docum ent can be obt ained from a Locator, including a public ident ifier of t he elem ent , a syst em ident ifier ( for exam ple, URL) , and t he line and colum n num bers in t he docum ent . Two except ion classes are used t o encapsulat e errors occurring during processing of XML docum ent s. The SAXException class encapsulat es a generic SAX error condit ion cont aining a nest ed root except ion. The SAXParseException class encapsulat es a generic error during parsing of an XML docum ent . I nform at ion about t he locat ion of t he error can also be obt ained from a SAXParseException using t he sam e t ype of inform at ion t hat is obt ained from a Locator obj ect . The AttributeList int erface is im plem ent ed by a parser provider and describes an int erface t o an XML elem ent 's list of at t ribut es.

- 869 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The AttributeList.getLength() m et hod ret urns t he num ber of at t ribut es cont ained by t he list . Alt hough t he order of at t ribut es in an AttributeList is arbit rary, t he String version of nam es, t ypes, and values of at t ribut es m ay be ret rieved by an index num ber using t he getName(int), getType(int), and getValue(int) m et hods, respect ively. The t ype and value of a nam ed at t ribut e m ay also be ret rieved using t he getType(String) and getValue(String) m et hods, respect ively. The InputSource class encapsulat es a source of XML docum ent dat a input . Public ident ifiers, syst em ident ifiers, a byt e st ream , a charact er st ream , and encoding all have associat ed set t ers and get t ers on t he InputSource class. Public and syst em ident ifiers of an input source are opt ional and have sem ant ics t hat are specific t o an applicat ion. A charact er st ream represent at ion of t he XML cont ent t akes preference over use of a byt e- st ream represent at ion if bot h are specified. The syst em ident ifier is used as a URI in creat ing an input st ream connect ion if neit her a charact er st ream nor a byt e st ream is specified. Finally, t he encoding form at of an input st ream can also be specified. SAX Applica t ion H a n dle r I nt e r fa ce s Figure 31.4 represent s t he abst ract ions used by applicat ions t o receive not ificat ion of XML docum ent parsing event s from a SAX XML docum ent parser. The four int erfaces shown represent int erfaces t hat are im plem ent ed by applicat ions t o receive such event s. Obj ect im plem ent at ions of t hese int erfaces are regist ered wit h an XML parser. A default im plem ent at ion of t hese int erfaces is defined wit hin a HandlerBase class. Figur e 3 1 .4 . SAX a pplica t ion ha ndle r s.

- 870 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The DTDHandler is im plem ent ed by applicat ion classes t hat handle event s relat ed t o DTD processing. Specifically, event s relat ed t o not at ion and unparsed ent it y declarat ions can be received, and t he associat ed inform at ion can be st ored for lat er reference when parsing an associat ed XML docum ent . The DTDHandler.notationDecl() m et hod is im plem ent ed t o receive not ificat ion of t he declarat ion of a not at ion in a parsed DTD. An applicat ion uses t his inform at ion for lat er reference and includes t he nam e of t he not at ion, an opt ional public ident ifier for t he not at ion, and an opt ional syst em ident ifier ( for exam ple, URL) . The DTDHandler.unparsedEntityDecl() m et hod can be im plem ent ed t o receive not ificat ion of a declarat ion of an unparsed ent it y in t he DTD. The unparsed ent it y's nam e, opt ional public ident ifier, opt ional syst em ident ifier, and associat ed not at ion nam e m ay be passed int o t his m et hod. List ing 31.3 shows a sam ple DTDHandler im plem ent at ion via a SampleDTDHandler class t hat sim ply print s inform at ion when it s im plem ent ed m et hods are called. List in g 3 1 .3 D TD H a n dle r ( SampleDTDHandler.java)

- 871 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

package ejava.xmlch31; import org.xml.sax.DTDHandler; import org.xml.sax.SAXException; /** * implements DTDHandler to receive DTD events from parser */ public class SampleDTDHandler implements DTDHandler { /** * receive information about DTD entity information. */ public void notationDecl(String name, String publicID, String systemID) throws SAXException { System.out.println(" Notation Name :" +name + " publicID :" +publicID + "System ID : " +systemID); } /** * receive information about a DTD unparsed entity */ public void unparsedEntityDecl(String name, String publicID, String systemID, String notationName) throws SAXException { System.out.println(" Entity :" + name +" public ID :" + publicID + "System ID :" +systemID + "Notation Name :" + notationName); } } The EntityResolver int erface is im plem ent ed by applicat ion classes t hat resolve ext ernal ent it ies. The single EntityResolver.resolveEntity() m et hod is im plem ent ed t o receive a public ident ifier and syst em ident ifier of t he ext ernal ent it y being referenced. The applicat ion creat es and ret urns an InputSource obj ect associat ed wit h t he ext ernal XML cont ent . I f a null value is ret urned, it is assum ed t hat t he syst em ident ifier URL form can be used t o ident ify t he ext ernal ent it y locat ion. A parser calls t his m et hod before it at t em pt s t o open an ext ernal ent it y. List ing 31.4 shows a sam ple EntityResolver im plem ent at ion via a SampleEntityResolver class t hat sim ply print s inform at ion when it s im plem ent ed m et hods are called.

- 872 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

List ing 3 1 .4 Ent it y Re solve r ( SampleEntityResolver.java)

package ejava.xmlch31; import org.xml.sax.EntityResolver; import org.xml.sax.SAXException; import org.xml.sax.InputSource; import java.io.IOException; import java.net.URL; import java.io.InputStream; import org.xml.sax.SAXParseException;

/** * Implements EntityResolver. If it sees a specific * systemID, it creates a different InputSource to * read data. */ public class SampleEntityResolver EntityResolver {

implements

/** * to resolve each entity, resolveEntity is called by parser */ public InputSource resolveEntity(String publicID, String systemID) throws SAXException, IOException { System.out.println("Public ID :" + publicID); System.out.println("System ID :" + systemID); String urlString = "http://www.beeshirts.com/examples/src/ejava/xmlch31/XMLD ocument.xml";

if (systemID.equals(urlString)) { // return input source URL url = new URL(urlString); InputStream inputStream = url.openStream(); return new InputSource(inputStream); } else { // return null and require default systemID return null; } } }

- 873 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The ErrorHandler int erface is im plem ent ed by applicat ions t hat need t o handle warnings, errors, and fat al errors t hat can occur during XML parsing. A parser passes a SAXParseException during a call t o an appropriat e ErrorHandler m et hod, and t he applicat ion decides how t o handle t he except ion. The applicat ion m ay also t hrow a SAXException when one of t hese m et hods is called. List ing 31.5 shows a sam ple ErrorHandler im plem ent at ion via a SampleErrorHandler class t hat sim ply print s inform at ion when it s im plem ent ed m et hods are called. List ing 3 1 .5 Er r or H a ndle r ( SampleErrorHandler.java)

package ejava.xmlch31; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * implements Error Handler */ public class SampleErrorHandler implements ErrorHandler { /** * it receives the errors of type recoverable Errors */ public void error(SAXParseException saxParseException) throws SAXException { printException(saxParseException); } /** * to receive the Fatal or non recoverable Error */ public void fatalError(SAXParseException saxParseException) throws SAXException { printException(saxParseException); } /** * To receive warnings from the parser */ public void warning(SAXParseException saxParseException) throws SAXException { printException(saxParseException);

- 874 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

} private void printException(SAXParseException saxParseException) { System.out.println(saxParseException); System.out.println("Column # :" + saxParseException.getColumnNumber()); System.out.println("Line # : " + saxParseException.getLineNumber()); System.out.println("System ID :"+ saxParseException.getSystemId()); System.out.println("Public ID :"+saxParseException.getPublicId()); } } The DocumentHandler int erface is t he prim ary int erface im plem ent ed by applicat ions t hat need t o handle m ost XML docum ent parsing–relat ed event s. The DocumentHandler. startDocument() m et hod is called when parsing of an XML docum ent begins, and DocumentHandler.endDocument() is called when parsing ends. When t he parser encount ers t he st art t ag of an XML docum ent elem ent , t he DocumentHandler.startElement() m et hod is called. The elem ent nam e and elem ent 's at t ribut e cont ent s will be passed as param et ers t o t he startElement() m et hod. Any IMPLIED at t ribut e values will be om it t ed from t he AttributeList obj ect passed int o startElement(). For each startElement() m et hod call, a DocumentHandler.endElement() m et hod will be called wit h an elem ent nam e indicat ing t hat t he end of t he elem ent was parsed. The endElement() m et hod is also called for em pt y elem ent s. The DocumentHandler.setLocator() m et hod can be used by an applicat ion t o obt ain a Locator obj ect from a parser such t hat t he locat ion of event s in an XML docum ent , wit hin t he scope of elem ent boundaries, can be inferred. The DocumentHandler.characters() m et hod is called by a parser t o not ify an applicat ion of an array of charact ers t hat have been ret rieved from an XML docum ent elem ent 's charact er dat a. The DocumentHandler.ignorableWhitespace() m et hod is used t o report whit espace charact ers read from an XML docum ent elem ent . Any processing inst ruct ions em bedded in an XML docum ent can be received by an applicat ion using t he DocumentHandler.processingInstruction() m et hod. The processing inst ruct ion nam e and associat ed param et er dat a are passed as param et ers t o t he processingInstruction() m et hod.

- 875 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

List ing 31.6 shows a sam ple DocumentHandler im plem ent at ion via a SampleDocumentHandler class t hat sim ply print s inform at ion when it s im plem ent ed m et hods are called. List in g 3 1 .6 D ocu m e n t H a n dle r ( SampleDocumentHandler.java)

package ejava.xmlch31; import org.xml.sax.DocumentHandler; import org.xml.sax.SAXException; import org.xml.sax.Locator; import org.xml.sax.AttributeList; import org.xml.sax.Parser; import org.xml.sax.SAXParseException; import java.io.File; /** * An example document handler */ public class SampleDocumentHandler DocumentHandler {

implements

/** * to receive the character data for each element */ public void characters(char[] value, int start, int length) throws SAXException { String newValue = new String(value); System.out.println(" Present Char Chunk :" + newValue.substring(start,start+length) ); } /** * to receive information about end of the document */ public void endDocument() throws SAXException { System.out.println("End of Document "); }

/** * to receive information about end of an element in the document */ public void endElement(String elementName) throws SAXException

- 876 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

{ System.out.println(" End of

Element :"+elementName) ;

} /** * Receive notification of ignorable whitespace in element content. */ public void ignorableWhitespace(char[] value, int start , int length) throws SAXException { String newValue = new String(value); if(length > 0){ System.out.println(" ignorable Value is :" + newValue.substring(start,start+length-1) ); } } /** * The Parser will invoke this method once for each processing * instruction found */ public void processingInstruction(String target, String data) throws SAXException { System.out.println("Processing Instruction Target :"+target); System.out.println("Processing Instruction data :"+data); } /** * To get information about the document Locator */ public void setDocumentLocator(Locator locator) { System.out.println("Column , Current Event Ends :"+ locator.getColumnNumber()); System.out.println("Line , Doc Event Ends :" +locator.getLineNumber()); System.out.println(" public ID for current Event :" +locator.getPublicId()); System.out.println("Public System ID :" +locator.getSystemId()); } /**

- 877 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

* To receive the information about starting of document */ public void startDocument() throws SAXException { System.out.println(" The parser started parsing document :"); } /** * Info about started parse of new element */ public void startElement(String elementName , AttributeList attributeList) throws SAXException { System.out.println(" Element :"+elementName +" Started "); int totalAttributes = attributeList.getLength(); for(int i = 0; i < totalAttributes; i++){ String name = attributeList.getName(i); String type = attributeList.getType(i); String value = attributeList.getValue(i); System.out.println("Attribute Name :" + name + " Type : "+ type +" Value :" +value); } } } As a final not e, t he HandlerBase class provides a default im plem ent at ion for all four of t he XML docum ent event handler int erfaces. Applicat ions ext end t his class when t hey want t o override t his default behavior. SAX Pa r se r I nt e r fa ce s Figure 31.5 depict s t he det ail for t hose int erfaces im plem ent ed by SAX parser providers. A parser fact ory is used t o creat e parser inst ances, and t wo parser abst ract ions can be used for int erfacing wit h a SAX parser. The Parser int erface is t he SAX- st andard parser int erface. The SAXParser class is a JAXP wrapper t o a st andard SAX parser int erface. Bot h parser abst ract ions can be used t o init iat e t he parsing of an XML docum ent cont ent st ream . Figur e 3 1 .5 . SAX pa r se r int e r fa ce s.

- 878 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The SAXParser class is a helper class t hat wraps a regular Parser obj ect and provides a set of m et hods t hat im plem ent a m ore convenient way of init iat ing t he parsing of an XML docum ent . Aside from m et hods for det erm ining XML nam espace awareness and DTD validat ion capabilit y, t he SAXParser also defines various m et hods t hat help init iat e t he parsing of a docum ent . The SAXParser.parse() m et hods all t ake a HandlerBase obj ect as an argum ent along wit h a reference t o an XML docum ent cont ent st ream in t he form of a File reference, an InputStream, an InputSource, or a URL String locat ion. The SaxParser.getParser() m et hod can be used t o obt ain a reference t o t he underlying st andard Parser int erface obj ect . The SAXParserFactory abst ract class can be used t o configure and creat e Parser obj ect s. A SAX parser provider supplies a concret e im plem ent at ion of t he SAXParserFactory class, and t he definit ion of t his class is defined via t he javax.xml.parsers.SAXParserFactory syst em propert y. The

- 879 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

static SAXParserFactory.newInstance() m et hod is used t o ret urn an inst ance of t his concret e fact ory im plem ent at ion. DTD validat ion capabilit y and XML nam espace awareness of parsers can all also be set and checked using appropriat ely nam ed m et hods on a SAXParserFactory obj ect inst ance. Finally, new inst ances of SAXParser obj ect s can be creat ed by calling t he newSAXParser() m et hod. List ing 31.7 present s a SAX sam ple driver class t o t ie t oget her a com plet e sam ple usage of SAX. The SaxExample class t akes an XML docum ent filenam e from t he com m and line via a main() m et hod and induces t he parsing of t his docum ent . A SaxParserFactory is first creat ed and t hen used t o creat e a validat ing SAXParser obj ect . The SAXParser obj ect is t hen used t o obt ain a handle t o t he st andard Parser obj ect . The handlers of List ings 31.3 t hrough 31.6 are t hen set ont o t he Parser. Last ly, t he Parser is t old t o parse t he XML docum ent . List ing 3 1 .7 SAX e x a m ple ( SaxExample.java) .

package ejava.xmlch31; import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParser; import org.xml.sax.SAXException; import org.xml.sax.Locator; import org.xml.sax.AttributeList; import org.xml.sax.Parser; import org.xml.sax.SAXParseException; import java.io.File; /** * An example to induce the parsing of an XML document */ public class SaxExample { public static void main(String[] argv) { if(argv.length != 1){ System.out.println(" Usage : "+ "java ejava.xmlch31.SaxExample "); System.exit(0); } try { String xmlFileURI = "file:" + new File (argv [0]).getAbsolutePath (); // Get Parser Factory SAXParserFactory saxParserFactory = SAXParserFactory.newInstance (); // set Document Validation true

- 880 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

saxParserFactory.setValidating (true); // get SAX parser from Factory SAXParser saxParser = saxParserFactory.newSAXParser(); // get a Parser from Factory Parser parser = saxParser.getParser(); // set Document Handler to receive document Handler Events parser.setDocumentHandler (new SampleDocumentHandler()); // set DTD Handler to receive DTD events from Parser parser.setDTDHandler(new SampleDTDHandler()); // set EntityResolver to receive EntityResolver Events. parser.setEntityResolver(new SampleEntityResolver()); // set ErrorHandler to receive Errors and warnings. parser.setErrorHandler(new SampleErrorHandler()); // parse document parser.parse (xmlFileURI); } catch (SAXParseException saxParseException) { System.out.println (" Parsing error" + ", at line " + saxParseException.getLineNumber () + ", in file " + saxParseException.getSystemId ()); System.out.println(" " + saxParseException.getMessage ()); saxParseException.printStackTrace(); } catch (SAXException saxException) { saxException.printStackTrace (); } catch (Throwable throwable) { throwable.printStackTrace (); } } } N ot e Not e t hat t he older version of JAXP equipped wit h t he J2EE reference im plem ent at ion did not include t he javax.xml.parsers.SAXParserFactory or javax.xml. parsers.SAXParser classes. Rat her, an org.xml.sax.helpers.ParserFactory class is used t o creat e a reference t o a new st andard SAX Parser obj ect .

- 881 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

For exam ple, when using t he J2EE reference im plem ent at ion, in our List ing 31.7 exam ple we would replace t he lines t hat ret rieve a SAXParser obj ect from t he SAXParserFactory and t hen a Parser from t he SAXParser wit h a call t o

Parser parser = ParserFactory.makeParser();

D ocu m e n t Obj e ct M ode l The Docum ent Obj ect Model ( DOM) was developed by t he W3C t o provide a st andard set of language- independent int erfaces t o m anipulat e XML and HTML docum ent s. We are m ainly int erest ed in t he DOM Level 1 specificat ion ( ht t p: / / www.w3.org/ TR/ REC- DOMLevel- 1/ ) in t erm s of t he definit ions it provides for a set of basic int erfaces t o m anipulat e XML docum ent s. These int erfaces are defined using t he OMG CORBA I DL not at ion. A Java binding for such int erfaces is also present ed in t he specificat ion and is t he st yle of int erface t hat we focus on in t his sect ion. A DOM Level 2 specificat ion ( ht t p: / / www.w3.org/ TR/ DOM- Level- 2/ ) is also under developm ent t o define m echanism s for t he dynam ic access and m odificat ion of XML docum ent cont ent , st ruct ure, and st yle. The st andard Java- binding int erfaces t o DOM m ap t o an org.w3c.dom Java package. The JAXP from JavaSoft provides a reference im plem ent at ion of t he DOM Level 1 int erfaces. Addit ionally, JAXP also defines a few non- DOM- st andard abst ract ions in a javax.xml.parsers package used as a DOM parser inst ance fact ory and DOM parser class. N ot e Throughout t he archit ect ure descript ion and sam ple code in t his sect ion, we assum e use of t he JAXP v1.0 im plem ent at ion. At t he t im e of t his writ ing, t he J2EE reference im plem ent at ion cam e equipped wit h t he DOM st andard abst ract ions from t he JAXP, but it did not com e equipped wit h t he abst ract ions cont ained in t he javax.xml. parsers package. Fut ure versions of t he J2EE are expect ed t o require incorporat ion of a fully im plem ent ed JAXP specificat ion. Refer t o Appendix A of t his book t o det erm ine how t o obt ain t he appropriat e JAXP im plem ent at ion. The code snippet s st rewn t hroughout t his sect ion can be found in t he DOMExample.java file on t he CD in t he

- 882 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

examples/src/ejava/xmlch31 direct ory. We also include a sim ple rundom.bat script exam ple on t he CD t o dem onst rat e how t o com pile and execut e t he code present ed in t his sect ion. An XMLLIB_HOME environm ent variable is assum ed t o reference t he root direct ory of your JAXP library inst allat ion. Not e t hat t he rundom.bat script uses t he dtdAndXmlDocument.xml file on t he CD. However, you m ust ensure t hat t he dtdAndXmlDocument.xml file properly references t he order.dtd in t he DOCTYPE declarat ion as described in t he dtdAndXmlDocument.xml file com m ent and shown here:









- 955 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





- 956 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



















- 958 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





































- 960 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

user-data-constraint id ID #IMPLIED> transport-guarantee id ID #IMPLIED> auth-constraint id ID #IMPLIED> role-name id ID #IMPLIED> login-config id ID #IMPLIED> realm-name id ID #IMPLIED> form-login-config id ID #IMPLIED> form-login-page id ID #IMPLIED> form-error-page id ID #IMPLIED> auth-method id ID #IMPLIED> security-role id ID #IMPLIED> security-role-ref id ID #IMPLIED> role-link id ID #IMPLIED> env-entry id ID #IMPLIED> env-entry-name id ID #IMPLIED> env-entry-value id ID #IMPLIED> env-entry-type id ID #IMPLIED> ejb-ref id ID #IMPLIED> ejb-ref-name id ID #IMPLIED> ejb-ref-type id ID #IMPLIED> home id ID #IMPLIED> remote id ID #IMPLIED> ejb-link id ID #IMPLIED>

The DTD of List ing 32.1 is used t o define t he st andard st ruct ure for deploym ent descript ors used in deploying J2EE Web applicat ions. To ut ilize such a st andard, valid J2EE Web applicat ion deploym ent descript ors m ust cont ain t he following DOCTYPE reference:

You'll in fact not e t hat t he general st ruct ure of our web.xml deploym ent descript or file equipped wit h t he CD and used t o configure t he BeeShirts.com servlet applicat ion adheres t o t he following t op- level form :







- 961 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE















N ot e At t he t im e of t his writ ing, t he BEA WebLogic Server v5.0 and v5.1 required t hat you specify an older Web API version num ber in t he DOCTYPE reference of a web.xml file. The BEA WebLogic Server also did not support use of t he st andard elem ent in a web.xml file. The DOCTYPE reference for BEA WebLogic is defined as such:

We t hus have placed t hree sam ple XML files in t he examples\src\ejava\servletsch32 direct ory. The weblogic-web.xml file defines t he BEA WebLogic version of t he web.xml file for use wit h our exam ples. The j2eeweb.xml file defines t he J2EE reference im plem ent at ion's version of t he web.xml file for use wit h our exam ples. During execut ion of our sam ple com pilat ion and deploym ent script s for each im plem ent at ion, t he proper XML file is copied t o t he st andard web.xml file nam e. The web.xml file on t he CD is sim ply a snapshot of t he st andard Web XML deploym ent descript or for use wit h our exam ples and is ident ical t o j2ee-web.xml.

- 962 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

W e b Applica t ion D e ploym e nt Pr oce dur e s The process for deploying J2EE applicat ions involves one of est ablishing environm ent variables, configuring server propert ies, com piling Java code, creat ing XML- based deploym ent descript ors, packaging archive files, and deploying archives t o a J2EE server environm ent . Alt hough we focus on t he deploym ent of our J2EEbased Java Servlet applicat ion in t his sect ion, t he process described here can be generalized t o t he deploym ent of JSP and EJB applicat ions as well. Appendix A, " Soft ware Configurat ion," provides inst ruct ions for how t o inst all and perform t he basic configurat ion of bot h a J2EE reference im plem ent at ion server and a BEA WebLogic Server used t o deploy our J2EE- based Web applicat ions. However, t he procedure for deploying J2EE- based Web applicat ions assum es t he following general st eps: 1. Se t J2 EE Se r ve r Envir onm e nt Va r ia ble s: Environm ent variables m ust oft en be set for running a J2EE server environm ent and will vary per vendor im plem ent at ion and operat ing- syst em plat form . For exam ple, we set root inst allat ion direct ories for t he J2SE ( JAVA_HOME) , J2EE reference im plem ent at ion ( J2EE_HOME) , and BEA WebLogic Server ( WEBLOGIC_HOME) as described in Appendix A. 2. Configur e J2 EE Se r ve r Pr ope r t ie s: Configurat ion propert ies for m ost J2EE server im plem ent at ions can be set t o suit your part icular net work and operat ing environm ent . For exam ple, we m odify t he J2EE reference im plem ent at ion's [J2EE_HOME]\config\ web.properties file such t hat t he http.port propert y is set equal t o 7001. We also set t he BEA WebLogic Server's [WEBLOGIC_HOME]\weblogic.properties file such t hat a weblogic.httpd.webApp.beeshirts propert y is set t o reference a WAR file t hat we will generat e for BEA WebLogic ( t hat is, [WEBLOGIC_HOME]/myserver/servletsch32.war) . Appendix A describes t hese configurat ion propert ies in m ore det ail. 3. Com pile J2 EE W e b Applica t ion Code : All J2EE Web com ponent code m ust be com piled using a st andard Java com piler. 4. Cr e a t e a J2 EE W e b Applica t ion D e ploym e n t D e scr ipt or : An XML- based deploym ent descript or is creat ed according t o t he Web applicat ion DTD defined previously. We include a Web applicat ion deploym ent descript or for our BeeShirts.com servlet - based st orefront on t he CD in t he file nam ed web.xml. Many product s creat e t his file for you from a GUI - based configurat ion t ool.

- 963 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

5. Pa ck a ge J2 EE W e b Applica t ion Code : The Web deploym ent descript or, all com piled J2EE servlet classes, all HTML files, all im age files, and all ot her Web resources need t o be packaged int o a Web applicat ion archive file wit h a .war ext ension. J2EE- based product s m ay supply com m and- line or GUI - based ut ilit ies, or bot h, for t his purpose. 6. St a r t t he J2 EE Se r ve r : The J2EE- com pliant server m ust generally be st art ed or already be st art ed at t his st age. The exact m echanism for st art ing a server is oft en vendordependent but can be as sim ple as invoking a single st art up com m and from t he com m and line. 7. Cr e a t e a J2 EE Applica t ion D e ploym e n t D e scr ipt or : A J2EE applicat ion deploym ent descript or m ust be creat ed t o collect one or m ore Web, EJB, and applicat ion client m odules int o a cohesive J2EE applicat ion. We have included an application.xml file for our applicat ion deploym ent descript or on t he CD. Many product s will creat e t his file for you aut om at ically or via a GUI - based configurat ion t ool. 8. Pa ck a ge J2 EE Applica t ion Code : The applicat ion deploym ent descript or, Web applicat ions, EJB applicat ions, and applicat ion client s need t o be packaged int o an Ent erprise ARchive ( EAR) file wit h a .ear ext ension. Many product s also creat e t his archive for you aut om at ically or via GUI - based developm ent t ools. 9. D e ploy t h e J2 EE W e b Applica t ion Code : Finally, t he int egrat ed J2EE applicat ion is deployed t o t he J2EE server environm ent for access by ent erprise applicat ion client s. This st ep also is oft en aut om at ed via GUI t ools. W e b Applica t ion D ir e ct or y St r uct ur e The root Web applicat ion cont ext is defined wit hin a Web server aft er t he host address for t hat server ( for exam ple, http://www.beeshirts.com/myRootContext) . Files t hat are served direct ly t o t he client , such as HTML and im age files, can be placed direct ly under t he root Web applicat ion cont ext . Files t hat are not direct ly served t o t he client are placed under a WEB-INF direct ory t hat sit s under t he root Web applicat ion cont ext . The cont ent s under t he WEB-INF direct ly are not publicly available and are subj ect t o t he m anagem ent const raint s of t he J2EE server environm ent . A web.xml file under WEB-INF cont ains t he Web applicat ion deploym ent descript or inform at ion. All Java Servlet s and auxiliary Java classes are root ed under t he WEB-INF\classes direct ory. JAR files wit h .jar file ext ensions t hat cont ain Java Servlet s and auxiliary Java classes are placed under t he WEB-INF\lib direct ory.

- 964 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

This ent ire direct ory st ruct ure is t ypically cont ained wit hin a WAR file. A WAR file also cont ains a Manifest.mf file under a META-INF direct ory. For exam ple, a servletsch32.war file creat ed for our sam ple Web applicat ion cont ains t he following file st ruct ure:

\*.gif \*.jpg \*.html \WEB-INF\web.xml \WEB-INF\classes\ejava\servletsch32\*.class \META-INF\Manifest.mf J2 EE Re fe r e nce I m ple m e nt a t ion Se r ve r St a r t up a nd D e ploym e n t The J2EE reference im plem ent at ion com es packaged wit h a J2EEcom pliant Java Servlet v2.2 and JSP v1.1 cont ainer environm ent . This Java Servlet and JSP reference im plem ent at ion was developed by t he Apache Soft ware Foundat ion's Jakart a proj ect and is som et im es referred t o by it s codenam e of " Tom cat ." When using t he J2EE reference im plem ent at ion server wit h our exam ples, you m ust first st art t he server. You m ust first change t o t he [J2EE_HOME]\bin direct ory on t he m achine on which you've inst alled t he reference im plem ent at ion. Then sim ply begin an inst ance of t he server by execut ing t he j2ee com m and from t hat direct ory. The -verbose opt ion can be used t o display m ore det ailed server inform at ion t o t he screen as t he server is running. The version opt ion can be used t o display t he current J2EE version num ber. The server m ay be st opped wit h t he -stop opt ion. Alt hough t he -singleVM opt ion is t he default JVM process opt ion for running all applicat ions in a single process, t he -multiVM opt ion m ay also be used t o launch separat e JVM processes for each deployed J2EE applicat ion. Our compilej2ee.bat file equipped wit h t he CD provides a Windows- based sam ple script for com piling, packaging, and deploying a J2EE applicat ion t o a running J2EE reference im plem ent at ion server. The compilej2ee.bat file uses t he J2EE packager t ool t o creat e a Web applicat ion given a web.xml deploym ent descript or and t arget WAR filenam e. The packager t ool follows t he m ost basic synt ax for creat ing WAR files as shown here:

[J2EE_HOME]\bin\packager -webArchive web.xml warFileName.war

- 965 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Alt ernat ively, a -classpath classPath opt ion can be used t o designat e t he CLASSPATH for servlet and auxiliary Java classes. The -classFiles classFileList opt ion designat es t hat only cert ain class files in t he colon- separat ed class file list are t o be included in t he WAR file. A root direct ory for all cont ent files ( for exam ple, direct ly referenced im age and HTML files) can also be specified on t he com m and line. Finally, a -contentFiles contentFileList opt ion can be used t o designat e t hat only cert ain cont ent files in t he colon- separat ed cont ent file list are t o be included in t he WAR file. We also use t he packager t ool in our compilej2ee.bat sam ple script t o creat e a J2EE applica t ion EAR file. The packager t ool used for creat ing EAR files given a WAR filenam e and ot her archive files, as well as given an ent erprise applicat ion nam e, follows t he basic synt ax shown here:

[J2EE_HOME]\bin\packager –enterpriseArchive warFileName.war:[otherArchiveFiles] ApplicationName earApplicationFileName.ear Alt ernat ively, a -alternativeDescriptorEntries archiveFileName/xmlFileName.xml:… opt ion can be used t o reference alt ernat e XML descript ors for each of t he archives designat ed in t he archive list . Alt hough t he packager ut ilit y is supposed t o creat e properly defined J2EE application.xml files, our compilej2ee.bat file provides a m echanism for using a canned application.xml file for assigning our J2EE applicat ion t o t he beeshirts root servlet cont ext as shown here:

ServletApp Application description

servletsch32.war beeshirts

A J2EE reference im plem ent at ion deploytool wit h no com m and- line argum ent s spawns a GUI - based deploym ent t ool for creat ing J2EE applicat ion EAR files, as well as for deploying J2EE applicat ions. The deploytool invoked wit h t he -deploy opt ion deploys an applicat ion

- 966 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

cont ained by an associat ed EAR filenam e t o a J2EE server running ont o a nam ed host m achine according t o t he following form :

[J2EE_HOME]\bin\deploytool -deploy earFileName.ear serverHostName The deploytool invoked wit h t he -uninstall opt ion can rem ove a nam ed ent erprise applicat ion from a J2EE server running on a specified host m achine as follows:

[J2EE_HOME]\bin\deploytool -uninstall ApplicationName serverHostName Aft er t he BeeShirts.com Web applicat ion is deployed according t o t he preceding guidelines, our root BeeShirtsServlet is accessed from a local m achine using t he URL ht t p: / / localhost : 7001/ beeshirt s/ BeeShirt sServlet . N ot e You m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb.properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. Refer t o Appendix A for m ore det ails.

BEA W e bLogic Se r ve r St a r t u p a n d D e ploym e n t The BEA WebLogic Server is an ent erprise- class server environm ent for creat ing and deploying J2EE- com pliant Web and EJB applicat ions. Our compileweblogic.bat file equipped on t he CD cont ains a sam ple Windows script for com piling, packaging, and deploying our Web applicat ion t o a BEA WebLogic Server. At t he t im e of t his writ ing, t he BEA WebLogic Server v5.0 and v5.1 did not support deploym ent of J2EE applicat ion EAR files. Thus, our sam ple compileweblogic.bat file sim ply creat es t he appropriat e web applicat ion direct ory st ruct ure populat ed wit h our exam ple code, and t hen uses t he jar com m and t o creat e a servletsch32.war file m apped from t his direct ory st ruct ure. This WAR file m ust be referenced by t he weblogic.httpd.webApp.beeshirts propert y defined wit hin t he BEA WebLogic Server's [WEBLOGIC_HOME]\weblogic.properties file. The

- 967 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

weblogic.properties file's weblogic.httpd.documentRoot propert y should also be set t o myserver/ for our exam ples. The BEA WebLogic Server can t hen be st art ed using t he [WEBLOGIC_HOME]\ startweblogic.cmd com m and script . Appendix A describes t he general configurat ion procedures for t he BEA WebLogic Server.

Se r vle t Con figu r a t ion Using t he st andard Web applicat ion deploym ent descript or, we can configure our Java Servlet processing environm ent in a st andard fashion. Alt hough it can be argued t hat all t he param et ers est ablished wit hin t he deploym ent descript or are a form of applicat ion configurat ion, we are specifically referring t o t he configurable init ializat ion and environm ent param et ers of servlet s and servlet cont ainer environm ent s. Servlet s can be configured wit h init ializat ion param et ers t hat are obt ained via t he ServletConfig int erface im plem ent at ion. Servlet cont ainers can also be configured wit h init ializat ion param et ers obt ained via t he ServletContext int erface im plem ent at ion. Servlet s can also reference global cont ext configurat ion environm ent param et ers t hat can be accessed via JNDI lookups under a st andard environm ent cont ext . This sect ion describes t hese m echanism s for configuring your servlet s and servlet cont ainer environm ent s. I n dividu a l Se r vle t Configur a t ion As shown earlier in Figure 32.3 and Figure 32.4, t he GenericServlet class and HttpServlet subclass im plem ent t he ServletConfig int erface for receiving init ializat ion inform at ion from t he servlet cont ainer environm ent . The ServletConfig.getServletName() value is ret rieved from t he Web deploym ent descript or wit hin a elem ent inside of a part icular elem ent . The ServletConfig.getInitParameterNames() ret rieve t he values from wit hin an sub- elem ent of . The ServletConfig.getInitParameter() m et hod can be used wit h a param et er nam e defined wit hin a t o ret rieve a value defined wit hin a parallel elem ent nam ed . A sam ple snippet of a part icular XML deploym ent descript or docum ent defining t hese values is shown here:



OrderStatus

- 968 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ejava.servletsch32.OrderStatusServlet

email [email protected]

lastName Mellone





Thus, our OrderStatusServlet t hat is bound t o t he nam ed OrderStatus servlet in t he preceding snippet m ay be used t o ret rieve init ial param et er values as such ( calls are assum ed t o be m ade from wit hin OrderStatusServlet here) :

// Returns the name "OrderStatus" String name = this.getServletName(); // Returns an Enumeration of String objects // including "email", "lastName", etc… Enumeration names = this.getInitParameterNames(); // Returns the paramValue "[email protected]" String emailAddressFromParameter = getInitParameter("email"); Se r vle t Cont e x t Configur a t ion The ServletContext abst ract ion shown in Figure 32.3 encapsulat es an int erface t o a servlet cont ainer environm ent t hat can also be configured via an XML deploym ent descript or. The ServletContext.getInitParameterNames() ret rieves t he values from wit hin a sub- elem ent of . The ServletContext.getInitParameter() m et hod can be used wit h a param et er nam e defined wit hin a t o ret rieve a value defined wit hin a parallel elem ent nam ed . A sam ple snippet of a part icular XML docum ent defining t hese values is shown here:



- 969 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

StoreName BeeShirts Site 105 Designates the deployed web site.







For exam ple, we could ret rieve a ServletContext obj ect and t he init ializat ion param et ers from wit hin a part icular Java Servlet as shown here:

// Get the ServletContext from this current Servlet ServletContext ctx = this.getServletContext(); // Returns an Enumeration of String objects // including "StoreName", etc… Enumeration names = ctx.getInitParameterNames(); // Returns the paramValue "BeeShirts Site 105" String storeName = getInitParameter("StoreName"); The default t im eout , in m inut es, for a session can also be est ablished for t he cont ainer environm ent using t he and elem ent s as defined in our web.xml file:



30



I f we were t o ret rieve such inform at ion from an HttpSession obj ect , we could use t he following code snippet :

HttpSession session = … // retrieve session object // Returns a value of 1800 seconds = 30 minutes X 60 seconds/minute int maxTimeoutInSeconds = session.getMaxInactiveInterval();

- 970 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Se r vle t Applica t ion Con figu r a t ion Access t o param et ers of a servlet environm ent can ret urn only String value param et ers. A m ore generic m eans t o access Java obj ect s m anaged from wit hin a servlet cont ainer environm ent is provided via JNDI lookup services t hrough t he J2EE cont ainer. A JNDI cont ext can be creat ed from wit hin a Java Servlet and used t o look up cert ain t ypes of Java obj ect s t hat have been configured via t he servlet deploym ent descript or. Environm ent configurat ion nam es defined in an elem ent , values in an elem ent , t ypes defined in an elem ent , and descript ions defined in a elem ent can all be defined inside elem ent s wit hin t he servlet deploym ent descript or file. The environm ent values are t hen read from wit hin a servlet via t he JNDI API . Such environm ent values can only be read and not m odified at runt im e. Accept able t ypes for t hese environm ent values are java.lang.Boolean, java.lang.String, java.lang.Integer, java.lang.Double, and java.lang.Float. As an exam ple, we have defined a configurable welcom e m essage for t he front page of our BeeShirts.com Web applicat ion from wit hin an env-entry nam ed WelcomeMessage as shown here:



Customizable description for the Application

WelcomeMessage A big welcome to our online TShirts shoppe.
Buying T-Shirts of your choice is just a click
away. Through our site you can select from a wide
range of shirts. All you have to do is choose
your shirts and order them online. Happy browsing.
  • Wide Variety of Shirts
  • Wide Range of Sizes
  • Secure Shopping
  • Hand Made Designs

    - 971 -

    Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

  • Many More Features …


java.lang.String

Servlet s access such environm ent variables by first creat ing an inst ance of a javax.naming. InitialContext obj ect using t he param et erless form of t he InitialContext const ruct or. The servlet t hen perform s a lookup() on t he InitialContext wit h a nam e t hat begins wit h java:comp/env. The obj ect ret urned from t he lookup() is of t he associat ed . Environm ent ent ry nam es can be also be nam ed as subcont ext s below java:comp/env, such as java:comp/env/foo/bar. Lookups via t he InitialContext can t hus be m ade wit h respect t o relat ive and absolut e cont ext references as discussed in Chapt er 19, " Nam ing Services." As an exam ple of program m at ic access t o a configurable obj ect , t he WelcomeMessage defined in t he previous XML docum ent can be ret rieved from wit hin a servlet as is t he case from wit hin our BeeShirtsServlet class's writePageCenterArea() m et hod ext ract ed as a snippet here:

String msg = ""; try{ // Get initial context and lookup welcome message via JNDI InitialContext ctx = new InitialContext(); msg = (String) ctx.lookup("java:comp/env/WelcomeMessage"); } catch(NamingException namingException){ namingException.printStackTrace(); }

Se r vle t Se r vice M a n a ge m e n t J2EE servlet cont ainers provide various services t hat can be t apped by Java Servlet com ponent im plem ent at ions. These m anagem ent services provide for an efficient , scalable, configurable, and dependably assured com put ing environm ent . To provide such m anagem ent services, J2EE servlet cont ainers oft en rest rict what a servlet com ponent can do by use of Java securit y rest rict ions, such as providing read/ writ e- only file perm issions, connect - only socket perm issions ( t hat is, cannot creat e server socket s) , and read- only syst em propert y perm issions. Servlet cont ainers can t hus effect ively

- 972 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

provide service m anagem ent for t hread pooling, servlet act ivat ion and inst ance pooling, t ransact ions, securit y, availabilit y, EJB obj ect nam ing, and resource int erface obj ect nam ing. Alt hough we have explored m any of t hese services in a broader API cont ext in previous chapt ers, we explore t heir specific applicat ion here t o use wit h servlet s inside of J2EE Web cont ainer environm ent s. Se r vle t Thr e a d a nd Act iva t ion Se r vice M a na ge m e nt The Java Servlet fram ework does not im plicit ly provide prot ect ion of a part icular servlet inst ance for concurrent access by m ult iple client t hreads. A servlet cont ainer m ay act ivat e a single inst ance of a part icular servlet t o handle a request from one Web client and hand t hat inst ance off t o a t hread t hat has been allocat ed for t hat Web client request . A subsequent call from anot her Web client t o t he sam e servlet t ype m ay cause t he servlet cont ainer t o use t he sam e act ive servlet inst ance and hand t hat servlet obj ect off t o a different Web client handler t hread. Many servlet cont ainer im plem ent at ions will pull hot t hread handlers from a t hread pool t o avoid t he overhead associat ed wit h creat ing new t hreads per request . Thread synchronizat ion can be im plem ent ed by t he servlet developer using synchronized blocks or m et hods as discussed in Chapt er 4, " Java Foundat ions for Ent erprise Developm ent ." However, declaring an ent ire service() or doXXX() m et hod synchronized can add significant perform ance overhead if pending client request s m ust block unt il t he current t hread ret urns from such m et hods. Of course, synchronizat ion of concurrent servlet request s need be a concern only for synchronizing shared st at e t hat is subj ect t o m odificat ion. Thus, class and field at t ribut es of a servlet class are oft en prim e candidat es t o exam ine when considering how t o m ake your servlet s t hread safe. Variables t hat are local t o a servlet m et hod, however, are of course local t o t he st ack creat ed by t he invoking t hread and are t herefore aut om at ically t hread safe. I f you creat e a servlet t hat im plem ent s t he javax.servlet.SingleThreadModel m arker int erface, t his will serve as an indicat or t o t he servlet cont ainer im plem ent at ion t hat it should allow only one t hread t o invoke t he service() or doXXX() m et hods at a t im e. Servlet cont ainer im plem ent at ions oft en creat e pools of servlet inst ances t hat are allocat ed t o Web client request t hreads as t he request s are received. Most oft en, t he size of t hese servlet inst ance pools is configurable as well. Thus, alt hough im plem ent ing t he SingleThreadModel int erface can m inim ize concern over t hread synchronizat ion issues, you can also rest assured t hat perform ance degradat ion due t o im posing single-

- 973 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t hreaded servlet access rest rict ions will be m inim ized via servlet inst ance pooling. Nevert heless, servlet inst ance pools do increase t he m em ory overhead of a Web applicat ion. The t rade- off will be yours t o consider based on your specific applicat ion and your COTS servlet cont ainer im plem ent at ion. EJB a nd Re sour ce N a m ing Se r vice M a na ge m e nt Much like environm ent obj ect s can be configured wit hin an XML deploym ent descript or and accessed by a servlet via JNDI , so t oo can EJB and resource int erface obj ect s. EJB client references can be defined wit hin a Web applicat ion deploym ent descript or inside of elem ent s. I nform at ion such as t he EJB reference nam e, class t ype, and int erface nam es can be defined under t his elem ent . Servlet s can t hen act as client s t o t hese EJBs in a very st raight for ward fashion using t he JNDI API wit h EJB reference nam es looked up under a st andard java:comp/env/ejb root cont ext nam e. We defer det ailed discussion of EJB references from J2EE client s unt il Chapt er 36, " Modeling Com ponent s wit h Ent erprise JavaBeans," and Chapt er 37, " Advanced Ent erprise JavaBeans Serving." Web applicat ions can also be configured for access t o resources in a sim ple m anner as defined under elem ent s in t he Web applicat ion XML deploym ent descript or. Resources include JDBC dat a sources, JMS connect ions, JavaMail sessions, and URLs. Web applicat ions can t hen obt ain access t o such resources using JNDI and a st andard JNDI lookup nam ing convent ion. EJB applicat ions can also access dat abase m anagem ent and m essaging services in a fashion sim ilar t o Web applicat ions. Alt hough it is possible t o access dat abase m anagem ent and m essaging services from wit hin a Web server t ier, we defer m uch of our discussion on how such services are m ore com m only accessed t o our EJB discussion in Chapt er 36 and Chapt er 37. Se r vle t Tr a n sa ct ion Se r vice M a n a ge m e n t Servlet s can begin, com m it , and rollback t ransact ions using t he javax.transaction. UserTransaction int erface as described in Chapt er 23, " Transact ion Services." Using such an int erface, servlet s can access m ult iple shared resources and EJBs wit hin t he cont ext of a single at om ic t ransact ion. A handle t o a UserTransaction obj ect is obt ainable using JNDI wit h a lookup via t he nam e of java:comp/UserTransaction . A servlet t ransact ion m ay be begun only wit hin a service() m et hod t hread, and t he t ransact ion m ust be com m it t ed or rolled back before ret urning from t he service() m et hod. Ot herwise, t he servlet cont ainer will abort

- 974 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t he t ransact ion. Thus, we m ight have access t o and dem arcat ion of a t ransact ion as shown here:

public void service (HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException { try{ InitialContext ctx = new InitialContext(); UserTransaction transaction = (UserTransaction) ctx.lookup("java:comp/UserTransaction"); transaction.begin(); // Do some work involving shared resources… if( // Everything is OK? ) transaction.commit(); else transaction.rollback(); } catch(…){ // Handle exceptions } } Transact ion cont ext inform at ion m ust be propagat ed from process t o process in a st andard fashion for dist ribut ed t ransact ions t o be possible. A J2EE servlet cont ainer environm ent prim arily concerns it self wit h such m at t ers. However, t he following rules m ay be assum ed by Web com ponent developers for t ransact ion propagat ion in J2EE environm ent s: • •

• •

Se r vle t t o EJB: The t ransact ion cont ext of a JTA t ransact ion m ust be propagat ed from a servlet t o an EJB when bot h operat e inside of a J2EE cont ainer environm ent . Se r vle t t o D a t a Re sour ce : A servlet 's access t o a resource ( t hat is, DBMS via JDBC) can be m anaged wit hin t he cont ext of a JTA t ransact ion as long as t he servlet did not creat e it s own t hread and inst ead has relied on t he creat ion of t he t hread by t he J2EE cont ainer. Se r vle t t o W e b Se r ve r Re sour ce : Servlet s are required t o propagat e t ransact ion cont ext t o ot her Web resources only when request s are dispat ched via a RequestDispatcher. W e b Clie nt t o Se r vle t : Servlet s are not required t o handle a t ransact ion cont ext propagat ed by t heir Web client s.

- 975 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JDBC connect ion resources are perhaps t he m ost com m on t ype of resource t hat servlet developers encount er and m ust t ake int o considerat ion when dealing wit h t ransact ional environm ent s. Servlet com ponent developers should be part icularly sensit ive t o t he following rules relat ed t o JDBC connect ion handling: • • • •

I nt e r - Thr e a d Sha r ing: JDBC connect ions should not be shared bet ween t hreads. Cla ss At t r ibut e St or a ge : JDBC connect ions should not be st ored in static servlet class at t ribut es. Single Thr e a de d St or a ge : JDBC connect ions can be st ored in servlet class inst ance at t ribut e fields if t he servlet im plem ent s t he SingleThreadModel. M u lt it h r e a de d St or a ge : JDBC connect ions should not be st ored in servlet class inst ance at t ribut e fields if t he servlet does not im plem ent t he SingleThreadModel.

Se r vle t Se cur it y Se r vice M a na ge m e nt The Java Servlet fram ework is int egrat ed wit h m any Java 2.0 securit y feat ures and also augm ent s t he Java 2.0 securit y fram ework t o provide an easy way t o provide secure servlet s. Servlet securit y deals wit h ident it y and aut hent icat ion, aut horizat ion, int egrit y, and confident ialit y. I n part icular, t he J2EE Java Servlet fram ework provides a m eans t o declarat ively define securit y at t ribut es in a Web applicat ion XML deploym ent descript or t hat is used t o configure t he online operat ional securit y aspect s of t he associat ed servlet s. Alt ernat ively, cert ain feat ures of t he securit y fram ework are also exposed t o servlet s via API s t hat enable m ore elaborat e pro gram m at ic securit y provisioning by servlet applicat ion developers. Se r vle t Aut h e n t ica t ion

The elem ent defined wit hin t he elem ent of t he Web applicat ion XML deploym ent descript or is used t o define t he part icular aut hent icat ion configurat ion used by a Web applicat ion. The sub- elem ent of defines t he t ype of aut hent icat ion used. Aut hent icat ion of principals t hat access servlet s is accom plished in one of four ways, including basic, digest - based, form s- based, and SSL client cert ificat e–based aut hent icat ion. These four aut hent icat ion t ypes, wit h t heir associat ed elem ent value in parent heses, are defined here: •

Basic Aut hent icat ion ( BASIC) : A Web server asks t he Web client t o aut hent icat e t he user wit hin a part icular dom ain

- 976 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





• • • • • •

ident ified by a st ring sent t o t he client . The sub- elem ent of defines t his dom ain nam e st ring. The Web client responds wit h a usernam e and password solicit ed from t he Web user. Digest - Based Aut hent icat ion ( DIGEST) : Alt hough a usernam e and password are used t o aut hent icat e a user as wit h basic aut hent icat ion, an added layer of securit y is provided by encoding t he passw ord using a sim ple crypt ographic algorit hm . Form s- Based Aut hent icat ion ( FORM) : St andard HTML form s for login and failed login can be defined using a form s- based aut hent icat ion schem e wit hin t he subelem ent of . When a user at t em pt s t o log in, st andard field nam es of j_username and j_password are post ed t o a specified Web server URL using a st andard act ion nam ed j_security_check. As a sam ple snippet , t he form wit hin t he referenced login HTML page m ay be defined as shown here:



SSL Client Cert ificat e–Based Aut hent icat ion ( CLIENT-CERT) : Client aut hent icat ion via SSL using client cert ificat es is perhaps t he m ost secure m eans for aut hent icat ion. Because t his form of aut hent icat ion requires SSL over HTTP, t his form of aut hent icat ion is som et im es referred t o as HTTPS- based client aut hent icat ion.

Cert ain aut hent icat ion- relat ed inform at ion associat ed wit h an HTTP request can be ext ract ed from t he HttpServletRequest when needed. The getAuthType() m et hod can be used t o ident ify any secure aut hent icat ion schem e used t o prot ect access t o t he servlet ( for exam ple, BASIC, DIGEST, or null for " none" ) . The user ident it y nam e t hat was aut hent icat ed and associat ed wit h an HTTP servlet request ( opt ionally null if no aut hent icat ion) is obt ained via a call t o getRemoteUser(). Finally, a handle t o an aut hent icat ed user in java.security.Principal form can be obt ained from a call t o getUserPrincipal(). Se cu r e Se r vle t Com m u n ica t ion s

When a servlet request is sent t o a Web server using a secure prot ocol, t he ServletRequest. isSecure() m et hod call can be used t o ret urn a boolean value indicat ing t his fact . When SSL is used wit h HTTP, an array of javax.security.cert.X509Certificate obj ect s is ret urned from a - 977 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

call t o ServletRequest.getAttribute() using t he at t ribut e nam e javax.servlet. request.X509Certificate. The securit y of a cookie can also be specified using t he Cookie.setSecure(boolean) m et hod and det erm ined from t he Cookie.getSecure() m et hod. Cookie securit y sim ply indicat es whet her t he cookie is t o be t ransm it t ed over a secure prot ocol. Se r vle t Aut hor iz a t ion

Aft er a user has been ident ified using one of t he previously defined aut hent icat ion m echanism s, t he aut horizat ion t o servlet resources ident ified by URLs can be det erm ined. Servlet aut horizat ion is based on a role- based access cont rol t echnique. Securit y roles are m apped t o principals or groups. When a request is m ade by a part icular principal on a resource wit h an associat ed securit y role, t he principal nam e or group t o which t he principal belongs is com pared wit h t he principal nam e or group associat ed wit h t he required role t o det erm ine whet her access t o t he resource is allowed. A collect ion of securit y roles valid for a part icular J2EE servlet environm ent can be defined wit hin t he XML deploym ent descript or's sub- elem ent of t he elem ent . The sim ply defines a set of valid role nam es and opt ional descript ions in t his way:

Sytem Administration Role admin



Access t o a part icular servlet can t hen be rest rict ed t o access by users of a defined role using the subelem ent of a elem ent . A elem ent defines a securit y role assum ed by t he applicat ion, and a elem ent refers t o one of t he servlet cont ainer- m anaged elem ent 's values as illust rat ed here:

UserAccountManagement …

SystemAdmin

- 978 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

admin



The role of a user associat ed wit h a part icular HTTP servlet request can be det erm ined via a call t o t he HttpServletRequest.isUserInRole(String) m et hod wit h a role nam e param et er designat ing t he securit y role defined wit hin a Web deploym ent descript or. More sophist icat ed Web resource aut horizat ion can be specified wit h t he sub- elem ent of . A collect ion of Web resources can be specified and associat ed for access only by principals belonging t o cert ain associat ed roles. Furt herm ore, t he secure nat ure of t he com m unicat ions link over which access occurs can also be defined. As an exam ple for lim it ing access t o det ailed user inform at ion st ored on a Web server, we m ight have t his:



UserInfo URL for all detailed user information /users/* POST

Only allow system administrator access admin

Require SSL session to get user info CONFIDENTIAL



Se r vle t Ava ila bilit y Se r vice M a n a ge m e n t

- 979 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Web- enabling an ent erprise opens t he gat eway t o an ent erprise syst em for access by a large I nt ernet or int ranet com m unit y. Alt hough access t o resources can be rest rict ed t o aut horized users via securit y m echanism s, t he dem and for service by Web client s placed on a Web server can be significant ly large for m ost Webenabled ent erprise applicat ions. Thus, availabilit y of service for Web- enabled applicat ions built using servlet s m ust be considered from t he out set of design. Mult iple Web client request s m ust not bring your Web- enabled ent erprise int erface t o it s knees. Furt herm ore, t he scalabilit y of Web client usage will need t o be considered by any ent erprise syst em t hat want s t o expand it s Web client base. Fort unat ely for t he Java Servlet developer, t he m anagem ent of such availabilit y can be kept t ransparent t o t he developer and m anaged by a part icular Java Servlet cont ainer and server im plem ent at ion environm ent . Most Web servers and servlet cont ainer im plem ent ers support scalabilit y and availabilit y in part by providing efficient t echniques for t hread pooling and servlet inst ance pooling. As a client request is received by t he server, t he server fram ework handles t he efficient allocat ion of syst em m em ory and t hread resources t o t he request t ransparent ly t o t he servlet applicat ion developer. Transact ion m anagem ent services also provide a cert ain degree of availabilit y by m anaging dist ribut ed access t o shared dist ribut ed resources in a fashion t hat perm it s for t he at om icit y, consist ency, isolat ion, and durabilit y of operat ions. More sophist icat ed m eans for providing highly available Webenabled applicat ions m ay also be provided by vendors t hat im plem ent load- balancing, clust ering, and failover t echniques. Load- balancing and clust ering basically involve t he m anagem ent of m ult iple JVM processes wit hin t he sam e m achine or across different dist ribut ed m achines t o spread t he load of client request s. I n t he event of a part icular process or m achine's failure, a failover t echnique m ay be em ployed t o dist ribut e client request s t o anot her redundant JVM process or m achine. Such feat ures are relat ively sim ple for st at eless servlet s, but t he st orage of HttpSession inform at ion in st at eful Web applicat ions m akes such redundancy m anagem ent m ore difficult . Vendors t hus m ay have t o guarant ee t he capabilit y t o persist HttpSession inform at ion or provide t he capabilit y t o serialize and deserialize HttpSession inform at ion across different JVM processes. J2EE servlet cont ainer environm ent s t hat support dist ribut able servlet s can deploy inst ances of servlet s t o different JVM processes on t he sam e m achine or on ot her net worked host m achines in a st andard fashion. A cont ainer environm ent can be viewed as a

- 980 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

dist ribut ed environm ent dom ain t hat cont ains and m anages m ult iple dist ribut ed JVM processes. An opt ional elem ent placed wit hin t he elem ent of a Web applicat ion's XML deploym ent descript or designat es t he capabilit y t o run t he Web applicat ion inside of a dist ribut able servlet environm ent . By specifying t hat a Web applicat ion can operat e in a dist ribut able fashion, we are t elling t he servlet cont ainer environm ent t hat t he Web applicat ion adheres t o a few behavioral const raint s t o facilit at e dist ribut ion. Web cont ainers can t hen im plem ent feat ures of clust ering and failover t hat would ot herwise not be possible for nondist ribut able servlet s. The rest rict ions t hat m ust be adhered t o by t he servlet s m ainly revolve around t he t ype of obj ect s t hat are st ored in an HttpSession obj ect . Only java.io.Serializable, javax.ejb. EJBObject, javax.ejb.EJBHome, javax.transaction.UserTransaction, and javax.naming.Context obj ect s m ay be st ored in an HttpSession by a dist ribut able servlet . Ot herwise, an IllegalArgumentException m ay be t hrown by t he cont ainer when an at t em pt ed HttpSession st orage operat ion is perform ed. By rest rict ing such obj ect t ypes t o being added t o a servlet HttpSession obj ect , t he servlet cont ainer can guarant ee t he m obilit y of servlet session obj ect st at e during failover or clust ering.

Con clu sion s We have covered t he gam ut of developm ent t opics t hat concern t he Web- enabling of ent erprise applicat ions using Java Servlet s. The J2EE Java Servlet archit ect ure provides a com ponent - cont ainer m odel t hat can result in a significant am ount of sim plified HTTP com m unicat ions paradigm and m anagem ent service abst ract ion for t he servlet developer. We've explored m eans t o m anipulat e HTTP request s, responses, sessions, and cookies via st andard higher- level API s. However, t he Java Servlet API is very rich in support and can som et im es be cum bersom e t o digest for t he Java newcom er. JavaServer Pages, as you'll see in t he next chapt er, can address t his issue t o a cert ain ext ent . We have also explored t he use of a J2EE server environm ent for t he deploym ent of Java Servlet Web com ponent s. Deploying and configuring Java Servlet s is sim plified and st andardized wit h t he J2EE. J2EE servers also provide m any m anagem ent services, such as securit y and availabilit y, t hat can be configurably m anaged from wit hin t he cont ext of XML deploym ent descript ors. However, t he ext ension of som e of t hese declarat ive m anagem ent feat ures t o cert ain ent erprise applicat ions can be lim it ed. Nevert heless, you can

- 981 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

always fall back on program m at ic use of t he various ent erprise Java API s t hat we have described in previous chapt ers.

Ch a pt e r 3 3 . Ja va Se r ve r Pa ge s I N TH I S CH APTER • • • • • • • • •

JSP Overview JSP Language Basics JSP Translat ion and Com pilat ion Direct ives Java Script ing from JSP Java Abst ract ions of JSP St andard Java Obj ect s from JSP St andard Java Act ions from JSP JSP Configurat ion and Deploym ent Cust om Java Act ions and Tags from JSP

JavaServer Pages ( JSPs) are t ext docum ent s int erpret ed by a JSP cont ainer t hat can cont ain a m ixt ure of st at ic HTML and script ing language com m ands for dynam ically generat ing Web responses t o Web request s and for com m unicat ing wit h server- side applicat ions and dat a. JSPs are t ranslat ed and com piled int o Java Servlet s but are easier t o develop t han Java Servlet s and m ay be viewed as a t echnology for providing a way t o Web- enable an ent erprise via a program m ing paradigm m ore fam iliar t o Web program m ers. JSP developers can use a sim plified script ing language–based synt ax for em bedding HTML int o JSPs, for direct ing how JSPs are t ranslat ed int o Java Servlet s, for em bedding Java int o JSPs, and for accessing st andard obj ect s and act ions provided by JSP cont ainers. The configurat ion and deploym ent of JSPs also has a sim plified XMLbased deploym ent descript or approach akin t o t he approach provided for Java Servlet s. I n t his chapt er, you will learn: • • • • •

The archit ect ure and concept s behind use of JavaServer Pages. The basic language of JSPs and t he basic st ruct ure of JSP docum ent s. The com m ands used for direct ing t ranslat ion and com pilat ion of JSPs int o Java Servlet im plem ent at ion classes. The m et hodology and synt ax for em bedding Java code direct ly int o JSPs. The API s and st andard obj ect s used by JSPs for int eract ing wit h m anaged obj ect s provided by t he JSP cont ainer for m anipulat ing request s, responses, sessions, and JSP inform at ion.

- 982 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • •

The st andard JSP script ing language t ags and act ions t hey invoke. The configurat ion and deploym ent of JSPs in a J2EE- com pliant environm ent . The basic approach for providing cust om JSP script ing language t ags and associat ed act ions.

JSP Ove r vie w JavaServer Page t echnology provides a m eans for specifying special script ing language com m ands inside of a t ext - based docum ent t hat are used on t he server side t o process request s from a client and t o generat e responses for t he client . As is t he case wit h Java Servlet s, JSPs use HTTP as t he default request / response com m unicat ions paradigm and t hus m ake JSPs ideal as a Web- enabling t echnology. HTML, XML, and ot her t em plat e dat a can be defined in a JSP and are sent direct ly t o a Web client wit hout any addit ional processing on t he server side. However, JSP script ing language com m ands insert ed int o t he sam e page are processed on t he server side before a request ed page is delivered back t o a Web client . JSP is oft en at t ract ive t o a Web- enabling ent erprise developer because regular t em plat e dat a can be used direct ly wit hin a JSP, t he JSP script ing com m and language has a sim ple XML- like synt ax, and Java code can be used wit hin t he page. JSP is also defined in a generic enough fashion t hat fut ure versions of t he specificat ion will be able t o support ot her em bedded languages besides Java. However, t he m ost recent JSP v1.1 st andard requires use of only Java as t he em bedded script ing language. JSP v1.1 is required by t he J2EE v1.2 and also depends on t he Java Servlet s v2.2 st andard described in Chapt er 32, " Java Servlet s." JSP Ar chit e ct ur e Figure 33.1 depict s t he basic archit ect ure of a JSP environm ent . The first t hing t o not e is t hat JSP ext ends and depends on t he Java Servlet API and im plem ent at ion. Alt hough JSPs are writ t en by applicat ion developers, t hey are ult im at ely convert ed t o Java Servlet s. An im plem ent at ion class of t he JSP is act ually an underlying servlet represent at ion of t he JSP. However, addit ional sem ant ics are im posed on t he im plem ent at ion t o sat isfy t he expect ed int erface cont ract bet ween t he JSP cont ainer and t he JSP im plem ent at ion class. Thus, alt hough developers creat e JSP com ponent s using a com binat ion of HTML, XML, JSP com m and synt ax, and an em bedded script ing language ( for exam ple, Java) , all t he benefit s provided t o t he Java Servlet com ponent by it s cont ainer environm ent are provided t o t he JSP com ponent by it s

- 983 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

cont ainer environm ent . Because JSPs and Java Servlet s are bot h generically viewed as Web com ponent s from a J2EE cont ainer's perspect ive, t hey share t he sam e m echanism s for configurat ion and service m anagem ent . Figu r e 3 3 .1 . The JSP a r ch it e ct u r e .

JSPs can also refer t o request , response, and session m anagem ent obj ect s creat ed by a cont ainer direct ly from t he JSP. As you'll see in lat er sect ions, such obj ect s can be used t o perform request handling, response handling, and session m anagem ent from wit hin a JSP using t he sam e API s for such obj ect s as were used wit h Java Servlet s. JSPs t hus reap all t he benefit s provided by Java Servlet s and Web cont ainer environm ent s, but t hey have t he added advant age of being sim pler and m ore nat ural t o program for Webenabling ent erprise developers. Ph a se s of a JSP Figure 33.2 depict s t he various t ransform at ions t hat a JSP m ust go t hrough before it can process request s online. A developer first creat es a JSP using JSP synt ax and t he collect ion of request , response, and session m anagem ent abst ract ions provided by t he JSP API and program m ing m odel. A t ranslat ion t ool is t hen used t o t ransform t he JSP int o Java Servlet im plem ent at ion source code, which in t urn is com piled int o a Java Servlet im plem ent at ion class file by a Java com piler t ool. This t ranslat ion and com pilat ion process - 984 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

m ay be perform ed offline before or during deploym ent , or it m ay be perform ed online by t he JSP cont ainer upon request of a part icular JSP. The specific approach depends on a developer's preference and t he specific JSP vendor t ools provided. Finally, t he com piled Java Servlet im plem ent at ion class is act ivat ed by t he JSP cont ainer in t he sam e m anner t hat a Java Servlet is act ivat ed. The act ivat ed JSP represent at ive obj ect is t hen capable of processing act ual request s, responses, and session act ions. Figur e 3 3 .2 . The pha se s of a JSP.

BeeShirts.com JSP Ex a m ple s We have creat ed a JSP version of t he Java Servlet –based BeeShirts.com e- com m erce st orefront t hat was present ed in Chapt er 32 and placed t he new JSP code on t he CD. Because t his sam ple code is m oderat ely large, we also won't be insert ing all t he source code from t he CD int o t he chapt er t ext but will be providing core snippet s from such code as relevant t opics are int roduced. Figure 33.3 does, however, provide you wit h a logical diagram of t he various JSPs used t o service request s and generat e responses for t his sam ple code. These JSPs essent ially provide t he sam e funct ionalit y as t he code from Chapt er 32. We also ut ilize t he im ages and BeeShirts.com ent it y classes ( Customer, Item, and so on) developed in Chapt er 32 as were illust rat ed in Figure 32.7. Figur e 3 3 .3 .

BeeShirts.com JSPs.

- 985 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

N ot e All t he sam ple code st rewn t hroughout t his chapt er is cont ained on t he CD under t he examples\src\ejava\jspch33 direct ory. Because t he code on t he CD represent s a m oderat ely large am ount of Webbased BeeShirts.com st orefront code, we do not present all t he code in t his chapt er. Rat her, we describe t he basic st ruct ure of such code and present snippet s from t hat code germ ane t o chapt er t opics as t hey are discussed. We should also not e t hat t his code depends on som e of t he code from Chapt er 32 st ored on t he CD under t he examples\src\ejava\servletsch32 direct ory.

The BeeShirts.com JSPs shown in Figure 33.3 and t he Chapt er 32 Java Servlet classes and HTML pages t o which t hey relat e are briefly defined here: •

ErrorDisplay: I s a global JSP t o provide a st andard page for displaying JSP errors as t hey occur. JSPs experiencing errors aut om at ically are rout ed t o t his page.

- 986 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • •

• •





• •







BeeShirts: Provides t he root JSP t hat generat es t he BeeShirts.com st art ing page akin t o t he BeeShirtsServlet of Chapt er 32. BeeShirtsTopArea: I s a special JSP t o display t he t op logo port ion of t he BeeShirts.com Web page. This JSP is included by all t he root page JSPs. BeeShirtsLeftArea: I s a special JSP t o display t he left port ion of t he BeeShirts.com Web page displaying t he BeeShirts.com but t on opt ions. This JSP is included by all t he root page JSPs. AboutUs: Handles t he request generat ed by clicking t he About Us but t on and displays som e sim ple BeeShirts.com inform at ion akin t o t he AboutUsServlet of Chapt er 32. ContactInformation: Handles t he request generat ed from clicking t he Cont act but t on and displays som e sim ple cont act inform at ion akin t o t he ContactInformationServlet of Chapt er 32. Registration: I s referenced from t he Join but t on and handles display of r egist rat ion form or regist rat ion inform at ion. Will execut e an included RegistrationForm JSP if a GET request is received and will execut e an included DisplayRegistrationInformation JSP if a POST is received. RegistrationForm: Displays a regist rat ion form and subm it s a POST t o t he current Registration JSP when t he Regist er but t on is clicked akin t o t he registration.html file of Chapt er 32. DisplayRegistrationInformation: Displays t he result s of a user regist rat ion akin t o t he RegistrationServlet of Chapt er 32. BrowseShirts: I s referenced from t he Browse but t on and handles display of a browsing query form or display of browse result inform at ion. Will execut e an included BrowseShirtsForm JSP if a GET request is received and will execut e an included DisplayBrowsedShirts JSP if a POST is received. BrowseShirtsForm: Creat es a display t hat allows a user t o query for t he T- shirt s t hey m ight be int erest ed in purchasing akin t o t he BrowseShirtsServlet of Chapt er 32. Subm it s a POST t o BrowseShirts when a Query but t on is clicked. DisplayBrowsedShirts: Displays search result s from a browse query akin t o t he BrowseShirtsServlet of Chapt er 32. Subm it s a POST t o Cart when an ADD TO CART but t on is clicked. Cart: I s referenced from t he View Cart but t on and handles display of current shopping- cart cont ent s or display of a

- 987 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •

• • •

• •



st at us m essage when an it em is added t o t he cart . Will execut e an included DisplayItemsInTheCart JSP if a GET request is received and will execut e an included AddAnItemToTheCart JSP if a POST is received. DisplayItemsInTheCart: Handles t he GET t o display t he current cont ent s of t he shopping cart akin t o t he CartServlet of Chapt er 32. AddAnItemToTheCart: Handles t he POST from t he DisplayBrowsedShirts JSP ADD TO CART but t on t o add a TShirt it em t o t he shopping cart akin t o t he CartServlet of Chapt er 32. CheckOut: Handles t he GET request generat ed from t he Check Out but t on and dispat ches request s appropriat ely akin t o t he CheckOutServlet of Chapt er 32. OrderStatus: Handles t he GET request generat ed from clicking t he Order St at us but t on and includes t he LoginForm JSP. LoginForm: Displays an order st at us login form akin t o t he OrderStatusServlet of Chapt er 32. Whenever t he Login or Rem ind but t on is clicked, a POST is sent t o t he VerifyLogin JSP. VerifyLogin: Handles t he POST from eit her a Login or a Rem ind but t on being pressed akin t o t he OrderStatusServlet of Chapt er 32. TermsAndConditions: Handles t he request generat ed from clicking t he Term s but t on and displays som e sim ple t erm s and condit ions inform at ion akin t o t he TermsAndConditionsServlet of Chapt er 32. Delivery: Handles t he request generat ed from t he Delivery but t on and displays som e canned delivery inform at ion akin t o t he deliveryinformation.html page of Chapt er 32.

JSP La n gu a ge Ba sics JSPs cont ain a m ixt ure of t em plat e dat a ( for exam ple, HTML and XML) int erspersed wit h JSP elem ent s. JSP elem ent s are defined wit hin begin and end t ags and are t he port ions of a JSP t hat are t ranslat ed and com piled by a JSP com piler int o Java Servlet s. These JSP elem ent s are t he port ions of a JSP t hat represent t he com m ands t hat are int erpret ed by JSP cont ainers t o service request s from client s. The t em plat e dat a, on t he ot her hand, represent s t he com m ands t hat are ult im at ely int erpret ed by client s and t herefore sim ply pass unaffect ed t hrough t he JSP com piler and cont ainer processing infrast ruct ure. Figure 33.4 is a concept ual logical diagram t hat depict s t he m ain com ponent s of a JSP and t he hierarchy of JSP elem ent s used t o build JSPs.

- 988 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figur e 3 3 .4 . A conce pt dia gr a m for com pone nt s of a JSP.

Three m ain t ypes of JSP elem ent s are defined in t he JSP specificat ion. A direct ive elem ent is int erpret ed at t ranslat ion t im e and can be used t o t ell a JSP com piler t o include ot her files in t he com pilat ion of a JSP, define at t ribut es about t he JSP page being t ranslat ed, and define any libraries of cust om elem ent s used in t he JSP. A script ing elem ent is used t o define any variable and m et hod declarat ions, expressions t o be evaluat ed, and blocks of com m ands known as script let s all in t erm s of t he host language support ed by t he JSP cont ainer ( for exam ple, Java) . Finally, act ion elem ent s are com m ands t hat have a purely t aglike look t o t hem but are im plem ent ed by t he host language t ransparent ly t o t he JSP program m er. Eit her a set of cust om act ions can be defined or a set of st andard act ions can be used t o forward request s t o ot her resources, include responses from ot her resources, look up or creat e JavaBean obj ect s for use wit hin a JSP, set JavaBean propert y values, get JavaBean propert y values, and em bed Java applet s or JavaBeans direct ly int o a JSP using t he Java Plug- in synt ax. JSP St a n da r d a n d XM L- Ba se d Ele m e n t s JSP elem ent s can be int erpret ed by t he JSP cont ainer. Elem ent s should not be confused wit h t ags. JSP elem ent s represent a unit of int erpret able JSP synt ax wit h a st art and end t ag. JSP t ags, on t he ot her hand, sim ply represent a sm all piece of m arkup code t hat m ay be used inside of a JSP elem ent and do not necessarily have st art and end t ags.

- 989 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JSP elem ent s have a synt ax sim ilar t o XML elem ent s and have st art and end t ags, have case- sensit ive elem ent nam es, can be em pt y elem ent s, have opt ional at t ribut e values, and have an opt ional elem ent body. Alt hough JSP elem ent synt ax is ident ical t o XML in som e cases, it is only sim ilar t o XML in ot her cases. The JSP specificat ion does define a convent ion for expressing JSPs as XML docum ent s, but it is not recom m ended t hat such a convent ion be used for hand- aut horing of JSPs. Rat her, due t o t he som et im esawkward synt ax t hat m ust result from expressing JSPs via XML, t he XML represent at ion of JSPs is prim arily specified for im plem ent at ion by JSP developm ent t ools. Furt herm ore, t he specificat ion is current ly not com plet ely well- defined and is not required t o be support ed by JSP v1.1 cont ainers. When represent ing a JSP using XML, a elem ent along wit h an xmlns:jsp at t ribut e is used t o define t he root of t he XML- based JSP docum ent t hat m ust be form at t ed according t o a st andard DTD. Ta gs Alt hough we som et im es t hink of t ags as discret e snippet s of m arkup t hat define part s of a JSP or HTML page, t he t erm t ags as it relat es t o cust om t ag ext ensions is act ually an im port ant part of t he JSP specificat ion wit h a very specific m eaning. Cust om t ags relat e t o cust om act ions t hat can be defined by developers using a special set of JSP t ag ext ension Java classes and int erfaces. These cust om act ions are im plem ent ed by cust om Java- based t ag handler classes t hat handle any cust om t ags insert ed int o a JSP. A collect ion of t hese t ag handlers is referred t o as a t ag library, which can be referenced and ut ilized by JSPs using a special t ag library direct ive. Furt herm ore, an XML- based t ag library descript or file can also be used t o configure a part icular t ag library. We have m uch m ore t o say about cust om t ags and act ions in a lat er sect ion. Com m e n t s Com m ent s in JSP pages can be used t o docum ent JSP source code or used t o em bed inform at ion t o be sent t o t he client . Com m ent s t hat are t o be ignored during processing and used t o docum ent JSP source code are included bet ween charact ers. Com m ent s specific t o t he t ype of script ing language being used wit h t he JSP m ay also be used wit hin script ing elem ent s. Thus, for Javabased JSP script ing, we would place docum ent at ion com m ent s bet ween charact ers. As an exam ple of such com m ent s, we have t his:

- 990 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Com m ent s t hat are t o be sent t o t he client response st ream are defined wit hin

BeeShirts BeeShirts BeeShirts.jsp



I f t he JSP is precom piled int o an im plem ent at ion class, t he elem ent can be used. I f it is st ill desirable t o refer t o t he JSPs using t he JSP nam e or som e ot her configurable URL pat t ern, a elem ent can be used. For exam ple, we use a BEA WebLogic precom piler t o t ranslat e and com pile t he BeeShirts.jsp file int o a _beeshirts Java class file in t he ejava.jspch33 package, and t hen set deploym ent descript or ent ries for t his JSP in a weblogic_app.xml file on t he CD like t his:

- 1027 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



BrowseShirts BrowseShirts BrowseShirts.jsp

numberOfShirts 8 Number Of Shirts to Read

shirt_0 0,XL,White, 11.5, 123,145,shirtOne.jpg

First Shirt Information





Recall t hat t he DisplayBrowsedShirts JSP is included as part of t he BrowsedShirts t ranslat ion unit . The DisplayBrowsedShirts.getQueriedShirts() script let m et hod is where access t o such values is perform ed wit h calls such as t his:

javax.servlet.ServletConfig config = getServletConfig(); String nShirtsString = config.getInitParameter("numberOfShirts"); Such a call m ight also be m ade from direct ly wit hin a JSP using t he config im plicit obj ect in t his way:

- 1029 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

String nShirtsString = config.getInitParameter("numberOfShirts"); The sam e BrowseShirts configurat ion is also st ored in t he values displayed here:



numberOfShirts 8 java.lang.String

shirt_0

0,XL,White, 11.5, 123,145,shirtOne.jpg

java.lang.String



The DisplayBrowsedShirts.getQueriedShirtsFromEnvironment() script let m et hod im plem ent s t he form of configurat ion t hat is ut ilized by our act ual online JSP processing exam ple. This m et hod is where access t o values is perform ed wit h calls t o t he InitialContext obj ect st ored wit hin our JSPHelper class as such:

String nShirtsString = (String) JSPHelper.initialContext.lookup("java:comp/env/numberOfSh irts"); As previously m ent ioned, t he OrderStatus JSP also has configurat ion inform at ion defined for it . The VerifyLogin JSP, which is part of t he OrderStatus JSP t ranslat ion unit , cont ains a constructDefaultUserInformation() m et hod t hat reads configurat ion inform at ion from t he ent ries for OrderStatus. The constructDefaultUserInformationFromEnvironment() m et hod reads t his inform at ion from t he ent ries and is t he m et hod act ually invoked by our sam ple code. D ir e ct JSP D e ploym e nt Pr oce dur e Conside r a t ions

- 1030 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The process for deploying JSP com ponent s follows m any of t he st eps described in Chapt er 32 t o deploy Java Servlet s. Set t ing J2EE server environm ent variables and configuring J2EE server propert ies are t wo init ial st eps t hat m ust be perform ed, as was t he case in Chapt er 32. The creat ion of XML- based deploym ent descript ors as well as t he packaging and deploym ent of archives are also very sim ilar. Our compilej2ee.bat file, in fact , cont ains sam ple script s for aut om at ically execut ing m any of t hese st eps for use wit h t he J2EE reference im plem ent at ion. This part icular script deploys JSPs direct ly in t heir unt ranslat ed source form . The first special considerat ion for deploying JSPs direct ly is t o ensure t hat t he JSP files are placed under t he root cont ext of t he Web applicat ion. We accom plish t his in our sam ple compilej2ee.bat script file by sim ply copying t he .jsp files associat ed wit h t his chapt er's exam ple t o a root direct ory, nam ed deploycontent, which cont ains a collect ion of Web cont ent files. The cont ent direct ory also includes ot her direct ly accessible cont ent files, such as .gif, .jpg, and .html files. The J2EE reference im plem ent at ion's packager ut ilit y is subsequent ly used t o creat e a jspch32.war file from t hese cont ent files in a deploycontent direct ory, any com piled Java classes in a deployclasses direct ory, and a web.xml deploym ent descript or as illust rat ed here:

%J2EE_HOME%\bin\packager -webArchive -classpath deployclasses deploycontent web.xml jspch33.war We subsequent ly creat e a J2EE ent erprise applicat ion nam ed JspApp inside of a jspch32.ear ent erprise applicat ion archive file using our newly creat ed WAR file wit h a com m and of t he following form :

call %J2EE_HOME%\bin\packager -enterpriseArchive jspch33.war JspApp jspch33.ear Before we deploy t he jspch32.ear file, we also insert our own application.xml file int o t he EAR file from wit hin t he compilej2ee.bat script . The m ain body of our application.xml file sim ply defines t he root cont ext of beeshirtsjsp for our JSPbased Web applicat ion as shown here:

- 1031 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JspApp Application Description

jspch33.war beeshirtsjsp

Assum ing t hat t he J2EE reference im plem ent at ion server was st art ed ( t hat is, by calling %J2EE_HOME%\bin\j2ee -verbose) , t he compilej2ee.bat script can t hen successfully deploy t he EAR file using t he deploytool ut ilit y as shown here:

%J2EE_HOME%\bin\deploytool -deploy jspch33.ear localhost Finally, t he root BeeShirts.com JSP can be accessed from a Web browser wit h t his URL: ht t p: / / localhost : 7001/ beeshirt sj sp/ BeeShirt sJsp You'll not ice a slight delay t he first t im e each JSP is accessed due t o t he t im e it t akes t he J2EE reference im plem ent at ion t o t ranslat e and com pile each JSP. Subsequent request s t o t he sam e JSP are processed m uch fast er. N ot e You m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb.properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. Refer t o Appendix A, " Soft ware Configurat ion," for m ore det ails.

Pr e com pile d JSP D e ploym e nt Pr oce dur e Conside r a t ions The ent erprise- class BEA WebLogic Server com es equipped wit h a com piler t ool t hat we use from wit hin a compileweblogic.bat file t o precom pile our BeeShirts.com JSP files. The java.weblogic.jspc program for precom piling JSPs using a

- 1032 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

specified package nam e is invoked from wit hin compileweblogic.bat using t his general com m and form :

java weblogic.jspc -package packageName JspFileName.jsp As an exam ple for com piling t he BeeShirt s JSP, we have t his:

java weblogic.jspc -package ejava.jspch33 BeeShirts.jsp Aft er com piling and deploying each JSP im plem ent at ion class as was done for Java Servlet s in Chapt er 32, we are ready t o access our BeeShirts.com applicat ion from a Web browser. At t he t im e of t his writ ing, t he BEA WebLogic Server v5.0 and v5.1 did not support deploym ent of J2EE applicat ion EAR files. Thus, our sam ple compileweblogic.bat file sim ply creat es t he appropriat e web applicat ion direct ory st ruct ure populat ed wit h our exam ple code and t hen uses t he jar com m and t o creat e a jspch33.war file m apped from t his direct ory st ruct ure. This WAR file m ust be referenced by t he weblogic.httpd.webApp.beeshirtsjsp propert y defined wit hin t he BEA WebLogic Server's [WEBLOGIC_HOME]\weblogic.properties file. The weblogic.properties file's weblogic.httpd.documentRoot value should also be set t o myserver/ for our exam ples. The BEA WebLogic Server can t hen be st art ed using t he [WEBLOGIC_HOME]\startweblogic.cmd com m and script . Appendix A describes t he general configurat ion procedures for t he BEA WebLogic Server.

Cu st om Ja va Act ion s a n d Ta gs fr om JSP I n an earlier sect ion, you saw how a few st andard JSP act ions can be used t o m ake writ ing JSPs an easier t ask and m ore nat ural t o developers used t o writ ing script ing language–based Web- enabling code. JSP act ions encapsulat e a set of operat ions t hat are im plem ent ed behind t he scenes in Java code. Such act ions can t hen be used t o provide a sim ple set of script ing t ags and at t ribut es describing an act ion t o be perform ed. JSP also defines a m echanism for ext ending t he capabilit y of JSP act ions by providing a m echanism t o creat e your own cust om act ions and t ags. Act ions defined in t erm s of a begin t ag, at t ribut es, an opt ional body, and an end t ag can be im plem ent ed using a set of special Java classes and int erfaces. A set of cust om classes t hat ext end t hese abst ract ions is t hen insert ed int o a class archive referred t o as a t ag library. Such libraries can be configured at deploym ent t im e and

- 1033 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

referenced from wit hin JSPs using taglib direct ives. The cust om classes are referred t o as t ag handlers and are sim ple nonvisible JavaBean com ponent s t hat im plem ent a special t ag handling int erface cont ract . A JSP cont ainer can creat e or locat e t ag handler obj ect s whenever an associat ed act ion is defined in t he JSP. This sect ion briefly describes t he JSP t ag ext ension abst ract ions and how t hey are used wit h t ag libraries, t ag library descript or files, and taglib direct ives t o ext end t he funct ionalit y available t o JSP program s. JSP Cust om Ta g Ex t e nsion Abst r a ct ions Abst ract ions from t he javax.servlet.jsp.tagext package are used t o creat e cust om t ag ext ensions. To creat e a cust om t ag handler, you m ust im plem ent eit her t he javax.servlet. jsp.tagext.Tag or t he javax.servlet.jsp.tagext.BodyTag int erfaces, or you m ust ext end eit her t he javax.servlet.jsp.tagext.TagSupport or t he javax.servlet.jsp.tagext. BodyTagSupport classes. Figure 33.8 depict s t hese key t ag ext ension abst ract ions and how t hey relat e t o cust om t ag handlers. Figu r e 3 3 .8 . JSP cu st om t a g e x t e n sion a bst r a ct ion s.

- 1034 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Tag int erface defines a set of basic operat ions called by t he cont ainer t o m anage a cust om act ion defined wit hin a JSP. A cont ainer will first set a PageContext obj ect and any parent t ags ont o t he Tag im plem ent at ion when t he cont ainer encount ers an associat ed cust om t ag in t he JSP. Any at t ribut es of t he cust om act ion are t hen set according t o t he propert ies of a JavaBean com ponent m odel ont o t he t ag handler. The cont ainer t hen calls doStartTag() when it want s t he t ag handler t o begin processing an act ion. A call t o doEndTag() occurs when t he cont ainer processes t he end t ag in t he JSP. The TagSupport class is a ut ilit y class wit h som e helper m et hods t hat can also be direct ly ext ended by a cust om t ag handler inst ead of im plem ent ing t he Tag int erface. The BodyTag int erface is used when a cust om act ion can cont ain an act ion body. Aft er st art ing a t ag, a cont ainer calls t he setBodyContent() m et hod wit h a handle t o a BodyContent obj ect . The BodyContent obj ect can be used t o read t he body dat a t hat has been out put t o an out put st ream by t he cont ainer. The doInitBody() m et hod is t hen called by t he cont ainer t o ask t he t ag handler t o begin evaluat ing t he body t hat is out put t o t he out put st ream . The cont ainer t hen calls doAfterBody() as part s of t he body are evaluat ed. The BodyTagSupport class is a ut ilit y class t hat im plem ent s t he BodyTag int erface and can also be ext ended by cust om body t ag handlers. I n addit ion t o t hese basic cust om t ag ext ension abst ract ions, a collect ion of abst ract ions is also defined t o describe m et a inform at ion about libraries used t o collect im plem ent at ion classes. Figure 33.9 depict s t hese abst ract ions and t heir relat ions. The TagExtraInfo class is ext ended by a cust om t ag im plem ent at ion t o provide addit ional inform at ion about a cust om t ag library. A TagExtraInfo obj ect can use TagData ( nam e/ value at t ribut e pairs) t o ret rieve VariableInfo t o describe any script ing variables creat ed or m odified by a t ag. I nform at ion relat ed t o a part icular cust om t ag is ext ract ed from a TagInfo class. At t ribut es associat ed wit h t hat t ag can t hen be ext ract ed from a collect ion of associat ed TagAttributeInfo obj ect s. Finally, a TagLibraryInfo obj ect can be used t o provide m ore inform at ion about t he t ag library it self. Figur e 3 3 .9 . JSP cust om t a g libr a r y a bst r a ct ions.

- 1035 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Ta g Libr a r ie s A t ag library is a collect ion of cust om t ag handler im plem ent at ion classes. They are oft en packaged in a JAR file and can be st ored under t he WEB-INF/lib direct ory of a WAR file or can be st ored in t heir unpackaged class form under t he WEB-INF/classes direct ory of a WAR file. A t ag library descript or ( TLD) is an XML file used t o describe t he cont ent s of a t ag library. JSP cont ainers use such files t o int erpret JSPs t hat have taglib references t o cust om t ags defined in an associat ed t ag library. The locat ion of TLD file is defined by a elem ent wit hin t he elem ent of a web.xml deploym ent descript or file. A elem ent cont ains a elem ent t hat point s t o t he locat ion of t he t ag library classes. The elem ent also cont ains a elem ent t hat point s t o t he locat ion of t he TLD file t o be associat ed wit h t he t ag library classes. For exam ple:



- 1036 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

/tag/BeeShirtsActions /WEB-INF/tld/BeeShirts.tld



I f no locat ion m apping is defined in t he web.xml file, t he uri at t ribut e of a taglib direct ive m ay be used t o define t he locat ion of t he TLD file. However, a taglib direct ive in a JSP m ore com m only refers t o a library t hat has been defined in a web.xml file as exem plified here:

Act ion code t hat follows from t he taglib direct ive in t he JSP m ay ut ilize cust om act ions defined in t hese libraries. For exam ple, assum e for now t hat a displayOrder act ion nam e associat ed wit h a cust om beeshirts library is t o be invoked from wit hin a JSP. We m ight have som et hing like t his:

So how does t he displayOrder nam e m ap t o a specific cust om t ag handler class, you ask? The answer lies wit hin t he TLD file it self. A name elem ent wit hin a tag elem ent wit hin a TLD file defines t he nam e of a part icular t ag library. Tag inform at ion associat ed wit h t hat nam e is also used wit hin t he TLD file t o describe ot her inform at ion about t he part icular t ag handler. We close here wit h a descript ion of t he TLD DTD in List ing 33.4. Not e t hat we have augm ent ed t his TLD DTD wit h our own elem ent descript ions and have included only t he core cont ent of t he DTD in t he int erest of brevit y. List ing 3 3 .4 Abr idge d TLD File D TD ( ht t p:/ / j a va .sun.com / j 2 e e / dt ds/ w e b- j spt a glibr a r y_ 1 _ 1 .dt d)













Con clu sion s JavaServer Pages ( JSPs) provide a Web program m er–friendly m eans t o Web enable ent erprise applicat ions. JSPs enable direct em bedding of HTML t em plat e dat a int o server- side Web docum ent s and use of a synt ax t hat is m ore fam iliar t o Web- orient ed developers and t o developers who m ay be less fam iliar wit h

- 1038 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ent erprise- class Java program m ing. The use of act ions, t ags, and im plicit obj ect s from direct ly wit hin t he JSP provides t he Web developer wit h a m ore fam iliar script - based program m ing environm ent . However, arbit rarily com plex Java code can also be insert ed int o JSPs as a script ing language and t hus provides added benefit t o t hose developers who know Java and want t o m ix it s m ore powerful synt ax wit h t he sim plicit y of creat ing JSPs. JSP is in t he early st ages of developm ent and current ly has a lim it ed set of st andard act ions and t ags for Web- enabling developers t o use. However, JSP does provide a m eans t o creat e cust om t ag libraries and act ions. As m ore cust om act ions and t ag libraries are defined by t hird- part y vendors and st andardized by t he JSP specificat ion, t he growt h in accept ance and use of JSP am ong Web- enabling developers will also increase. By em ploying JSPs as part of your Web- enabling ent erprise solut ion now, you will gain advant ages in m ore rapid applicat ion developm ent , as well as in providing t he basis for fut ure use of m ore sophist icat ed t hird- part y and st andard JSP ext ensions. As a f i nal not e, gi ven t he f l exi bi l i t y pr ovi ded by JSPs i n enabl i ng t he use of Java f r om di r ect l y wi t hi n JSPs, one may be t empt ed t o cr eat e over l y compl ex Web- enabl i ng code, but we gener al l y r ecommend mai nt ai ni ng t he pur e pr esent at i on- or i ent ed nat ur e of t he Web t i er i n t hi s book. Al t hough we want ed t o hi ghl i ght t he capabi l i t i es of JSPs i n t hi s chapt er , we gener al l y advocat e t he use of JSPs f or gener at i ng Web pr esent at i on l ogi c and t he gl ue l ogi c needed t o t al k wi t h ent er pr i se busi ness l ogi c and dat a component s. The chapt er s t hat f ol l ow descr i be t he ar chi t ect ur e and appr oach f or devel opi ng such ent er pr i se busi ness l ogi c and dat a component s i n t he cont ext of appl i cat i on ser ver f r amewor ks and Ent er pr i se JavaBeans.

- 1039 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Pa r t VI I : En t e r pr ise Applica t ion s En a blin g I N TH I S PART 34 Ent erprise Applicat ion Plat form s 35 Applicat ion Servers and Ent erprise JavaBeans 36 Modeling Com ponent s wit h Ent erprise JavaBeans 37 Advanced Ent erprise JavaBeans Serving 38 Ent erprise Applicat ion I nt egrat ion

- 1040 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Ch a pt e r 3 4 . En t e r pr ise Applica t ion Pla t for m s I N TH I S CH APTER • • • • • • • • •

Ent erprise Plat form s Overview TP Monit or Plat form s OTMs Generic Applicat ion Fram eworks St andard Java- Based Generic Applicat ion Fram ework CORBAcom ponent s Microsoft 's Generic Applicat ion Fram ework Applicat ion- Specific Plat form s Ent erprise Applicat ion Managem ent

Ent er pr i se appl i cat i on pl at f or ms pr ovi de of f - t he- shel f and st andar d r ef er ence ar chi t ect ur es f or bui l di ng ent er pr i se appl i cat i ons. Ent er pr i se pl at f or ms pr ovi de ent er pr i se appl i cat i ons wi t h di st r i but ed accessi bi l i t y, common di st r i but ed ser vi ces, dat a- enabl i ng ser vi ces, Web- enabl i ng ser vi ces, and connect i vi t y t o l egacy appl i cat i ons. Al t hough no ent er pr i se appl i cat i on pl at f or m i s compl et e and of f er s al l t hi ngs t o al l t ypes of appl i cat i ons, such f r amewor ks pr ovi de excel l ent st ar t i ng poi nt s f or mor e r api dl y bui l di ng r obust and di st r i but ed ent er pr i se appl i cat i ons. Thi s chapt er cover s t he basi c evol ut i on of ent er pr i se appl i cat i on pl at f or ms and t he most basi c ar chi t ect ur e of such pl at f or ms f or enabl i ng scal abl e and dependabl e access t o ent er pr i se appl i cat i ons.

I n t his chapt er, you will learn: • • • • • •

The basic cont ext of an ent erprise applicat ion plat form and it s basic role in t he ent erprise. The basic services and archit ect ure of Transact ion Processing ( TP) m onit ors. The basic services and archit ect ure of Obj ect Transact ion Monit ors ( OTMs) . The basic services and archit ect ure of generic ent erprise applicat ion fram eworks som et im es referred t o as applicat ion servers. The basic services and archit ect ure of t he Java- based generic ent erprise applicat ion fram ework known as t he J2EE. The basic services and archit ect ure of t he CORBA- based generic ent erprise applicat ion fram ework known as CORBAcom ponent s.

- 1041 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •



The basic services and archit ect ure of t he Microsoft Windows– based generic ent erprise applicat ion fram ework known as t he Microsoft Dist ribut ed Net work Archit ect ure ( DNA) . The basic role of applicat ion- specific ent erprise fram eworks as provided by Ent erprise Resource Planning ( ERP) syst em s, Product Dat a Managem ent ( PDM) syst em s, CORBA vert ical facilit ies, and Java vert ical facilit ies. The basic role of dist ribut ed ent erprise applicat ion m anagem ent services such as t hose provided by t he Java Managem ent Ext ension ( JMX) .

En t e r pr ise Pla t for m s Ove r vie w As we've already discussed t hroughout t he book, ent erprise applicat ions have part icular needs t hat m ake rapidly building t hem a com plicat ed proposit ion at t im es. We've discussed num erous m et hods for effect ively building ent erprise applicat ions such as obj ect - orient ed and com ponent - based developm ent paradigm s. We've also described m any t echniques and t echnologies for com m unicat ions- enabling, providing com m on st andard COTS services, providing syst em s assurance, and Web- enabling an ent erprise syst em . Ent erprise plat form s can encapsulat e all such developm ent paradigm s, t echniques, t echnologies, and services inside of an int egrat ed fram ework for building ent erprise applicat ions. Such fram eworks oft en follow t he com ponent cont ainer m odel of developm ent advocat ed t hroughout t his book. Figure 34.1 depict s a high- level overview of an ent erprise applicat ion fram ework and it s cont ext . At t he cent er of t he diagram is t he fram ework it self wit h a set of services t hat it provides for use by ent erprise applicat ion com ponent s. I nt erface cont ract s from com ponent t o fram ework and from fram ework t o com ponent oft en exist t o provide well- defined responsibilit y boundaries. From an ent erprise applicat ion client 's perspect ive, t hey are able t o t ap t he applicat ion- specific funct ionalit y of t he ent erprise applicat ion com ponent wit h all t he dist ribut ion, usabilit y, scalabilit y, assurance, and accessibilit y benefit s enabled by t he ent erprise applicat ion fram ework. Such services are oft en provided t ransparent t o t he ent erprise applicat ion com ponent or are encapsulat ed by fram ework API s. Ent erprise applicat ion fram eworks also oft en offer seam less connect ivit y t o ext ernal ent erprise syst em s and resources such as DBMSs. Finally, m any fram eworks provide a m eans t o easily configure and deploy ent erprise applicat ions, as well as som et im es provide an int egrat ed environm ent for developing ent erprise applicat ion com ponent s. Figur e 3 4 .1 . The e nt e r pr ise a pplica t ion fr a m e w or k a r chit e ct ur e .

- 1042 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

TP M on it or Pla t for m s Transact ion Processing ( TP) m onit ors were one of t he first t ypes of ent erprise plat form s hav ing significant com m ercial success whose services could be relied on and ut ilized by ent erprise applicat ions. The ent erprise applicat ions involved here are t ransact ion- processing applicat ions t hat have requirem ent s t o operat e wit hin t he cont ext of a t ransact ion. TP m onit ors are operat ing environm ent s t hat m anage t he t ransact ional behavior of t ransact ion- processing applicat ions. TP m onit ors handle t he creat ion, t erm inat ion, and m anagem ent of t he t ransact ional cont ext s for t he t ransact ion- processing applicat ion. Because effect ive t ransact ion m anagem ent involves t he m anagem ent of dat abase connect ions, net work resources, and operat ing- syst em resources, a TP m onit or can offload a significant am ount of coding effort t hat would ot herwise need t o be developed by applicat ions program m ers. Furt herm ore, because t ransact ionprocessing applicat ions have ent erprise class client request scalabilit y requirem ent s, TP m onit ors are designed t o m anage t he scalabilit y and availabilit y of applicat ions as well. TP m onit ors are m iddle- t ier servers t hat sit bet ween a dist ribut ed t ransact ion applicat ion client and resources ( for exam ple, DBMSs) , as depict ed in Figure 34.2. TP m onit ors provide t he following services t o t ransact ion- processing applicat ions t hat run inside of t heir environm ent : Figur e 3 4 .2 . The t r a nsa ct ion- pr oce ssing m onit or a r chit e ct ur e .

- 1043 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE









N a m ing Se r vice Suppor t : TP m onit ors oft en m anage t he m apping of a client 's request of a nam ed applicat ion service t o t he act ual reference for t hat applicat ion running in t he TP m onit or's dom ain. Conne ct ion H a ndling: Client connect ions are m ult iplexed by a TP m onit or process connect ion handler. The connect ion handler helps m anage t he ut ilizat ion of net work resources and funnels client request s t o t ransact ion processing applicat ions. Re sour ce H a ndling: A TP m onit or can also be configured t o use inform at ion em bedded in a part icular client request t o an applicat ion and det erm ine which resource ( for exam ple, DBMS) should be used t o sat isfy t he request . Furt herm ore, st andard int erfaces t o resources, such as t he X/ Open XA int erface, can provide access t o a het erogeneous variet y of resources. Ava ila bilit y Assur a nce : TP m onit ors can provide for a m ore scalable client request base via load balancing across redundant servers. TP m onit ors can also oft en support failover t o redundant processes in t he event of a failure.

TP m onit ors were popular precursors t o t he applicat ion fram eworks t hat we ut ilize in t his book. Many TP m onit ors adopt t he X/ Open DTP st andard. TP m onit ors t hus funct ion as t ransact ion m anagers wit h addit ional services needed t o build scalable ent erprise- class t ransact ion processing applicat ions. However, t he need t o build ent erprise class applicat ions wit h m ore general needs aside from pure t ransact ion processing alone has given rise t o new t erm inology and t o m ore generic applicat ion fram eworks. Furt herm ore, t he need for st andards t hat support obj ect - and com ponent - based applicat ion m odels also has driven t he evolut ion of TP m onit ors. You'll learn about a few of t he m ore significant evolut ions from TP m onit oring m odels t o m ore generic and st andard applicat ion plat form s t hroughout t he rem ainder of t his chapt er.

OTM s - 1044 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The popularit y of TP m onit or product s has been indicat ive of t he general need for assist ance by organizat ions t hat want t o build ent erprise syst em s m ore rapidly and m ore robust ly t han was previously possible. However, t he m odern het erogeneous ent erprise has also placed a higher prem ium on st andard int eroperabilit y, as well as on use of obj ect - orient ed and com ponent - based syst em developm ent paradigm s. The largely propriet ary and rem ot e procedure- orient ed nat ure of t he older TP m onit ors fell short in t hese regards. This has been t he reason for t he int roduct ion of t he Obj ect Transact ion Monit or ( OTM) int o t he m arket place. OTMs, as depict ed in Figure 34.3, offer various feat ures and services t hat m ake t hem an at t ract ive solut ion for m odern ent erprise syst em s developm ent . For one, OTMs ext end t he TP m onit or concept t o define and int eract wit h obj ect - orient ed int erfaces. OTMs are also const ruct ed according t o t he com ponent cont ainer m odel of developm ent and t herefore provide TP m onit or services t o com ponent - based ent erprise applicat ions. Thus, t ransact ion services, connect ion handling services, nam ing services, resource m anagem ent , and availabilit y services can all be provided t o com ponent s built on t op of OTM fram eworks. Because OTMs follow t he com ponent - cont ainer m odel, t hey also quit e nat urally augm ent t he TP m onit or suit e of general services t o provide a form of com ponent act ivat ion service. Figur e 3 4 .3 . The Obj e ct Tr a nsa ct ion M onit or a r chit e ct ur e .

As anot her general rule, OTMs are also built on t op of a dist ribut ed obj ect com put ing paradigm such as CORBA. I n fact , m ost popular OTM im plem ent at ions t oday, such as I nprise's I TS and I ona's OrbixOTM product s, are built on t op of an ORB and also ut ilize CORBA Obj ect Transact ion Services. The core OTM product s in t he m arket place have also beefed up t heir product offerings wit h addit ional feat ures and services for applicat ions. These services - 1045 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

include asynchronous event m essaging services ( for exam ple, CORBA Event Service) , secure com m unicat ion services ( for exam ple, SSL) , logging services, dist ribut ed obj ect adm inist rat ion services, recovery and fault - t olerance services, and int eroperabilit y int erfaces wit h ot her t ransact ion m onit oring and com m unicat ion paradigm s. Thus, as OTM product s have m at ured, t hey have also grown in t he scope of t heir ent erprise applicat ion applicabilit y.

Ge n e r ic Applica t ion Fr a m e w or k s As m ore services are added t o an OTM fram ework, any pure t ransact ion processing applicat ion focus of t he fram ework becom es blurred. Rat her, t he fram ework begins t o serve as a m ore generic fram ework for building a m ore general class of ent erprise applicat ions. These m ore generic applicat ion fram eworks have consequent ly assum ed a new m arket ing t erm and have now becom e what we refer t o as applicat ion servers. Alt hough we have highlight ed t he evolut ionary pat h of such applicat ion servers from TP m onit ors and OTMs, vendors from ot her m ar ket focuses have also beefed up t heir product offerings wit h applicat ion server– orient ed feat ures. Dat abase vendors, such as Oracle and Sybase, have part icularly been aggressive wit h building auxiliary applicat ion services at op t heir exist ing dat abase m anagem ent service fram eworks. Web server vendors, such as Net scape and Net Dynam ics ( now owned by Sun) , have also evolved t heir Webserving product suit es t o support m ore generic ent erprise applicat ion serving capabilit ies. Of course, as perhaps t he only exam ple of a vendor who has at t em pt ed t o grow an ent erprise applicat ion fram ework out of an operat ing syst em , Microsoft has also defined an ent erprise applicat ion service fram ework t hat is dependent on and int egrat ed wit h t he Microsoft Windows operat ing syst em . Figure 34.4 depict s a generic archit ect ure for such a convergence of ent erprise applicat ion service provisioning. Alt hough not all applicat ion server product s cont ain all t he services depict ed in t his diagram , m ost of t he core services provided by any part icular product have a represent at ive set of services in t he diagram . Wit h such a generic set of ent erprise applicat ion services provided by an ent erprise applicat ion fram ework, ent erprise applicat ion com ponent s can be m ore rapidly built and allow a developer t o focus on t he business logic of an applicat ion rat her t han on com m on applicat ion infrast ruct ure services. Som e ent erprise applicat ion service product s will also provide t ools t o facilit at e t he developm ent , deploym ent , and configurat ion of ent erprise applicat ions wit hin t he ent erprise applicat ion fram ework. Figur e 3 4 .4 . The ge ne r ic a pplica t ion se r ve r fr a m e w or k a r chit e ct ur e .

- 1046 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Many of t he services depict ed in Figure 34.4 have already been described in t his book. However, t he ent erprise applicat ion fram ework provides a m eans t o offer access and ut ilizat ion of such services t o ent erprise applicat ion com ponent s in a fashion t hat sim plifies ent erprise applicat ion developm ent . We have already seen an exam ple of t his wit h t he ent erprise Web- enabling int erfaces described in t he cont ext of J2EE Java Servlet s and JSPs in Part VI , " Ent erprise Web Enabling." This part of t he book begins t o focus on t he general ent erprise applicat ion–enabling aspect s of an ent erprise syst em as provided by an ent erprise applicat ion fram ework. I n fact , we t ypically dist inguish bet ween product s t hat provide Webenabling services and product s t hat provide m ore general ent erprise applicat ion–enabling services because Web- enabling solut ions can require less in t he way of service support t han can m ore generic ent erprise applicat ion–enabling solut ions. Alt hough we indeed have covered m any of t he services in Figure 34.4 t hroughout t his book, a few new t erm s should j um p out at you. For one, obj ect persist ence services wit hin a dat a connect ivit y service suit e of t ools can help m ap applicat ion obj ect s int o relat ional dat abase m odels. Ent erprise applicat ion int egrat ion services m ay also be provided t o enable connect ivit y t o legacy and auxiliary ent erprise applicat ions from ent erprise applicat ion com ponent s built at op t he ent erprise applicat ion fram ework. A set of m anagem ent

- 1047 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

services for m anaging ent erprise applicat ions such as net work and syst em adm inist rat ion, logging, and debugging services m ay also be provided wit hin a fram ework. Furt herm ore, a set of configurat ion and deploym ent services is alm ost always provided t o facilit at e t he configurat ion and deploym ent of ent erprise applicat ion com ponent s t hat operat e inside of t he ent erprise applicat ion fram ework environ m ent . Generic ent erprise applicat ion fram eworks t hus provide a plat form for creat ing ent erprise applicat ions and allow an ent erprise applicat ions developer t o focus on im plem ent at ion of ent erprise business logic and rules.

St a n da r d Ja va - Ba se d Ge n e r ic Applica t ion Fr a m e w or k As m any vendor- specific ent erprise applicat ion fram ework solut ions began t o ent er t he m arket , t he t hreat of m any divergent cam ps of ent erprise applicat ion developm ent solut ion provisioning was height ened. Ent erprise applicat ion com ponent s developed for one fram ework would be able t o operat e only inside t he confines of t hat fram ework vendor's product suit e. Even t hough CORBA t echnologies for vendor int eroperabilit y were being used inside of t he fram ework, t here was no assurance t hat com ponent s which were developed for one vendor product would also work inside of anot her product . Sun Microsyst em s began t o address t his t hreat wit h t he int roduct ion of t he Ent erprise JavaBeans ( EJB) specificat ion in 1998. The EJB specificat ion defined a Java- based st andard int erface cont ract t hat exist s bet ween ent erprise applicat ion com ponent s and ent erprise applicat ion service fram ework product s. Thus, EJBs im plem ent ed for one vendor's ent erprise applicat ion service fram ework product solut ion could run at op anot her vendor's ent erprise applicat ion service fram ework product solut ion. The int erfaces rem ain fixed, but t he underlying service provisioning im plem ent at ions nat urally vary from vendor t o vendor. Sun lat er ext ended t his concept t o t he m ore pervasive J2EE specificat ion as described in Chapt er 5, " Java Ent erprise Syst em Archit ect ure wit h t he J2EE." Figure 34.5 depict s t he st andard server- side ent erprise applicat ion serving archit ect ure defined by t he J2EE specificat ion. Java Servlet s, JSPs, and EJBs can all be developed t o ut ilize t he Java ent erprise API s shown in Figure 34.5, which provide st andard int erfaces t o m any of t he services of an applicat ion server fram ework. Figur e 3 4 .5 . The J2 EE st a nda r d a pplica t ion se r ve r fr a m e w or k a r chit e ct ur e .

- 1048 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

We have already described m any of t he API s shown in Figure 34.5 t hroughout t his book. Alt hough not all t he API s depict ed require t hat vendors provide com plet e im plem ent at ions of t he underlying services, fut ure versions of t he J2EE specificat ion will require such full im plem ent at ion com pliance levels. Furt herm ore, XML API s and API s for im plem ent ing ent erprise applicat ion int egrat ion connect ivit y such as t hat defined in t he J2EE Connect ors st andards will also becom e a st andard requirem ent in fut ure J2EE specificat ions. Because t he J2EE incorporat es t he J2SE int o it s archit ect ure, J2EE vendors can also im plem ent applicat ion service product s t hat are operat ing syst em and hardware plat form - independent . However, som e vendors m ay st ill indeed opt t o t ake advant age of cert ain plat form - specific opt im izat ion feat ures wit hin t heir applicat ion service im plem ent at ions. Wit hin t he confines of t he st andard API s, vendors in fact will prim arily different iat e t heir product offerings based on levels of syst em assurance and perform ance. Vendors are also current ly able t o different iat e t heir product s in t erm s of offering sophist icat ed developm ent and deploym ent t ools and t ools t hat int egrat e J2EE- based applicat ions wit h ot her ent erprise syst em s, resources, and client s. Perhaps m ost significant is t he fact t hat vendors current ly and will m ost likely cont inue t o define valueadded funct ionalit y via API s t hat lie out side of t he st andards. I t is t hus up t o t he applicat ions developer t o provide adapt er logic for such API s t o fully enable m igrat ion bet ween plat form im plem ent at ions. Nevert heless, t he level of plat form int eroperabilit y achievable t hrough even t he current set of J2EE specificat ions has never before been possible. I n addit ion t o st andard applicat ion service API specificat ions, t he J2EE specificat ion has also defined a st andard form at for describing

- 1049 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

how applicat ions should be deployed via XML- based deploym ent descript ors. Addit ionally, st andard m eans for building Java- based applicat ion client s and Java applet s t o connect wit h J2EE server- side applicat ions are also defined. The effort t o provide st andard int erfaces for ent erprise applicat ion com ponent s has t hus com e a long way in a relat ively short am ount of t im e. St andards have already begun t o spill over int o ot her areas of applicat ion developm ent t hat lie out side of pure server- com ponent st andardizat ion. Only t im e will t ell how fully vendors will em brace all of t hese st andards. We suspect t hat as t he scope of J2EE st andardizat ion grows, levels of com pliance will be and should be est ablished t o provide a com prom ise for som e vendors t o allow t heir product s t o shine, as well as t o lower t he barrier of ent ry for newcom ers.

CORBAcom pon e n t s As Sun was defining a pure Java- based st andard for creat ing ent erprise applicat ions via EJBs, t he OMG was also hard at work t o define a CORBA- based ent erprise applicat ion fram ework. The CORBAcom ponent s specificat ion defines language- independent st andards for building ent erprise com ponent s using exist ing and ext ended CORBA t echnology st andards according t o a new m odel of developm ent referred t o as t he CORBAcom ponent s m odel. Because of t he popularit y of EJBs, t he CORBAcom ponent s m odel also defines an explicit m apping t o t he EJB m odel and allows for t he deploym ent of EJB com ponent s t o CORBAcom ponent s- based fram eworks. The CORBAcom ponent s m odel, however, is also t out ed t o be ext endable t o ot her applicat ion server int erface m odels as well and is cert ainly language- independent . Figure 34.6 illust rat es t he archit ect ure of t he CORBAcom ponent s m odel and t he new int erface m odels t hat have em erged as a result . I nt erfaces t o CORBAcom ponent s from a client perspect ive are st ill defined according t o CORBA I DL and can also t ake advant age of t he capabilit y t o ut ilize com ponent act ivat ion service int erfaces, as well as int erface wit h facet s or views of a com ponent 's overall int erface. CORBAcom ponent s can be defined t o connect t o ot her CORBA ent erprise obj ect s via an int erface synt ax for t he com ponent known as recept acles. Com ponent at t ribut es, sources of event s from com ponent s, and event s t hat a com ponent consum es can also be defined for a com ponent and enable t he cont ainer t o m anage configurat ion and event handling services for com ponent s. Addit ionally, a m eans for defining local int erfaces t o t he con t ainer from t he com ponent and int erfaces t o com ponent s from cont ainers is specified. As a final not e on new int erface m odels, t he new Com ponent I m plem ent at ion Definit ion Language ( CI DL) provides a

- 1050 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

m eans t o describe t he st ruct ure and st at e of com ponent im plem ent at ions t hat play a significant role for cont ainers t o provide obj ect persist ence services. Figu r e 3 4 .6 . Th e CORBAcom pon e n t s fr a m e w or k a r ch it e ct u r e .

Configurat ion and deploym ent is also a concern for CORBAcom ponent s, and a st andard m eans for configuring and deploying com ponent s via XML- based descript ors is specified in t he CORBA Com ponent s specificat ion. Such an approach and support ing t ools sim plify t he capabilit y for CORBAcom ponent s t o use CORBAservices t hat are ot herwise very difficult for applicat ion developers t o use out of t he box. Alt hough XML descript ors can be used t o describe how t o configure and deploy a part icular applicat ion, a com plem ent t o CORBA Com ponent s, known as t he CORBA Com ponent Script ing specificat ion, is also being developed t o provide a m ore elaborat e m eans for cust om izing t he business logic and assem bly of com ponent s using easy- t o- use script ing languages. All of t hese feat ures m ake CORBAcom ponent s an int erest ing st andard t o m onit or and wat ch for furt her developm ent and signs of indust ry accept ance. Alt hough CORBAcom ponent s has shown init ial prom ise wit h it s effort t o define com pat ibilit y wit h t he EJB m odel of developm ent , only t im e will t ell how com pat ible t he t echnologies will rem ain in t he fut ure.

M icr osoft 's Ge n e r ic Applica t ion Fr a m e w or k I t should com e as no surprise t o you t hat Microsoft also has defined it s own ent erprise applicat ion fram ework archit ect ure and t hat it is

- 1051 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t ight ly int egrat ed wit h t he Windows operat ing syst em . Alt hough som e people frown on such high levels of dependency and t ight coupling, ot hers argue t hat such a high level of int egrat ion and plat form - dependent solut ions has produced a m ore cohesive ent erprise archit ect ure for m ore im m ediat e use by indust ry. Figure 34.7 depict s t his Dist ribut ed Net work Archit ect ure ( DNA) of Microsoft . Much of t he plat form services depict ed in Figure 34.7 are in fact already em bedded int o t he Windows 2000 server operat ingsyst em plat form . Figu r e 3 4 .7 . M icr osoft W in dow s D ist r ibu t e d N e t w or k Ar ch it e ct u r e .

At t he core of t he Microsoft DNA vision is t he Windows server- side operat ing- syst em environm ent wit h it s t out ed support for building scalable, available, and secure ent erprise applicat ions. Above t hat , COM and DCOM serve as t he fundam ent al m odels for local and dist ribut ed com ponent - based developm ent . COM+ has also been developed by Microsoft t o support a m ore sophist icat ed cont ainercom ponent m odel of developm ent for COM- based applicat ions t hat can also t ake advant age of new configurat ion and deploym ent feat ures. Addit ionally, HTTP- based com m unicat ions and Web server developm ent are m ade possible wit h t he I nt ernet I nform at ion Server ( I I S) and Act ive Server Pages ( ASP) t echnology. A host of addit ional ent erprise services are also provided by t he Microsoft DNA. The Microsoft Act ive Direct ory Service ( ADS) provides advanced nam ing and direct ory services. Messaging services are provided wit h Microsoft Message Queue Server ( MSMQ) t echnology and a new event not ificat ion service provided wit h

- 1052 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

COM+ . Dat abase connect ivit y is provided wit h t he ODBC dat abaseindependent int erface, and a new in- m em ory dat abase service pro vides for enhanced dat abase access perform ance. Finally, t he Microsoft Transact ion Server ( MTS) serves as t he dist ribut ed t ransact ion service for m anaging dist ribut ed t ransact ion applicat ions. Wit h Microsoft 's significant penet rat ion of t he m arket place via it s operat ing- syst em plat form , Microsoft 's DNA is cert ain t o be anot her ent erprise applicat ion fram ework t o keep an eye on for fut ure developm ent s.

Applica t ion - Spe cific Pla t for m s I nst ead of supplying general plat form s and fram eworks for building ent erprise applicat ions, a few com panies have earned t heir revenue by supplying m ore applicat ion- specific fram eworks t o use in ent erprise applicat ion environm ent s. Such fram eworks are designed t o facilit at e one or m ore specific business act ivit ies of an ent erprise and perhaps even wit hin a specific applicat ion dom ain. Som e of t hese applicat ion- specific fram eworks build on exist ing generic ent erprise applicat ion plat form s, alt hough ot hers are built on propriet ary plat form s. The key advant age t o using such plat form s is t hat t hey are oft en m ore rapidly deployed when t he abst ract applicat ion m odel for which t hey've been built closely m at ches t he act ual ent erprise applicat ion t o which it is applied. The key disadvant age t o using such plat form s is t he lack of ext endibilit y and int eroperabilit y of such product s. The OMG has part ially addressed t he issue of applicat ion- specific int eroperabilit y wit hin it s suit e of higher- level CORBA specificat ions. As we discussed in Chapt er 14, " Modeling Com ponent s wit h CORBA," CORBAfacilit ies are specificat ions defined at a higher level t han t he CORBA ORB and CORBAservices specificat ions. CORBAfacilit ies defined at t he vert ical m arket level define st andard int erfaces t o specific t ypes of applicat ions such t hat vendors who im plem ent t hose specificat ions can provide a st andards- based int erface t o an applicat ion- specific fram ework. Sim ilarly, CORBA Dom ain I nt erfaces define st andard int erfaces t o syst em s from cert ain indust rial dom ains, such as m anufact uring. Ent erprise Resource Planning ( ERP) soft ware is nonst andardized applicat ion- specific fram eworks t hat have been very popular wit h ent erprise I T depart m ent s. ERP soft ware plat form s, such as t hose by PeopleSoft , SAP, BAAN, and J.D. Edwards, are used t o m anage som e specific aspect of a business such as part s purchasing, product planning, invent ory m anagem ent , order t racking, supply m anagem ent , cust om er service, finance, qualit y m anagem ent , and hum an resources. ERPs are oft en supplied wit h client soft ware,

- 1053 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

server soft ware, and a dat abase connect ivit y solut ion all t ight ly int egrat ed wit h one anot her. Alt hough ERP soft ware is cat ered t o a specific business act ivit y, cust om izat ion of t hat business act ivit y for a specific ent erprise is oft en possible via som e form of script ing and dat abase configurat ion. Alt hough ERPs have seen som e success in indust ry due t o t he near- t erm benefit s from t heir applicat ion, a lack of ext endibilit y and int eroperabilit y of cert ain ERP product s can lead t o a st agnant and isolat ed ent erprise syst em s solut ion. Product Dat a Managem ent ( PDM) syst em s are anot her applicat ionspecific t ype of ent erprise syst em m ainly cat ering t o t he m anufact uring dom ain and used t o m anage engineering design inform at ion as it evolves from init ial concept t o product ion and m aint enance. Engineering inform at ion m anaged by PDM syst em s includes product part inform at ion, specificat ions, schem at ics, and so on. PDM syst em fram eworks t ypically provide a generic set of business m odeling libraries t hat can be cust om ized for a part icular PDM applicat ion. PDM syst em s include dat a persist ence services, dat a classificat ion and relat ionship m anagem ent services, and soft ware services for m anaging t he flow of dat a and t he t racking of operat ions perform ed on dat a. Even Sun has vent ured int o t he applicat ion- specific fram ework business and st andards process wit h a collect ion of Java- based applicat ion- specific fram eworks. As an exam ple, t he Java Elect ronic Com m erce Fram ework ( JECF) is used for support ing elect ronic com m erce applicat ions. The Java Telephony API ( JTAPI ) fram ework is used t o provide a st andard Java- based m eans for support ing t elephony net works across a range of plat form s. Applicat ion- specific fram eworks are very at t ract ive t o I T depart m ent s and t o ent erprise organizat ions t hat want t o rapidly deploy a specific t ype of business ent erprise applicat ion. However, organizat ions need t o be wary of whet her t he abst ract m odel for which t he applicat ion- specific fram ework has been built can be cust om ized well enough t o sufficient ly m odel t he ent erprise's act ual business process. More oft en t han not , such applicat ion- specific fram eworks require ext ensive consult ing t im e t o assist wit h t he cust om izat ion and help wit h redefining t he organizat ion's business process t o fit int o t he new m odel provided by t he fram ework. Ent erprises also need t o be aware of t he underlying archit ect ure on which t he applicat ion- specific fram ework has been built . Applicat ion- specific fram eworks built at op CORBA and t he J2EE m ay have a great er chance for ext endibilit y and int eroperabilit y t han t hose product s built at op propriet ary underpinnings.

En t e r pr ise Applica t ion M a n a ge m e n t

- 1054 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

This chapt er described m any of t he ent erprise applicat ion fram eworks of t he past , present , and im m inent fut ure. This book in general focuses on t he specific Java- based ent erprise applicat ion t echnologies and fram eworks you can use t o build ent erprise syst em s. Alt hough a det ailed discussion of how t hese applicat ions can be m anaged in a dist ribut ed ent erprise net work at runt im e is beyond t he scope of t his book, it is nonet heless an im port ant considerat ion and som et hing t hat warrant s som e m ent ion here. Ent erprise applicat ion m anagem ent deals wit h t he m anagem ent of ent erprise applicat ions across a het erogeneous dist ribut ed net work for applicat ions t hat range from scalable dist ribut ed applicat ions t o em bedded ent erprise applicat ions. The m anagem ent of such applicat ions is great ly facilit at ed when t hey can be configured, m onit ored, shut down, rest art ed, and updat ed from a rem ot e adm inist rat ion locat ion. Alt hough m any st andard net work m anagem ent fram eworks exist , Sun and a few key indust ry leaders have developed a Java- based st andard via t he Java Com m unit y Process. The Java Managem ent Ext ension ( JMX) specificat ion defines a fram ework, a set of API s, and services for m anaging dist ribut ed net work services. An inst rum ent at ion- level st andard defines a m eans for m aking any Java- based obj ect resource capable of being m anaged by t he JMX fram ework. An agent - level st andard defines a m eans for building dist ribut ed agent cont ainers of inst rum ent ed Java- based obj ect resources. Agent s provide services t o such resources and com m unicat e wit h dist ribut ed net work m anagem ent servers defined at a m anagem ent - level st andard. Finally, JMX also defines API s t o enable use of exist ing net work m anagem ent st andards. Ent erprise applicat ion m anagem ent t hus m ay require som e inst rum ent at ion considerat ions when you're building your ent erprise applicat ions so t hat t hey can be m anaged by a dist ribut ed net work m anagem ent fram ework such as JMX. Som e ent erprise- class J2EE environm ent s indeed provide a m eans t o m anage Java Servlet s, JSPs, and EJBs via a user- friendly GUI - based m anagem ent int erface. However, effect ive use of such services m ay require nonst andard inst rum ent at ion of your J2EE com ponent s. Fut ure int egrat ion of JMX and t he J2EE and t he st andardizat ion of ot her adm inist rat ion services such as debugging and logging wit hin t he J2EE m ay provide furt her levels of port abilit y bet ween applicat ion servers.

Con clu sion s The t erm Ent erprise Applicat ion Plat form m ay m ean different t hings t o different people depending on t heir concept of what an ent erprise applicat ion is. I n general, ent erprise applicat ion plat form s provide a

- 1055 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

set of services t o ent erprise applicat ions oft en in a t ransparent and configurable fashion or via well- defined and higher- level API s. The services provided are infrast ruct ure services t hat reduce t he am ount of hand- coding by developers for creat ing such services and allow a developer t o focus on t he business logic of an ent erprise applicat ion. We exam ined t he evolut ion of generic ent erprise applicat ion fram eworks from TP m onit ors t o OTMs, as well as from Web servers, from dat abase servers, and even from operat ing syst em s ( t hat is, Microsoft ) . We've also discussed t he advant ages and disadvant ages of m any applicat ion- specific fram eworks and explored t he basic feat ures of ent erprise applicat ion m anagem ent service fram eworks. We of course focus on t he Java ent erprise–based approach t o developm ent in t his book, which includes t he st andard J2EE ent erprise applicat ion fram ework. Throughout t he book we've already discussed m any of t he services under such a fram ework and learned about t he Web- enabling aspect s of such a fram ework, and we are now ready t o explore t he final leg of our j ourney. Chapt er 36, " Modeling Com ponent s wit h Ent erprise JavaBeans," and Chapt er 37, " Advanced Ent erprise JavaBeans Serving," describe t he J2EE EJB approach t o ent erprise applicat ion enabling, and Chapt er 38, " Ent erprise Applicat ion I nt egrat ion," describes ent erprise applicat ion int egrat ion solut ions. Chapt er 35, " Applicat ion Servers and Ent erprise JavaBeans," follows t his chapt er and provides a m ore indept h concept ual fram ework t o underst and t he subsequent chapt ers by describing t he basic archit ect ure of applicat ion servers wit h a specific focus on how EJB applies in such cont ext s.

Ch a pt e r 3 5 . Applica t ion Se r ve r s a n d En t e r pr ise Ja va Be a n s I N TH I S CH APTER • • • • • • • •

St andalone Ent erprise Applicat ions Applicat ion Server–Based Ent erprise Applicat ions Applicat ion Server Archit ect ure Provider Roles Applicat ion Server Com ponent s Applicat ion Server Client I nt erfaces Applicat ion Server Client I m plem ent at ions Ent erprise Applicat ion Configurat ion and Deploym ent Applicat ion Service Managem ent

The preceding chapt er provided a high- level view of how services can be provided by ent erprise applicat ion plat form s t o m ake developing ent erprise applicat ions an easier t ask. This chapt er gives m ore specific det ails behind how such services are provided t o ent erprise applicat ion com ponent s and who fulfills what role in - 1056 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t hese applicat ion server archit ect ures. Throughout our discussions, we specifically focus on and int roduce t he not ion of Ent erprise JavaBeans ( EJBs) and discuss how EJB applicat ion servers help applicat ion- enable an ent erprise. We also int roduce t hese concept s in t he cont ext of building a sim ple EJB server and client . I n t his chapt er, you will learn: • • • •

• • • •

The pros and cons of building ent erprise applicat ions in a st andalone runt im e environm ent . The archit ect ure and pros and cons of building ent erprise applicat ions using an applicat ion server and EJBs. The part it ioning of knowledge am ong archit ect ure providers and t he roles t hey assum e when applicat ion servers are used. The basic approach for building ent erprise applicat ion com ponent s t o operat e wit hin an applicat ion server wit h a specific discussion and exam ple of EJB com ponent im plem ent at ions. The basic approach for building ent erprise applicat ion client int erfaces t o ent erprise applicat ion com ponent s wit h a specific discussion of EJB client int erfaces. The basic approach for im plem ent ing ent erprise applicat ion client s including an exam ple of EJB st andalone and J2EE applicat ion client s. The feat ures provided by applicat ion servers for configuring and deploying applicat ions wit h a specific exam ple of XMLbased EJB deploym ent descript ors. The basic underlying approaches by applicat ion servers for providing m anagem ent services t o ent erprise applicat ion com ponent s.

St a n da lon e En t e r pr ise Applica t ion s Throughout Part s I I , I I I , I V, and V of t his book, we described t he t echnologies t hat can be used t o build Java ent erprise applicat ions. Direct use of t hese t echnologies t ypically requires an applicat ion archit ect ure as depict ed in Figure 35.1. Here we see a " st andalone" ent erprise applicat ion ut ilizing t he API s offered by a dat abase connect ivit y solut ion ( for exam ple, JDBC) , a dist ribut ed ent erprise com m unicat ions paradigm ( for exam ple, CORBA, RMI , DCOM) , a set of dist ribut ed com m unicat ions services ( for exam ple, JNDI , JMS, JTS) , and an ent erprise securit y assurance solut ion ( for exam ple, Java Securit y) . Of course, all of our sam ple applicat ions of t hese services built t hus far in t his book have used a Java runt im e environm ent . Figur e 3 5 .1 . St a nda lone e nt e r pr ise a pplica t ions.

- 1057 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The sam ple Java ent erprise applicat ions we have built using t hese services have run in a st andalone fashion wit hout t he use of any cont ainer environm ent or ent erprise applicat ion fram ework. These applicat ions are j ust plain old Java applicat ions wit h which you are probably m ost fam iliar, and t hey operat e using a JDK 1.1 or J2SE t ype of environm ent along wit h separat ely packaged st andard Java ext ension API s and im plem ent at ions. Such st andalone applicat ions were oft en, in fact , t he only opt ion available t o ent erprise program m ers using Java before t he birt h of applicat ion server environm ent s. St andalone ent erprise applicat ions, however, can require a lot of coding effort t o m ake t hem fully funct ional in a m ult iuser, het erogeneous, dist ribut ed, secure, and scalable ent erprise environm ent . Recall from Part I I I , " Dist ribut ed Ent erprise Com m unicat ions Enabling," t hat use of t he com m unicat ionsenabling t echnologies oft en requires t he need t o underst and a special int erface language, requires t hread- safet y design considerat ions, and requires an underst anding of how t o creat e scalable server im plem ent at ions. Also recall from Part I I , " Ent erprise Dat a Enabling," t hat use of JDBC requires careful

- 1058 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

considerat ion of which drivers t o use and how t o creat e connect ion resources. The preceding chapt er int roduced som e of t he concept s for why applicat ion server fram eworks, such as J2EE EJB fram eworks, help alleviat e som e of t hese concerns, but t his chapt er furt her explains how such applicat ion server fram eworks accom plish t his t ask. Furt herm ore, we pursue t his discussion in t he cont ext of EJB applicat ion servers wit h a support ing int roduct ory- level EJB exam ple.

Applica t ion Se r ve r – Ba se d En t e r pr ise Applica t ion s Chapt er 34, " Ent erprise Applicat ion Plat form s," described t he various t ypes of ent erprise applicat ion fram eworks t hat have evolved over t he years and t he t ypes of services t hey provide for ent erprise applicat ion developers. These applicat ion services essent ially provide all t he services shown under t he st andalone ent erprise applicat ion depict ed in Figure 35.1 and help alleviat e som e of t he infrast ruct ure coding t hat would ot herwise be em bedded wit hin t he st andalone ent erprise applicat ion. Figure 35.2 depict s anot her view of an applicat ion server archit ect ure, including t he prim ary elem ent s t hat com pose a funct ioning ent erprise applicat ion serving environm ent . Specific relat ionships t o J2EE and EJB concept s are also indicat ed in t he diagram . These are t he prim ary applicat ion server elem ent s: Figur e 3 5 .2 . Pr im a r y a pplica t ion se r ve r a r chit e ct ur e e le m e nt s.

- 1059 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







Ent e r pr ise Applica t ion Com pone nt : The ent erprise applicat ion com ponent encapsulat es t he business logic and dat a of an ent erprise applicat ion. Ent erprise applicat ion com ponent s are writ t en in a fashion t hat frees t hem from direct ly m anaging lower- level infrast ruct ure services. The Ent erprise JavaBean is t he ent erprise applicat ion com ponent for J2EE- based environm ent s. En t e r pr ise Applica t ion M odu le : The ent erprise applicat ion m odule cont ains one or m ore ent erprise applicat ion com ponent s t o form an individual ent erprise service. Ent erprise applicat ion m odules also cont ain a m odule deploym ent descript or for defining t he configurat ion and deploym ent propert ies of t he m odule. Such ent it ies correspond t o EJB m odules packaged int o JAR files in t he J2EE environm ent along wit h XML- based EJB applicat ion m odule deploym ent descript ors. En t e r pr ise Applica t ion : The ent erprise applicat ion represent s a cohesive collect ion of ent erprise applicat ion m odules, as well as perhaps Web applicat ion m odules. Addit ionally, an ent erprise applicat ion deploym ent descript or cont ains any ent erprise applicat ion assem bly inform at ion. J2EE ent erprise applicat ions are com posed of one or m ore Web and EJB m odules represent ed by WAR and EJB JAR files

- 1060 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





packaged int o an EAR file along wit h an XML- based J2EE applicat ion deploym ent descript or. Ent e r pr ise Applica t ion Cont a ine r : The ent erprise applicat ion cont ainer provides t he runt im e environm ent in which ent erprise applicat ions operat e. They also provide t he int erfaces and glue logic bet ween ent erprise applicat ion com ponent s and t he services provided by an underlying applicat ion server im plem ent at ion. To provide a m eans t o deploy ent erprise applicat ions, cont ainers also im plem ent t he configurat ion and deploym ent t ools. Finally, cont ainers also som et im es offer t ools t o enable t he runt im e deploym ent and m anagem ent of ent erprise applicat ions. Wit h J2EE cont ainers, such as servlet , JSP, and EJB cont ainers, no st andard m eans for syst em m anagem ent is provided. However, st andards do exist for t he set of Java ent erprise API s t hat need t o be provided and for t he m eans by which applicat ions are deployed and configured using XML- based deploym ent descript ors. En t e r pr ise Applica t ion Se r ve r : The ent erprise applicat ion server provides t he syst em s infrast ruct ure funct ionalit y such as ent erprise com m unicat ion services ( for exam ple, ORBs) , t ransact ion m anagem ent services, securit y and services in an int egrat ed applicat ion server environm ent . I n a J2EE environm ent , t he applicat ion server provides t he im plem ent at ion of J2EE- based services and API s. Current ly, t here are no st andard int erfaces defined bet ween a J2EE cont ainer and applicat ion server. I n fact , m any t im es in t he t rade lit erat ure and even in t his book, t he t erm s applicat ion server and cont ainer are used t o m ean bot h t he cont ainer and t he server.

Regardless of cert ain m arket ing claim s, applicat ion server fram eworks do not negat e t he need for underst anding t he t echnologies described earlier in t his book. For one, as you'll see, applicat ion server environm ent s provide a m eans for configuring m any of t he services t hat we have described t hus far and shield t he developer from underst anding all aspect s of t he Java ent erprise API s, but t hey do not com plet ely negat e t he need t o underst and t hese API s. Many applicat ion server fram eworks, such as EJB, st ill at least require t he developer t o have an underst anding of a subset of t he API s. Applicat ion servers oft en m anage how associat ed obj ect s are creat ed, delet ed, and allocat ed but st ill expose t he m ain part s of an API for ent erprise applicat ions t o ut ilize t hose services. Furt herm ore, use of an applicat ion server at every dist ribut ed locat ion wit hin an ent erprise where som e applicat ion service m ust be provided will be com plet ely im pract ical in m any scenarios.

- 1061 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Applicat ion servers oft en have a significant m onet ary cost associat ed wit h t hem and can require a powerful enough underlying plat form t hat ent erprise engineers will alm ost always opt for t he use of st andalone ent erprise applicat ions in m any scenarios. However, applicat ion servers becom e t he hubs and engines of t he ent erprise, whereas st andalone applicat ions becom e m ore suit ed for m oderat ely scalable or perhaps em bedded t ypes of applicat ions dist ribut ed t hroughout an ent erprise. Alt hough one m ight argue on m ore t heoret ical grounds t hat such applicat ions fall int o t he high- end deskt op realm of J2SE applicat ions or even t he m ore em bedded realm of J2ME applicat ions, we cont end based on pract ical experiences t hat such applicat ions are st ill an int egral part of building ent erprise syst em s. Such st andalone ent erprise applicat ions st ill have a need t o use t he various ent erprise t echnologies described in t his book and oft en require dist ribut ed com m unicat ions, JNDI services, t rading services, JMS services, t ransact ion m anagem ent services, securit y services, and dat abase connect ivit y. The t ruly ent erprise- class archit ect and developer will t hus always need t o underst and and be able t o em ploy t he full suit e of Java ent erprise t echnologies for building Java ent erprise applicat ions in bot h st andalone and applicat ion server–based environm ent s such as t he J2EE.

Applica t ion Se r ve r Ar ch it e ct u r e Pr ovide r Role s Given t he basic ent erprise applicat ion server archit ect ure elem ent s defined in t he preceding sect ion, we can bet t er underst and who plays what role in providing such an archit ect ure wit hin an ent erprise syst em . Figure 35.3 depict s t he prim ary role players in providing t he ent erprise applicat ion server archit ect ure elem ent s defined in Figure 35.2. Som e of t he roles indicat ed in t his diagram m ay act ually be provided by soft ware t ools as opposed t o act ual people, or m ay perhaps be a com binat ion of bot h people and t ools. Furt herm ore, one or m ore roles m ay act ually be im plem ent ed by one person/ t ool, or one or m ore people/ t ools m ay in fact im plem ent one or m ore of t he roles. However, defining such roles does provide a m ore nat ural encapsulat ion of what person/ t ool cont ains what engineering knowledge and how t hey provide t hat knowledge t o an ent erprise applicat ion server archit ect ure. These prim ary applicat ion server archit ect ure provider roles are list ed here: Figur e 3 5 .3 . Applica t ion se r ve r e le m e nt pr ovide r s.

- 1062 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







En t e r pr ise Applica t ion Se r ve r Pr ovide r : The ent erprise applicat ion server provider is t he provider of syst em s infrast ruct ure funct ionalit y cont ained wit hin an applicat ion server im plem ent at ion. I n a J2EE environm ent , t he applicat ion server provider provides t he im plem ent at ion of J2EE- based services and API s. Because no st andard int erfaces are defined bet ween a J2EE cont ainer and an applicat ion server, t he roles of cont ainer and applicat ion service provider are oft en t he sam e. En t e r pr ise Applica t ion Con t a in e r Pr ovide r : The ent erprise applicat ion cont ainer provider supplies t he ent erprise applicat ion runt im e environm ent , service int erfaces and glue logic, deploym ent and configurat ion services, and m anagem ent services. As m ent ioned, t he roles of cont ainer and applicat ion service provider are oft en t he sam e. Ent e r pr ise Applica t ion Com pone nt D e ve lope r : The ent erprise applicat ion com ponent developer prim arily represent s a dom ain expert skilled in underst anding t he business logic and dat a needs of an ent erprise applicat ion. Their m ain dut y is t o creat e ent erprise applicat ion com ponent s and com bine t hem int o a cohesive m odule along wit h any deploym ent descript or inform at ion on t he st ruct ure and dependencies of t he com ponent s. Wit h respect t o EJB and t he J2EE, t his person is also referred t o as t he EJB provider or bean provider. EJB providers creat e EJBs and package t hem int o EJB JAR m odules along wit h XML- based EJB applicat ion m odule deploym ent descript ors.

- 1063 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







Ent e r pr ise Applica t ion Asse m ble r : The ent erprise applicat ion assem bler com poses one or m ore ent erprise applicat ion m odules int o a cohesive ent erprise applicat ion. The applicat ion assem bler also defines any applicat ion assem bly deploym ent descript or propert ies, as well as perhaps adding or alt ering t he m odule- level deploym ent descript ors t o provide assem bly configurat ion inform at ion. I n t he J2EE world, t his assem bly process m ay involve collect ing one or m ore Web and EJB m odules int o a cohesive ent erprise applicat ion. Thus, WAR and EJB JAR files are packaged int o an EAR file along wit h an XML- based J2EE applicat ion deploym ent descript or. En t e r pr ise Applica t ion D e ploye r : The ent erprise applicat ion deployer t akes an assem bled ent erprise applicat ion and deploys t his applicat ion t o t he ent erprise applicat ion cont ainer/ server environm ent . Deployers are knowledgeable of t he specific cont ainer/ server and operat ing environm ent t o which an applicat ion will be deployed. An ent erprise applicat ion deployer m ay need t o m odify or add t o exist ing m odule or applicat ion- layer deploym ent descript or propert ies t o accom plish t his t ask. Alt hough st andard deploym ent descript ors exist for t he J2EE, deployers oft en define addit ional vendor- specific deploym ent propert ies t o support configurat ion of cont ainer/ server- specific environm ent propert ies. Furt herm ore, deployers will also generat e t he appropriat e st ubs, skelet ons, and im plem ent at ion classes needed by a cont ainer t o support use of t he ent erprise applicat ion com ponent s. Ent e r pr ise Applica t ion Syst e m Adm inist r a t or : The ent erprise applicat ion syst em adm inist rat or m onit ors and m anages t he runt im e com m unicat ions, dat abase, securit y, and com put ing resources of an ent erprise applicat ion operat ing wit hin t he ent erprise applicat ion cont ainer/ server environm ent . No st andard syst em adm inist rat ion int erfaces or services are defined for J2EE applicat ion environm ent s at t his t im e, but vendors m ay choose t o provide t heir own vendorspecific services.

Applica t ion Se r ve r Com pon e n t s One of t he m ost at t ract ive feat ures of an applicat ion server is t he capabilit y it provides for ent erprise soft ware developers t o be able t o focus on developing t he business logic and dat a for an ent erprise applicat ion. Business logic and dat a are encapsulat ed wit hin t he ent erprise applicat ion com ponent s t hat get plugged int o an applicat ion server environm ent . For t he J2EE, t hese ent erprise applicat ion com ponent s are im plem ent ed as Ent erprise JavaBeans.

- 1064 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Thus, ent erprise developers focus on defining t he applicat ion logic and dat a wit hin t he com ponent , and t he applicat ion server handles how dist ribut ed client s access such com ponent s in a scalable and secure fashion. Applicat ion servers also im plem ent m uch of t he infrast ruct ure logic t hat com ponent s use t o access ot her ent erprise syst em s and ent erprise dat abase resources. Very oft en, applicat ion servers define an int erface cont ract t o which ent erprise applicat ion com ponent s m ust adhere if t hey want t o enable t he applicat ion cont ainer/ server environm ent t o be able t o m anage t he lifecycle of t hat com ponent . Lifecycle m anagem ent of com ponent s includes inst ance creat ion, inst ance dest ruct ion, st at e m anagem ent , and perhaps dat abase connect ivit y m anagem ent . As an exam ple, List ing 35.1 depict s t he basic logic provided for a sim ple credit - m anagem ent bean t hat receives credit inform at ion from a client via it s business- logic–specific public createCreditRecord() m et hod and hands off t he inform at ion t o a server- side credit m anagem ent handler. I n t his sim plified exam ple, we first call t he applicat ion- specific shouldUseChapter36Handler() m et hod t o read a Boolean variable from a com ponent configurat ion propert y nam e java:comp/env/Handler t o det erm ine whet her a special handler ( t o be provided in Chapt er 36, " Modeling Com ponent s wit h Ent erprise JavaBeans" ) should be used. The default value for t his chapt er's exam ple will direct t he com ponent t o call it s applicat ion- specific handleNewCredit() m et hod, which sim ply print s t he credit inform at ion t hat was received. N ot e All t he sam ple code present ed in t his chapt er is cont ained on t he CD in t he examples\src\ejava\ejbch35\creditmgr direct ory. This chapt er's sam ple code also references t he CreditManagerHandler class in t he examples\src\ejava\ejbch36\credit direct ory. However, t his Chapt er 36 class is not invoked at runt im e in t he exam ples present ed here, so it needs t o be in t he CLASSPATH only during com pilat ion.

List ing 3 5 .1 EJB Ent e r pr ise Applica t ion Com pone nt ( CreditManagerSessionEJBean.java)

package ejava.ejbch35.creditmgr; import javax.ejb.SessionBean;

- 1065 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

import javax.ejb.SessionContext; import javax.naming.InitialContext; public class CreditManagerSessionEJBean implements SessionBean { private SessionContext ctx; // Standard interfaces public void setSessionContext(SessionContext aCtx){ ctx = aCtx; } public void ejbCreate(){ logic */ }

/* implement any creation

public void ejbRemove(){ logic */ }

/* implement any removal

public void ejbPassivate(){ persistence */ } public void ejbActivate(){ activation */ }

/* implement any state

/* implement any state

// Application-specific interfaces

/** Hand off info to credit management handler. */ public void createCreditRecord(int customerID, String cardType, String cardName, String cardNumber, java.util.Date expirationDate, String defaultConfirmationNumber) { // If configured to use chapter 36's handler, then use it if(shouldUseChapter36Handler()){ ejava.ejbch36.credit.CreditManagerHandler.handleNewCredit ( customerID, cardType, cardName, cardNumber, expirationDate, defaultConfirmationNumber); } else{ // Otherwise, use default handler from this chapter

- 1066 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

this.handleNewCredit(customerID, cardType, cardName, cardNumber, expirationDate, defaultConfirmationNumber); } } /** Determine if should use chapter 36's handler or default */ private boolean shouldUseChapter36Handler() { // Local variable to store credit management handler flag boolean hasHandler = false; // Get initial context and determine if need use special handler try{ InitialContext ctx = new InitialContext(); Boolean handler = (Boolean) ctx.lookup("java:comp/env/Handler"); hasHandler = handler.booleanValue(); } catch(Exception namingException){ System.out.println("No special handler defined. Using default."); } return hasHandler; } /** Default printout of credit data */ private void handleNewCredit(int customerID, String cardType, String cardName, String cardNumber, java.util.Date expirationDate, String defaultConfirmationNumber) { // Print out all credit information as the default functionality System.out.println("\nCREATE: Credit Information Record"); System.out.println(" Customer ID: " + customerID); System.out.println( " Card Type: " + cardType + " Card Name: " + cardName); System.out.println(" Card Number :" +cardNumber); System.out.println( " Expire Date: " + expirationDate.toString() + " Confirm Number: " + defaultConfirmationNumber);

- 1067 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

} } Alt hough t he applicat ion- specific logic of t his part icular com ponent exam ple is rat her st raight forward, it does also illust rat e t he com ponent cont ract t hat m ust be honored for t his part icular t ype of EJB com ponent . Our EJB com ponent first indicat es it s capabilit y t o operat e inside of an EJB cont ainer by im plem ent ing t he javax.ejb.SessionBean int erface. The setSessionContext() and various ejbXXX() m et hods defined on t he EJB support t his int erface cont ract and enable t he EJB t o operat e inside of a J2EE EJB cont ainer. Thus, by im plem ent ing a few sim ple m et hods and providing it s own business logic, t he EJB com ponent becom es a first - class cit izen of a J2EE ent erprise applicat ion environm ent and can be m anaged by t he EJB cont ainer.

Applica t ion Se r ve r Clie n t I n t e r fa ce s Ent erprise applicat ion com ponent s are writ t en t o provide som e t ype of service t o ent erprise applicat ion client s. Thus, applicat ion server environm ent s m ust define som e way for client s t o t ap t he services of t hese com ponent s. The m echanism by which applicat ion servers offer t hese services is via som e dist ribut ed applicat ion service int erface. These are t he basic client int erface problem s t hat applicat ion servers m ust solve: •



• •

D ist r ibut e d Busine ss- Spe cific I nt e r fa ce s: The applicat ion service int erface needs t o expose only t he business- specific operat ions defined on a com ponent t hat have been defined t o be dist ribut able. D ist r ibut e d Busine ss- Spe cific N a m ing a nd Life Cycle M a n a ge m e n t : The applicat ion service int erface m ust provide a m eans for client s t o look up, creat e, and dest roy com ponent inst ances and references. I nt e r fa ce D e finit ion La ngua ge : The applicat ion service int erface m ust ut ilize som e language for defining int erfaces usable by client s. I nt e r fa ce Com m unica t ions Pr ot ocol: The applicat ion service int erface m ust ut ilize som e underlying com m unicat ions prot ocol usable by client s.

To sat isfy t hese needs, J2EE applicat ion service fram eworks define st andards for creat ing client int erfaces t o EJB com ponent s. These corresponding st andards include t he following:

- 1068 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• •





EJB Re m ot e I nt e r fa ce s: EJB rem ot e int erfaces define t he business- specific operat ions t o be dist ribut ed by an EJB t o it s client s. EJB H om e I n t e r fa ce s a n d JN D I : EJB hom e int erfaces define business- specific and st andard m eans for creat ing and dest roying EJB com ponent s, as well as for looking up cert ain EJB com ponent inst ances. JNDI is also used t o obt ain init ial EJB hom e int erface handles. Ja va a nd I D L: Because EJB depends on RMI , Java- based EJB client int erfaces can be defined. Addit ionally, CORBA I DL EJB client int erfaces can also be defined via a CORBA- t o- EJB m apping. I I OP: The st andard prot ocol over which EJB client s com m unicat e wit h EJB applicat ion server environm ent s is I I OP. RMI / I I OP and a CORBA- t o- EJB m apping bot h support t his capabilit y. JRMP m ay also be used for EJBs t hat com m unicat e via st andard RMI / JRMP. The act ual underlying prot ocol, however, is t ransparent t o bot h t he EJB client and t he com ponent developer.

As an exam ple of an EJB rem ot e int erface t o our CreditManageSessionEJBean defined earlier, List ing 35.2 defines t he one rem ot e int erface operat ion defined for our sim ple EJB. The ext ension of our int erface from javax.ejb.EJBObject signifies t hat t his is a rem ot e EJB int erface. Because it is a rem ot e int erface and RMI int erface language sem ant ics are im plied by EJB, t he m et hod also declares t hat it can t hrow a java.rmi.RemoteException. We should also not e t hat EJBObject ext ends java.rmi.Remote. List ing 3 5 .2 EJB Clie nt Re m ot e I nt e r fa ce ( CreditManagerSession.java)

package ejava.ejbch35.creditmgr; import javax.ejb.EJBObject; import java.rmi.RemoteException; /** Provides a means to take customer credit info into the system. */ public interface CreditManagerSession extends EJBObject { /** Create a credit record for a customer. */ public void createCreditRecord(int customerID, String cardType, String cardName, String cardNumber, java.util.Date expirationDate,

- 1069 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

String defaultConfirmationNumber) throws RemoteException; } The corresponding EJB hom e int erface used t o creat e an inst ance of a rem ot e CreditManagerSession int erface obj ect is defined in List ing 35.3. Here we see a single create() m et hod used t o creat e an inst ance of our EJB from t he client 's perspect ive. The ext ension of t his int erface from javax.ejb.EJBHome, as you'll see in t he next chapt er, also inherit s remove() m et hods t hat are used t o dest roy inst ances of t he EJB obj ect from t he client 's perspect ive. List ing 3 5 .3 EJB Clie nt H om e I nt e r fa ce ( CreditManagerSessionHome.java)

package ejava.ejbch35.creditmgr; import javax.ejb.EJBHome; import javax.ejb.CreateException; import java.rmi.RemoteException; public interface CreditManagerSessionHome extends EJBHome { /** Create an instance of a credit manager. */ CreditManagerSession create() throws CreateException, RemoteException; }

Applica t ion Se r ve r Clie n t I m ple m e n t a t ion s Applicat ion server client s m ay use t he aforem ent ioned int erfaces t o speak wit h ent erprise applicat ion com ponent s operat ing inside of an applicat ion server eit her in a st andalone fashion or perhaps inside of it s own cont ainer environm ent . St andalone client s provide t heir own runt im e environm ent and com m unicat e wit h t he applicat ion server t ier using a dist ribut ed com m unicat ions paradigm such as CORBA or RMI . St andalone applicat ion client s are also responsible for ensuring t hat t hey have com m unicat ions and service libraries inst alled on t heir m achine t hat are com pat ible wit h t he applicat ion server's com m unicat ions and service libraries. Som e applicat ion server environm ent s m ay also provide a cont ainer environm ent in which t heir client s can operat e which helps guarant ee t hat t he client and server have com pat ible com m unicat ions and service libraries, as well as providing a hook for m ore sophist icat ed client - server com m unicat ions.

- 1070 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The sam e t wo general approaches apply t o client s of J2EE EJBs. EJB client s operat ing in a st andalone fashion include regular Java- based client s perhaps operat ing on t op of a J2SE- based plat form wit h t he correct st andard Java ent erprise library ext ensions needed for com m unicat ions wit h t he EJB server. These libraries include JNDI v1.2, EJB v1.1 client libraries, RMI / I I OP v1.0 libraries, and possibly JMS v1.0 and JDBC 2.0 ext ension libraries. St andalone EJB client s m ay also be Web- t ier Java Servlet s or JSPs, as well as perhaps CORBA client s t alking wit h an EJB server t hat support s a pure EJBCORBA m apping. EJB client s can also operat e inside of a st andard J2EE cont ainer environm ent . Such client s m ay be ot her EJBs, Java Servlet s, JSPs, or J2EE applicat ion client s. J2EE applicat ion client s m ay be viewed sim ply as J2SE- based Java applicat ions along wit h support for a m inim al set of cont ainer environm ent requirem ent s. J2EE applicat ion client s essent ially require a J2SE runt im e environm ent com plet e wit h Java I DL and core JDBC 2.0, as well as t he provisioning of t he st andard Java ent erprise JNDI v1.2, EJB v1.1 client , RMI / I I OP v1.0, JMS v1.0, and JDBC 2.0 ext ension libraries. Addit ionally, J2EE applicat ion client s have a m inim alist st andard XML- based deploym ent descript or for configuring t heir operat ing environm ent . As an exam ple of an EJB applicat ion client t hat can run in bot h a st andalone m ode and a J2EE applicat ion client cont ainer environm ent , List ing 35.4 present s a client of our previously defined CreditManagerSessionEJBean. I f t he client is execut ed wit h t he standalone opt ion flag, it will process t he client code assum ing a st andalone environm ent ; ot herwise, it assum es t hat a J2EE applicat ion client environm ent is provided. The runStandaloneClient() call needs t o creat e a JNDI InitialContext as usual wit h init ializat ion propert ies sent in from t he com m and line as syst em environm ent propert ies. When using t he J2EE reference im plem ent at ion, t he org.omg.CORBA.ORBInitialHost syst em propert y needs t o be set t o t he host nam e for t he nam e service, and t he java.naming.factory.initialValue syst em propert y defines t he init ial JNDI cont ext fact ory class. When t he BEA WebLogic server is being used, t he java.naming.provider.url syst em propert y needs t o be set t o t he host nam e for t he nam e service, and t he java.naming.factory.initial syst em propert y defines t he init ial JNDI cont ext fact ory class. Aft er an init ial cont ext is creat ed, t he JNDI nam e of CreditManagerHome is used t o locat e t he EJB's hom e int erface obj ect .

- 1071 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

List ing 3 5 .4 EJB Clie nt I m ple m e nt a t ion ( CreditManagerClient.java)

package ejava.ejbch35.creditmgr; import import import import import import import

javax.naming.Context; javax.naming.InitialContext; javax.rmi.PortableRemoteObject; java.rmi.RemoteException; java.io.BufferedReader; java.io.IOException; java.io.InputStreamReader;

public class CreditManagerClient { /** Main method determines if is standalone or J2EE client */ public static void main(String[] args) throws Exception { // Create new client instance CreditManagerClient myClient = new CreditManagerClient(); // If pass in "-standalone" flag, then run standalone client if( (args.length > 0) && (args[0].equalsIgnoreCase("standalone")) ){ myClient.runStandaloneClient(); } else{ // Else run J2EE application client myClient.runJ2EEClient(); } } /* Method to run client as a standalone client */ public void runStandaloneClient() { try{ // Get initial context for standalone client using // system environment variables for context parameters Context context = new InitialContext(); // Look up server reference using raw JNDI name Object object = context.lookup("CreditManagerHome"); // Now run common client code runCommonClientBody(object); } catch(Exception exception){

- 1072 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

exception.printStackTrace(); } } /* Method to run client as a J2EE application client */ public void runJ2EEClient() { try{ // Get initial context using container provided context Context context = new InitialContext(); // Look up server reference using EJB reference from // the XML deployment descriptor Object object = context.lookup("java:comp/env/ejb/CreditManagerHome"); // Now run common client code runCommonClientBody(object); } catch(Exception exception){ exception.printStackTrace(); } } /** Method to run code that is common for both client types */ private void runCommonClientBody(Object creditManagerHomeRef) throws Exception { System.out.println("Class Type :"+ creditManagerHomeRef.getClass().getName()); // Narrow to credit manager reference CreditManagerSessionHome creditManagerHome = (CreditManagerSessionHome) PortableRemoteObject.narrow(creditManagerHomeRef, ejava.ejbch35.creditmgr.CreditManagerSessionHome.class);

// Create handle to server object now using home factory CreditManagerSession creditManagerSession = creditManagerHome.create(); // Solicit user information from input and send to CreditManager

- 1073 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

processCreditRecords(creditManagerSession); } /** Solicits user information from input and sends to EJB */ private void processCreditRecords(CreditManagerSession mgr) throws Exception { // Declare credit record variables int customerID = 0; String cardType = ""; String cardName = ""; java.util.Date expirationDate = new java.util.Date(); String defaultConfirmationNumber = ""; String cardNumber = ""; // Loop forever to get input and send to manager until // escape from program with Ctrl-C while(true){ // Solicit credit record variable information from user input System.out.println(" Enter a new credit record."); System.out.println("Enter Customer ID (####):" ); customerID = Integer.parseInt(readStringFromInput()); System.out.println("Enter Card Type (CREDIT/DEBIT):"); cardType = readStringFromInput(); System.out.println("Enter Card Name (VISA/MC/AMEX):"); cardName = readStringFromInput(); System.out.println("Enter Card Number (##############) :"); cardNumber = readStringFromInput(); System.out.println("Enter Expire Date (MM/DD/YYYY):"); String expirationDateString = readStringFromInput();

// Create and format date using date formatter java.text.DateFormat dateFormat = java.text.DateFormat.getInstance(); expirationDate = dateFormat.parse(expirationDateString+ " 0:0 PM EST" ); // Now print info on client side System.out.println("\nCLIENT SIDE: Credit Information Record"); System.out.println(" Customer ID: " + customerID);

- 1074 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

System.out.println( " Card Type: " + " Card Name: System.out.println(" Card Number :" System.out.println( " Expire Date: expirationDate.toString() + " Confirm Number: " + defaultConfirmationNumber);

+ cardType " + cardName); +cardNumber); " +

// Now send info to manager mgr.createCreditRecord(customerID, cardType, cardName, cardNumber, expirationDate, defaultConfirmationNumber); } } /* Special helper to read a String from standard user input */ public static String readStringFromInput() { String readValue = null; try{ BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); readValue = reader.readLine(); } catch(IOException ioException){ ioException.printStackTrace(); } return readValue; } } The runJ2EEClient() m et hod inst ant iat es an InitialContext obj ect using what ever syst em propert ies are set for it by t he J2EE applicat ion cont ainer environm ent . A JNDI lookup is t hen perform ed using t he EJB reference of java:comp/env/ejb/CreditManagerHome as configured by t he J2EE applicat ion client 's cont ainer environm ent and deploym ent descript ors. Bot h client t ypes t hen invoke t he runCommonClientBody() m et hod, which uses t he hom e int erface t o creat e a CreditManagerSession rem ot e int erface obj ect inst ance and t hen calls processCreditRecords(). The processCreditRecords() m et hod sim ply solicit s credit record dat a from t he com m and line and invokes t he EJB's rem ot e CreditManagerSession. createCreditRecord() m et hod aft er all dat a is input .

En t e r pr ise Applica t ion Con figu r a t ion a n d D e ploym e n t

- 1075 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Applicat ion server configurat ion and deploym ent involves est ablishing a set of propert ies t hat define how your ent erprise applicat ions should behave and int eract at runt im e. The est ablishm ent of t hese propert ies m ay be perform ed m anually via set t ing of a t ext - based configurat ion file, or it m ay be perform ed via use of som e GUI - based configurat ion and deploym ent t ool. J2EEbased configurat ion, as you have already seen in Chapt er 32, " Java Servlet s," and Chapt er 33, " JavaServer Pages," involves defining st andard elem ent v alues in an XML- based deploym ent descript or file. Many J2EE vendor product s also define GUI - based m echanism s for set t ing t hese deploym ent descript ors. Se r ve r Configur a t ion a n d D e ploym e n t Ex a m ple As an exam ple of a st andard XML- based deploym ent descript or for our CreditManagerSession EJB, List ing 35.5 present s t he st andard ejb-jar.xml file cont aining t his inform at ion. Met a- dat a about t he EJB, t he EJB's t ype inform at ion, and t he EJB's class inform at ion are all defined in t his file. This file is used along wit h com piled versions of t he EJB's classes and int erfaces t o creat e an EJB JAR m odule. The EJB JAR m odule is t hen encapsulat ed wit hin an EAR file, which is deployed t o a J2EE- com pliant EJB cont ainer/ server. N ot e All XML files and sam ple build script s for creat ing t he EJB server applicat ion are provided on t he CD in t he examples\src\ejava\ejbch35\creditmgr direct ory. A buildj2ee.bat script file is used t o build and deploy t he EJB t o t he J2EE reference im plem ent at ion server and also uses a server- specific sun-j2ee-ri.xml file in addit ion t o t he st andard ejb-jar.xml file. You m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb. properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. Refer t o Appendix A, " Soft ware Configurat ion," for m ore det ails. A buildweblogic.bat file is used t o build and deploy t he EJB t o t he BEA WebLogic Server and also uses a serverspecific weblogic-ejb-jar.xml file in addit ion t o t he st andard ejb-jar.xml file. WebLogic also requires t hat you add t he CreditManagerEJB. jar file built for t his exam ple t o t he weblogic.ejb.deploy propert y list in t he [WEBLOGIC_HOME]\weblogic.properties file. Appendix A - 1076 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

describes t he st eps needed t o configure J2EE reference im plem ent at ion and BEA WebLogic servers. The next chapt er also describes how t o build EJB server applicat ions in m uch m ore det ail.

List ing 3 5 .5 EJB Se r ve r Configur a t ion ( ejb-jar.xml)



Credit Manager Server CreditManager

Credit Manager EJB CreditManagerEJB CreditManagerEJB ejava.ejbch35.creditmgr.CreditManagerSessionHome ejava.ejbch35.creditmgr.CreditManagerSession

ejava.ejbch35.creditmgr.CreditManagerSessionEJBean

Stateless Container

Clie nt Configur a t ion a nd D e ploym e n t Ex a m ple As an exam ple of a st andard XML- based deploym ent descript or for our CreditManagerClient J2EE applicat ion client , List ing 35.6 present s t he st andard client.xml file cont aining t his inform at ion. Met a- dat a about t he client and t he EJB reference inform at ion are bot h defined in t his file for t he client . This file is used along wit h a

- 1077 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

com piled version of t he client class t o creat e a client JAR m odule, such as t he packager -applicationClient com m and opt ion for use wit h t he J2EE reference im plem ent at ion. A Main-Class at t ribut e added t o t he client JAR file specifies t he class nam e of t he class ( for exam ple, ejava.ejbch35.CreditManagerClient) t hat provides t he main() m et hod im plem ent at ion t o be execut ed at st art up. Finally, t he client JAR file is t hen referenced from wit hin a special J2EE applicat ion client launcher program provided wit h t he J2EE reference im plem ent at ion t o execut e t he applicat ion client code using a com m and of t his basic form :

[J2EE_HOME]\bin\runclient -client myApClient.jar -name [displayName] [apArguments] N ot e The client.xml file and sam ple build script s for creat ing t he EJB client applicat ion are provided on t he CD in t he examples\src\ejava\ejbch35\creditmgr direct ory. The J2EE reference im plem ent at ion also uses a vendor- specific sun-j2ee-ri-client.xml file in addit ion t o t he st andard client.xml file. The buildj2ee.bat file com piles t he st andalone client and builds t he J2EE applicat ion client for use wit h t he J2EE reference im plem ent at ion. The buildweblogic.bat file com piles t he st andalone client for t he BEA WebLogic server. Addit ionally, t he runJ2EEApClient.bat file execut es t he EJB client as a J2EE applicat ion client using t he J2EE reference im plem ent at ion server. The runStandaloneJ2EEClient.bat file execut es t he EJB client as a st andalone client using t he J2EE reference im plem ent at ion server. The runStandaloneWebLogicClient.bat file execut es t he EJB client as a st andalone client using t he BEA WebLogic server.

List ing 3 5 .6 EJB Clie nt Configur a t ion ( client.xml)



CreditManagerJ2EEClient Credit Manager Client

ejb/CreditManagerHome Session ejava.ejbch35.creditmgr.CreditManagerSessionHome ejava.ejbch35.creditmgr.CreditManagerSession

N ot e When running t he J2EE applicat ion client via our runJ2EEApClient.bat script , you will be prom pt ed for a user nam e and password in a pop- up window. Ent er guest for a user nam e and guest123 for a password. These default aut hent icat ion values are set in t he [J2EE_HOME]config\auth.properties file.

Applica t ion Se r vice M a n a ge m e n t I n addit ion t o t he ease wit h which ent erprise applicat ion com ponent s can be built and wit h which client s can connect t o t hese com ponent s, applicat ion servers also m ake it easy for ent erprise applicat ion com ponent s t o t ap various ent erprise services. Service m echanism s include dat a connect ivit y, com m unicat ions enabling, securit y, availabilit y, ent erprise applicat ion int egrat ion, and m ore. Som e of t hese services are t ransparent ly provided using declarat ive configurat ion param et ers in a deploym ent descript or file. Ot her services have t heir API exposed t o t he ent erprise applicat ion com ponent by t he applicat ion server. Regardless of how t he com ponent accesses t hese services, t he applicat ion server oft en creat es, allocat es, dest roys, and generally m anages t he lifecycle of all underlying service- relat ed obj ect s. J2EE- based servers are no different . For exam ple, securit y and t ransact ion m anagem ent are provided as services t o t he EJB ( as - 1079 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

well as Web com ponent s) in a declarat ive fashion using configurable deploym ent descript or propert ies. Access t o such services can also be provided program m at ically via exposed API s. JDBC is anot her exam ple in which t he J2EE cont ainer/ server will m anage t he creat ion and dest ruct ion of connect ions and t he allocat ion of connect ions t o J2EE com ponent s from a JDBC connect ion pool. J2EE com ponent s can t hen ut ilize t he JDBC connect ion and st at em ent API s as usual. We close t he chapt er here wit h a brief list of t hose services com m only m anaged by applicat ion servers wit h specific focus on EJB- based servers and how such service m anagem ent is provided: •







D ist r ibu t e d Com m u n ica t ion s Se r vice s: Applicat ion servers t ransparent ly provide dist ribut ed com m unicat ion support for server- side com ponent s. For exam ple, EJB cont ainers provide handler code for calls t o server- side skelet ons from client - side st ubs. These handlers t hen delegat e calls t o EJB server com ponent inst ances pulled from an EJB pool of inst ances and are allocat ed t o t heir own t hread, which is also oft en ret rieved from a pool of t hreads. Thus, EJB server com ponent s can be im plem ent ed wit hout worrying about m anaging server- side resources or t hreads. St a t e M a n a ge m e n t : Applicat ion servers oft en handle t he resolut ion of part icular client request s t o t he st at e m anaged for t hat client on t he server side. EJB st at eful session obj ect s provide a m eans t o resolve request s from a part icular client t o part icular server- side obj ect inst ances. The passivat ion and act ivat ion of such st at e are also m anaged by t he EJB cont ainer/ server. D a t a ba se Conne ct ivit y: Applicat ion servers oft en provide handles t o pooled dat abase connect ions via an API and m ay also provide obj ect - relat ional dat a m apping services. EJBs provide direct access t o t he JDBC API from com ponent s wit h t he capabilit y t o configure dat abase resources via deploym ent descript ors. Alt hough t he JDBC API m ay be exposed, EJB servers handle t he creat ion, dest ruct ion, and allocat ion of dat abase connect ions from a pool. EJB cont ainers also provide an obj ect - t o- relat ional m eans for specifying how fields of an obj ect aut om at ically m ap t o colum ns in a dat abase t able or view. Such m appings allow for a m ore obj ect - orient ed int erface t o EJBs, wit h t he cont ainer handling t he act ual relat ional dat abase insert s, delet es, queries, and updat es. Configur a t ion Se r vice s: Applicat ion servers also provide ways t o define propert ies of an applicat ion t hat can be read from configurat ion files. JNDI is used in EJB applicat ion server environm ent s for looking up environm ent configurat ion

- 1080 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







inform at ion specified in deploym ent descript ors. Com ponent specific init ializat ion param et ers can also be specified in deploym ent descript ors for t he aut om at ic init ializat ion of com ponent s during act ivat ion. Se cu r it y: Securit y in applicat ion servers can be specified declarat ively and program m at ically. Declarat ive securit y param et ers in J2EE deploym ent descript ors can define required aut hent icat ion m echanism s and aut horizat ion param et ers. Securit y roles and how t hey m ap t o groups and users can all be specified declarat ively t o im plem ent t he access cont rol decision logic for defining who can access what EJB. Addit ionally, program m at ic securit y int erfaces provide for m ore sophist icat ed and applicat ion- specific access cont rol when t he lim it ed J2EE securit y m odel does not suffice. Ava ila bilit y: Availabilit y of service in applicat ion servers is provided prim arily as a funct ion of proper t hread m anagem ent , resource m anagem ent , t ransact ion m anagem ent , and st at e m anagem ent . J2EE- based servers provide bot h declarat ive and program m at ic m eans for m anaging JTA/ JTS- based t ransact ions from wit hin EJB server com ponent s and from wit hin a few EJB client t ypes. Addit ionally, EJB servers provide t hread, resource, and st at e m anagem ent t o enable t he capabilit y t o build scalable ent erprise applicat ions. Addit ionally , som e applicat ion servers provide clust ering and failover m echanism s. En t e r pr ise Applica t ion I nt e gr a t ion a n d Conne ct ivit y: Many applicat ion server product s realize t he im port ance not only for connect ing t o back- end ent erprise dat a, but also for connect ing t o back- end ent erprise business logic. At t he t im e of t his writ ing, no st andard m eans for connect ing t o back- end ent erprise applicat ions from wit hin J2EE environm ent s was specified. EJBs can ut ilize t echnologies such as CORBA and XML for int egrat ing wit h ent erprise applicat ions, but such t echnologies require addit ional hand- coding. EJB connect ors are an up- and- com ing t echnology t o be em ployed wit hin a fut ure EJB and J2EE specificat ion for aut om at ically connect ing t o back- end ent erprise syst em s.

Con clu sion s I n t his chapt er, you got a glim pse of how applicat ion server archit ect ures part it ion t he problem of building ent erprise applicat ions by part it ioning an ent erprise archit ect ure int o elem ent s whose providers can encapsulat e t he proper level of knowledge needed t o creat e t hose ele m ent s. Ent erprise applicat ion cont ainer and server providers can t hus focus on what t hey know best , which

- 1081 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

is t o provide infrast ruct ure and dom ain- independent services, and ent erprise applicat ion com ponent developers can focus on what t hey know best , which is t he business logic and dat a specific t o a part icular dom ain. We also saw how EJB m akes im plem ent ing such ent erprise applicat ion server com ponent s a sim ple t ask. EJB client s t alk t o EJBs using st andard int erface pat t erns and can also operat e inside of t heir own J2EE applicat ion client cont ainer environm ent . Finally, applicat ion servers and EJB can m ake configuring and deploying com ponent s and providing m anagem ent services for com ponent s a sim ple m at t er of declaring propert ies in an XML file. Alt hough st andalone ent erprise applicat ions will st ill be key com ponent s of an ent erprise syst em solut ion, ent erprise applicat ion servers and EJB can provide your ent erprise wit h a cent ral hub t o rapidly deploy t he lion's share of your ent erprise syst em 's business logic and dat a handling.

Ch a pt e r 3 6 . M ode lin g Com pon e n t s w it h En t e r pr ise Ja va Be a n s I N TH I S CH APTER • • • • • • • • •

EJB Overview EJB Configurat ion and Deploym ent Basics Session Bean Server Com ponent s Session Bean Client I nt erfaces Session Bean Configurat ion and Deploym ent EJB and JDBC Ent it y Bean Server Com ponent s Ent it y Bean Client I nt erfaces Ent it y Bean Configurat ion and Deploym ent

J2EE Ent erprise JavaBeans ( EJBs) provides a m odel for developing server- side ent erprise applicat ion com ponent s t hat can m ake building port able and dist ribut ed ent erprise applicat ions an easier t ask t han is required for building st andalone ent erprise applicat ions. EJB cont ainers/ servers provide dist ribut ed com m unicat ions- enabling services, dat a- enabling services, com m on dist ribut ed com m unicat ion services, and syst em s assurance services for EJB com ponent s wit h m inim al effort on t he part of a developer t o ut ilize t hese services. This chapt er describes t his J2EE EJB com ponent m odel in t erm s of how t o build t hese server- side ent erprise applicat ion com ponent s, how client s t o t hese com ponent s are creat ed, and how t hese com ponent s can be configured and deployed using st andard J2EE XML- based deploym ent descript ors. I n t his chapt er, you will learn:

- 1082 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • • • • •

The basic archit ect ure and concept s involved in building EJBs, including t he concept s of session and ent it y bean t ypes. The com m on approach for configuring and deploying all t ypes of EJBs. The st eps required for building server- side session EJB com ponent s, including st at eless and st at eful session beans. The st eps required for building EJB client s t o session beans. The st eps required t o configure and deploy session beans. The basic relat ion bet ween EJB and JDBC and how JDBC access can be achieved from wit hin EJB com ponent s. The st eps required for building server- side ent it y EJB com ponent s, including bean- m anaged persist ence and cont ainer- m anaged persist ence ent it y beans. The st eps required for building EJB client s t o ent it y beans. The st eps required t o configure and deploy ent it y beans.

EJB Ove r vie w Ent erprise JavaBeans ( EJBs) represent s a powerful com ponent m odel for building dist ribut ed, server- side, and Java- based ent erprise applicat ion com ponent s. The Ent erprise JavaBeans m odel can be st arkly cont rast ed wit h t he regular JavaBeans m odel described in Chapt er 7, " Modeling Com ponent s wit h JavaBeans." The JavaBeans m odel defines a m eans for building Java- based com ponent s for use in cont ainers t hat have a nondist ribut ed nat ure, have m any client - side GUI sem ant ics associat ed wit h t hem , and do not define st andard operat ions t o enable sophist icat ed life- cycle m anagem ent of JavaBean com ponent s. The Ent erprise JavaBeans m odel, on t he ot her hand, defines a m eans for building Java- based com ponent s for use in cont ainers t hat do offer dist ribut ed client connect ivit y, have exclusive server- side sem ant ics associat ed wit h t hem , and define various st andard operat ions t o enable sophist icat ed life cycle m anagem ent of Ent erprise JavaBean com ponent s. EJBs, in fact , have t he following key feat ures: • • • •

Provide a m odel for defining server- side com ponent s. Provide a m odel for defining dist ribut ed client int erfaces t o t he services provided by t hese com ponent s. Provide st andard operat ions and sem ant ics for allowing a cont ainer t o creat e, dest roy, allocat e, persist , and act ivat e com ponent inst ances. Provide a st andard m odel for defining a com ponent t hat m aint ains a conversat ional session wit h a client wit h session m anagem ent handled by t he cont ainer.

- 1083 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



• • • •

Provide a st andard m odel for defining a com ponent t hat encapsulat es a dat a- source ( for exam ple, dat abase) ent ry wit h obj ect - t o- relat ional dat a m apping being handled by t he cont ainer. Provide a st andard for defining configurat ion and deploym ent charact erist ics of a com ponent independent of it s im plem ent at ion. Provide a st andard m odel for declarat ively defining t he securit y at t ribut es of a com ponent . Provide a st andard m odel for declarat ively defining t he t ransact ions at t ribut es of a com ponent . Provide a st andard com ponent int erface cont ract such t hat com ponent s can run in any vendor- com pliant cont ainer/ server t hat im plem ent s t hat st andard int erface cont ract .

The EJB com ponent m odel is t hus a very powerful m odel for building ent erprise applicat ions and is t he focal point of t he J2EE archit ect ure. The J2EE v1.2 requires t hat all EJB v.1.1 API s and im plem ent at ions be included wit hin J2EE EJB cont ainers and t hat EJB v1.1 client API s and im plem ent at ions be included wit h J2EE Web cont ainers and J2EE applicat ion client s. EJB v1.1 represent s a significant advancem ent over EJB v1.0. EJB v1.1 com pliance deprecat es a set of javax.ejb.deployment package abst ract ions provided by EJB v1.0, requires st andard XML- based deploym ent descript ors t o be used, and requires use of EJB ent it y beans, whereas in EJB v1.0 t hey were opt ional. EJB Ar chit e ct ur e Figure 36.1 depict s t he basic archit ect ure of EJB- based client - server ent erprise applicat ions. The client side of an EJB archit ect ure cont ains t he EJB int erfaces needed for invoking business- specific m et hods on an EJB, as well as for m anaging handles t o server- side obj ect s. The server side of an EJB archit ect ure cont ains t he inst ances of t he act ual EJB com ponent im plem ent at ion as well as t he cont ainer code t hat m aps calls t o and from client s and EJBs aft er appropriat e service m anagem ent infrast ruct ure logic has been e XEcut ed. RMI rem ot e int erface sem ant ics are current ly im plied by t hese int erfaces and t hus enable RMI / JRMP, RMI / I I OP, and RMI - t oCORBA I DL m appings t o be used as t he int erface m echanism . Figu r e 3 6 .1 . The EJB a r ch it e ct u r e .

- 1084 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The prim ary elem ent s of t hese applicat ion- specific elem ent s of an EJB archit ect ure as depict ed in t he diagram are list ed here: • •







EJB Clie nt s: EJB client applicat ions ut ilize JNDI t o look up references t o hom e int erfaces and use hom e and rem ot e EJB int erfaces t o ut ilize all EJB- based funct ionalit y. EJB H om e I nt e r fa ce s ( a nd St ubs) : EJB hom e int erfaces provide operat ions for client s t o creat e, rem ove, and find handles t o EJB rem ot e int erface obj ect s. Underlying st ubs m arshal hom e int erface request s and unm arshal hom e int erface responses for t he client . EJB Re m ot e I nt e r fa ce s ( a nd St ubs) : EJB rem ot e int erfaces provide t he business- specific client int erface m et hods defined for a part icular EJB. Underlying st ubs m arshal rem ot e int erface request s and unm arshal rem ot e int erface responses for t he client . EJB I m ple m e nt a t ions: EJB im plem ent at ions are t he act ual EJB applicat ion com ponent s im plem ent ed by developers t o provide any applicat ion- specific business m et hod invocat ion, creat ion, rem oval, finding, act ivat ion, passivat ion, dat abase st orage, and dat abase loading logic. Cont a ine r EJB I m ple m e nt a t ions ( Sk e le t ons a nd D e le ga t e s) : The cont ainer m anages t he dist ribut ed com m unicat ion skelet ons used t o m arshal and unm arshal dat a sent t o and from t he client . Cont ainers also m ay st ore EJB im plem ent at ion inst ances in a pool and use delegat es t o perform any service m anagem ent operat ions relat ed t o a part icular EJB before calls are delegat ed t o t he EJB im plem ent at ion inst ance.

EJB Type s EJBs are dist inguished along t wo m ain funct ional roles. Wit hin each prim ary role, t he EJBs are furt her dist inguished according t o t wo

- 1085 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

subroles. By part it ioning EJBs int o roles, t he program m er can develop an EJB according t o a m ore focused program m ing m odel t han would be t he case if such roles were not dist inguished. Such roles also allow t he EJB cont ainer t o det erm ine how t o best m anage a part icular EJB based on it s program m ing m odel t ype. These are t he t wo m ain dist inct ions of EJBs: •



Se ssion Be a ns: Session beans are EJBs t hat are creat ed t o perform som e act ion on t he ent erprise syst em and possibly ret urn result s t o t he client . Session beans correspond t o t he cont rollers of a syst em exposed for m anipulat ion t o client s. Session beans m ay t hus be t hought of as t he " verbs" of a part icular problem dom ain for which t hey are im plem ent ed t o solve. Session beans are part icularly well- suit ed t o encapsulat e coarse- grained " front line" service ent ry point s int o t he syst em . The creat ion of fine- grained session bean service point s is discouraged due t o pot ent ial resource lim it at ions when such applicat ions m ust scale. Ent it y Be a ns: Ent it y beans are EJBs t hat are creat ed t o encapsulat e som e dat a cont ained by t he ent erprise syst em . Such dat a m ay be creat ed, rem oved, or found by client s. Dat a m ay also be ret rieved and updat ed by client s wit h EJB cont ainers det erm ining how any updat es occur based on t he t ransact ion sem ant ics for a part icular ent it y bean. Ent it y beans also have special prim ary key classes defined for t hem t hat relat e t o t he prim ary keys of an associat ed ent it y st ored in t he dat abase. Ent it y beans correspond t o som e ent erprise syst em ent it y. Ent it y beans m ay t hus be t hought of as t he " nouns" of a part icular problem dom ain for which t hey are im plem ent ed t o solve. Because client s could pot ent ially hold m any ent it y references as t he result of a find operat ion, m any effect ive EJB designs will provide access t o ent it y beans only from session beans and lim it how m any ent it y bean handles are ret urned t o a client . Scalabilit y can becom e severely t a XEd if an excessive num ber of ent it y bean rem ot e obj ect references are doled out t o client s.

Wit hin t he realm of session beans, t wo furt her dist inct ions m ay be m ade: •



St a t e le ss Se ssion Be a ns: St at eless session beans represent t hose session EJBs creat ed wit h no regard for t he m aint enance of any st at e bet ween subsequent calls by a client . St at eless session beans t hus represent pure input and out put engines. St a t e ful Se ssion Be a ns: St at eful session beans represent t hose session EJBs creat ed t o m aint ain st at e for a part icular - 1086 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

client bet ween subsequent calls before som e m axim um am ount of t im e has expired. St at eful session beans t hus represent input and out put engines t hat can ut ilize t he st at e creat ed by a client from a previous invocat ion. Wit hin t he realm of ent it y beans, t wo dist inct ions also apply: •



Be a n - M a n a ge d Pe r sist e n ce ( BM P) Ent it y Be a n s: BMP ent it y beans represent t hose ent it y EJBs in which all code dealing wit h t he insert , delet e, querying, and updat e of dat a t o a relat ional dat a source ( for exam ple, a dat abase) is perform ed by t he ent it y EJB developer. Cont a ine r - M a na ge d Pe r sist e nce ( CM P) Ent it y Be a ns: CMP ent it y beans represent t hose ent it y EJBs in which all code dealing wit h t he insert , delet e, querying, and updat e of dat a t o a relat ional dat a source ( for exam ple, a dat abase) is provided by t he cont ainer EJB im plem ent at ions. Cont ainers prim arily provide such an im plem ent at ion by using deploym ent descript or–based inform at ion t o m ap EJB class fields t o relat ional dat a t able colum ns and t hen subsequent ly generat e t he SQL code using t hese m appings.

EJB Ex ce pt ion Type s Because EJB int erfaces im ply RMI sem ant ics, all dist ribut ed EJB client int erfaces ext end from java.rmi.Remote and t hrow t he java.rmi.RemoteException from each of t heir m et hods. I n addit ion t o RemoteException obj ect s, EJBs can also t hrow ot her EJB- specific except ions t hat relat e t o error and failure scenarios result ing from t he invocat ion of EJB operat ions. Figure 36.2 depict s t his EJB except ion hierarchy. Those except ions shown in Figure 36.2 t hat have been int roduced for EJB- specific except ion behavior are list ed here: Figur e 3 6 .2 . EJB e x ce pt ions.

- 1087 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

• • • • • • •

EJBException: This except ion is t hrown by an EJB when an applicat ion- specific m et hod cannot be com plet ed. NoSuchEntityException: This except ion is t hrown by an EJB when an applicat ion- specific m et hod cannot be com plet ed because a part icular ent it y bean does not exist . CreateException: This except ion is t hrown when a part icular EJB cannot be creat ed. DuplicateKeyException: This except ion is t hrown when a part icular ent it y EJB cannot be creat ed when obj ect s wit h t he sam e key already exist . RemoveException: This except ion is t hrown when a part icular EJB cannot be rem oved. FinderException: This except ion is t hrown when a collect ion of one or m ore ent it y EJBs cannot be found. ObjectNotFoundException: This except ion is t hrown when a singular ent it y EJB obj ect cannot be found.

EJB D e ve lopm e nt Conside r a t ions a nd St e ps The st eps t o developing EJBs m ay be part it ioned along t wo m ain lines: server- side and client - side developm ent . Alt hough server- side developm ent of dist ribut ed com m unicat ions servers, such as CORBA

- 1088 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and RMI , m ay t ake on a som ewhat com plicat ed nat ure at t im es, server- side developm ent of EJBs is sim plified because m uch of t he com m unicat ions, st at e m anagem ent , resource allocat ion, and t hread m anagem ent infrast ruct ure coding is provided by t he cont ainer. These are t he m ain st eps em ployed for server- side EJB developm ent : 1. I m ple m e nt EJB St a nda r d I nt e r fa ce s: Any int erfaces required by t he st andard EJB com ponent m odel t o enable cont ainer- based m anagem ent of t he EJB should be im plem ent ed. 2. I m ple m e nt EJB Busine ss- Spe cific I nt e r fa ce s: Any business- specific int erfaces provided by your EJB and any support ing helper and ut ilit y classes should be im plem ent ed. 3. Cr e a t e Clie nt Re m ot e I nt e r fa ce s: The rem ot e int erface for your EJB t hat defines all business- specific int erfaces t o t he EJB should be creat ed. 4. Cr e a t e Clie nt H om e I nt e r fa ce s: The hom e int erface for your EJB t hat defines t he applicat ion- specific m et hods for creat ing your EJB, as well as applicat ion- specific m et hods for finding your EJB ( if it is an ent it y bean) should be creat ed. 5. Com pile EJB Code : The EJB im plem ent at ion, hom e int erface, and rem ot e int erface should be com piled. 6. Con figu r e M odu le D e ploym e nt D e scr ipt or s: The st andard EJB deploym ent descript or should be configured t o define t he specific st ruct ural charact erist ics and dependencies of your EJB. Any deploym ent descript ors needed by your cont ainer/ server provider should also be configured. 7. Pa ck a ge EJB int o EJB JAR M odule : The st andard EJB deploym ent descript or, any vendor- specific deploym ent descript ors, and one or m ore of your com piled EJB class files should be packaged int o an EJB JAR m odule. 8. Configur e Applica t ion D e ploym e n t D e scr ipt or : A st andard J2EE deploym ent descript or should be configured for a cohesive collect ion of J2EE m odules. 9. Pa ck a ge EJB M odule s int o J2 EE EAR Applica t ion: The st andard J2EE deploym ent descript or and one or m ore EJB JAR files should be packaged int o a J2EE EAR applicat ion. 10. D e ploy t he J2 EE Applica t ion: The J2EE EAR applicat ion should be deployed t o a J2EE- com pliant applicat ion cont ainer/ server environm ent . On t he client side, client s m ust sim ply be designed t o ut ilize t he proper EJB client int erfaces and libraries. EJB client developm ent proceeds along t he following lines:

- 1089 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

1. St a n da r d Clie n t Libr a r y Ve r ifica t ion: The proper EJB client libraries m ust be est ablished, including correct versions of t he JNDI v1.2, EJB v1.1 client , RMI / I I OP v1.0, JMS v1.0, and JDBC 2.0 core ext ension libraries. 2. EJB Clie nt I nt e r fa ce Ge ne r a t ion: The properly com piled int erfaces and st ubs specific t o a part icular EJB m ust also be provided t o an EJB client . 3. Clie nt I m ple m e nt a t ion: The EJB client m ay be im plem ent ed t o ut ilize any int erfaces as appropriat e. 4. Clie nt Code Com pila t ion: The EJB client code should be com piled. 5. Configur e Applica t ion Clie nt D e ploym e nt D e scr ipt or s ( Opt iona l) : Any st andard J2EE applicat ion client deploym ent descript or should be configured t o define t he specific configurat ion propert ies of your EJB client . 6. Pa ck a ge Clie nt int o Applica t ion Clie nt JAR ( Opt iona l) : The st andard J2EE Applicat ion Client deploym ent descript or and com piled EJB client class files should be packaged int o a J2EE applicat ion client JAR. 7. La unch t he J2 EE Applica t ion Clie nt ( Opt iona l) : The J2EE applicat ion client m ay be launched wit hin a special J2EE applicat ion client cont ainer environm ent . BeeShirts.com EJB Applica t ion We have creat ed a back- end ent erprise applicat ion serving fram ework for our BeeShirts.com exam ple using EJBs and placed t he code on t he CD. The next chapt er illust rat es how such EJBs can be int egrat ed wit h t he BeeShirts.com e- com m erce st orefront present ed in Chapt er 32, " Java Servlet s," and Chapt er 33, " JavaServer Pages," but t his chapt er lays t he foundat ion for providing a scalable ent erprise applicat ion–enabled back end for BeeShirts.com using EJBs. Because our sam ple code is m oderat ely large for inclusion in t his book, we also won't insert all t he source code in t he chapt er t ext but will provide core list ings and snippet s from t he code as relevant t opics are int roduced. Figure 36.3 provides you wit h a logical diagram of t he EJBs at play in our exam ple. Figur e 3 6 .3 .

BeeShirts.com EJBs.

- 1090 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

N ot e All t he sam ple code st rewn t hroughout t his chapt er is cont ained on t he CD under t he examples\src\ejava\ejbch36 direct ory. Because t he code on t he CD represent s a m oderat ely large am ount of BeeShirts.com ent erprise applicat ion com ponent code, we do not present all t he code in t his chapt er. Rat her, we will describe t he basic st ruct ure of such code and present snippet s from t hat code germ ane t o chapt er t opics as t hey are discussed. We should also not e t hat t his code depends on som e of t he code from Chapt er 32 st ored on t he CD under t he examples\src\ejava\servletsch32 direct ory and from Chapt er 35 st ored under t he examples\src\ejava\ejbch35 direct ory.

You'll not e from Figure 36.3 t hat we depict only EJB hom e and rem ot e obj ect s in t his diagram , along wit h a collect ion of Serializable ent it y obj ect s from Chapt er 32's code base. The session beans in t he diagram represent t he prim ary client int erfaces t o t he BeeShirts.com EJB applicat ion. All ent it y beans are accessed behind t he wall of session beans. Any dat a from an ent it y bean ret urned t o t he client is ret urned in t he form of an associat ed Serializable ent it y obj ect using classes from Chapt er 32. Such a design helps reduce t he num ber of client references t o dist ribut ed - 1091 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ent it y obj ect s, which can becom e t oo excessive for applicat ions t hat need t o scale. The BeeShirts.com EJBs and t heir helper obj ect s are described here: •











TShirt: A cont ainer- m anaged persist ence ent it y bean t hat encapsulat es T- shirt dat a and provides a m echanism t o read T- shirt im age dat a as byt es from t he server's file syst em . This EJB is defined by a TShirt rem ot e int erface, a TShirtHome hom e int erface, and a TShirtEJBean im plem ent at ion. Chapt er 32's Serializable TShirt obj ect is also used t o encapsulat e T- shirt result dat a sent back t o an EJB client . Item: A cont ainer- m anaged persist ence ent it y bean encapsulat ing it em dat a from t he dat abase. This EJB is defined by an Item rem ot e int erface, ItemHome hom e int erface, and ItemEJBean im plem ent at ion. Chapt er 32's Serializable Item obj ect is also used t o encapsulat e it em result dat a sent back t o an EJB client . Customer: A cont ainer- m anaged persist ence ent it y bean encapsulat ing cust om er and address dat a from t he dat abase. This EJB is defined by a Customer rem ot e int erface, CustomerHome hom e int erface, and CustomerEJBean im plem ent at ion. Chapt er 32's Serializable Customer and Address obj ect s are also used t o encapsulat e cust om er result dat a sent back t o an EJB client . Credit: A bean- m anaged persist ence ent it y bean encapsulat ing credit dat a from t he dat abase. This EJB is defined by a Credit rem ot e int erface, CreditHome hom e int erface, CreditEJBean im plem ent at ion, CreditPrimaryKey prim ary key class, CreditDefinition helper int erface of schem a const ant nam es, and CreditDBAccess helper class t hat perform s t he act ual dat abase access calls. Order: A cont ainer- m anaged persist ence ent it y bean encapsulat ing order dat a from t he dat abase. This EJB is defined by an Order rem ot e int erface, OrderHome hom e int erface, and OrderEJBean im plem ent at ion. Chapt er 32's Serializable Order obj ect is also used t o encapsulat e order result dat a sent back t o an EJB client . BrowseSession: A st at eless session bean wit h a queryShirts() m et hod t o m anage t he query for TShirt inform at ion via t he TShirt ent it y bean and t o m ap t his dat a int o a collect ion of Serializable TShirt obj ect s t o be ret urned t o t he client . This EJB is defined by a BrowseSession rem ot e int erface, BrowseSessionHome hom e int erface, and BrowseSessionEJBean im plem ent at ion.

- 1092 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE







CreditManagerSession: A st at eless session bean ( from Chapt er 35, " Applicat ion Servers and Ent erprise JavaBeans" ) wit h a createCreditRecord() m et hod t o m anage t he insert ion of credit inform at ion int o t he dat abase by first consult ing an ejava.ejbch36. credit.CreditManagerHandler , which in t urn ut ilizes t he Credit ent it y bean t o perform t he act ual dat abase insert . This EJB is defined by a CreditManagerSession rem ot e int erface, a CreditManagerSessionHome hom e int erface, a CreditManagerSessionEJBean im plem ent at ion, and a CreditManagerHandler helper class. ShoppingCartSession: A st at eful session bean encapsulat ing t he inform at ion associat ed wit h a user shopping session at BeeShirts.com. The addAnItemToTheCart() m et hod is used t o add select ed T- shirt it em ident ifiers t o t he user's shoppingcart st at e. The getSelectedItemsInTheCart() m et hod is used t o ret rieve TShirt ent it y beans associat ed wit h t he Tshirt it em ident ifiers, convert t heir dat a int o Serializable TShirt obj ect s, and t hen ret urn t hese Serializable obj ect s in a collect ion. The checkout() m et hod creat es an Order ent it y bean ent ry, convert s t he user's T- shirt it em s st ored in t he session t o Serializable TShirt obj ect s, ret rieves t he associat ed user's Customer ent it y bean, and adds Serializable TShirt and Customer inform at ion t o a Serializable Order obj ect ret urned t o t he client . This EJB is defined by a ShoppingCartSession rem ot e int erface, ShoppingCartSessionHome hom e int erface, and ShoppingCartSessionEJBean im plem ent at ion. OrderManagerSession: A st at eless session bean providing a queryOrders() m et hod t hat first ret rieves any Order ent it y beans associat ed wit h t he cust om er, ret rieves Item ent it y beans associat ed wit h t hose orders, ret rieves TShirt ent it y beans associat ed wit h t hose it em s, and t hen creat es a collect ion of Serializable Order obj ect s cont aining Serializable Order and TShirt dat a t o be ret urned t o t he client . This EJB is defined by an OrderManagerSession rem ot e int erface, OrderManagerSessionHome hom e int erface, and OrderManagerSessionEJBean im plem ent at ion. N ot e Each Chapt er 36 sam ple BeeShirts.com EJB has it s own direct ory under t he examples\src\ejava\ejbch36 direct ory. Wit hin each subdirect ory, an ejb-jar.xml file is used as a st andard EJB deploym ent descript or, a sun-j2ee-ri.xml

- 1093 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

provides J2EE reference im plem ent at ion–specific propert ies, and weblogic-ejb-jar.xml provides BEA WebLogic– specific propert ies. A weblogic-cmp-rdbms.xml file m ay be provided as well for BEA WebLogic–specific cont ainerm anaged persist ence bean propert ies. Wit hin each Chapt er 36 subdirect ory exist s a sam ple buildj2ee.bat script and buildweblogic.bat script for building each bean for t he J2EE reference im plem ent at ion and BEA WebLogic Server, respect ively. A buildj2eeall.bat script and buildweblogicall.bat script are also provided in t he examples\src\ejava\ejbch36 direct ory; t hese call all buildj2eejar.bat or buildweblogic.bat script s in each EJB direct ory and induce t he deploym ent of t he beans t o t he J2EE reference im plem ent at ion and BEA WebLogic Server, respect ively. Each Chapt er 36 bean direct ory also has a sam ple st andalone EJB client nam ed TestClient. A runJ2EEClient.bat and runWebLogicClient.bat file build and execut e t he TestClient for use wit h EJBs deployed t o t he J2EE reference im plem ent at ion and BEA WebLogic Server, respect ively. When using t he buildj2eeall.bat script t o deploy all EJBs t o t he J2EE reference im plem ent at ion server, a special runJ2EEClientWithAll.bat script in each EJB direct ory can be used t o build and execut e t he TestClient t o t est t he associat ed EJB deployed along wit h t he ot her beans on t he server. The only except ion t o all of t hese convent ions for t his chapt er are t he EJB client script file nam es and J2EE applicat ion client XML deploym ent descript or file nam es added t o t he examples\src\ejava\ejbch36\creditmgr direct ory. These file nam es follow t he nam ing convent ion for t he credit m anager EJB as defined in Chapt er 35 but are m odified here t o enable t he CreditManagerSession EJB t o now t alk wit h t he dat abase via t he CreditManagerHandler int roduced in t his chapt er. Not e t hat you m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb.properties file m ust be rem oved in order t o properly run t he J2EE

- 1094 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

reference im plem ent at ion server. Refer t o Appendix A for m ore det ails.

EJB Con figu r a t ion a n d D e ploym e n t Ba sics As explained in Chapt er 5, " Java Ent erprise Syst em Archit ect ure wit h t he J2EE," and illust rat ed in Chapt ers 32 and 33, J2EE ent erprise applicat ions are com posed of one or m ore individual J2EE m odules. J2EE m odules have deploym ent descript ors specific t o t he m odule t ype, and J2EE ent erprise applicat ions also have t heir own deploym ent descript or form at . We explored t he J2EE ent erprise applicat ion deploym ent descript or form at in Chapt er 31, " XML," and t he J2EE Web applicat ion m odule deploym ent descript or in Chapt er 32. I n t his chapt er we int roduce t he EJB applicat ion m odule deploym ent descript or. I n t his sect ion we int roduce t he basics for underst anding EJB deploym ent descript ors, deployed archives, and deploym ent procedures. EJB D e ploym e n t D e scr ipt or Top- Le ve l Ele m e nt s J2EE EJB applicat ion m odule deploym ent descript ors are defined in XML files nam ed ejb-jar.xml. Because configuring EJB deploym ent descript ors is m ore involved t han configuring Web com ponent deploym ent descript ors, we t ake a slight ly different t ack in describing t he form at and use of t he EJB deploym ent descript or. We in fact describe elem ent s of t he EJB deploym ent descript or as t hey becom e relevant t o t he t opic at hand t hroughout t his chapt er and t he next chapt er. We t hus carve out pieces of t he XML EJB m odule DTD and describe t hem as t he elem ent s t hey define becom e relevant . The t op- level elem ent s of an EJB deploym ent descript or, shown in List ing 36.1, are cont ainers used t o define EJB applicat ion m et a- dat a, EJB st ruct ure, assem bly inform at ion, and t he archive filenam e for any EJB client files. List in g 3 6 .1 EJB D TD Top- Le ve l Ele m e n t s



- 1095 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





















- 1130 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



As an exam ple, t he session- relat ed elem ent s of our st at eful BrowseSession bean's ejb-jar. xml file are shown in List ing 36.10. You'll not e t hat in addit ion t o st andard m et a- dat a and st ruct ural inform at ion about t he EJB, it has defined elem ent s for all t he EJBs it accesses as a client t o t hose beans. I t also defines a elem ent t o a dat a- source connect ion, as we describe in t he next sect ion. List in g 3 6 .1 0 Ex a m ple of EJB Se ssion Be a n D e ploym e n t D e scr ipt or I nfor m a t ion



no description CartJar

ShoppingCartSessionEJB ShoppingCartSessionEJB ejava.ejbch36.shoppingcart.ShoppingCartSessionHome< /home> ejava.ejbch36.shoppingcart.ShoppingCartSession

- 1131 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ejava.ejbch36.shoppingcart.ShoppingCartSessionEJBean

Stateful Container

ejb/tshirt Entity ejava.ejbch36.tshirt.TShirtHome ejava.ejbch36.tshirt.TShirt

ejb/item Entity ejava.ejbch36.item.ItemHome ejava.ejbch36.item.Item

ejb/order Entity ejava.ejbch36.order.OrderHome ejava.ejbch36.order.Order

ejb/customer Entity ejava.ejbch36.customer.CustomerHome ejava.ejbch36.customer.Customer

jdbc/demoPool javax.sql.DataSource Container



Vendor- specific deploym ent descript or files t o configure and deploy session beans for bot h t he J2EE reference im plem ent at ion and t he BEA WebLogic im plem ent at ion are also needed and are provided wit h t he exam ples on t he CD. Developers will m ost oft en use GUI based deploym ent t ools provided by vendors t o develop such files, but we want ed t o explicit ly provide you wit h a sense of what t hey cont ain wit h our sam ple code on t he CD. N ot e

- 1132 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

No inform at ion on t he J2EE reference im plem ent at ion's sunj2ee-ri.xml file was readily available at t he t im e of t his book's writ ing. The GUI - based deploym ent t ool for t he J2EE reference im plem ent at ion is t he sam e deploytool ut ilit y we have been using in com m and- line m ode. The GUI version of t he deploytool is sim ply invoked from t he com m and line using [J2EE_HOME]\bin\deploytool. For m ore inform at ion on t he weblogic-ejb-jar.xml file form at , see t he WebLogic EJB reference m anual at ht t p: / / www.weblogic.com / docs50/ classdocs/ API _ej b/ EJB_re ference.ht m l. BEA WebLogic also provides a GUI - based weblogic.ejb. ui.deployer.DeployerTool ( execut ed as a Java applicat ion) described at ht t p: / / www.weblogic.com / docs50/ classdocs/ API _ej b/ EJB_d eploy.ht m l.

EJB a n d JD BC The need t o connect t o dat abases from wit hin EJB is clearly one of t he m ore significant feat ures of t he EJB specificat ion. All J2EE- based com ponent s m ay need t o t alk wit h a dat abase, and J2EE provides support for t his need via JDBC. Vendors such as Oracle and a fut ure J2EE specificat ion will allow t he use of SQLJ t o provide dat abase connect ivit y. However, our prim ary approach advocat ed in t his book and assum ed here is t he use of JDBC. J2EE- com pliant environm ent s provide access t o t he JDBC API and a convenient m eans for configuring JDBC resources via t he XML- based deploym ent descript or and for connect ing t o JDBC resources via JNDI . N ot e Many of t he concept s discussed here wit h respect t o dat abase connect ivit y from EJB assum e a basic underst anding of such t opics as SQL, JDBC, relat ional/ obj ect t ranslat ions, and em bedded SQL via SQLJ. We encourage you t o review our coverage of t hese t opics, prim arily in Chapt ers 8 t hrough 10, at t his t im e if you are a lit t le rust y on t he associat ed concept s.

JDBC driver configurat ion and dat a- source ident ificat ion are accom plished via t he XML- based deploym ent descript or for J2EE m odules. The elem ent can be defined for individual J2EE EJB session and ent it y beans, J2EE servlet s and JSPs,

- 1133 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

and J2EE applicat ion client s. Zero or m ore JDBC resources m ay be configured per EJB, servlet , JSP, or applicat ion client wit hin t he J2EE deploym ent descript or. As an exam ple of JDBC resource configurat ion for ent it y EJBs as ext ract ed from t he ejb-xml.jar file for our BeeShirts.com Credit ent it y bean, we have t his:







jdbc/ejavaPool javax.sql.DataSource Container





Ut ilizing such a dat a source from wit hin an ent it y bean is t hen a sim ple m at t er of looking up t he nam ed dat a source from wit hin t he EJB and obt aining a handle t o a javax.sql. DataSource obj ect . The DataSource obj ect , as described in Chapt er 10, " Advanced JDBC," can t hen be used t o obt ain a java.sql.Connection obj ect . The underlying cont ainer is responsible for det erm ining how t his Connection obj ect is t o be allocat ed t o your bean and will m ost likely m aint ain a pool of connect ions. From t hat point on, t he bean can use t he Connection obj ect t o creat e JDBC st at em ent s and obt ain result s as usual. For exam ple, t he ejava.ejbch36.EJBHelper class provides a m et hod t o ret urn a Connection obj ect using t he configured DataSource reference as shown here:

public static String BEESHIRTS_DATA_SOURCE = "java:comp/env/jdbc/ejavaPool"; /** Get database Connnection for BeeShirts.com data source */

- 1134 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public static Connection getDBConnection() throws SQLException, NamingException { // Create initial context InitialContext initialContext = new InitialContext(); // Look up DataSource object DataSource dataSource = (DataSource) initialContext.lookup(EJBHelper.BEESHIRTS_DATA_SOURCE); // Request Connection object from pool managed by DataSource Connection connection = dataSource.getConnection(); // Close context initialContext.close(); // Return Connection object return connection; }

Because bean- m anaged ent it y beans m ust m anage t heir own connect ivit y t o t he dat abase, a m eans for connect ing t o a dat abase via Java m ust be em ployed. Alt hough we use JDBC resources only from wit hin a bean- m anaged persist ence ent it y bean EJB in t his chapt er, JDBC resources can also be explicit ly accessed from session beans, Java Servlet s, and JSPs. Session bean access t o JDBC resources configured inside of zero or m ore elem ent s is locat ed wit hin t he sub- elem ent of t he elem ent in an EJB deploym ent descript or and wit hin t he elem ent in t he Web deploym ent descript or. However, we t end t o st ray away from direct access t o ent erprise dat a st ored in dat abases from Java Servlet s and JSPs as a general design philosophy t o avoid securit y problem s and t o m aint ain t he Web server t ier as a scalable present at ion layer. I nside of t he applicat ion- serving t ier, we also avoid any direct dat abase access from wit hin session EJBs because t hat is t he prim ary role filled by ent it y EJBs. However, t he opt ion is st ill available, and t he m eans by which such resources are configured and accessed is t he sam e.

En t it y Be a n Se r ve r Com pon e n t s An ent it y bean is a class t hat represent s a logical classificat ion of dat a in a dat abase. An ent it y bean class cont ains fields t hat m ap t o elem ent s of a dat abase schem a definit ion. Ent it y bean fields m ost easily m ap direct ly t o colum ns of a dat abase t able, and t he ent it y bean it self m ay be likened t o an act ual dat abase t able. Relat ions am ong ent it y beans m ay t hus be analogous t o relat ions am ong t ables. Views and t able j oins m ay also be likened t o an ent it y bean

- 1135 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

wit h t he elem ent s of t hose dat a sources m apping t o t he fields of an ent it y bean class. N ot e Many of t he concept s discussed here wit h respect t o ent it y beans assum e a basic underst anding of SQL, JDBC, and relat ion/ obj ect t ranslat ions. We encourage you t o review our coverage of t hese t opics in Chapt ers 8 t hrough 10 at t his t im e.

Ent it y bean inst ances t hat cont ain populat ed values wit hin t heir fields correspond t o an act ual ent ry wit hin a dat a source. Thus, an ent it y bean inst ance m ay correspond t o a part icular row wit hin a t able or perhaps be relat ed t o t he single result of a t able j oin query. For exam ple, our Customer BeeShirts.com ent it y bean class t hat encapsulat es a cust om er direct ly relat es t o a CUSTOMER t able in our sam ple dat abase. Fields of t he Customer ent it y bean direct ly relat e t o colum ns of t he CUSTOMER dat abase. An inst ance of a Customer ent it y bean cont ains t he dat a for a part icular cust om er whose field values direct ly correspond t o t he colum n values in t he CUSTOMER t able for a row associat ed wit h t hat cust om er. Ent it y bean com ponent s can be developed in one of t wo ways by developers. Bean- m anaged persist ence ( BMP) ent it y beans cont ain code ( t ypically JDBC code) creat ed by developers t o m anage all dat abase insert s, delet ions, querying, and updat es associat ed wit h a part icular ent it y bean. Cont ainer- m anaged persist ence ( CMP) ent it y beans are defined in such a way by developers t hat t he EJB cont ainers can aut om at ically provide all t he code required for m anaging all dat abase insert s, delet ions, querying, and updat es associat ed wit h t he ent it y bean. Developers opt t o use BMP ent it y beans m ost oft en when t heir cont ainer does not support CMP ent it y beans, when a part icular dat a source is t oo com plex t o enable effect ive CMP ent it y bean m apping, or when t he developer desires m ore cont rol over how t he dat a should be m anaged. Ot herwise, CMP ent it y beans can significant ly reduce t he am ount of handcoding required t o dat a- enable ent erprise applicat ions. This sect ion describes t he concept s involved in ent it y beans in general, as well as describing t he specific approaches t o building bot h BMP and CMP ent it y bean com ponent s. Ent it y Be a n Pooling

- 1136 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

A part icular server- side inst ance from a cont ainer's point of view m ay not always correspond t o a part icular dat a- source ent ry ( for exam ple, a row in a t able) at all t im es. Ent it y bean cont ainer im plem ent at ions oft en pool a lim it ed num ber of server- side ent it y bean inst ances belonging t o t he sam e t ype in order t o preserve resources and provide a scalable EJB client base. When t he num ber of ent it y bean inst ances exceeds som e m axim um value, t he cont ainer m ay begin t o passivat e and persist t he st at e of som e inst ances in order t o reuse t hose inst ances t o populat e t hem wit h t he st at e of ot her dat a- source ent ries. Thus, from a cont ainer's perspect ive, server- side ent it y bean inst ances m ay be viewed as host s for dat a from part icular dat a- source ent ries. These server- side inst ances can be dist inguished from t he dist ribut ed client - side inst ance st ubs for such ent it y beans, which are of course under t he m anagem ent of t he client applicat ion. How a cont ainer m anages server- side ent it y bean inst ance pooling is very m uch t ransparent t o t he ent it y bean developer. An ent it y bean developer designs a bean under t he assum pt ion t hat any act ions on t he bean relat e t o t he st at e it cont ains and t herefore relat e t o a part icular dat a- source ent ry t o which t hat st at e m aps. When properly designed and when adhering t o t he specified ent it y bean com ponent int erface cont ract , t he cont ainer will m anage when and how inst ances of ent it y beans act ually get allocat ed t o part icular dat a- source ent ries t hroughout t he operat ion of t he syst em . Pr im a r y Ke ys Alt hough EJB cont ainers m ay pool ent it y beans and reuse serverside ent it y bean inst ances t o encapsulat e different dat a- source ent ries at different t im es, t here m ust be a way t o uniquely ident ify a part icular dat a- source ent ry. I f t he client - side handle were t o sim ply refer t o t he server- side ent it y bean inst ance direct ly, t here would be no guarant ee t hat t he inst ance is act ually relat ed t o t he correct dat a- source ent ry given t he EJB cont ainer inst ance pooling and reuse policies. Ent it y beans t hus ut ilize t he concept of a prim ary key. A prim ary key uniquely ident ifies t he dat a- source ent ry t hat is associat ed wit h a part icular ent it y bean inst ance. That is, alt hough a part icular ent it y bean inst ance can be allocat ed wit h different dat a- source ent ry values at different t im es by a cont ainer, t he prim ary key provides a way t o ident ify t he part icular dat a- source ent ry t hat should underlie an ent it y bean inst ance. When EJB client s creat e or look up part icular dat a- source ent ries using ent it y bean int erfaces, t he cont ainer t hen associat es a prim ary key wit h t he EJB ent it y bean handle( s) ret urned t o t he client . Thus, for exam ple, if a - 1137 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

cust om er ent it y bean has a cust om er first and last nam e t hat represent s a prim ary key for a cust om er ent it y bean, t hose t wo values should uniquely ident ify a row in a cust om er t able for t he cont ainer. From t he program m er's point of view, however, it m aps t o a unique ent it y bean inst ance. Be a n - M a n a ge d Pe r sist e n ce Ent it y Be a n s This sect ion describes how t o build ent it y beans using BMP ent it y bean com ponent sem ant ics. Many of t he concept s and t echniques used here also apply t o CMP ent it y beans. However, BMP ent it y beans, as you will see, require a significant am ount of hand- coding. I n a cert ain sense, t here is not m uch difference bet ween using BMP ent it y beans and creat ing hom egrown JDBC- based com ponent s. The difference lies in how t he im plem ent at ion of such JDBC logic is encapsulat ed. Specifically, st andard m et hods on a BMP ent it y bean im ply which JDBC st at em ent t y pes should be creat ed and processed. Addit ionally, BMP ent it y beans can inherit t he declarat ive t ransact ional and securit y aspect s of EJBs, as we describe in t he next chapt er. BM P En t it y Be a n Logica l Com pon e n t Ar ch it e ct u r e

Figure 36.8 int roduces t he basic elem ent s needed t o const ruct a BMP ent it y bean. Public, nonfinal, and nonabst ract ent it y bean im plem ent at ions, such as MyBeanManagedEntityEJBean, m ust im plem ent t he javax.ejb.EntityBean int erface, which in t urn ext ends t he EnterpriseBean m arker int erface. The EntityBean int erface defines a set of operat ions t hat m ust be im plem ent ed by an ent it y bean t o support t he life cycle m anagem ent cont ract required by t he EJB cont ainer. Bean- m anaged ent it y EJBs can also im plem ent public, nonfinal, and nonst at ic business- specific m et hods, such as t he someMethod() and anotherMethod() sam ple m et hods shown in t he diagram . A bean- m anaged ent it y bean will also t ypically define som e st at e in t he form of field variables t hat cont ain cached versions of t he dat a- source ent ry values. As a final not e, ent it y bean im plem ent at ions m ust also have a public param et erless const ruct or and should not im plem ent t he finalize() m et hod. Figur e 3 6 .8 . Be a n- m a na ge d pe r sist e nce e nt it y EJBs.

- 1138 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

BM P En t it y Be a n Con t e x t Se t t in g a nd Unse t t in g

The javax.ejb.EntityContext int erface is im plem ent ed by a cont ainer obj ect t hat provides a handle t o an ent it y bean's runt im e cont ext . EntityContext ext ends t he m ore generic EJBContext and defines a m et hod for obt aining a handle t o a rem ot e EJB int erface handle, as well as for obt aining a handle t o t he bean inst ance's prim ary key. The setEntityContext() m et hod on an EntityBean im plem ent at ion is invoked by a cont ainer im m ediat ely aft er an inst ance of t he bean is const ruct ed. The bean should save t his value in a field variable for lat er use. An ent it y bean will also find calling t he getPrimaryKey() m et hod useful in det erm ining t he prim ary key t hat t his part icular ent it y bean inst ance ident ifies. An unsetEntityContext() m et hod is also required t o be im plem ent ed by ent it y bean im plem ent at ions. A cont ainer will call t his m et hod when t he ent it y bean inst ance is t o be decoupled from t he cont ainer cont ext . That is, t he cont ainer is about t o t erm inat e t his bean inst ance from t he bean pool, and t he bean should t ake care t o close any resources t hat were opened during a call t o setEntityContext().

- 1139 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

BM P En t it y Be a n Fin ding

Whenever a client desires t o locat e part icular exist ing ent it y bean inst ances t hat correspond t o part icular exist ing dat a- source ent ries, t he cont ainer will invoke one of t he ejbFind XXX (…) m et hods on t he ent it y bean. The ejbFind XXX (…) m et hods fill a role sim ilar t o a SQL SELECT st at em ent in dat abase funct ionalit y. BMP im plem ent at ions generally need t o t hrow a FinderException during processing of t hese m et hods t o indicat e t hat an applicat ion error has occurred. The ejbFindByPrimaryKey() m et hod m ust be defined on all ent it y beans. An im plem ent at ion of t his m et hod m ust t ake t he prim ary key of an ent it y bean as an input param et er, verify t hat t he associat ed dat a- source ent ry ident ified by t he prim ary key exist s in t he dat abase, and t hen ret urn t he prim ary key t o t he cont ainer. I f t he request ed dat a- source ent ry does not exist , a BMP im plem ent at ion m ay t hrow t he ObjectNotFoundException subclass of FinderException t o indicat e t hat t he request ed obj ect could not be found. Most likely, a BMP ent it y bean will form ulat e a SELECT st at em ent query t o issue t o t he dat abase via JDBC t o im plem ent t his m et hod t o verify t hat t he dat a wit h t he prim ary key exist s in t he dat abase. Zero or m ore addit ional ejbFind XXX (…) m et hods m ay also be defined t hat t ake zero or m ore business- specific input param et ers and m ust at t em pt t o locat e any associat ed dat a- source ent ries in t he dat abase. For each locat ed ent ry, a collect ion of prim ary keys associat ed wit h each ent ry should be ret urned from t he ejbFind XXX () m et hod. The collect ion m ay be ret urned in one of t wo form s. For JDK 1.1 and above com pat ibilit y, a java.util.Enumeration of prim ary key obj ect s can be ret urned. For Java 2.0 and above com pat ibilit y, a java.util. Collection of prim ary key obj ect s can be ret urned. A BMP im plem ent at ion of t hese m et hods can ut ilize t he JDBC API t o issue a SQL SELECT st at em ent as a funct ion of t he input param et ers and bean t ype and t hen use t he result s t o creat e a collect ion of associat ed prim ary key obj ect s. I f t he underlying query result s in no prim ary keys t o ret urn, an em pt y collect ion should be ret urned. BM P En t it y Be a n Cr e a t ion a nd Re m ova l

Zero or m ore ejbCreate(…) m et hods wit h zero or m ore param et ers m ay be defined on an ent it y bean. The opt ional ejbCreate() m et hods perform a funct ion akin t o dat abase INSERT st at em ent s in t hat t hey creat e an ent ry in t he dat a source associat ed wit h t his ent it y bean t ype and populat e it wit h any dat a est ablished wit hin

- 1140 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t he ent it y bean. Dat a can be est ablished wit hin t he bean via t he init ializat ion of any field variables during const ruct ion, as well as by using any values passed as param et ers t o an ejbCreate(…) m et hod. A cont ainer calls ejbCreate(…) on an ent it y bean due t o a client induced creat ion event on t he bean. The ejbCreate(…) m et hods m ust ret urn an applicat ion- specific Java Object t hat represent s t he prim ary key for t his newly creat ed ent it y bean. The prim ary key class m ust be serializable, m ust provide a default param et erless const ruct or, m ust im plem ent t he equals() m et hod, and m ust im plem ent t he hashCode() m et hod as is illust rat ed wit h t he MyBMPPrimaryKey class in Figure 36.8. BMP ent it y beans m ust im plem ent t he necessary dat abase connect ivit y logic t o perform t he dat abase SQL INSERT wit hin t he ejbCreate(…) m et hods. The prim ary m echanism t o accom plish t his t ask is via t he JDBC API , which can be configured via XML- based dat a- source configurat ion param et ers. BMP ent it y beans m ay t hrow t he CreateException t o indicat e t hat an ent it y bean cannot be creat ed for som e reason. BMP ent it y beans m ay also t hrow t he DuplicateKeyException subclass of CreateException if an ent it y bean could not be creat ed due t o t he exist ence of a dat a- source ent ry wit h t he sam e prim ary key. For each ejbCreate(…) m et hod defined, t he ent it y bean m ust also define an ejbPostCreate(…) m et hod using t he sam e input param et ers. The ejbPostCreate() m et hod is called by t he cont ainer aft er it calls ejbCreate() and aft er t he cont ainer associat es an inst ance of t he ent it y bean wit h t he client reference. Thus, any init ial act ions your ent it y bean desires t o perform using a fully associat ed ent it y bean inst ance can be done when t his m et hod is called. The ejbPostCreate(…) m et hods m ay also t hrow a CreateException t o indicat e an applicat ion error t hat has occurred during t his m et hod call. When a client induces a rem ove act ion on an ent it y bean, t he cont ainer calls t he ejbRemove() m et hod. The ejbRemove() m et hod for an ent it y bean m eans t hat t he associat ed dat a- source ent ry should be delet ed from t he dat abase akin t o a SQL DELETE st at em ent in funct ionalit y. A BMP ent it y bean will need t o obt ain a handle t o t he prim ary key using it s ent it y cont ext 's getPrimaryKey() m et hod and t hen use t he JDBC API t o form ulat e a SQL DELETE st at em ent for t his part icular dat a- source ent ry. A BMP im plem ent at ion of ejbRemove() m ay also t hrow t he RemoveException t o indicat e a general except ion t hat has occurred during t he at t em pt ed delet ion operat ion.

- 1141 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

BM P En t it y Be a n Pa ssiva t ion a nd Act iva t ion

The ejbPassivate() and ejbActivate() m et hods m ust be im plem ent ed for ent it y beans as t hey were for st at eful session beans. The ejbPassivate() m et hod is called by t he cont ainer before it ret urns t he ent it y bean t o t he pool of bean inst ances. This occurs m ost likely when t he bean has been inact ive for som e period and perhaps will be select ed for passivat ion according t o a least recent ly used algorit hm . The ent it y bean should clean up any resources and st at es t hat cannot be serialized t o a passive persist ent st ore. None of t he bean's field values t hat relat e t o dat asource ent ry elem ent s should be persist ed wit hin t his m et hod, t hough. The ejbActivate() m et hod generally perform s t he inverse operat ions of ejbPassivate(). A cont ainer calls ejbActivate() when it needs t o bring t he st at e of a previously passivat ed bean int o act ive m em ory due t o som e client dem and on t hat bean. The BMP im plem ent at ion m ust reest ablish any resources t hat were closed during t he call t o ejbPassivate() and populat e any dat a t hat was serialized during t he call t o ejbPassivate(). This dat a does not include t he bean's field values t hat relat e t o dat a- source ent ry elem ent s, however. BM P Ent it y Be a n St or ing a nd Loa ding

Whereas ejbPassivate() and ejbActivate() relat e t o closing and opening any non–dat a- source relat ed resources, t he ejbLoad() and ejbStore() m et hods explicit ly deal wit h t he dat a- source inform at ion. A cont ainer will call ejbStore() and ejbLoad() on an ent it y bean whenever it want s t he bean t o synchronize t he st at e of t he dat abase field dat a in t he bean wit h t he st at e of t he associat ed dat a act ually st ored in t he dat a source. A cont ainer calls ejbStore() on a bean when it want s t he bean inst ance t o updat e t he associat ed dat a- source ent ry wit h t he st at e of t he dat a in t he bean inst ance. This operat ion t hus sat isfies a funct ion sim ilar t o t hat of a SQL UPDATE in t he dat abase. However, t he det erm inat ion of when t his updat e is perform ed is a funct ion of t he cont ainer's t ransact ion m anagem ent decision- m aking logic. A cont ainer will also call ejbStore() right before it m akes a call t o ejbPassivate(). BMP im plem ent at ions will t ypically use JDBC t o im plem ent SQL UPDATE st at em ent s when ejbStore() is invoked. A cont ainer calls ejbLoad() on a bean when it want s t he bean inst ance t o be updat ed wit h t he lat est st at e values of t he associat ed dat a- source ent ry in t he dat abase. This operat ion t hus updat es t he

- 1142 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

in m em ory bean inst ance represent at ion of t he dat abase ent ry. A BMP im plem ent at ion will t ypically call getPrimaryKey() on t he associat ed ent it y cont ext t o first det erm ine t he specific dat a- source ent ry associat ed wit h t his bean inst ance. The BMP im plem ent at ion will t hen query t he dat a- source ent ry's elem ent values using JDBC and updat e t he st at e of t he bean. A cont ainer det erm ines when ejbLoad() is called as a funct ion of t ransact ion m anagem ent and also calls ejbLoad() before calls t o ejbRemove() and aft er calls t o ejbActivate(). BM P En t it y Be a n Com pon e n t I nt e r fa ce Ru le s Su m m a r y

The life cycle of an ent it y bean is significant ly m ore com plicat ed t han t hat of a session bean and relies heavily on t ransact ion m anagem ent . Such com plexit y is part of t he reason why ent it y bean support was not required by EJB v1.0–com pliant im plem ent at ions t o lower t he barrier for ent ry int o t he EJB m arket place. Alt hough we defer discussion of t ransact ion m anagem ent wit h EJBs unt il t he next chapt er, we present t he basic st eps t hat a cont ainer for an ent it y bean m ust follow ( wit hout t ransact ion m anagem ent ) here: 1. I n st a n t ia t e EJB: The cont ainer calls Class.newInstance() wit h t he nam e of your EJB t o creat e a new inst ance of t he ent it y bean when t he cont ainer decides it needs an ent it y bean inst ance for it s pool of ent it y beans. 2. Se t Cont e x t : The cont ainer calls setEntityContext() on t he EJB wit h a cont ainer- creat ed EntityContext obj ect . 3. Add EJB t o Pool: The cont ainer m ay now add t he ent it y bean t o a pool of server- side ent it y bean inst ances of t his sam e t ype. Not e t hat t hese server- side inst ances are not yet relat ed t o a client - side reference. 4. Call ejbFind XXX (…): The cont ainer m ay use any available bean inst ance from t he pool t o im plem ent t he funct ionalit y of a select m et hod as induced by a client . The ret urned prim ary key or keys are used t o creat e delegat es of ent it y beans but are not inst ances of server- side ent it y beans t hem selves. Client - side references are associat ed wit h t hese delegat es. 5. Call ejbCreate(…) and ejbPostCreate(…): The cont ainer m ay use a bean inst ance's im plem ent at ion of t hese m et hods t o insert a new dat abase ent ry int o t he dat abase as induced by a client . 6. Call ejbActivate(): The cont ainer calls ejbActivate() whenever a client dem ands t hat a part icular dat abase ent ry be accessed in m em ory and requires t he bean t o allocat e any needed resources.

- 1143 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

7. Call ejbLoad(): A cont ainer calls ejbLoad() when it want s t o synchronize t he st at e of dat abase- relat ed fields wit h t he field values of an ent it y bean inst ance. 8. D e le ga t e Clie nt Ca lls: The cont ainer delegat es EJB client calls t o t he ent it y bean whose reference is associat ed wit h t he client . Calls from a client pass from t he client st ub t o t he cont ainer's skelet on represent at ion of t he EJB and t hen t o t he server- side bean inst ance im plem ent at ion it self. 9. Call ejbStore(): The cont ainer calls ejbStore() when it want s t o synchronize t he st at e of t he ent it y bean's dat abaserelat ed fields wit h t he dat abase by m eans of a dat abase updat e operat ion. 10. Call ejbPassivate(): The cont ainer calls ejbPassivate() whenever it want s t o release t he resources consum ed by an ent it y bean so t hat t he bean inst ance can be used t o encapsulat e anot her dat abase ent ry. 11. Call ejbRemove(): A cont ainer calls ejbRemove() when a client induces t he delet ion of an associat ed dat abase ent ry. This does not rem ove t he bean inst ance from t he pool, t hough. 12. Unse t Cont e x t : A cont ainer calls unsetEntityContext() when a bean inst ance is about t o be rem oved from t he pool as det erm ined by t he cont ainer's m anagem ent policy. BMP ent it y beans t hus require a significant am ount of hand- coding t o accom plish t he desired effect s of dat abase connect ivit y. BMP ent it y beans provide im plem ent at ions for t he m anagem ent of bean inst ance st at e and resources, as well as for t he m anagem ent of dat abase dat a and connect ivit y. BMP ent it y beans m anage bean inst ance st at e and resources t hrough business- specific m et hods, as well as t hrough t he im plem ent at ion of st andard m et hods t hat effect resource closing ( via ejbPassivate) , resource opening ( via ejbActivate) , and st at e m anagem ent ( via setEntityContext and unsetEntityContext) . BMP ent it y beans m anage dat abase dat a and connect ivit y t hrough t he im plem ent at ion of st andard m et hods t hat effect dat abase ent ry querying ( via ejbFind XXX ) , insert ion ( via ejbCreate) , post - insert ion ( via ejbPostCreate) , delet ion ( via ejbRemove) , synchronizat ion updat es ( via ejbStore) , and inm em ory synchronizat ion ( via ejbLoad) . BMP ent it y beans provide t his funct ionalit y t hrough t he use of a Java ent erprise t echnology such as JDBC. BMP ent it y beans t hus m ay be viewed as providing st andard int erfaces for JDBC- based code t hat want t o operat e inside of t he J2EE EJB cont ainer environm ent . BM P En t it y Be a n Ex a m ple

- 1144 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The only exam ple of a BMP ent it y bean in our BeeShirts.com applicat ion is t he Credit EJB. Only t he core port ions of t his CreditEJBean BMP ent it y bean are shown in List ing 36.11, wit h except ion handling excluded from t he list ing for sim plicit y in present at ion. The dat abase ent it y creat ion, rem oval, finding, and updat ing logic of t he CreditEJBean largely delegat es t o a helper class in t his bean's direct ory on t he CD called CreditDBAccess. Each ejb XXX () call t hat m ust perform som e dat abase- relat ed act ivit y first obt ains a connect ion from our EJBHelper class, set s t his connect ion ont o CreditDBAccess, and t hen inst ruct s CreditDBAccess t o perform an insert , delet e, select , or updat e operat ion, depending on t he ejb XXX () m et hod invoked on CreditEJBean. All credit inform at ion associat ed wit h t he credit ent it y is st ored in t he CreditEJBean obj ect 's creditInformation Hashtable wit h key nam es t aken from t he CreditDefinition int erface's const ant nam es. Addit ionally, a CreditPrimaryKey class, shown in List ing 36.12, defines t he prim ary key for t his bean, which includes a cust om er I D, an order I D, and a card num ber. List in g 3 6 .1 1 BM P En t it y Be a n Ex a m ple ( CreditEJBean.java)

package ejava.ejbch36.credit; …// imports excluded here… public class CreditEJBean implements EntityBean { private EntityContext entityContext; private Hashtable creditInformation; // Stores credit information /** Create CREDIT table entry based on initial creditInformation */ public CreditPrimaryKey ejbCreate(Hashtable creditInformation) throws CreateException, RemoteException { CreditDBAccess dbAccess = new CreditDBAccess(); Connection connection = null; … // Get connection, set on CreditDBAccess, and perform INSERT connection = EJBHelper.getDBConnection(); dbAccess.setConnection(connection); dbAccess.insert(creditInformation); … // Create primary key and return CreditPrimaryKey primaryKey = new CreditPrimaryKey();

- 1145 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

primaryKey.customerID = ((Integer)creditInformation. get(CreditDefinition.CUSTOMER_ID)).intValue(); primaryKey.orderID = ((Integer)creditInformation.get(CreditDefinition.ORDER_ID )).intValue(); primaryKey.cardNumber = ((String)creditInformation.get(CreditDefinition.CARD_NUMB ER)); return primaryKey; } /** No need for post creation semantics */ public void ejbPostCreate(Hashtable creditInformation) throws CreateException, RemoteException { } /** No need for activation semantics */ public void ejbActivate(){ } /** No need for passivation semantics */ public void ejbPassivate(){ } /** Verify that primary key for Credit exists */ public CreditPrimaryKey ejbFindByPrimaryKey( CreditPrimaryKey primaryKey) throws FinderException, RemoteException { if ((primaryKey == null)){ throw new FinderException ("PrimaryKey should not be null"); }

// Throws exception if cannot load based on this key loadCreditData(primaryKey); return primaryKey; } /** Look up all primary keys for Credit objects with customer ID */ public Collection ejbFindByCustomerID(int customerID) throws FinderException, RemoteException { Connection connection = null; CreditDBAccess dbAccess = new CreditDBAccess(); … // Get/set connection, SELECT credit info from database connection = EJBHelper.getDBConnection();

- 1146 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

dbAccess.setConnection(connection); Vector results = dbAccess.select(customerID); // Return Matching Primary Keys return results; … }

/** Look up primary keys for Credit with customer ID and order ID */ public Collection ejbFindByCustomerIDAndOrderID( int customerID, int orderID) throws FinderException, RemoteException { Connection connection = null; CreditDBAccess dbAccess = new CreditDBAccess(); … // Get/Set connection, SELECT credit information connection = EJBHelper.getDBConnection(); dbAccess.setConnection(connection); Vector results = dbAccess.select(customerID, orderID); // Return Matching Primary Keys return results; … } /** Remove data source entry associated with this bean from DBMS */ public void ejbRemove() { Connection connection = null; CreditDBAccess dbAccess = new CreditDBAccess(); … // Get/Set Connection, DELETE this credit info from DB connection = EJBHelper.getDBConnection(); dbAccess.setConnection(connection); dbAccess.delete((CreditPrimaryKey)entityContext.getPrimar yKey()); … } /** Store EJB data to database */ public void ejbStore() { Connection connection = null; CreditDBAccess dbAccess = new CreditDBAccess(); … // Get/Set connection, UPDATE credit info in DB

- 1147 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

connection = EJBHelper.getDBConnection(); dbAccess.setConnection(connection); dbAccess.update(creditInformation); … } /** Load EJB data from database */ public void ejbLoad() throws RemoteException { // Get primary key CreditPrimaryKey primaryKey = (CreditPrimaryKey) entityContext.getPrimaryKey(); … // Now load the actual data based on primary key loadCreditData(primaryKey); … } /** Private method to load credit data into bean using primary key */ private void loadCreditData(CreditPrimaryKey primaryKey) throws RemoteException { Connection connection = null; CreditDBAccess dbAccess = new CreditDBAccess(); … // Get Connection, set connection, SELECT credit info connection = EJBHelper.getDBConnection(); dbAccess.setConnection(connection); creditInformation = dbAccess.select(primaryKey.customerID, primaryKey.orderID, primaryKey.cardNumber); … } /** Sets the EntityContext for the EJBean. */ public void setEntityContext(EntityContext entityContext) { this.entityContext = entityContext; } /** Unsets the EntityContext for the EJBean. */ public void unsetEntityContext() { entityContext = null; } /** Set credit information onto bean */

- 1148 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public void setCreditInformation(Hashtable creditInformation) { this.creditInformation = creditInformation; } /** Retrieve credit info from bean. */ public Hashtable getCreditInformation() { return creditInformation; } } List in g 3 6 .1 2 Pr im a r y Ke y Ex a m ple ( CreditPrimaryKey.java)

package ejava.ejbch36.credit; import java.io.Serializable; public class CreditPrimaryKey implements Serializable { public int customerID; public int orderID; public String cardNumber; public int hashCode() {

return super.hashCode(); }

public boolean equals(Object object) { if(object instanceof CreditPrimaryKey){ CreditPrimaryKey otherKey = (CreditPrimaryKey)object; if( otherKey.orderID == orderID && otherKey.customerID == customerID && otherKey.cardNumber.equals(cardNumber)){ return true; } else{ return false; } }else { return false; } } } We do not list t he CreditDBAccess code here because it is rat her long and cont ains only JDBC code not germ ane t o t he t opic of EJB. We encourage you t o t ake a look at t he CreditDBAccess class on t he CD, however. CreditDBAccess wraps all t he act ual JDBC calls t o

- 1149 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

be perform ed by t he CreditEJBean. Using t he schem a nam es from t he CreditDefinition int erface and dat a passed int o it s part icular m et hods, it m akes t he appropriat e JDBC calls j oining bot h t he CREDIT_TABLE and t he CARD_TYPE dat abase ent it ies. The CreditDBAccess m et hod has select(), insert(), delete(), and update() m et hods t o perform t he relat ional dat abase operat ions relat ed t o t hese m et hod nam es. A Hashtable used by t hese m et hods whose elem ent s are nam ed according t o t he CreditDefinition class ident ify bot h CreditEJBean dat a elem ent s and dat abase colum ns. The Hashtable is used during CreditDBAccess calls t o insert() and update() and is ret urned from select() calls. The CreditDBAccess.delete() call is invoked only wit h t he CreditPrimaryKey. Cont a ine r - M a na ge d Pe r sist e nce Ent it y Be a ns As you have j ust seen, creat ing BMP ent it y beans can be quit e a chore. Alt hough t he am ount of hand- coding m ay be equivalent t o what you would expect for im plem ent ing JDBC- based connect ivit y t o access your ent erprise dat a, EJB also provides a m eans t o sim plify t he am ount of effort required t o creat e ent it y beans via it s cont ainer- m anaged persist ence ( CMP) ent it y bean st andards. Wit h CMP, t he cont ainer im plem ent s all t he JDBC dat abase access logic for you. The cont ainer t hus handles t he obj ect - t o- relat ional m apping necessary t o t ransfer dat a from your EJB ent it y obj ect t o relat ional dat abase ent it ies and from t he relat ional dat abase ent it ies t o your EJB ent it y obj ect . We describe how t o creat e CMP ent it y bean com ponent s in t his sect ion. We prim arily focus on t hose aspect s of developing CMPs t hat differ from t he developm ent of BMPs and avoid reit erat ing discussion of t he com m on concept s shared by CMPs and BMPs. CM P En t it y Be a n Logica l Com pon e n t Ar ch it e ct u r e

Figure 36.9 depict s t he basic archit ect ure behind creat ing CMP ent it y bean com ponent s. A public, nonfinal, and nonabst ract CMP ent it y bean im plem ent at ion, such as MyContainerManagedEntityEJBean, m ust im plem ent t he EntityBean int erface. CMP ent it y EJBs can also im plem ent public, nonfinal, and nonst at ic business- specific m et hods, such as t he someMethod() and anotherMethod() sam ple m et hods shown in t he diagram . Also not e t hat ent it y bean im plem ent at ions m ust also have a public param et erless const ruct or and should not im plem ent t he finalize() m et hod. Figur e 3 6 .9 . Cont a ine r - m a na ge d pe r sist e nce EJBs.

- 1150 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CM P Ent it y Be a n a nd Pr im a r y Ke y Cont a ine r - M a na ge d Fie lds

CMP ent it y beans m ust t ake addit ional care t o define any fields t hat will be m anaged by t he cont ainer as public and ensure t hat t he associat ed t ypes are serializable. These cont ainer- m anaged fields m ap direct ly t o elem ent s of t he dat a- source ent ry associat ed wit h t his CMP ent it y bean. For exam ple, a cont ainer- m anaged field m ay m ap direct ly t o a colum n in a part icular dat abase t able. The cont ainer figures out which of t he fields will be m anaged via a specificat ion in t he EJB deploym ent descript or for t his bean. A prim ary key for a CMP ent it y bean m ay sim ply be specified as a single field of t he CMP ent it y bean. CMP ent it y bean prim ary keys m ay also be uniquely defined using a separat e class cont aining one or m ore public field nam es t hat m ap t o field nam es of t he CMP ent it y bean. Alt ernat ely, t he bean provider m ay specify no prim ary key for a CMP ent it y bean. I n such a case, t he vendor's deploym ent t ools should be used t o select a prim ary key t o be associat ed wit h t hat bean at deploym ent t im e. CM P En t it y Be a n Con t e x t Se t t in g a nd Unse t t in g

Set t ing and unset t ing t he EntityContext associat ed wit h a CMP ent it y bean is accom plished using t he setEntityContext() and unsetEntityContext() m et hods, respect ively. Cont ainers call t hese m et hods on CMP ent it y beans for t he sam e reasons and during t he sam e phases of a bean's life cycle as t hey do for BMP ent it y beans. However, CMP ent it y beans m ay not be as int erest ed

- 1151 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

in using t he EntityContext for it s capabilit y t o ret urn t he bean's prim ary key because t he cont ainer handles t he resolut ion of dat asource ent ry t o bean inst ance. CMPs m ay, however, decide t o m anage t he allocat ion and closing of resources t ied t o a bean inst ance from wit hin t he ent it y cont ext set t ing and unset t ing m et hod. CM P En t it y Be a n Fin ding

CMP ent it y beans relieve t he program m er from having t o define and writ e ejbFind XXX (…) m et hods. Rat her, t he cont ainer deduces how t o im plem ent such m et hods for t he CMP ent it y bean by reading cert ain configurat ion inform at ion from t he EJB deploym ent descript ors, as you'll soon see. The im plem ent at ion of t hese m et hods is t hus t ransparent t o t he developer. These m et hods m ay be im plem ent ed by EJB vendor product s wit hin subclasses of t he CMP ent it y bean or by separat e ent it ies t o which t he calls are delegat ed and result s received. Regardless of t he underlying im plem ent at ion, t he CMP bean developer need not worry about writ ing any code t o support t hese operat ions. CM P En t it y Be a n Cr e a t ion a nd Re m ova l

The ejbCreate(…) m et hods are also opt ional for CMP ent it y beans. Thus, t he bean developer need not worry about im plem ent ing t he act ual dat abase INSERT relat ed code t o support t his m et hod. Rat her, t he developer need only ensure t hat each cont ainer- m anaged field value is properly init ialized wit h any default values and wit h values passed in as param et ers t o t he ejbCreate(…) m et hod. The cont ainer will init ialize all cont ainer- m anaged field values t o t he Java language default s ( for exam ple, 0 and null) before it calls t his m et hod. Such default value init ializat ion m ay be all t hat is needed for a part icular EJB and t hus not require any special ejbCreate(…) im plem ent at ion on t he part of t he bean developer. The bean developer should also eit her ret urn a null value for t he prim ary key from t his m et hod or declare a void ret urn t ype because t he cont ainer will handle t he creat ion of a prim ary key. CMP bean providers m ust also define ejbPostCreate(…) m et hods t hat m at ch ejbCreate(…) m et hods in t erm s of param et ers. The ejbPostCreate() m et hod is called by t he cont ainer aft er it calls ejbCreate() and aft er t he cont ainer associat es an inst ance of t he ent it y bean wit h t he client reference. Thus, any init ial act ions your ent it y bean desires t o perform using a fully associat ed ent it y bean inst ance can be done when t his m et hod is called. Cont ainers handle all prim ary key resolut ions and t hrowing of EJB except ions as appropriat e.

- 1152 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The cont ainer calls ejbRemove() on a CMP right before it delet es associat ed dat a from t he dat abase. The bean developer need only focus on any act ions t hat m ust be perform ed before t he dat a is delet ed from t he dat abase. The cont ainer im plem ent s all dat abase delet ion code and t hrows any EJB except ions as appropriat e. CM P En t it y Be a n Pa ssiva t ion a nd Act iva t ion

The ejbPassivate() and ejbActivate() m et hods m ust be im plem ent ed by CMP ent it y bean developers as t hey were for BMP ent it y bean developers. Developers m ust t hus clean up any non– dat a- source ent ry relat ed resources wit hin an ejbPassivate() m et hod im plem ent at ion. Developers m ust also reest ablish any non– dat a- source ent ry relat ed resources wit hin an ejbActivate() m et hod im plem ent at ion. CM P Ent it y Be a n St or ing a nd Loa ding

The cont ainer for CMP ent it y beans also handles m ost of t he work t hat was previously im plem ent ed inside of ejbLoad() and ejbStore() BMP ent it y bean m et hod calls. Cont ainers m anage t he act ual st orage of dat a t hat was previously im plem ent ed wit hin t he ejbStore() call. CMP bean developers need worry only about readying any cont ainer- m anaged field values for persist ence t o t he dat abase, such as by deriving any recent updat es t hat need t o be reflect ed in t he cont ainer- m anaged field values before t hey are persist ed. CMP developers sim ilarly need t o worry only about reflect ing any changes t hat were m ade t o a bean's field values wit hin t he ejbLoad() m et hod im plem ent at ion. Aft er a cont ainer handles updat ing t he cont ainer- m anaged field values, t he ejbLoad() m et hod is called and t he CMP ent it y bean im plem ent at ion of t his m et hod m ay need t o derive any changes t o ot her st at e t hat result from t his synchronizat ion wit h t he dat abase. CM P En t it y Be a n Com pon e n t I nt e r fa ce Ru le s Su m m a r y

The life cycle of CMP ent it y beans is essent ially ident ical t o t hat of BMP ent it y beans. Thus, we do not reit erat e t he ent it y bean com ponent life cycle guidelines here. The only difference is in who im plem ent s t he funct ionalit y em bedded inside of t he ent it y bean life cycle m et hods. For CMP ent it y beans, t he cont ainer im plem ent s m uch of t his funct ionalit y, and for BMP ent it y beans, it is t he bean developer's j ob. CMP ent it y beans t hus alleviat e a significant am ount of t he handcoding t hat was required by BMP ent it y beans in order t o accom plish t he desired effect s of dat abase connect ivit y. CMP ent it y

- 1153 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

bean providers sim ply ready beans for cont ainer- m anaged persist ence operat ions wit hin calls t o t he ejbCreate(), ejbPostCreate(), ejbRemove(), ejbLoad(), and ejbStore() m et hods. CMP ent it y bean developers should, however, m anage bean inst ance st at e and resources t hrough business- specific m et hods, as well as t hrough t he im plem ent at ion of st andard m et hods t hat effect resource closing ( via ejbPassivate) , resource opening ( via ejbActivate) , and st at e m anagem ent ( via setEntityContext and unsetEntityContext) . Most oft en, t he am ount of coding t hat is perform ed wit hin such m et hods is eit her ext rem ely m inim al or nonexist ent . CMP ent it y beans t hus m ay be viewed as providing st andard int erfaces for enabling a J2EE EJB cont ainer t o im plem ent obj ect - relat ional m apping for an EJB and for providing t he underlying dat abase connect ivit y solut ion. CM P En t it y Be a n Ex a m ple

List ing 36.13 cont ains t he core port ions from our TShirtEJBean CMP ent it y bean im plem ent at ion wit h non- germ ane port ions of t he com plet e code, such as except ion handling, not list ed here for sim plicit y in present at ion. This TShirtEJBean sim ply defines it s public field m em bers t o be m anaged by t he cont ainer, ent it y cont ext handling, ejbCreate() init ializat ion sem ant ics, ot her ejb XXX () m et hods not needing any im plem ent at ion, and a series of business- specific get t ers and set t ers for it s dat a. Addit ionally, a public getImageBytes() m et hod is defined t o ret rieve an array of byt es for T- shirt im age dat a st ored on t he local file syst em using t he filenam es cont ained wit hin t he TShirtEJBean obj ect 's respect ive im age nam e fields. That 's about it for t he exam ple! As you can see, CMP ent it y bean code im plem ent at ions can be t rem endously m ore sim ple t han BMP ent it y bean code im plem ent at ions. However, we have t o specify m ore inform at ion about t he CMP ent it y bean in it s XML- based deploym ent descript or, as you'll see in a subsequent sect ion. N ot e Your part icular EJB applicat ion server environm ent securit y rest rict ions m ust be configured such t hat java.io.FilePermission read access is perm it t ed for t he TShirtEJBean.getImageBytes() m et hod t o successfully com plet e.

List in g 3 6 .1 3 CM P En t it y Be a n Ex a m ple ( TShirtEJBean.java)

- 1154 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

package ejava.ejbch36.tshirt; …// imports excluded here… public class TShirtEJBean implements EntityBean { // CMP fields public Integer SHIRT_ID; public String SHIRT_SIZE; public String COLOR; public String DESIGN_FRONT; public String DESIGN_BACK; public String PICTURE_FRONT; public String PICTURE_BACK; public Integer ITEM_ID_FK; public double UNIT_PRICE; // Context private EntityContext ctx; // Set/get entity context public void setEntityContext(EntityContext aCtx) { = aCtx; } public void unsetEntityContext(){ ctx = null; }

ctx

// Initialize TShirt info only during creation public Integer ejbCreate(Integer shirtID, String size, String color, String designFront, String designBack, String pictureFront, String pictureBack, double unitPrice, Integer itemID) throws CreateException, RemoteException { SHIRT_ID = shirtID; SHIRT_SIZE = size; COLOR = color; DESIGN_FRONT = designFront; DESIGN_BACK = designBack; PICTURE_FRONT = pictureFront; PICTURE_BACK = pictureBack; UNIT_PRICE = unitPrice; ITEM_ID_FK = itemID; return null; } // Not needed public void ejbPostCreate(Integer shirtID, String size, String color, String designFront, String designBack,

- 1155 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

String pictureFront, String pictureBack, double unitPrice, Integer itemID) throws CreateException, RemoteException { /* No impl */ } // Standard you CMP! public void public void public void public void public void

methods not needing implementation…thank ejbActivate(){ } ejbPassivate(){ } ejbRemove(){ } ejbLoad(){ } ejbStore(){ }

// Getters for our TShirt data public Integer getID(){ return SHIRT_ID; } public String getSize(){ return SHIRT_SIZE; } public String getColor(){ return COLOR; } public Integer getItemID(){ return ITEM_ID_FK; } public double getUnitPrice(){ return UNIT_PRICE; } public String getDesignFront(){ return DESIGN_FRONT; } public String getDesignBack() { return DESIGN_BACK;} public String getPictureFront(){ return PICTURE_FRONT; } public String getPictureBack(){ return PICTURE_BACK;} // Setters for our TShirt data public void setID(Integer shirtID){ SHIRT_ID = shirtID; } public void setSize(String size){ SHIRT_SIZE = size; } public void setColor(String color){ COLOR = color; } public void setItemID(Integer itemID){ ITEM_ID_FK = itemID; } public void setUnitPrice(double unitPrice){ UNIT_PRICE = unitPrice; } public void setDesignFront(String file){ DESIGN_FRONT = file; } public void setDesignBack(String file){ DESIGN_BACK = file; } public void setPictureFront(String file){ PICTURE_FRONT = file; } public void setPictureBack(String file){ PICTURE_BACK = file; } // Special method to read TShirt images as bytes given picture names public byte[] getImageBytes(String imageType) { if(imageType == null){ return null;} if(imageType.equals("PictureFront")) { return readImage(PICTURE_FRONT);}

- 1156 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

else if(imageType.equals("PictureBack")) { return readImage(PICTURE_BACK);} else{ return null; } } // Helper method to read byte array of data from named file private byte[] readImage(String fileName) { if( (fileName == null)||(fileName.equals("")) ){ return null;} // Set local variables File imageFile = null; FileInputStream fin = null; byte[] returnBytes = null; … // Create File handle to fileName, read from FileInputStream imageFile = new File(fileName); int size = (int)imageFile.length(); fin = new FileInputStream(imageFile); returnBytes = new byte[size]; int length = fin.read(returnBytes); … // Return the bytes read from the file return returnBytes; } }

En t it y Be a n Clie n t I n t e r fa ce s Building and using hom e and rem ot e client int erfaces for ent it y beans is very sim ilar t o building and using hom e and rem ot e client int erfaces for session beans. I n fact , except for an addit ional t ype of finder m et hod t hat needs t o be added t o t he ent it y bean hom e int erface definit ion, only a few subt le sem ant ic differences exist . We describe how t o build ent it y bean int erfaces and how client s access t hese int erfaces in t his sect ion. Ent it y Be a n Re m ot e I nt e r fa ce s Ent it y bean rem ot e int erfaces encapsulat e t he client 's view of an ent it y bean. The approach by which ent it y bean rem ot e int erfaces are developed is ident ical t o t hat of session bean rem ot e int erfaces. Ent it y bean int erfaces t ypically consist of get t ers and set t ers for ret rieving and est ablishing dat a t o be associat ed w it h an ent it y bean, but t hey can also have ot her arbit rary applicat ion- specific int erfaces

- 1157 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

defined for t hem . This sect ion describes how t o build and use ent it y bean rem ot e int erfaces. En t it y Be a n Re m ot e I nt e r fa ce Logica l Ar ch it e ct u r e

Figure 36.10 depict s t he basic logical archit ect ure for building and using rem ot e EJB client int erfaces t o dist ribut ed ent it y EJBs. All applicat ion- specific int erfaces t o dist ribut ed EJB obj ect s, such as MyEntityEJB shown in t he diagram , m ust ext end t he javax.ejb.EJBObject int erface. As wit h session beans, ent it y beans also em ploy underlying st ubs, skelet ons, and cont ainer m anagem ent services for im plem ent ing dist ribut ed and m anaged access t o server- side ent it y EJBs from client - side int erfaces. The only real difference bet ween ent it y bean and session bean rem ot e int erfaces lies in a few subt le sem ant ic differences, as we discuss next . Figu r e 3 6 .1 0 . En t it y be a n r e m ot e int e r fa ce a r ch it e ct u r e .

Ent it y Be a n Applica t ion- Spe cific Re m ot e I nt e r fa ce s

As wit h session bean rem ot e int erfaces, an applicat ion- specific rem ot e EJB int erface m ust be creat ed for each ent it y bean

- 1158 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

com ponent . This int erface provides t he dist ribut ed int erface used by ent it y bean client s t o invoke t he applicat ion- specific logic of ent it y beans. For each dist ribut able applicat ion- specific m et hod on an ent it y bean server- side com ponent , such as MyEntityEJBean.someMethod(), an associat ed applicat ion- specific m et hod m ust be defined on t he EJB client - side rem ot e int erface, such as MyEntityEJB.someMethod(). As a side effect of t heir dist ribut able nat ure, each m et hod in t he applicat ion- specific rem ot e int erface should also declare t hat it can t hrow a java.rmi.RemoteException. Of course, such rules apply only t o t hose server- side com ponent m et hods you want t o be m ade dist ribut able. En t it y Be a n Ge n e r ic Re m ot e I nt e r fa ce s

I n addit ion t o applicat ion- specific int erfaces on an EJB rem ot e int erface, a set of m et hods inherit ed from EJBObject can also be invoked on a rem ot e ent it y bean obj ect . When client s want t o det erm ine whet her EJB obj ect s are ident ical t o ot hers, t he EJBObject.isIdentical() m et hod can be called. The EJBObject.getEJBHome() m et hod ret urns a handle t o t he ent it y bean's hom e int erface obj ect t hat is used t o creat e rem ot e int erface obj ect s. The EJBObject.getHandle() m et hod ret urns an obj ect t hat im plem ent s t he javax.ejb.Handle int erface for serializing and persist ing EJBObject references. Unlike session bean client s, ent it y bean client s can m ake a valid call t o EJBObject.getPrimaryKey() on a rem ot e int erface t o obt ain t he prim ary key obj ect associat ed wit h t he ent it y bean obj ect . A very im port ant difference bet ween session bean client int erface and ent it y bean client int erface sem ant ics is t he im plicat ion of calling t he EJBObject.remove() m et hod. For session beans, t his m et hod cleans up client references and possibly dest roys a serverside st at eful session obj ect . For ent it y beans, a call t o remove() will result in t he delet ion of an associat ed dat a- source ent ry from t he dat abase. Thus, ent it y bean client s m ust be part icularly careful when using t his m et hod and m ake sure t hat t hey int end for t he dat a t o be delet ed and not t he obj ect reference. As a final not e, on t he server side, an ent it y bean can obt ain a reference t o an EJBObject wit h which it is associat ed by calling getEJBObject() on it s EntityContext obj ect . Bean com ponent s m ay want t o obt ain such a reference for use as input or out put param et ers in t heir applicat ion- specific m et hods. Ent it y bean developers m ust be careful, t hough, t o be sure t hat any EJBObject references passed around in such a m anner are not accessed by

- 1159 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

m ore t han one client at one t im e t o guarant ee correct behavior for all client s. En t it y Be a n Re m ot e I nt e r fa ce Ex a m ple s

Our sam ple rem ot e int erfaces corresponding t o t he t wo t ypes of ent it y beans present ed earlier really convey no new inform at ion past t hat for session bean rem ot e int erfaces. Nevert heless, List ing 36.14 is present ed t o show you t he Credit rem ot e int erface for our BMP CreditEJBean described in List ing 36.11. List ing 36.15 present s t he TShirt rem ot e int erface for our CMP TShirtEJBean t hat was present ed in List ing 36.13. List ing 3 6 .1 4 BM P En t it y Be a n Re m ot e I n t e r f a ce Ex a m ple ( Credit.java)

package ejava.ejbch36.credit; import javax.ejb.EJBObject; import java.rmi.RemoteException; import java.util.Hashtable; public interface Credit extends EJBObject { /** Set credit information onto the bean using key names taken from the CreditDefinition interface */ public void setCreditInformation(Hashtable creditInformation) throws RemoteException; /** Get credit information from the bean accessible with key names from CreditDefinition interface. */ public Hashtable getCreditInformation() throws RemoteException; } List ing 3 6 .1 5 CM P En t it y Be a n Re m ot e I nt e r f a ce Ex a m ple ( TShirt.java)

package ejava.ejbch36.tshirt; import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface TShirt extends EJBObject { /** Getters for TShirt data **/ public Integer getID() throws RemoteException; public String getSize() throws RemoteException; public String getColor() throws RemoteException; public Integer getItemID() throws RemoteException;

- 1160 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public double getUnitPrice() throws RemoteException; public String getDesignFront() throws RemoteException; public String getDesignBack() throws RemoteException; public String getPictureFront() throws RemoteException; public String getPictureBack() throws RemoteException; /** Setters for TShirt data **/ public void setID(Integer shirtID) throws RemoteException; public void setSize(String size) throws RemoteException; public void setColor(String color) throws RemoteException; public void setItemID(Integer itemID) throws RemoteException; public void setUnitPrice(double unitPrice) throws RemoteException; public void setDesignFront(String designFront) throws RemoteException; public void setDesignBack(String designBack) throws RemoteException; public void setPictureFront(String pictureFront) throws RemoteException; public void setPictureBack(String pictureBack) throws RemoteException; /** Read image as bytes given names: PictureFront or PictureBack **/ public byte[] getImageBytes(String imageType) throws RemoteException; } Ent it y Be a n H om e I nt e r fa ce s Ent it y bean client s use hom e int erfaces t o creat e, find, and rem ove ent it y beans. Creat ion of ent it y beans act ually relat es t o t he insert ion of a new ent ry int o a dat a source ( for exam ple, a new row in a dat abase t able) . I nt erfaces for finding ent it y beans provide a m echanism for querying for dat a- source ent ries wit h result s ret urned in an obj ect - orient ed fashion ( t hat is, in t erm s of ent it y bean obj ect s) . Rem oving an ent it y bean relat es t o t he delet ion of it s associat ed dat a- source ent ry in t he dat abase. This sect ion describes how t o creat e and ut ilize ent it y bean int erfaces t o perform t hese basic funct ions as well as addit ional support ing funct ionalit y. En t it y Be a n H om e I nt e r fa ce Logica l Ar ch it e ct u r e

Figure 36.11 depict s t he archit ect ure behind creat ing ent it y bean hom e int erfaces and how client s m ay use t hese int erfaces. To obt ain handles t o applicat ion- specific EJB hom e int erface obj ect s, such as MyEntityEJBHome, which m ust ext end t he st andard javax.ejb.EJBHome int erface, we use JNDI t o look up nam ed hom e - 1161 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

references. Server- side skelet ons and t he cont ainer handle m apping calls from ent it y bean client st ubs t hat im plem ent applicat ionspecific hom e int erfaces ont o a part icular ent it y bean inst ance. Hom e int erfaces can also be used t o persist t heir handles for lat er reconst ruct ion and for obt aining m et a- dat a about t he EJBs t hat t hey serve t o creat e. Figur e 3 6 .1 1 . Ent it y be a n hom e int e r fa ce a r chit e ct ur e .

En t it y Be a n H om e Obj e ct Look u p

The m eans by which ent it y bean hom e obj ect s are looked up by client s is ident ical t o t he m eans by which session bean hom e obj ect s are looked up. JNDI is used whet her your client operat es inside of a J2EE cont ainer or out side of a cont ainer in a st andalone fashion. I f a client operat es inside of a J2EE cont ainer, elem ent s can be used t o refer t o EJB hom e int erfaces during lookup. Ent it y beans t hat want t o act as client s t o ot her EJBs define elem ent s wit hin t heir elem ent definit ion inside of an ejb-jar.xml file.

- 1162 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Ent it y Be a n Applica t ion- Spe cific H om e I nt e r fa ce s

A series of one or m ore create(…) m et hods are defined on t he cust om hom e int erface t o represent t he different ways in which t he associat ed ent it y bean dat a- source ent ry can be creat ed. A single create(…) m et hod m ust be defined on t he hom e int erface for each ejbCreate(…) m et hod defined on t he ent it y bean im plem ent at ion. Each version of a create(…) m et hod ret urns an inst ance of t he ent it y bean's rem ot e int erface ( for exam ple, MyEntityEJB) and cont ains zero or m ore input param et ers relat ed t o t he specific t ypes of init ializat ion param et ers needed by t he associat ed ejbCreate(…) m et hods. Each create(…) m et hod m ust also be defined t o t hrow a java.rmi.RemoteException and javax.ejb.CreateException. Addit ionally, each create(…) m et hod m ust be defined t o t hrow any applicat ion- specific except ions t hat have been defined for it s associat ed ejbCreate(…) m et hod. The create() m et hods are not t he only applicat ion- specific m et hods t hat can be defined on an ent it y bean hom e int erface. A collect ion of finder m et hods are also defined t hat enable t he client t o query for exist ing ent it y beans. A find XXX (…) m et hod on t he ent it y bean hom e int erface m ust exist for each ejbFind XXX (…) m et hod t hat exist s on t he ent it y bean im ple m ent at ion. For CMP ent it y beans, because no ejbFind XXX (…) m et hods are explicit ly defined on an ent it y bean im plem ent at ion, t he valid find XXX (…) m et hods can be det erm ined from t he ent it y bean deploym ent descript or ( as you'll learn in a subsequent sect ion) . Each find XXX (…) m et hod defined on t he ent it y bean client hom e int erface should also declare t hat RemoteException and FinderException obj ect s can be t hrown back t o t he client . All ent it y bean hom e int erfaces m ust define at least one findByPrimaryKey() m et hod because all ent it y beans m ust define an ejbFindByPrimaryKey() m et hod. The findByPrimaryKey() m et hod m ust be defined such t hat it ret urns a handle t o an ent it y bean rem ot e obj ect ( for exam ple, MyEntityEJB) . The cont ainer handles associat ing t he prim ary key ret urned from t he ejbFindByPrimaryKey() ent it y bean m et hod t o an act ual bean inst ance and ret urned ent it y bean client rem ot e int erface st ub. The ot her find XXX (…) m et hods m ust also be defined t o m at ch each associat ed ejbFind XXX (…) m et hod and should have t he sam e input and out put param et ers. The difference on t he client side is t hat t he Enumeration or Collection obj ect ret urned from find XXX (…) cont ains im plem ent at ions of ent it y bean rem ot e obj ect s as opposed t o prim ary keys cont ained in t he collect ions ret urned from

- 1163 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

associat ed ejbFind XXX (…) m et hods on server- side ent it y bean im plem ent at ions. En t it y Be a n Ge n e r ic H om e I nt e r fa ce s

I n addit ion t o calling EJBObject.remove() on a rem ot e ent it y bean obj ect t o delet e an associat ed dat a- source ent ry, ent it y bean client s can also call remove(Handle) inherit ed from EJBHome by t he hom e int erface obj ect . The Handle, of course, needs t o relat e t o t he part icular EJBObject t hat is t o be rem oved. Ent it y bean obj ect s m ay also be rem oved by passing t he prim ary key obj ect associat ed wit h a part icular ent it y bean t o t he remove(Object) m et hod defined at t he EJBHome level. As wit h session beans, t he EJBHome.getEJBMetaData() m et hod is called t o obt ain a handle t o a EJBMetaData obj ect t hat provides a m echanism for client s t o discover cert ain inform at ion about an ent it y bean. Ent it y bean EJBMetaData m et hods provide t he sam e sem ant ics as t hey do for session beans when calling getEJBHome() t o ret urn t he hom e obj ect , getHomeInterfaceClass() t o ret urn t he hom e int erface Class, getRemoteInterfaceClass() t o ret urn t he rem ot e int erface Class, and isSession() t o det erm ine whet her it is a session or an ent it y EJB. Addit ionally, t he getPrimaryKeyClass() m et hod can be called t o ret urn t he Class obj ect t hat represent s t he ent it y bean's prim ary key class. A call t o isStatelessSession() always ret urns false for ent it y beans. On t he server side, an ent it y bean can ext ract a handle for it s EJBHome obj ect wit h a call t o getEJBHome() on it s EntityContext obj ect ( as inherit ed from EJBContext) . Bean com ponent s m ay want t o obt ain such a reference for creat ing, finding, and rem oving ent it y beans of t heir own t ype. En t it y Be a n H om e I nt e r fa ce Ex a m ple s

I n addit ion t o creat ion m et hods, our ent it y bean hom e int erface exam ples include finder m et hod definit ions in t hem according t o t he way in which t he ent it y bean obj ect s can be select ed. List ing 36.16 depict s t he CreditHome BMP ent it y bean hom e int erface associat ed wit h t he CreditEJBean of List ing 36.11. Here, our create() m et hod is m apped by t he cont ainer t o a call t o our CreditEJBean.ejbCreate() m et hod, and t he find XXX (…) m et hods m ap t o calls t o associat ed CreditEJBean.ejbFind XXX (…) m et hods. List in g 3 6 .1 6 BM P En t it y Be a n H om e I n t e r fa ce Ex a m ple ( CreditHome.java)

- 1164 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

package ejava.ejbch36.credit; import import import import import import import

javax.ejb.EJBHome; javax.ejb.CreateException; java.rmi.RemoteException; java.util.Hashtable; java.util.Enumeration; javax.ejb.FinderException; java.util.Collection;

public interface CreditHome extends EJBHome { /** Create a Credit entity given credit information whose keys are defined according to names from CreditDefinition */ public Credit create(Hashtable creditInformation) throws CreateException, RemoteException; /** Find a Credit entity given its primary key */ public Credit findByPrimaryKey(CreditPrimaryKey primaryKey) throws FinderException, RemoteException ; /** Find Credit entities given with the given customer ID */ public Collection findByCustomerID(int customerID) throws FinderException, RemoteException; /** Find Credit entities given the customer ID and order ID */ public Collection findByCustomerIDAndOrderID(int customerID, int orderID) throws FinderException, RemoteException; } List ing 36.17 present s t he TShirtHome CMP hom e int erface for t he TShirtEJBean of List ing 36.13. Alt hough it is apparent t hat t he create(…) m et hod m aps t o t he TShirtEJBean. ejbCreate() m et hod, j ust how t he find XXX (…) m et hods are m apped or even defined m ay not be so apparent t o you j ust yet . No ejbFind XXX (…) m et hods are defined on our TShirtEJBean. I n t he next sect ion, we show how such m et hods are defined by t he cont ainer aft er appropriat e hint s are given t o t he cont ainer during configurat ion and deploym ent of t he CMP ent it y bean. List in g 3 6 .1 7 CM P En t it y Be a n H om e I n t e r fa ce Ex a m ple ( TShirtHome.java)

package ejava.ejbch36.tshirt; import javax.ejb.EJBHome;

- 1165 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

import import import import

javax.ejb.CreateException; java.rmi.RemoteException; javax.ejb.FinderException; java.util.Enumeration;

]public interface TShirtHome extends EJBHome { /** Create a TShirt entity given all of its field data */ public TShirt create(Integer shirtID, String size, String color , String designFront, String designBack, String pictureFront, String pictureBack, double unitPrice, Integer itemID) throws CreateException, RemoteException; /** Find a TShirt entity given its primary key */ public TShirt findByPrimaryKey(Integer shirtID) throws FinderException, RemoteException; /** Find TShirt entities given a TShirt size and color */ public Enumeration findBySizeAndColor(String size, String color) throws FinderException, RemoteException; /** Find TShirt entities given a TShirt Item ID */ public Enumeration findByItemID(Integer itemID) throws FinderException, RemoteException; }

En t it y Be a n Con figu r a t ion a n d D e ploym e n t We have already present ed t he basic t op- level deploym ent descript or and session bean elem ent s in t his chapt er. As you saw previously, t he root elem ent cont ained an elem ent , which in t urn cont ained a collect ion of elem ent s. As opposed t o j ust elem ent s, t he elem ent can also cont ain a collect ion of elem ent s. Each elem ent is used t o describe t he configurat ion and deploym ent of an individual ent it y bean. The bean elem ent DTD st ruct ure, shown in List ing 36.18, defines ent it y bean m et a- dat a; a unique nam e in t he EJB JAR file; t he bean's class, int erface, and prim ary key nam es; t he t ype of ent it y bean; configurat ion param et ers; references t o ot her EJBs and dat abase connect ions; securit y sem ant ics; and elem ent s t o assist in t he obj ect - relat ional m apping for CMP ent it y beans. List in g 3 6 .1 8 EJB D TD En t it y Be a n Ele m e n t s

- 1166 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

























Met hods ident ified by such elem ent s have t ransact ions m anaged for t hem by t he cont ainer according t o t he specified t ransact ion at t ribut e t ype. A session bean using such declarat ive t ransact ion specificat ions m ust have all of it s business- specific rem ot e int erface m et hods associat ed wit h a part icular t ransact ion at t ribut e. An ent it y bean needs bot h it s business- specific rem ot e int erface m et hods and it s hom e int erface m et hods associat ed wit h a t ransact ion at t ribut e. I f no t ransact ion at t ribut es are specified for t he EJB, such at t ribut es m ust be defined eit her by default or m anually at deploym ent t im e. Of course, if a part icular resource m anager ( for exam ple, DBMS) will not provide t ransact ion coordinat ion wit h your applicat ion server via it s resource adapt er ( for exam ple, JDBC) , t hen a t ransact ion at t ribut e of NotSupported should be defined t o t urn off cont ainer- m anaged t ransact ion dem arcat ion and suspend client - m anaged t ransact ion dem arcat ion. As an exam ple, suppose t hat we've defined t he following t ransact ion- unaware bean for which we want t o allow a cont ainer t o m anage t ransact ion dem arcat ion:

package ejava.ejbch37.transactions; import javax.ejb.*; import java.rmi.*; public class MyEntityEJBean implements EntityBean { public void myMethod(){ /* Do something…*/ } public void myMethod(String foo){ /* Do something…*/ } public void myMethod(String foo, Object bar) { /* Do something…*/ }

- 1182 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public void myOtherMethod(){ /* Do something…*/ public void myOtherMethod(String foo){ /* Do something…*/ } … }

}

Now suppose t hat during assem bly t im e, we decide t he following about t his bean's t ransact ion sem ant ics: A. All rem ot e m et hods should have a Required t ransact ional at t ribut e by default . That is, t he cont ainer will dem arcat e a t ransact ion if t he client does not . B. The rem ot e myMethod(String, Object) m et hod should have a Never t ransact ional at t ribut e associat ed wit h it . That is, t he cont ainer won't dem arcat e a t ransact ion; neit her can t he client or an except ion will be t hrown. C. Bot h rem ot e myOtherMethod() m et hods should have a Supports t ransact ional at t ribut e associat ed wit h t hem . That is, t he cont ainer will not dem arcat e t ransact ions, but t he client m ay. Given such t ransact ional sem ant ics, we would define our ejbjar.xml file for t his bean according t o t he basic st ruct ure shown here:



Transaction-unaware Bean MyEntityEJBean …



MyEntityEJBean Remote *

Required

MyEntityEJBean

- 1183 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Remote myMethod

java.lang.String java.lang.Object

Never

MyEntityEJBean Remote myOtherMethod

Supports

Alt hough bean im plem ent at ions should not at t em pt t o perform any t ransact ion dem arcat ion or isolat ion set t ing t hem selves under cont ainer- m anaged dem arcat ion, beans can call getRollbackOnly() and setRollbackOnly() on t heir EJBContext obj ect . EJBContext. setRollbackOnly() is used t o set t he current t ransact ion st at e such t hat it can only roll back and never com m it . The EJBContext.getRollbackOnly() m et hod can be called t o ret urn a boolean value indicat ing if such a st at e was already set . Set t ing a t ransact ion t o rollback is useful only t o inform t he cont ainer t hat an applicat ion error has occurred wit hin t he current t ransact ion, and t hat t he st at e of t he syst em affect ed by t his t ransact ion should t hus be considered invalid. The cont ainer will t hen roll back t he t ransact ion when it is appropriat e. St at eful session beans can also be m ade a t ad m ore t ransact ion aware when t hey im plem ent t he javax.ejb.SessionSynchronization int erface as shown in Figure 36.5. St at eful session beans t hat im plem ent t he SessionSynchronization int erface's afterBegin(), beforeCompletion(), and afterCompletion(boolean) m et hods can be inform ed when t he cont ainer has j ust begun a t ransact ion, is about t o com plet e a t ransact ion, or has j ust com plet ed t he t ransact ion wit h a true st at us if it com m it t ed, respect ively. On a final not e, som e vendors m ay also define t heir own specific t ransact ion sem ant ics for EJBs. For exam ple, t he BEA WebLogic

- 1184 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

weblogic-ejb-jar.xml file cont ains a elem ent t hat cont ains a elem ent t o define t he m axim um t im e in seconds a t ransact ion m ay exist bet ween it s beginning and com plet ion. I f t his t im e expires before t he t ransact ion can be com plet ed, t he t ransact ion w ill be rolled back.

EJB Se cu r it y St andard securit y m echanism s defined for EJBs are current ly largely focused around providing a m inim al set of const ruct s for EJB securit y access cont rol. Alt hough a m echanism for aut hent icat ing a user is im plied by virt ue of t he fact t hat a part icular user m ust be grant ed access t o a part icular EJB m et hod, no st andard m eans for aut hent icat ing a user is defined in EJB v1.1 and t he J2EE v1.2. Such st andard m echanism s are planned for t he J2EE v1.3, however, and will m ost likely focus around use of t he JAAS. Furt herm ore, a com binat ion of cont ainer- specific and user- definable securit y m echanism is also current ly needed t o creat e a t ruly secure and pract ical securit y environm ent for EJBs. This sect ion describes t he st andard program m at ic and declarat ive m eans available and t he addit ional m echanism s needed for providing pract ical EJB securit y. N ot e This sect ion cont ains a few sim ple code snippet s t hat can be found in soft - copy form on t he CD in t he examples/src/ejava/ejbch37/security direct ory.

St a nda r d Pr ogr a m m a t ic EJB Se cur it y M e cha nism s Alt hough bean- im plem ent ed securit y access cont rol logic is not recom m ended by t he EJB specificat ion, in m any pract ical cases it m ay be inevit able. The decision t o im plem ent your own securit y access cont rol logic will largely be a funct ion of which vendorspecific services your cont ainer and deploym ent t ools can provide. Two prim ary m ain hooks int o obt aining securit y inform at ion are provided via t he EJBContext obj ect ( and t wo ot her m et hods are deprecat ed) . Securit y- relat ed calls t o t he EJBContext obj ect are callable only from wit hin t he cont ext of a business- specific m et hod on an EJB. Ot herwise, a java.lang.IllegalStateException will be t hrown by t he cont ainer t o indicat e t hat no securit y cont ext exist s. The EJBContext.getCallerPrincipal() m et hod is invoked by an EJB t o obt ain a handle t o a java.security.Principal obj ect . The

- 1185 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Principal represent s t he part icular principal ident it y on behalf of which t he invoking EJB client is act ing. A call t o Principal.getName() by t he bean can ret urn a String obj ect t hat is used in som e business- specific securit y checking logic decision m aking. The EJBContext.isCallerInRole(String) m et hod is used t o ask t he EJB environm ent whet her t he current principal associat ed wit h t his securit y cont ext is a m em ber of t he role passed in as a String t o t his m et hod. A boolean ret urn value indicat es whet her t he caller is indeed in t his role. For exam ple, if we have an EJB t hat allows a client t o ret rieve sensit ive cust om er order dat a given a cust om er I D, we m ight rest rict such access only t o aut horized users in t he " adm in" role or t o t he part icular cust om er having t hat cust om er I D as a principal nam e as shown here:

public Object getMyOrder(String customerID) { Object returnData = ""; try{ // Get principal from context and principal name java.security.Principal caller = ejbContext.getCallerPrincipal(); String callerID = caller.getName(); // If not in admin role and not the user associated with // this order, then deny access… if( (ejbContext.isCallerInRole("admin") == true) ||(callerID.equalsIgnoreCase(customerID) )) { // Allow access to do security-critical stuff here… } else { // Access denied. Audit this event and return… } } catch(Exception e){ e.printStackTrace(); } return returnData; } St a n da r d D e cla r a t ive EJB Se cu r it y M e ch a n ism s Whenever a call t o EJBContext.isCallerInRole() is m ade from wit hin EJB code, an associat ed should be

- 1186 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

ident ified in t he EJB's deploym ent descript or for t hat bean. The elem ent is defined wit hin an elem ent for ent it y beans and wit hin a elem ent for session beans. List ing 37.2 shows t he DTD for t his securit y role reference and t he opt ional reference t o a role nam e defined during assem bly as we describe next . List ing 3 7 .2 EJB D TD Se cur it y Role Re fe r e nce s

The elem ent wit hin an EJB's elem ent is defined during EJB assem bly t o refer t o a defined wit hin a part icular elem ent as shown in List ing 37.3. All logical securit y roles defined for a part icular EJB m odule are ident ified by elem ent s t hat sit wit hin an elem ent t hat can opt ionally be defined wit hin t he root elem ent for an EJB m odule ( see List ing 36.1 in Chapt er 36) . Addit ionally, a elem ent is defined for each m et hod in an EJB t o define t hose securit y roles t hat can access such m et hods. The elem ent cont ained wit hin t he elem ent is defined in t he sam e m anner as it was for t ransact ion m anagem ent ( see List ing 37.1) . List ing 3 7 .3 EJB D TD Se cur it y Asse m bly Ele m e nt s



- 1187 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Thus, for our securit y- aware getMyOrder() m et hod on t he EJB shown in t he preceding sect ion, we can m ake t he fact t hat it references t he admin role relevant t o assem bly via it s ejb-jar.xml file ent ry as shown here:



Security Bean MySecureEJBean …

Bean references admin role.

admin Administrator



Administrator role for bean mgt.

Administrator



As a final exam ple of com plet ely declarat ive securit y specificat ion, say t hat we desire t o add anot her m et hod t o our sam e MySecureEJBean, which is securit y unaware:

- 1188 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public void printOrderInfo(String orderID) { // Assume that access to do security-critical stuff here // is allowed by virtue of fact that container allowed // method to be invoked… } Then we m ight be able t o capit alize on our abilit y t o declarat ively lim it access t o such a m et hod from only t hose users belonging t o a special ClassifiedPrinterUser role as shown here:





Role for classified printer users.

ClassifiedPrinterUser

ClassifiedPrinterUser

MySecureEJBean printOrderInfo



Ve ndor - Spe cific Acce ss Cont r ol M a pping Alt hough t he roles specified by an assem bler in t he elem ent s of an ejb-jar.xml file define logical roles assum ed by an EJB applicat ion, t he cont ainer and deploym ent t ools/ people m ust m ap t hese roles t o act ual user groups and/ or users in t he operat ional syst em . Addit ionally, t he cont ainer and deploym ent t ools/ people m ust m anage how t hese roles relat e t o part icular securit y dom ains from t he operat ional syst em . Vendor- specific m appings from logical securit y roles t o operat ional environm ent

- 1189 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

groups/ users m ay be perform ed in an aut om at ed fashion wit hout requiring t he developm ent of vendor- specific code. As an exam ple of vendor- specific m apping, t he BEA WebLogic Server's GUI DeployTool can be used t o m ap st andard J2EE EJB defined role nam es t o BEA WebLogic Server principal nam es. DeployTool populat es t he weblogic-ejb-jar.xml file's elem ent wit h one or m ore st andard EJB t o WebLogic- specific m appings. Declarat ive EJB securit y access cont rol checking m echanism s provide a codeless way for det erm ining whet her a part icular user in a part icular role is allowed access t o a part icular m et hod on a part icular EJB. However, som e ent erprise applicat ions m ay need t o provide access cont rol checking funct ionalit y in which access t o a part icular EJB m et hod should be allowed based on som e businessspecific st at es and logic of t he syst em associat ed wit h t hat user. For exam ple, it m ay not sim ply be valid t o say t hat all users belonging t o a part icular employee role have access or do not have access t o part icular get t er and set t er m et hods on som e TimeSheet EJB t hat encapsulat es em ployee t im esheet s in an ent erprise hum an resource m anagem ent applicat ion. Rat her, you m ay want t o im plem ent a securit y checking m echanism t hat provides access cont rol t o such TimeSheet EJB get t er and set t er m et hods based on whet her t he ident it y of t he invoking client m at ches som e employeeID field st at e of t he TimeSheet EJB. Alt hough bean developers can use t he st andard program m at ic EJB securit y access cont rol checking m echanism s t o im plem ent t he needed logic, som e EJB cont ainer vendors m ay provide addit ional access cont rol m echanism s t o im plem ent such feat ures. Ve ndor - Spe cific I de nt it y a nd Aut he nt ica t ion Vendor- specific m appings from logical securit y role t o operat ional environm ent groups/ users m ay not require any vendor- specific code, but t he exact m eans for how your cont ainer m anages t he access, addit ion, and rem oval of t he operat ional groups/ users wit hin it s auspices m ay indeed require vendor- specific code. For exam ple, if your ent erprise m anages user profile inform at ion in a dat abase, a vendor- specific m eans t o access t hat inform at ion via JDBC m ay be required. However, you m ay also decide t o use what ever m eans are provided by your part icular vendor t o aut om at ically m anage such inform at ion, which m ay not require specialized coding. Such m et hods m ight include a m eans t o specify user profile inform at ion in a sim ple t ext file, an XML file, or an LDAP st ruct ure.

- 1190 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The BEA WebLogic Server, in fact , uses it s weblogic.properties file as t he default m eans for st oring usernam es and passwords. WebLogic also provides a m eans t o m anage ident it ies st ored by Windows NT, UNI X, LDAP st ruct ures, or a cust om ext endible ident it y m anagem ent realm . The cust om ext endible ident it y m anagem ent realm , however, involves t he im plem ent a t ion of vendor- specific int erfaces t o support int eroperat ion wit h t he WebLogic securit y checking environm ent . The basic approach is t o creat e a special realm class t hat im plem ent s m et hods t o ret rieve and m odify user, group, and access cont rol inform at ion. Thus, user profile inform at ion m ay be st ored in a dat abase and m anaged in a business- specific fashion under t hese int erface im plem ent at ions. Your operat ional environm ent –specific im plem ent at ions of t hese int erfaces are based ent irely on vendor- specific int erfaces. However, such built - in support provides a lot of flexibilit y in how you m anage your specific operat ional user profiles. Furt herm ore, a proper adapt er design pat t ern im plem ent at ion ( see Chapt er 3, " Com ponent - Based Soft ware Developm ent for t he Ent erprise" ) can be used t o isolat e vendor- specific library dependencies from your business- specific logic. As previously m ent ioned, J2EE v1.3 will m ost likely incorporat e JAAS for st andard aut hent icat ion t o EJB servers. I n t he m eant im e, you'll have t o rely on ut ilizing vendor- specific m eans for aut hent icat ing client s in EJB server environm ent s. A principal ident it y nam e and set of credent ials m ust som ehow propagat e from EJB client t o EJB server for aut hent icat ion t o occur. BEA WebLogic accom plishes t his via set t ing of javax.naming.Context.SECURITY_PRINCIPAL and javax.naming.Context.SECURITY_CREDENTIALS propert ies ont o an InitialContext during init ial connect ivit y wit h t he EJB server from t he client . On t he BEA WebLogic server side, if a cust om realm is being used, special callbacks ont o t he cust om realm im plem ent at ion class are m ade t o pass such principal and credent ial inform at ion t o enable your code t o provide cust om aut hent icat ion of such users wit h t he syst em . An obj ect ret urned by your code t o t he WebLogic cont ainer represent ing an aut hent icat ed user of t he syst em is t hen associat ed wit h a server- side t hread handler for t he client . When subsequent request s are m ade from t hat sam e client associat ed w it h t he t hread, t he client 's credent ials from it s t hread handler t hen can be used in t he process of providing access cont rol for EJBs.

EJB Se cu r it y Au t h e n t ica t ion M ode l

- 1191 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Lim it a t ion s Herein lies t he rub wit h t he current EJB fram ework. EJB designs wit h m inim al or no securit y requirem ent s m ay be port able, but im plem ent at ion of com m ercially- viable and pract ical securit y m echanism s int o your EJB- based designs m ay lead one down t he pat h t o creat ing non- port able serverside code wit hout proper designs. Furt herm ore, a part icular vendor's m odel for associat ing principal and credent ial inform at ion wit h a part icular EJB invocat ion can lead t o unforeseen problem s wit h your EJB im plem ent at ions if you do not consider t his m odel carefully during EJB design. As an exam ple, associat ing t he securit y cont ext wit h server- side t hread represent at ives for EJB client s is som ewhat disj oint ed wit h t he EJB com ponent and client m odeling assum pt ions described in Chapt er 36. From m y ( t hat is, Paul Perrone's) own professional experience wit h designing and im plem ent ing sophist icat ed and product ion- ready EJB securit y m echanism s using EJBcom pliant servers, I 've had t o creat e m any design workarounds in pract ice and have m ade m any suggest ions direct ly t o EJB vendors regarding how t o bet t er support securit y t hat suit s EJB applicat ion serving m odels. The lat est BEA WebLogic Server v5.1 release seem s t o have act ually incorporat ed a few of t hese suggest ions. Nevert heless, it is som et hing t o be cognizant of and plan for if you m ust incorporat e ent erprise securit y m echanism s int o your EJB designs. Ex t e nding t he BeeShirts.com Ex a m ple D a t a M ode l As a final ext ension t o t he BeeShirts.com dat a m odel in t his book, we add BeeShirts.com aut hent icat ion inform at ion t o t he dat abase. Figure 37.1 depict s our addit ion of an AUTHENTICATION t able t o encapsulat e cust om er aut hent icat ion inform at ion. Here we see t hat a cust om er is relat ed t o aut hent icat ion inform at ion which cont ains t he cust om er's BeeShirts.com password. An aut hent icat ion t ype is also defined which, for our exam ple code purposes, is always set t o PASSWORD. The com plet e dat a m odel can be found in Appendix A, " Soft ware Configurat ion," but here we only int roduce an augm ent at ion t o t he m odel above and beyond what has already been int roduced. Appendix A also cont ains script s for configuring t he dat abase t o support t he schem a assum ed by t his book, as well as for configuring t he dat abase wit h som e sam ple dat a.

- 1192 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Figur e 3 7 .1 . The

BeeShirts.com a ut h e n t ica t ion a nd cu st om e r da t a m ode l.

BeeShirts.com Se cu r it y Our BeeShirts.com EJB code defined in Chapt er 36 did not em ploy any securit y m echanism s. We have t herefore provided a concret e exam ple on t he CD of how t o im plem ent a sim plified aut hent icat ion schem e for use wit h our BeeShirts.com EJBs. These aut hent icat ion relat ed EJBs have been placed under t he examples/src/ejava/ejbch37 direct ory on t he CD for t his chapt er. You should first not e t hat we added a cont ainer- m anaged persist ent ent it y bean for encapsulat ing aut hent icat ion inform at ion. An Authentication, AuthenticationHome, and AuthenticationEJBean define t his bean provided in t he ejava.ejbch37.authentication package. This bean has a cust om er I D Integer field/ prim ary key, a password String, and an aut hent icat ion t ype String ( always set t o PASSWORD) . - 1193 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

N ot e The aut hent icat ion ent it y bean code is cont ained on t he CD under t he examples/src/ ejava/ejbch37/authentication direct ory.

We have also added a st at eless session bean for password- based login, for cust om er regist ra t ion, and for rem inding t he user of a forgot t en password. An AuthenticationSession, AuthenticationSessionHome, and AuthenticationSessionEJBean define t his bean provided in t he ejava.ejbch37.authenticationsession package. A register() m et hod t akes a Serializable Customer obj ect as input , creat es a Customer ent it y bean, and creat es an Authentication ent it y bean based on t his inform at ion. The login() m et hod t akes a user em ail and password as input , finds an associat ed Customer ent it y bean, finds an associat ed Authentication ent it y bean, com pares t he found password wit h t he password subm it t ed t o t his m et hod, and ret urns a Serializable Customer obj ect if t he passwords m at ch or t hrows a FailedToLoginException if t he passwords do not com pare. A remindPassword() m et hod sends an associat ed password t o a user's em ail address. As you'll see in t he nex t sect ion, such beans will com e in handy when we're int egrat ing our EJBs int o t he Web t ier. N ot e The aut hent icat ion session bean code is cont ained on t he CD under t he examples/ src/ejava/ejbch37/authenticationsession direct ory. Ca ut ion Not e t hat in an act ual applicat ion, connect ivit y t o t he aut hent icat ion session bean would probably occur over an encrypt ed session such as SSL. Furt herm ore, any password rem ind funct ionalit y t hat sends a password in t he clear, alt hough it m ay be com m on, also provides real- world securit y issues and should probably ut ilize som e form of encrypt ed em ail, such as PGP, in a real applicat ion.

EJB/ W e b Con n e ct ivit y

- 1194 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

You saw an exam ple of how t o creat e bot h st andalone Java client s and J2EE applicat ion client s t o an EJB in Chapt er 35, " Applicat ion Servers and Ent erprise JavaBeans," and how t o m ake one EJB serve as a client t o anot her in Chapt er 36. Our sam ple EJBs developed for Chapt er 36 also have sim ple t est client s on t he CD for each EJB t hat dem onst rat e how t o exercise t he funct ionalit y of each bean. But you also m ay be wondering how one m akes t he business logic and dat a encapsulat ed behind a wall of EJBs accessible via t he Web. The solut ion advocat ed by t his book is t o use Java Servlet s or JSPs. As you'll discover, because Java Servlet s and JSPs operat e inside of a J2EE cont ainer environm ent , t urning t hem int o EJB client s is very sim ilar t o t he process in which J2EE applicat ion client s and EJBs are t urned int o EJB client s. BeeShirts.com: An I nt e gr a t e d J2 EE W e b a n d EJB e - Com m e r ce Applica t ion Given t he BeeShirts.com J2EE JSPs of Chapt er 33, " JavaServer Pages," and t he J2EE EJBs of Chapt ers 35 and 36, we have int egrat ed t hese t wo J2EE com ponent t iers t oget her and placed t he result ing code on t he CD for t his chapt er. We have also added t he t wo session and ent it y beans from t he preceding sect ion int o t he m ix t o provide a m eans for aut hent icat ing and regist ering users wit h t he syst em . As you'll see in subsequent sect ions of t his chapt er, part s of t he archit ect ure are also ext ended t o dem onst rat e t he use of JMS and JavaMail wit h EJB. Figure 37.2 depict s t he archit ect ure of t his fully int egrat ed BeeShirts.com e- com m erce ent erprise applicat ion. Figur e 3 7 .2 . The

BeeShirts.com e - com m e r ce e nt e r pr ise a pplica t ion.

- 1195 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The archit ect ure of Figure 37.2 can be part it ioned int o four prim ary t iers: •



Ent e r pr ise Clie nt Ena ble d Tie r : The prim ary int erface t o our BeeShirts.com applicat ion is t he Web int erface int roduced in Chapt er 32, " Java Servlet s," and Chapt er 33. Through t his int erface, BeeShirts.com cust om ers browse for T- shirt s, add shirt s t o a shopping cart , regist er, place orders, and learn about BeeShirts.com business pract ices. A sim ple credit m anager client t o dem onst rat e J2EE applicat ion client s was int roduced in Chapt er 35 and is used by BeeShirts.com cust om er represent at ives t o add cust om er credit - card inform at ion received via t he phone. Ent e r pr ise W e b Ena ble d Tie r : Our Web present at ion layer is com posed of JSPs as described in Chapt er 33. All BeeShirts.com Web request s and responses are handled at

- 1196 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





t his layer wit h any business logic and dat a request s delegat ed t o EJBs. En t e r pr ise Applica t ion En a ble d Tie r : Our BeeShirts.com applicat ion business logic and dat a are encapsulat ed by EJBs at t his t ier. Our EJB infrast ruct ure was int roduced in Chapt ers 35 and 36. Ent e r pr ise D a t a Ena ble d Tie r : Finally, our ent erprise dat a t ier cont ains all BeeShirts.com ent erprise dat a in a dat abase accessed by JDBC from BMP ent it y beans and via an EJB cont ainer for CMP ent it y beans. Most of our BeeShirts.com dat a schem a was int roduced in Chapt er 9, " Basic JDBC," and Chapt er 10, " Advanced JDBC," and subsequent ly em bellished in Chapt er 22, " Messaging Services," as well as in Figure 37.1.

The point s of BeeShirts.com JSP/ EJB int egrat ion are descr ibed here: •

• •







Cust om e r Re gist r a t ion: The DisplayRegistrationInformation JSP was engineered t o now invoke t he AuthenticationSession EJB's register() m et hod wit h a Serializable Customer obj ect before t he user is officially regist ered wit h t he syst em and added t o t he dat abase. T- Shir t Br ow sing: The DisplayBrowsedShirts JSP was engineered t o invoke t he BrowseSession EJB's queryShirts() m et hod t o query for act ual T- shirt dat a in t he dat abase. Sh oppin g- Ca r t I t e m Addit ion : The AddAnItemToTheCart JSP was engineered t o creat e a ShoppingCartSession EJB and add it t o t he JSP's session, if none was current ly in t he JSP session. The AddAnItemToTheCart JSP was t hen engineered t o invoke t he ShoppingCartSession EJB's addAnItemToTheCart() m et hod t o add select ed it em dat a t o t he shopping session. Shopping- Ca r t I t e m Re t r ie va l: The DisplayItemsInTheCart JSP was engineered t o use t he ShoppingCartSession EJB st ored in t he JSP session t o invoke t hat EJB's getSelectedItemsInTheCart() m et hod for ret rieving cart it em s from t his shopping session. Shopping- Ca r t Che ck out : The Checkout JSP was engineered t o invoke t he ShoppingCartSession EJB's checkOut() m et hod t o creat e an order for t he cust om er based on t he shopping cart session it em s and t hen display t his order for t he cust om er. Cust om e r Login: The VerifyLogin JSP was engineered t o invoke t he AuthenticationSession EJB's login() m et hod t o effect a login and receive a serialized Customer obj ect when a Login but t on is clicked.

- 1197 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





Or de r Qu e r y: The VerifyLogin JSP ( included from t he OrderStatus JSP) was engineered t o invoke t he OrderManager EJB's queryOrders() m et hod t o ret rieve a collect ion of orders for t his cust om er t hat will be displayed. Not e t hat t his occurs only if t he cus t om er can successfully log in. Cust om e r Pa ssw or d Re m inding: The VerifyLogin JSP was engineered t o invoke t he AuthenticationSession EJB's remindPassword() m et hod t o effect t he em ailing of a cust om er's password when a Rem ind but t on is clicked. N ot e Not e t hat we have left som e business logic wit hin t he VerifyLogin JSP t o check whet her t he user has exceeded a cert ain num ber of at t em pt ed logins. As an int erest ing exercise for t he reader, we encourage you t o t urn t he AuthenticationSession bean int o a st at eful session bean and m ove t his checking logic behind t he wall of t his bean t o furt her enable t he VerifyLogin JSP t o focus on pure Web present at ion.

W e b/ EJB Con n e ct ivit y Appr oa ch a n d Ex a m ple s Now t hat we've seen what was int egrat ed bet ween our BeeShirts.com Web and EJB com ponent s, let 's explore how t his is accom plished. Whet her from wit hin a Java Servlet or a JSP script let , t he applicat ion code for looking up EJB hom e int erface obj ect handles is very st raight forward. Aft er a param et erless javax.naming.InitialContext obj ect is creat ed, a lookup() is perform ed on t hat cont ext given an EJB reference nam e. EJB reference nam es follow t he general form of java:comp/env/ejb/MyEJBRefName. N ot e The reengineered JSP code for t alking wit h t he EJBs has been placed on t he CD under t he examples/src/ejava/ejbch37/webclient direct ory. Not e t hat we insert snippet s from such code in t his sect ion.

- 1198 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

We have added som e m et hods t o our JSPHelper class from Chapt er 33 t o assist wit h creat ing handles t o EJBs. For exam ple, t his new ejava.ejbch37.webclient.JSPHelper class m aint ains a privat e InitialContext obj ect creat ed from wit hin a getInitialContext() m et hod and used t o look up various EJB hom e obj ect s as shown here for t he BrowseSessionHome obj ect :

package ejava.ejbch37.webclient;

… public class JSPHelper { … private static String BROWSE_SESSION_REFNAME = "java:comp/env/ejb/browsesession"; … private static void getInitialContext() throws NamingException { initialContext = new InitialContext(); } … public static BrowseSessionHome getBrowseSessionHome() throws NamingException { if(browseSessionHome == null){ getInitialContext(); Object browseSessionHomeRef = initialContext.lookup(BROWSE_SESSION_REFNAME); browseSessionHome = (BrowseSessionHome)PortableRemoteObject. narrow(browseSessionHomeRef, ejava.ejbch36.browse.BrowseSessionHome.class); initialContext.close(); System.out.println("Got Browse Session :"+ browseSessionHome); } return browseSessionHome; } … }

- 1199 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Our DisplayBrowsedShirts JSP invokes t he JSPHelper.getBrowseSessionHome() m et hod from inside of a getQueriedShirts() m et hod defined wit hin t he JSP. At t he t op of t he JSP, t his getQueriedShirts() m et hod is called t o receive and display a Vector of Serializable TShirt obj ect s. The EJB client invocat ions on t he BrowseSessionHome and BrowseSession obj ect int erfaces are creat ed like any ot her EJB client code. The reengineered DisplayBrowsedShirts JSP is shown here:







NO Shirts Match Your Query Criteria
Queried For :
SHIRT_SIZE :
SHIRT_COLOR :


- 1200 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The m eans by which EJB reference nam es are m apped t o point t o t he correct EJBs is a funct ion of configuring your web.xml file for t he JSP or Java Servlet as well as a funct ion of deploym ent t im e m apping of EJB nam es t o JNDI nam es. Recall t hat t he web.xml file has an elem ent under t he root elem ent . At a m inim um , t he elem ent defines t he EJB reference nam e wit hin an elem ent , t he t ype of EJB being referenced wit hin an elem ent , t he hom e int erface class nam e wit hin a elem ent , and t he rem ot e int erface class nam e wit hin a elem ent . As an exam ple, an EJB reference t o t he BrowseSession bean ut ilized in t he preceding code snippet s is defined wit hin t he web.xml file for t hese exam ples t his way:

- 1201 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



A description of EjbRefName ejb/browsesession Session ejava.ejbch36.browse.BrowseSessionHome ejava.ejbch36.browse.BrowseSession



Wit h such elem ent s defined, t he rem aining st ep is t o define t he m apping from t o a JNDI nam e and JNDI nam e service host / port during deploym ent t im e in a vendor- specific fashion. Such an EJB reference t o JNDI nam e m apping is needed if t he Web applicat ion m odule ( t hat is, deployed as WAR files) is not incorporat ed as par t of t he sam e J2EE ent erprise applicat ion ( t hat is, deployed as an EAR file) as was t he EJB m odule ( t hat is, deployed as EJB JAR files) cont aining t he referenced EJB. I f t he Web applicat ion m odule and EJB m odule are part of t he sam e deployed J2EE ent erprise applicat ion, t hen a special elem ent wit hin t he elem ent inside of t he web.xml file can be defined t o refer t o t he of t he part icular EJB wit hin t he EJB m odule. N ot e The deploym ent descript ors and build script s for creat ing t he Web client m odule and for building t he ent erprise applicat ion for t his int egrat ed BeeShirts.com applicat ion are cont ained on t he CD in t he examples/src/ejava/ejbch37/webclient direct ory. The web.xml file cont ains t he st andard Web m odule descript or. The weblogic_app.xml file cont ains st andard Web m odule descript or inform at ion for deploying t he JSPs t o BEA WebLogic. The application.xml and sun-j2ee-ri.xml files cont ain int egrat ed JSP/ EJB ent erprise applicat ion deploym ent descript ors in t he st andard descript or form and J2EE reference im plem ent at ion–specific deploym ent inform at ion, respect ively. A buildj2ee.bat sam ple Windows script induces t he creat ion of all EJB JAR files by calling buildj2eejars.bat. I t t hen creat es a WAR file and creat es t he st andard EAR file

- 1202 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

for t he J2EE reference im plem ent at ion. Not e t hat you m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb.properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. The buildweblogic.bat sam ple script is used t o build all code for BEA WebLogic. Not e t hat t he buildweblogic.bat sam ple script independent ly copies our Serializable ent it y classes t o t he [WEBLOGIC_HOME]\myserver\serverclasses direct ory and does not package t hese files inside of t he deployable WAR file. This st ep was t aken due t o a class cast ing issue t hat occurs as we have experienced wit h t he BEA WebLogic v5.1 server when such classes are packaged inside of t he WAR file. Appendix A, " Soft ware Configurat ion," describes t hese build and deploym ent procedures in m ore det ail. Not e also t hat we have included a WebLogic specific weblogic.xml file in t he examples/src/ejava/ejbch37/webclient direct ory as well. This file cont ains JNDI nam e m appings for EJB references ut ilized by t he web applicat ion code. At t he t im e of t his writ ing, BEA WebLogic did not provide a PUBLIC URL for use from wit hin t he DOCTYPE t o reference t he st ruct ure of t his file and also did not provide a public nam e for t his DTD. Thus, we had t o use a SYSTEM URI t o reference t he DTD t hat sit s in t he [WEBLOGIC_HOME]/classes/weblogic/servlet/internal/d d/weblogic-web-jar.dtd file equipped wit h t he BEA WebLogic inst allat ion. You t hus m ust m odify t he weblogic.xml file t o reference t he correct root WebLogic inst allat ion direct ory for your environm ent . For exam ple:

EJB/ CORBA Con n e ct ivit y There are t wo perspect ives from which we m ight consider using CORBA wit h EJBs. These t wo perspect ives are EJB as CORBA client and EJB as CORBA server. Being able t o im plem ent eit her one involves a com plet ely different set of problem s. EJBs act ing as

- 1203 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CORBA client s can sim ply ut ilize t he CORBA API s provided by Java I DL as a st andard API required for all J2EE environm ent s. However, because J2EE- com pliant EJB cont ainers do not allow EJBs t o creat e t heir own server socket s in order t o enable t he cont ainer t o be able t o m anage syst em resources, EJBs cannot creat e and regist er t heir own CORBA servers. Rat her, EJB developers m ust rely on t he capabilit y t o offer CORBA int erfaces t o t heir EJB com ponent s t o be provided by t he cont ainer/ server provider. This sect ion briefly discusses t he approach t o creat ing CORBA client s and servers wit h J2EE- com pliant EJBs. EJBs a s CORBA Clie nt s As we j ust m ent ioned, t he Java I DL API s com e equipped as a st andard part of all J2EE cont ainer/ server environm ent s. EJB com ponent developers can t hus creat e t heir own client int erfaces t o dist ribut ed CORBA servers operat ing in anot her environm ent t hat m ay or m ay not be anot her J2EE- com pliant environm ent . Furt herm ore, t he dist ribut ed CORBA server m ay even be im plem ent ed in anot her language. The m eans by which t hese CORBA client s are built follows t he sam e t echnique described in Chapt er 14, " Modeling Com ponent s wit h CORBA," and Chapt er 15, " CORBA Com m unicat ions." The only caveat for creat ing such CORBA client s from wit hin EJBs is t hat callbacks t o t he client cannot be passed t o t he CORBA server unless t he EJB cont ainer/ server im plem ent s t he EJB- t o- CORBA m apping as described in t he next sect ion. EJBs a s CORBA Se r ve r s The specificat ion t hat m ust be followed by EJB cont ainer/ server vendors want ing t o provide CORBA int erfaces t o EJBs is defined in t he Ent erprise JavaBeans t o CORBA Mapping specificat ion ( ht t p: / / j ava.sun.com / product s/ ej b/ docs.ht m l) . Alt hough t he J2EE v1.2 and EJB v1.1 does not require t hat vendors im plem ent t his specificat ion, a fut ure J2EE and EJB st andard version will likely require it s support . The EJB- t o- CORBA m apping defines a st andard m eans for EJB server environm ent s t o be able t o bet t er int eroperat e wit h ot her server environm ent s because st andard CORBA com m unicat ion prot ocols, nam ing, t ransact ion cont ext propagat ion, and securit y cont ex t propagat ion are scoped wit hin t he specificat ion. Two m ain t ypes of client s can access such CORBA- enabled EJB servers. An EJB/ CORBA client is a Java- based client t hat uses JNDI for EJB hom e lookups, relies on RMI / I I OP, and uses t he JTA UserTransaction API for any client - side t ransact ion dem arcat ion. A pure CORBA client im plem ent ed in any language can use

- 1204 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

CosNam ing for EJB hom e lookups, relies on CORBA/ I I OP and I DLbased int erfaces, and uses t he OTS for any client - side t ransact ion dem arcat ion. CORBA- com pliant J2EE EJB servers provide support for t hese t wo t ypes of client s in t he following four key ways: •







CORBA D ist r ibut ion: J2EE EJB servers provide support for pure CORBA/ I I OP com m unicat ion prot ocols. Rem ot e and hom e int erfaces for EJBs are m apped from Java t o I DL in a st andard fashion. Client s t hus ut ilize such I DL t o int eract wit h CORBA- enabled EJB com ponent s narrowing any references as necessary. I DL m appings exist for all st andard client - relat ed abst ract ions in a javax::ejb m odule, such as EJBHome, EJBObject, Handle, HomeHandle, and EJBMetaData. I DL m appings m ust also be generat ed for any applicat ion- specific EJB hom e and rem ot e int erfaces. Furt herm ore, I DL m appings also exist for all EJB except ions and m ust also be generat ed for any applicat ion- specific except ions. CORBA N a m ing: A CosNam ing- com pliant nam ing service m ust be provided by a J2EE EJB server for client s t o look up handles t o EJBHome int erface obj ect s. EJB/ CORBA client s can access t his nam ing service via JNDI wit h a CosNam ing SPI plug- in. Pure CORBA client s use t he CosNam ing service direct ly. When EJB JAR files are deployed t o a server, t hey are deployed specifying t he root CosNam ing cont ext from which t he nam es defined in t heir ejb-jar.xml file are relat ive. Exact ly how such a root cont ext is defined is vendor specific. CORBA Tr a nsa ct ions: A CORBA Obj ect Transact ion Service ( OTS) im plem ent at ion m ust be provided by a J2EE EJB server t o enable support for CORBA client s t o propagat e t heir t ransact ion cont ext during client - m anaged t ransact ion dem arcat ion. The I DL for t hose EJBs t hat perm it at least one m et hod t o be wrapped by client - side t ransact ion dem arcat ion ( t hat is, t ransact ional at t ribut es of Supports, Required, or Mandatory) m ust be generat ed such t hat t he EJB int erfaces inherit from CosTransactions:: TransactionalObject. EJB/ CORBA client s can use t he JTA UserTransaction obj ect t o dem arcat e t heir own t ransact ion boundaries, whereas pure CORBA client s can use CosTransactions::Current for pure CORBA t ransact ion dem arcat ion. CORBA Se cur it y: Exact ly how CORBA securit y cont ext is propagat ed is a funct ion of t he specific CORBA securit y prot ocol t hat is used. Securit y cont ext m ay be propagat ed via one of t he st andard CORBA Securit y m echanism s described in Chapt er 28, " CORBA Securit y."

Aft er a CORBA- com pliant J2EE EJB server is used t hat adheres t o t he preceding requirem ent s, EJB developers can deploy t heir beans

- 1205 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t o such servers and let t he plat form handle all CORBA connect ivit y. Developers can generat e t he I DL for t heir applicat ion- specific client int erfaces using a st andard Java- t o- I DL m apping t ool. From t he client side, CORBA client developm ent proceeds as usual wit h t he proper I DL files in hand.

EJB a n d XM L Alt hough J2EE deploym ent environm ent s m ust ut ilize XML for parsing J2EE st andard deploym ent descript ors, t here is no explicit requirem ent for J2EE v1.2 servers t o expose t he XML API t o developers. J2EE v1.3, however, is expect ed t o require support for t he Java API for XML Parsing ( JAXP) as described in Chapt er 31, " XML." Most J2EE cont ainer vendors eit her already offer such support or provide support t hrough an older version of t he JAXP. Nevert heless, t hese older JAXP versions differ only in t heir m eans for creat ing handles t o parsers and in t he way in which a parse is init iat ed. The bulk of XML API int erfacing via eit her DOM ( org.w3c.dom packages) or SAX ( org.xml.sax package) has rem ained unaffect ed bet ween older JAXP releases and t he lat est JAXP release. Thus, you m ight safely t ake advant age of such API s from wit hin your EJBs t o m anipulat e XML docum ent s com m unicat ed bet ween t he EJB and it s client s or bet ween t he EJB and ot her back- end servers. One of t he easiest ways t o accom plish t his t ask is t o send and receive XML docum ent s over t he wire as Java String obj ect s. When t he EJB is receiving an XML docum ent over t he wire, it can easily use st andard JAXP libraries t o parse t he received String int o a DOM Document obj ect . However, when any applicat ion m ust creat e XML docum ent String obj ect s, a nonst andard m echanism m ust current ly be im plem ent ed. An applicat ion can, of course, creat e t he String obj ect from scrat ch wit h proper insert ion of bracket s and ot her synt ax it em s at t he right point s during const ruct ion of t he docum ent String, but such an XML docum ent creat ion approach is prone t o error. You m ay t hus provide your own t echnique for creat ing t he docum ent using hom egrown serializat ion API s, or you m ay inst ead rely on som e vendor- specific m eans. As an exam ple, t he following snippet illust rat es how one m ight go about creat ing a st ringified XML docum ent using t he st andard JAXP org.w3.dom and javax.xml.parsers libraries t o creat e t he init ial docum ent st ruct ure in an ordered fashion and t hen relying on a vendor- specific conversion of t hat docum ent int o a String in a few sim ple lines of code:

- 1206 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public String returnXML() { String returnData = ""; try{ // get new instance of doc factory, and builder DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // Now get XML Document Document xmlDocument = documentBuilder.newDocument(); // Set XML Document with data Element root = xmlDocument.createElement("CREDITINFO"); Element cardelement = xmlDocument.createElement("CARD"); root.setAttribute("CUSTOMER_ID", "08910"); cardelement.setAttribute("CARD_TYPE", "CREDIT"); cardelement.setAttribute("CARD_NAME", "VISA"); cardelement.setAttribute("CARD_NUMBER", "1234567890"); cardelement.setAttribute("EXPIRE_DATE", "11/27/00"); xmlDocument.appendChild(root); root.appendChild(cardelement); returnData = xmlToString(xmlDocument); } catch(Exception e){ e.printStackTrace(); } // Return XML document as a String return returnData; } private String xmlToString(org.w3c.dom.Document xmlDocument) { // Write XML Document to StringWriter object and get as String java.io.StringWriter stringWriter = new java.io.StringWriter(); try{ // Write document as String using vendor-specific call com.sun.xml.tree.XmlDocument sunXmlDocument = (com.sun.xml.tree.XmlDocument) xmlDocument; sunXmlDocument.write(stringWriter); }

- 1207 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

catch(Exception e){ e.printStackTrace(); } return stringWriter.toString(); } Encapsulat ing t he vendor- specific code t hat convert s t he st andard Document obj ect int o a String wit hin a single m et hod will help reduce t he am ount of m aint enance involved in port ing your EJB. You also, of course, can im plem ent such funct ionalit y yourself t o assist wit h EJB port abilit y. I t is expect ed t hat st andard XML serializat ion libraries will also be released by Sun in t he fut ure. The receiving end of t he st ringified XML docum ent sent over t he wire in t he preceding exam ple can fully ut ilize t he st andard JAXP v1.0 libraries. As an exam ple, we first sim ply need t o parse t he st ringified XML docum ent as usual and t hen t raverse t he DOM st ruct ure t o ext ract t he dat a we desire, as shown here:

public String receiveXML(String document) { String returnData = ""; try{ // Create doc factory and builder DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setValidating(false); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); // Parse document String using InputSource on StringReader StringReader ris = new StringReader(document); org.xml.sax.InputSource is = new org.xml.sax.InputSource(ris); Document xmlDocument = documentBuilder.parse(is); // Get document data from parsed structure in elegant fashion Element documentElement = xmlDocument.getDocumentElement(); NamedNodeMap namedNodeMap = documentElement.getAttributes(); Node node = namedNodeMap.getNamedItem("CUSTOMER_ID"); String customerIDString = node.getNodeValue(); NodeList nodeList = xmlDocument.getElementsByTagName("CARD");

- 1208 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Node cardItem = nodeList.item(0); NamedNodeMap attributesMap = cardItem.getAttributes(); Node cardTypeNode = attributesMap.getNamedItem("CARD_TYPE"); Node cardNameNode = attributesMap.getNamedItem("CARD_NAME"); Node cardNumberNode = attributesMap.getNamedItem("CARD_NUMBER"); Node expirationDateNode = attributesMap.getNamedItem("EXPIRE_DATE"); // Set attribute data from XML message int customerID = Integer.parseInt(customerIDString); String cardType = cardTypeNode.getNodeValue(); String cardName = cardNameNode.getNodeValue(); String cardNumber = cardNumberNode.getNodeValue(); String expirationDateString = expirationDateNode.getNodeValue(); returnData = customerID + ":" + cardType + ":" + cardName + ":" + cardNumber + ":" + expirationDateString; } catch(Exception e){ e.printStackTrace(); } // Return a parsed concatenated String of the XML document info return returnData; }

EJB a n d JM S EJBs provide a purely synchronous call m odel for client s. That is, client s invoke EJB rem ot e m et hods, an associat ed EJB com ponent inst ance m et hod is invoked, t he m et hod ret urns, and any dat a is ret urned t o t he invoking client . We explored JMS's asynchronous calling m echanism s in Chapt er 22. Such services allow a producer t o subm it a m essage t o a queue or t opic allowing a m iddleware m essaging server t o figure out how and when t o send t his t o t he dist ribut ed consum er obj ect inst ance. Regardless, t he m essaging service event ually invokes a m et hod on t he consum er t o receive t he m essage. I n t he m eant im e, t he producer has gone about it s business and has not blocked wait ing for a response as is t he case wit h EJB synchronous calls. You m ay be wondering whet her it is possible or you m ay have encount ered a sit uat ion already in which you would like t o m erge

- 1209 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

t he ease of server com ponent developm ent provided by EJBs wit h t he asynchronous calling nat ure of JMS. Unfort unat ely, as of t he EJB v1.1 and J2EE v1.2 specificat ion, t here was no st andard way t o do t his. I n fact , t he J2EE v1.2 specificat ion requires only t hat vendors supply t he JMS v1.0 API , but no underlying JMS m essaging service im plem ent at ion is required. EJB v2.0 and J2EE v1.3 will, however, define a st andard way for EJBs t o act as JMS consum ers and t hus support t he capabilit y t o be invoked wit h asy nchronous calls via JMS. However, a st andard way for EJBs t o act as JMS producers and nonst andard m eans for EJBs t o act as JMS consum ers is possible if your cont ainer provides a JMS im plem ent at ion in addit ion t o t he required JMS API . EJB a s JM S Pr oduce r Let 's first cover t he m eans by which EJBs can act as JMS producers. Recall from our Chapt er 36 discussion t hat elem ent s defined wit hin eit her an or a elem ent in an ejb-jar.xml file are used t o define a reference t o an ext ernal resource. EJBs m ust obt ain handles t o JMS connect ion fact ory obj ect s via JNDI using nam es defined wit hin elem ent s as is t he case for obt aining JDBC DataSource obj ect s. Eit her javax.jms.QueueConnectionFactory or javax.jms.TopicConnectionFactory obj ect s are defined in t hese elem ent s. As an exam ple of how t o define such elem ent s for enabling nam ed access t o a TopicConnectionFactory from an EJB, we have t his:





Don and Judy Perrone's Shirts Supply jms/donAndJudyShirts javax.jms.TopicConnectionFactory Container





- 1210 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Looking up such a reference from wit hin an EJB is t hen a sim ple m at t er of looking up t he nam ed JMS connect ion fact ory resource reference like t his:

try{ Context context = new InitialContext(); TopicConnectionFactory factory = (TopicConnectionFactory) context.lookup("java:comp/env/jms/donAndJudyShirts"); TopicConnection topicConnection = factory.createTopicConnection(); TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); … // proceed as usual with JMS publishing } catch(Exception exception){ // handle any exceptions } The code required t o im plem ent such JMS producer funct ionalit y t hen proceeds as described in Chapt er 22. Such JMS producer funct ionalit y can com e in handy wit h EJBs t hat want t o com m unicat e wit h auxiliary ent erprise syst em s for B2B or ent erprise applicat ion int egrat ion as we'll describe in t he next chapt er. EJB a s JM S Consum e r As m ent ioned previously, no current st andard m eans is available for t urning EJBs int o JMS consum ers. Recall t hat consum er list eners are creat ed by calling setMessageListener (MessageListener) on a MessageConsumer list ener represent at ive. Defining your EJB com ponent im plem ent at ions t o im plem ent t he MessageListener int erface would be im proper because t hat would bypass t he required use of EJB rem ot e and hom e int erfaces by EJB client s t o t alk wit h your EJBs. I t is also not possible t o set your rem ot e int erface ont o t he MessageConsumer as a MessageListener because your rem ot e int erface m ust be ext ended from t he EJBObject int erface. Furt herm ore, m anagem ent of t ransact ions t hat em body bot h JMS and EJB operat ions is a t ricky issue t hat is current ly not required of J2EE vendors. Anot her m eans for host ing EJBs as JMS consum ers is current ly possible, however. I f your J2EE server vendor does im plem ent JMS, as does t he BEA WebLogic Server product on t he CD, t hen t here is a chance you will

- 1211 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

be able t o effect ively hand- code connect ivit y from JMS t o an EJB. The m eans by which t his is done sim ply involves creat ing an independent JMS consum er list ener t hat delegat es calls t o t he EJB. We include an exam ple on t he CD ext ended from t he BEA WebLogic Server docum ent ed approach in which asynchronous calls are m ade t o our CreditManagerSession EJB from a JMS delegat e. The JMSReceiver class im plem ent s t he MessageListener int erface and regist ers it self as a JMS t opic consum er. I t t hen im plem ent s t he MessageListener.onMessage() int erface t o receive a m essage and invoke an appropriat e call ont o our CreditManagerSession bean. N ot e All t he sam ple code st rewn t hroughout t his sect ion is placed on t he CD in t he examples/src/ejava/ejbch37/creditmgr direct ory. A st andard ejb-jar.xml deploym ent descript or file and WebLogic specific weblogic-ejb-jar.xml deploym ent descript or file are also provided. Addit ionally, a buildweblogic.bat sam ple Windows script can be used t o build our exam ple for BEA WebLogic. This exam ple depends upon t he Credit EJB from Chapt er 36. Thus, you will need t o have built and deployed t he CreditEJB.jar file ( t hat is, run t he examples/src/ejava/ejbch36/credit/ buildweblogic.bat exam ple script ) before running t his exam ple. The runJMSWeblogicClient.bat file is used t o init iat e a client t o t his exam ple. The weblogic.properties file for t his exam ple needs t o have t he following ent ries:

weblogic.ejb.deploy=} [WEBLOGIC_HOME]/myserver/CreditEJB.jar,} [WEBLOGIC_HOME]/myserver/CreditManager37EJB.jar

JMSReceiver also im plem ent s a vendor- specific weblogic.common.T3StartupDef int erface. The T3StartupDef int erface is im plem ent ed by special WebLogic st art up classes t hat are creat ed and invoked during st art up of t he BEA WebLogic Server. The JMSReceiver.startup() m et hod required by T3StartupDef invoked during st art up is in fact where we regist er t he JMSReceiver as a m essage list ener on a t opic nam e passed in as an init ializat ion param et er t o startup(). The JMSReceiver.startup() m et hod im plem ent at ion is shown here:

- 1212 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

public String startup(String name, Hashtable args) throws Exception { // JMS_TOPIC_NAME from weblogic.properties info for startup class String topicName = (String)args.get("JMS_TOPIC"); if ( topicName == null) { throw new RemoteException(" topicName="+topicName); } // Get context, look up connection factory, // create connection/session Context context = new InitialContext(); topicConnectionFactory = (TopicConnectionFactory) context.lookup("javax.jms.TopicConnectionFactory"); topicConnection = topicConnectionFactory.createTopicConnection(); topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); // Look up topic and create one if does not exist try { topic = (Topic) context.lookup(topicName); } catch (NamingException namingException) { topic = topicSession.createTopic(topicName); context.bind(topicName, topic); } // Create subscriber, set self as message listener, start listening topicSubscriber = topicSession.createSubscriber(topic); topicSubscriber.setMessageListener(this); topicConnection.start(); context.close(); return "ok"; } The BEA WebLogic Server is inform ed about use of t he JMSReceiver as a st art up class and configured t o pass in init ializat ion param et ers t o JMSReceiver.startup() from wit hin t he weblogic.properties file for t he server as shown here:

# Define JMSReceiver as startup class with init parameters shown here weblogic.system.startupClass.JMSReceiver=} ejava.ejbch37.creditmgr.JMSReceiver weblogic.system.startupArgs.JMSReceiver=}

- 1213 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JMS_TOPIC=JMS_CREDIT_TOPIC When t he JMSReceiver receives a t opic subscript ion post ed t o JMS by a producer, JMSReceiver.onMessage() is invoked wit h t he Message. The JMSReceiver t hen parses t his m essage dat a and uses it in a call t o our CreditManageSession bean j ust like any ot her EJB client t o our bean. The onMessage() m et hod im plem ent at ion is shown here:

public void onMessage(Message message) { try{ // Received text data String receivedData = ((TextMessage)message).getText(); System.out.println("JMS Message Received: "+ receivedData); // This method parses data from the String and sets private // credit data to be sent later on the JMSReceiver instance. extractValuesFromString(receivedData); // This method uses the private credit data to make a regular // EJB call onto the CreditManagerSession bean. submitCreditDataToCreditManager(); } catch(Exception exception){ exception.printStackTrace(); } } Our CreditManagerClient class int roduced in Chapt er 35 as an EJB client t o t he CreditManagerSession bean has been augm ent ed on t he CD for t his chapt er t o support pub lishing an asynchronous JMS m essage t o t he EJB. The runJMSWeblogicClient.bat sam ple script on t he CD can be used t o run t his client . A special stringpublisher flag and JMS_TOPIC set equal t o t he JMS_CREDIT_TOPIC propert y are passed int o t he com m and- line st art up of CreditManagerClient. This induces CreditManagerClient t o invoke runJMSTopicProducer(), which creat es t he init ial JMS connect ion, session, and m essage wrapper before invoking processCreditRecords(). The processCreditRecords() solicit s credit dat a input from st andard user input and publishes t he m essage dat a t o t he t opic list ened t o

- 1214 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

by JMSReceiver. The CreditManagerClient is t hus sim ply a regular st andalone JMS client as was dem onst rat ed in Chapt er 22.

EJB a n d Ja va M a il We also explored t he JavaMail v1.1 st yle of asynchronous m essaging in Chapt er 22. JavaMail provides API s t o send em ail via a m essaging t ransport and ret rieve em ail from a m essage st ore. The JavaMail v1.1 API is, in fact , required by J2EE v1.2 for EJB and Web cont ainers. However, im plem ent at ion support is required only for sending m ail via a JavaMail Transport. The capabilit y t o receive em ail via a JavaMail Store is not required. For t hat m at t er, t he capabilit y t o creat e t hreads used t o receive not ificat ion of JavaMail Folder, Store, and Transport event s will generally be forbidden by J2EE cont ainer environm ent s. Thus, we focus on t he sim ple m eans available for EJBs t o send em ail via t he JavaMail API s. This, of course, will be t he m ost com m on need for EJBs t o use JavaMail anyway for not ificat ion of cert ain applicat ion- specific event s. The elem ent s defined wit hin eit her an or a elem ent in an ejb-jar.xml file are also used t o configure handles t o JavaMail Session obj ect s t hat serve as fact ory obj ect s for Transport obj ect s. EJBs can use JNDI t o look up handles t o t hese Session obj ect s aft er t hey're configured. N ot e This sect ion cont ains a few sim ple code snippet s t hat can be found on t he CD in t he code cont ained wit hin t he examples/src/ejava/ejbch37/authenticationsession direct ory.

Our AuthenticationSession bean, in fact , defines a JavaMail fact ory reference from wit hin it s ejb-jar.xml file as shown here:





Mail Session Reference mail/BeeShirtsMailSession

- 1215 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

javax.mail.Session Container





The dist ribut ed remindPassword() m et hod im plem ent at ion on our AuthenticationSessionEJBean class first finds a Customer ent it y bean based on an em ail address String, finds an Authentication ent it y bean based on a cust om er I D from Customer, and t hen invokes a sendMail() m et hod on a special MailSender helper class as shown here:

public boolean remindPassword(String email) { // get password and send Email lookupCustomerHome(); System.out.println("Customer Home :"+customerHome); // uniqueness constraint on email attribute associated // with customer in database enables us to get first and // only customer associated with this email Enumeration customers = customerHome.findByEmail(email); Customer customerBean = null; if(customers.hasMoreElements()){ customerBean = (Customer) customers.nextElement(); } System.out.println("Customer Bean :" +customerBean); if(customerBean == null){ return false; } // look up AuthenticationHome lookupAuthenticationHome(); Authentication authenticationBean = authenticationHome.findByPrimaryKey(customerBean.getID()); String password = authenticationBean.getPassword(); // send email MailSender.sendMail(email,password); … }

- 1216 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Finally, t he MailSender.sendMail() ut ilit y m et hod handles t he Session lookup from t he J2EE environm ent , creat ing t he em ail m essage and sending it t o t he cust om er as shown here:

package ejava.ejbch37.authenticationsession;

… public class MailSender { /** send email to the user to remind them of their password */ public static void sendMail(String toAddress, String password) { // Look up JavaMail Session reference Session session = null; try{ InitialContext context = new InitialContext(); session = (Session) context.lookup("java:comp/env/mail/BeeShirtsMailSession"); session.setDebug(true); } catch(NamingException namingException){ namingException.printStackTrace(); } // Get Mail Session try { // Create E-mail Message Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); InternetAddress[] address = { new InternetAddress(toAddress)} ; message.setRecipients(Message.RecipientType.TO, address); message.setSubject("Password Reminder"); message.setSentDate(new Date()); message.setText("Your BeeShirts.com password :" + password); // Send E-mail Message Transport.send(message); } catch (MessagingException messagingException) { messagingException.printStackTrace();

- 1217 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

} } }

Con clu sion s This chapt er illust rat ed how EJB relat es t o m any of t he key t echnologies described t hroughout t he book t hus far. I n som e inst ances, use of such t echnologies is sim plified by t he J2EE EJB cont ainer m odel. I n ot her cases, t he current st at e of J2EE and EJB specificat ion developm ent can st ill result in eit her t he use of vendor- specific int erfaces or a lit t le hand- coding t o m ake ut ilizat ion of t hese t echnologies wit h EJB a realit y. I n all cases, fut ure specificat ions are already in t he works t o m ake t he use of t hese t echnologies m uch easier from wit hin EJB and general J2EE cont ainer environm ent s. However, let 's sum m arize what is available now ( at t he t im e of t his writ ing) . EJB t ransact ions are perhaps int egrat ed t he best of all t echnologies m ent ioned in t his chapt er. EJB securit y can provide som e m inim al declarat ive access cont rol support , but real- world code will alm ost cert ainly ut ilize hand- coded or vendor- specific aut hent icat ion and m ore sophist icat ed access cont rol m odels. We have also seen a good exam ple of how easily t he J2EE Web t ier can int egrat e wit h t he EJB applicat ion t ier. Alt hough EJB- t o- CORBA m apping is fairly st raight forward and st andardized, int egrat ing CORBA client s wit h an EJB fram ework st ill relies on support being provided by t he cont ainer vendor. XML is not a current required J2EE API , but developers m ay t ap t he services of an XML parser t o send st ringified XML docum ent s wit h m inim al vendor specific or handcoded help and receive st ringified XML docum ent s using st andard JAXP calls. Finally, bot h JMS and JavaMail can be used t o send m essages in t heir specific m essaging genre from wit hin EJBs. Receiving m essages via JMS, however, will require som e handcoding and perhaps a lit t le vendor- specific support .

Ch a pt e r 3 8 . En t e r pr ise Applica t ion I n t e gr a t ion I N TH I S CH APTER • • • • • •

Ent erprise Applicat ion I nt egrat ion Overview EAI wit h JNI EAI wit h Dist ribut ed Ent erprise Com m unicat ion Paradigm s EAI wit h Messaging Services and JMS EAI wit h XML EAI wit h J2EE Connect ors

- 1218 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE



Em bedded Applicat ions I nt egrat ion

The int egrat ion of auxiliary and legacy ent erprise applicat ions wit h your Java ent erprise applicat ions is a problem t hat is generally addressed by ent erprise applicat ion int egrat ion ( EAI ) solut ions. EAI involves providing t ools, t echniques, and t echnologies for int egrat ing ent erprise dat a and applicat ion logic from disparat e syst em s. EAI can be part it ioned int o t hose int egrat ion effort s int ernal t o an ent erprise and t hose t hat ext end beyond a single ent erprise int o m ore business- t o- business ( B2B) specific arenas. This chapt er describes how m any of t he Java ent erprise t echnologies already described t hroughout t he book can be put t o work in providing int ernal and ext ernal EAI and B2B solut ions. We also int roduce a few new Java- based t echnologies t hat can be used for t his sam e purpose. I n t his chapt er, you will learn: • • • • • • •

The general problem s addressed by and solut ions provided by EAI . The approach for int egrat ing nat ive code via t he Java Nat ive I nt erface ( JNI ) as an int ernal EAI solut ion. The approach for int egrat ing applicat ions via dist ribut ed com m unicat ions t echnologies such as TCP/ I P, HTTP, CORBA, RMI , and DCOM. The approach for int egrat ing int ernal and ext ernal applicat ions via JMS. The approach for int egrat ing int ernal and ext ernal applicat ions via XML. The archit ect ure behind J2EE Connect ors for EAI t o be int roduced wit h t he J2EE v1.3. The em bedded Java t echnologies t hat m ay be used t o int egrat e em bedded applicat ions wit h your Java ent erprise applicat ions.

En t e r pr ise Applica t ion I n t e gr a t ion Ove r vie w Alt hough t his book has focused on how t o build new ent erprise applicat ions, m any ent erprise applicat ion developm ent problem s also involve int egrat ing wit h auxiliary or legacy ent erprise applicat ions. A significant port ion of overall developm ent t im e can, in fact , revolve around int egrat ion wit h ot her ent erprise applicat ions. Figure 38.1 depict s a very sim plified view of t he problem and Ent erprise Applicat ion I nt egrat ion solut ion. Here we see a legacy/ auxiliary ent erprise applicat ion on t he right side of t he diagram t hat we want t o int egrat e int o our Java ent erprise applicat ions. EAI involves solving t he problem regarding how t o

- 1219 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

int egrat e t he dat a and logic of such legacy/ auxiliary syst em s int o t he fram ework of your current and fut ure- generat ion ent erprise syst em s. Figur e 3 8 .1 . Ent e r pr ise a pplica t ion int e gr a t ion.

N ot e The Sun J2EE specificat ions and lit erat ure oft en refer t o t hese legacy/ auxiliary ent erprise applicat ions as ent erprise inform at ion syst em s ( EI Ss) .

When legacy/ auxiliary ent erprise applicat ions are int ernally m anaged by an ent erprise, we have an int ernal EAI problem t hat can offer m ore flexibilit y and cont rollabilit y over how a solut ion m ay be provided. When legacy/ auxiliary ent erprise applicat ions sit ext ernal t o an ent erprise, t hese ext ernal EAI problem s can becom e significant ly m ore com plicat ed because m ult iple ent erprise organizat ions m ust agree and com e t o som e consensus on how t heir syst em s will int egrat e. Such, however, are oft en t he problem s of business- t o- business ( B2B) applicat ions t hat m ust decide how t o exchange ent erprise dat a. EAI solut ions involve various t echnologies, t echniques, and product s t o enable one ent erprise syst em t o int egrat e wit h t he dat a and logic of anot her. Alt hough m any EAI solut ions involve t he use of quasiaut om at ed product s for int egrat ing one syst em wit h anot her, m ost t echniques st ill require a significant am ount of auxiliary engineering effort in addit ion t o t he need for t he purchase of addit ional COTS product s. Many EAI solut ions also perform int egrat ion at t he dat a level by t ransform ing dat a from one ent erprise syst em int o dat a used by anot her ent erprise syst em . Alt hough use of such EAI solut ions m ay be warrant ed in som e cases, a discussion of t heir use is out side t he scope of t his book. What we inst ead will do in t his

- 1220 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

chapt er is describe how you m ight provide EAI for your Java ent erprise applicat ions using Java t echnologies and t herefore m any of t he Java ent erprise t echnologies we have already described in t his book.

EAI w it h JN I The Java Nat ive I nt erface ( JNI ) , as illust rat ed in Figure 38.2, is built int o t he st andard Java plat form and provides a m eans for enabling Java code t o direct ly int eract wit h shared binary libraries nat ive t o a part icular operat ing syst em and hardware plat form . This int eract ion occurs wit hin t he sam e JVM process in which calls m ade from Java classes t o Java m et hods t agged as " nat ive" get m apped t o funct ion calls in a shared binary library loaded int o t he sam e process space. At t he Java level, pure Java code is oft en im plem ent ed above Java wrappers t hat pro vide t he nat ive code linkage from Java. I nside of t he shared library, special JNI t ypes are defined t o m ap from t he Java plat form t ype syst em t o t he nat ive plat form and language t ype syst em . The languages used t o im plem ent t hese shared libraries t o int erface wit h Java are m ost oft en C or C+ + based languages ( alt hough m eans for linking in assem bly and ot her language- based libraries do exist ) . Figur e 3 8 .2 . The Ja va N a t ive I nt e r fa ce ( JN I ) a r chit e ct ur e .

- 1221 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JNI can t hus provide one m eans for you t o int egrat e legacy applicat ion code im plem ent ed in ot her languages int o your Java ent erprise applicat ions. A com m on scenario encount ered by m any organizat ions is t he exist ence of legacy applicat ion code t hat can be used for a part icular ent erprise applicat ion. Rewrit ing t hat code in Java t o int egrat e it wit h your Java ent erprise environm ent m ay be t oo t im e- consum ing or perhaps undesirable. The con wit h using JNI , however, is t hat m em ory and t hreading resources inside of Java and m em ory and t hreading resources inside of t he shared library code are m anaged in disparat e fashions. Thus, use of JNI m ust proceed wit h caut ion, and you m ust consider t he ram ificat ions of such resource im pedance m ism at ch when using JNI . Nevert heless, JNI m ay oft en represent t he sim plist ic and m ost direct rout e for int egrat ing ent erprise Java wit h legacy code. This is especially t rue if t hat legacy code is fairly st at eless, consum es m inim al m em ory resources, and relies on only a sm all am ount of int eract ion across t he JNI boundary. Creat ing JNI - based bridges t o nat ive code from Java is sim plified if t he t arget nat ive plat form language is C or C+ + due t o t he alreadyavailable support provided by t he Java plat form for such bridging. The st eps involved wit h creat ing JNI - based bridges are list ed here: 1. D e fine a Ja va W r a ppe r Cla ss: The first st ep is t o define a Java class t hat will isolat e your int erface t o nat ive code from your pure Java code. We assum e t he exist ence of a sam ple wrapper here for illust rat ion purposes: 2. 3. package ejava.eaich38.jni; 4. 5. public class MyNativeWrapper { … } 6. D e fin e Syst e m Libr a r y Loa din g: We next need t o creat e a st andard Java class t hat loads t he t arget shared library. A com m on m eans for doing t his is t o insert a System.loadLibrary() st at em ent wit hin a static init ializer inside of your Java wrapper class. The nam e passed t o loadLibrary() is oft en t he ext ension- less form of your plat form 's library nam e. For exam ple, as shown here inside of MyNativeWrapper on a Windows plat form , we ant icipat e loading a MyNativeLibrary.DLL file like t his: 7. 8. static 9. { 10. // Try to load native library. 11. try{ 12. System.loadLibrary("MyNativeLibrary"); 13. } 14. catch(UnsatisfiedLinkError error){

- 1222 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

15. System.out.println("Error loading library."); 16. error.printStackTrace(); 17. } 18. } 19. D e fine N a t ive M e t hods: Your Java wrapper should t hen define as native t hose m et hods t hat will delegat e t o t he ext ernal shared library funct ion calls as shown here inside of our MyNativeWrapper class: 20. 21. public synchronized native void myNativeCall(String myParams) 22. throws UnsatisfiedLinkError; 23. public synchronized native int myOtherNativeCall(String hello) 24. throws UnsatisfiedLinkError; 25. public synchronized native int myOtherNativeCall(int hello) 26. throws UnsatisfiedLinkError; 27. public synchronized native int myOtherNativeCall(float hello) 28. throws UnsatisfiedLinkError; 29. Com pile Ja va W r a ppe r s: Your Java wrappers m ust now be com piled using a st andard Java com piler ( for exam ple, javac) . 30. Cr e a t e N a t ive H e a de r File s: The javah ut ilit y t hat com es wit h t he J2SE SDK can be execut ed wit h t he com piled Java wrapper class files t o generat e header files t hat im plem ent t he nat ive m et hod signat ures. The javah ut ilit y is invoked wit h a list of fully qualified Java wrapper class nam es and a few opt ions t hat offer a lit t le cont rol over how your header files are generat ed. As an exam ple, using javah wit h our MyNativeWrapper class is as sim ple as shown here: 31. 32. javah ejava.eaich38.jni.MyNativeWrapper 33. Cr e a t e N a t ive La ngua ge I m ple m e nt a t ion: The javah com m and will generat e a header file wit h a nam e t hat is an underscore- separat ed series of package nam e elem ent s and t he class nam e associat ed wit h t he Java wrapper ( for exam ple, ejava_eaich38_jni_MyNativeWrapper.h) . This file m ust be included by t he im plem ent at ion class, which m ust provide im plem ent at ions of t he prot ot ype funct ions defined in t he header file. The funct ion nam es will look like t he header filenam e wit h t he except ion t hat a Java_ nam e is used as a prefix, and t he associat ed m et hod nam e from which it is m apped is appended t o t he funct ion nam e. Addit ional ident ifiers associat ed wit h m et hod param et ers m ay also be t acked ont o t he funct ion nam es if m et hods are overloaded.

- 1223 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

For exam ple, we m ight define a sim ple MyNativeWrapperImpl.c file as shown here: 34. 35. #include 36. #include 37. 38. #include "ejava_eaich38_jni_MyNativeWrapper.h" 39. 40. /** Impl each ejava.eaich38.jni.MyNativeWrapper.myOtherNativeCall() */ 41. JNIEXPORT jint JNICALL 42. Java_ejava_eaich38_jni_MyNativeWrapper_myOtherNative Call__F 43. (JNIEnv *env, jobject object, jfloat myFloat) 44. { printf("Called myOtherNativeCall(float)"); return 0; } ; 45. 46. JNIEXPORT jint JNICALL 47. Java_ejava_eaich38_jni_MyNativeWrapper_myOtherNative Call__I 48. (JNIEnv *env, jobject object, jint myInt) 49. { printf("Called myOtherNativeCall(int)"); return 0; } ; 50. 51. JNIEXPORT jint JNICALL 52. Java_ejava_eaich38_jni_MyNativeWrapper_myOtherNative Call __Ljava_lang_String_2 53. (JNIEnv *env, jobject object, jstring myString) 54. { printf("Called myOtherNativeCall(String)"); return 0; } ; 55. 56. 57. /** Impl of ejava.eaich38.jni.MyNativeWrapper.myNativeCall() */ 58. JNIEXPORT void JNICALL 59. Java_ejava_eaich38_jni_MyNativeWrapper_myNativeCall 60. (JNIEnv *env, jobject object, jstring str) 61. { 62. jboolean strCopy; 63. const char *strPtr = (*env)>GetStringUTFChars(env, str, &strCopy); 64. printf("Called myNativeCall(%s)", strPtr); 65. (*env)->ReleaseStringUTFChars(env, str, strPtr); 66. return; 67. } ;

- 1224 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

68. Com pile I m ple m e nt a t ion a nd Cr e a t e Sha r e d Libr a r y: The nat ive language im plem ent at ions t hen need t o be com piled and any necessary shared libraries creat ed. On a Windows plat form , for exam ple, we m ight com pile our MyNativeWrapper.c im plem ent at ion and generat e a MyNativeLibrary.DLL. 69. Ex e cut e t he Ja va Applica t ion: A Java applicat ion is t hen execut ed as norm al. Not e, however, t hat t he shared library should be placed in t he library pat h of your Java applicat ion. The library pat h search m echanism is plat form specific. For Windows plat form s, we sim ply m ust m ake sure t he MyNativeLibrary.DLL is in our PATH. Calls t o such nat ive m et hods m ay be as sim ple as shown here: 70. 71. System.out.println("Beginning MyNativeWrapper Test"); 72. MyNativeWrapper wrapper = new MyNativeWrapper(); 73. wrapper.myNativeCall("Hello Bedford Falls!"); 74. wrapper.myOtherNativeCall("Hello You Ole'Building and Loan!"); 75. wrapper.myOtherNativeCall(4); 76. wrapper.myOtherNativeCall((float)4.0); 77. System.out.println("Ending MyNativeWrapper Test"); As a final not e, we close our short JNI discussion here wit h a brief com m ent about how t o properly define Java wrapper m et hod signat ures and how t o m anipulat e t he abst ract ions t hat funnel t hrough t o t he nat ive language side. This requires an underst anding of how Java t ypes and nat ive language t ypes m ap bet ween one anot her. The [JAVA_HOME]\include\jni.h file defines t he C language t ypes t hat m ap from m any Java- specific t ypes. All fundam ent al Java t ypes m ap t o a C t ype of t he sam e nam e wit h a j prepended ( for exam ple, jint, jfloat, jboolean) . Addit ionally, special C language t ypes are defined for part icular Java obj ect t y pes, including jstring for a Java String, jobject for a Java Object, jclass for a Java Class, jthrowable for Java except ions, and jArray t ypes for Java arrays of each Java fundam ent al t ype ( for exam ple, jintArray for arrays of fundam ent al int t ypes) .

EAI w it h D ist r ibu t e d En t e r pr ise Com m u n ica t ion Pa r a digm s I n t he preceding sect ion, we briefly explored t he use of JNI as an EAI solut ion suit able for fairly sim ple int egrat ion effort s involving well- defined auxiliary non- Java–based com ponent int erfaces. However, use of JNI represent s a purely nondist ribut ed approach t o EAI .

- 1225 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Som e ent erprise environm ent s, as illust rat ed in Figure 38.3, dem and dist ribut ed access t o services provided by part icular auxiliary ent erprise applicat ions. Many of t he dist ribut ed ent erprise com m unicat ions enabling paradigm s described in Part I I I , " Dist ribut ed Ent erprise Com m unicat ions Enabling," will t hus becom e applicable when such needs arise. Furt herm ore, a few of t hese dist ribut ed com m unicat ion approaches can be im plem ent ed direct ly from t he vant age point of a J2EE EJB com ponent , as you saw in Chapt er 37, " Advanced Ent erprise JavaBeans Serving," or from J2EE Web com ponent s. This sect ion briefly explains t hose approaches and considerat ions for using dist ribut ed ent erprise com m unicat ion paradigm s when providing EAI connect ivit y bet ween auxiliary or legacy ent erprise applicat ions and your Java ent erprise applicat ions. Figur e 3 8 .3 . EAI w it h dist r ibu t e d com m u n ica t ion pa r a digm s.

EAI w it h TCP/ I P As you saw in Chapt er 12, " Net work Com m unicat ions," use of TCP/ I P in Java ent erprise environm ent s can be a cost ly solut ion in t erm s of t im e spent coding, but it m ay be t he only dist ribut ion m echanism possible for cert ain environm ent s. I t is t hus at least im port ant t o consider how TCP/ I P can be used t o connect auxiliary ent erprise applicat ions t o your Java ent erprise applicat ions. An auxiliary or legacy applicat ion m ay already provide or be adapt able t o support a TCP/ I P- based int erface for t apping it s services. However, TCP/ I P- based support m ay not already be provided or a non- Java–based language m ay have been used t o im plem ent t he auxiliary applicat ion. I n such cases, JNI wit h Javabased TCP/ I P or t he nat ive language wit h nat ive socket libraries m ay be used t o im plem ent t he auxiliary ent erprise applicat ion dist ribut ed TCP/ I P int erface. I n eit her case, any Java ent erprise applicat ion, J2EE or st andalone, can act as a TCP/ I P client t o t his dist ribut ed auxiliary ent erprise applicat ion int erface using t he java.net libraries described in Chapt er 12. J2EE EJB com ponent s, however, would not be able t o support a socket callback m echanism

- 1226 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

if it were needed wit hout any cont ainer- provided support for such a feat ure. I n addit ion t o EJB rest rict ions, TCP/ I P- based EAI has plent y of ot her lim it at ions. One not able lim it at ion relat es t o t he significant am ount of hand- coding t hat m ust oft en be perform ed t o im plem ent cust om m arshaling and unm arshaling and ot her high- level prot ocol feat ures. I n general, TCP/ I P will be useful only when t he dist ribut ed auxiliary applicat ion requires a sim ple int erface or when lim it ed COTS m akes em ploying an auxiliary dist r ibut ed com ponent t echnology im possible. EAI w it h H TTP Alt hough HTTP has a focused Web- based applicabilit y, HTTP can be useful in low- cost EAI solut ions as well. Of course, any low- level program m ing of request and response handling via HTTP begins t o lose it s low- cost appeal if t he EAI solut ion is anyt hing but sim ple. Nevert heless, cert ain EAI solut ions are indeed sim ple. I n such cases, creat ing sim ple HTTP servers t o im plem ent GET funct ionalit y can be very st raight forward. Using t he java.net libraries described in Chapt er 12, a sim ple hom egrown HTTP server can be m ade t hat creat es a single ServerSocket obj ect t o block for incom ing client request s using accept(). The ret urned client Socket obj ect s can t hen be handed off t o a cust om server Thread, and t he list ener can go about it s business list ening for m ore incom ing socket request s. The cust om server Thread, however, can read HTTP request dat a from t he client using t he InputStream ret urned from Socket.getInputStream() and send any HTTP response dat a back t o t he client via an OutputStream ret urned from Socket.getOutputStream(). The cust om server Thread m ust parse any HTTP request dat a and subm it it t o t he legacy/ auxiliary applicat ion and t ransform any response from t he legacy/ auxiliary applicat ion int o HTTP response dat a. Thus, t he cust om server Thread m ust have int im at e knowledge of how t o parse HTTP request dat a and generat e HTTP response dat a at t he byt e level, which is largely why such cust om HTTP serving will oft en be pract ical only in t he sim plest of EAI cases. Of course, one of t he COTS- based Web- enabling solut ions of Part VI , " Ent erprise Web Enabling," m ay be also be used on t he legacy/ auxiliary applicat ion end t o offer EAI via HTTP. On t he HTTP client end of EAI , m any opt ions are available t o our Java ent erprise applicat ions. Because HTTP and sim ple HTTP client abst ract ions are built int o t he J2SE, bot h st andalone Java applicat ions and J2EE- based com ponent s can easily t ap t he services of a legacy/ auxiliary applicat ion int egrat ed wit h HTTP. As m ent ioned

- 1227 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

in Chapt er 13, " Web Com m unicat ions," t he st andard java.net.HttpUrlConnection and java.net.URL classes can be used as t he basis for building basic Web client funct ionalit y int o Java applicat ions. Connect ions can be creat ed, HTTP request s can be issued, and HTTP responses can be received using t hese t wo abst ract ions. J2EE cont ainer environm ent s have life a lit t le easier because handles t o java.net.URL fact ories for URL connect ions can be obt ained direct ly from JNDI using resource references. That is, say t hat we have a URL fact ory defined inside of a J2EE XML- based deploym ent descript or as shown here:

My URL Connection Factory url/MyHttpEAIServer java.net.URL Container

Then we can obt ain a handle t o such fact ories as shown here:

InitialContext ctx = new InitialContext(); java.net.URL myHttpEAIServer = (java.net.URL) ctx.lookup("java:comp/env/url/MyHttpEAIServer"); Of course, a cont ainer- specific way t o associat e such URL fact ory references t o rem ot e host s and port s m ust also be provided. Aft er t hat , your EJBs, Java Servlet s, and JSPs are in business for int egrat ing wit h a rem ot e applicat ion over HTTP. EAI w it h CORBA The m ost significant t echnique for im plem ent ing EAI over a dist ribut ed com m unicat ions paradigm is via CORBA. As described in Chapt er 14, " Modeling Com ponent s wit h CORBA," and Chapt er 15, " CORBA Com m unicat ions," CORBA is a language- and plat form independent solut ion for enabling dist ribut ed com m unicat ions. Thus, providing CORBA- based int erfaces t o auxiliary and legacy applicat ions enables a very high level of EAI wit h ot her applicat ions. On t he legacy/ auxiliary ent erprise applicat ion side, a nat ive language CORBA wrapper im plem ent at ion around t he applicat ion m ay be provided wit h dist ribut ed int erfaces defined via CORBA I DL. Alt ernat ively, JNI wit h Java can be used t o bridge t he auxiliary applicat ion locally wit h t he dist ribut ed CORBA int erface

- 1228 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

im plem ent ed via Java I DL or a com m ercial Java- based CORBA ORB im plem ent at ion. Regardless of whet her Java is used as a bridging t echnology on t he auxiliary ent erprise applicat ion side, t he int erface t o t he applicat ion is via I DL. Therefore, we can speak t o such applicat ions from wit hin st andalone Java applicat ions using Java I DL or a com m ercial ORB, and we can also speak t o such applicat ions from a J2EE EJB or Web com ponent . J2EE com ponent s, however, cannot im plem ent any sort of CORBA server callback m echanism due t o t he rest rict ions on creat ing server socket s in J2EE environm ent s by a com ponent . Of course, as described in Chapt er 37, a CORBA- enabled EJB can be defined in J2EE cont ainer environm ent s t hat support CORBA- t o- EJB m appings. EAI w it h RM I RMI , as described in Chapt er 16, " RMI Com m unicat ions," can also be used as a dist ribut ed EAI - enabling paradigm in cert ain cases. The st rong case for RMI on t he Java ent erprise applicat ion side is t hat m axim um int eroperabilit y is guarant eed wit h all J2EE EJB environm ent s because RMI is t he st andard EJB int erface t echnology. Callbacks t o EJBs over RMI are t hus a m at t er of im plem ent ing regular EJB client int erfacing on t he legacy/ aux iliary applicat ion side. RMI on t he legacy/ auxiliary applicat ion end m eans t hat JNI bridging will be needed if t he applicat ion is im plem ent ed in anot her language. Alt hough access from t he Java ent erprise applicat ion t ier m ay be sim plified in t his scenario, access t o your legacy/ auxiliary applicat ion from ot her ent erprise applicat ion environm ent s is lim it ed t o Java- based applicat ions t hat can use RMI . EAI w it h D COM As a final not e about dist ribut ed com m unicat ions enabling, we feel com pelled t o m ent ion t he part icular applicabilit y of DCOM in such scenarios. I f you are st ill puzzling over Chapt er 17, " Modeling Com ponent s wit h COM/ DCOM," and Chapt er 18, " DCOM Com m unicat ions," and wondering why we would ever t alk about COM/ DCOM in a Java ent erprise book, t hen we hope t he need can be finally clarified here when cast in t he light of t his chapt er's EAI t opic. When a Windows- based plat form host s your legacy/ auxiliary ent erprise applicat ion, DCOM m ay be your best bet for im plem ent ing connect ivit y of t hat applicat ion wit h your Java ent erprise applicat ion environm ent . Use of DCOM on t he auxiliary Windows- based applicat ion side t o provide a dist ribut ed int erface will allow you t o easily use what ever libraries and languages were used t o build t he original applicat ion.

- 1229 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Alt hough st andalone Java- based COM/ DCOM client s can be built on t he Java ent erprise side, you are also locked int o Windows- based plat form s if you use t he Microsoft JVM. However, som e J2EE cont ainer/ server vendors offer COM connect ivit y as a value- added service above and beyond t he st andard J2EE requirem ent s. Access t o EJBs as COM obj ect s is possible via som e vendor product s such as t he BEA WebLogic Server equipped wit h t his book. BEA WebLogic also allows for COM com ponent s t o be m ade accessible from Java com ponent s via WebLogic's own RMI im plem ent at ion. See ht t p: / / www.weblogic.com / docs50/ classdocs/ API _com .ht m l for m ore inform at ion on how t he BEA WebLogic product equipped wit h t his book int egrat es COM wit h it s Web and applicat ion server product s.

EAI w it h M e ssa gin g Se r vice s a n d JM S The dist ribut ed com m unicat ion paradigm s used for EAI all depend on t he capabilit y t o m ake synchronous calls ont o t he legacy/ auxiliary ent erprise applicat ions t hat are t o be int egrat ed. Such an approach t o EAI m ay be best suit ed for part icular int ernal EAI proj ect s as opposed t o ext ernal EAI or B2B proj ect s. When t he need arises t o perform ext ernal EAI , an asynchronous m essaging schem e is alm ost always t he best opt ion. As described in Chapt er 22, " Messaging Services," asynchronous m essaging schem es allow for a great er level of decoupling bet ween syst em s and also allow for t he cent ralized m anagem ent of reliable and robust m essage queuing by t he m essaging service provider. Of course, wit hin J2EE and Java ent erprise environm ent s, JMS is t he m essaging service t echnology of choice. Alt hough Chapt er 22 describes how t o im plem ent st andalone JMS consum ers and producers, Chapt er 37 describes t he pot ent ial for using JMS wit h J2EE EJBs based on t he current st at e of t he J2EE v1.2 specificat ion and based on a fut ure J2EE v1.3 specificat ion. Figure 38.4 shows t he basic archit ect ure for using JMS in an EAI solut ion. Because of JMS's underlying Service Provider I nt erface ( SPI ) –based archit ect ure, our Java ent erprise applicat ions can be built t o readily int egrat e wit h any part icular vendor's m essaging service im plem ent at ion t hat provides a JMS SPI im plem ent at ion. Thus, if our auxiliary ent erprise applicat ion is ext ernal t o our organizat ion, t he part icular m essaging syst em provided by t he auxiliary syst em m ay be easily int egrat ed wit h our Java ent erprise applicat ion. Furt herm ore, t he opt ions for int egrat ing t he legacy/ auxiliary ent erprise applicat ion ( if t hat is indeed also your part icular problem t o solve) are const rained only by t he availabilit y of a m essaging service int erface for t he auxiliary applicat ion language and plat form . Of course, t he auxiliary applicat ion m ay also

- 1230 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

decide t o use JMS as it s int erface t o an underlying m essaging service provider. Figur e 3 8 .4 . EAI w it h JM S.

Wit h JMS, all Java ent erprise applicat ions can act as JMS producers wit h no problem s. Java ent erprise applicat ions built as J2EE EJB com ponent s, however, current ly have lim it at ions wit h J2EE v1.2– based cont ainers in t erm s of direct ly being able t o host EJBs as JMS con sum ers. Rat her, a separat e JMS consum er delegat e t o an EJB is needed. The J2EE v1.3–based cont ainers, however, will enable full int egrat ion bet ween EJB and JMS.

EAI w it h XM L As described in Chapt er 31, " XML," XML is t he dat a represent at ion t echnology of choice for Java ent erprise environm ent s. XML is also t he em erging dat a represent at ion t echnology of choice am ong m ost ot her ent erprise applicat ion environm ent s. XML is part icularly at t ract ive t o EAI vendors and is alm ost always incorporat ed int o EAI product vendor archit ect ures. XML is used t o represent t he dat a t hat is t ransferred from one syst em t o anot her and t hus becom es t he st andard language used for passing m essages when pursuing EAI . St andard DTDs for int erpret ing exchanged XML docum ent s can be defined and shared bet ween syst em s t hat want t o be int egrat ed. A m eans for t ransform ing XML docum ent s from one syst em 's dialect t o anot her syst em 's dialect can also be achieved using t echnologies such as XSLT. Figure 38.5 depict s t he basic archit ect ure for int egrat ing your Java ent erprise environm ent wit h a legacy/ auxiliary ent erprise applicat ion environm ent via XML. A legacy/ auxiliary ent erprise applicat ion m ust eit her already have or be ext ended wit h an XML docum ent builder/ parser for const ruct ing and parsing XML

- 1231 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

docum ent s. Such product s are already very m uch com m ercially available for m ost plat form s wit h API s in various program m ing languages. Addit ionally, cert ain st andardized ways of conduct ing B2B and EAI have already begun t o result in com m ercially available libraries for encapsulat ing XML- based inform at ion in a fashion t hat is specific t o a part icular applicat ion. As a result , st andard DTDs em erge for describing such docum ent s, and st andard ways of t ransform ing docum ent s from one dialect int o anot her m ay be defined via an XSLT- like t echnology. Figur e 3 8 .5 . EAI w it h XM L.

On t he Java ent erprise applicat ion side, you have already seen in Chapt er 31 t hat st andard Java libraries exist for creat ing and parsing XML docum ent s using st andard SAX or DOM int erfaces. Chapt er 37 also describes t he capabilit y t o use XML for com m unicat ion via EJBs operat ing wit hin J2EE cont ainers. Such Java ent erprise applicat ions are t hus already largely readied for use of XML- based EAI now and will cert ainly be even m ore readied in t he fut ure as XML becom es m ore accessible t o all J2EE- com pliant cont ainer environm ent s wit h version 1.3 of t he J2EE specificat ion. The form of XML docum ent t hat get s passed bet ween ent erprise applicat ions will be applicat ion- specific. I n som e scenarios, you m ay act ually have cont rol over defining t he XML docum ent m essage form at s via specificat ion of DTDs t hat will be used on bot h ent erprise applicat ion sides of t he house t o be int egrat ed. I n ot her scenarios in which XML docum ent m essage form at s are already defined, you m ay opt t o int egrat e t he ent erprise applicat ion wit h t hose m essaging st andards, perhaps using som e reusable docum ent processing libraries. You m ay inst ead also define a set of t ransform at ions t o be perform ed on t he predefined XML docum ent s using a t echnology like XSLT t hat can t ransform XML docum ent s sent or received over t he wire int o a form at t hat your ent erprise applicat ion can underst and.

- 1232 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The ease wit h which any XML docum ent t ransform at ions and int egrat ion effort can be carried out will be a funct ion of t he t ype of XML docum ent . XML used in a dat a- driven applicat ion will result in XML docum ent form at s t hat sim ply cont ain serialized represent at ions of obj ect s t o be exchanged ( for exam ple, sending a serialized form of a credit obj ect t o an ext ernal credit vet t ing syst em ) . XML m ay also be used t o encapsulat e act ual com m ands or m et hod invocat ions incorporat ing such dat a as a com m and or m et hod nam e, param et er nam es, and param et er values, and subsequent ly requiring a serialized response m essage associat ed wit h t he part icular m et hod invocat ion. Finally, XML can also cont ain arbit rarily com plicat ed query dat a, CDATA, and processing inst ruct ions used in m ore sophist icat ed XML- based applicat ions. Because XML can represent sim ple t o arbit rarily com plicat ed dat a, it is a prim e EAI candidat e for represent at ion of dat a t hat m ust em anat e from and be consum ed by m any different ent erprise applicat ions. I n alm ost every regard, JMS as t he m essaging cont rol t echnology and XML as t he m essage represent at ion t echnology are t he perfect com binat ion for ext ernal EAI and B2B. When CORBA as an underlying m essaging com m unicat ion paradigm im plem ent at ion is added int o t he m ix, m axim um int eroperabilit y and plat form flexibilit y are ensured.

EAI w it h J2 EE Con n e ct or s On t he horizon t o be incorporat ed int o t he J2EE v1.3 archit ect ure are J2EE connect ors. J2EE connect ors, as illust rat ed in Figure 38.6, define a st andard Connect or Service Provider I nt erface t o be im plem ent ed by legacy/ auxiliary ent erprise applicat ion vendors ( aka " EI S" vendors per Sun t erm inology) . EI S vendors provide resource adapt ers im plem ent ing t he Connect or SPI t o provide connect ivit y bet ween t he m anagem ent services of a J2EE- based cont ainer/ server and t he vendor's EI S. By providing such resource adapt ers im plem ent ing st andard SPI s, J2EE cont ainer providers can properly m anage t he services provided by EI S vendors using an int erface t hat does not need t o vary per vendor EI S. EI S vendors can also be guarant eed t hat t heir product s will easily plug int o any ot her vendor's J2EE- com pliant server product . Figu r e 3 8 .6 . J2 EE con n e ct or a r ch it e ct u r e .

- 1233 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Connect or SPI defines t hree m ain int erface t ypes t hat can be im plem ent ed by EI S vendors. A resource m anagem ent int erface allows a J2EE- based server t o m anage how connect ions t o EI Ss are pooled and allocat ed t o J2EE com ponent client s on request . A t ransact ion m anagem ent int erface allows a J2EE- based server t o m anage dist ribut ed t ransact ions t hat involve m ult iple EI Ss. Finally, a securit y m anagem ent int erface m anages secure access t o t he EI S from com ponent s inside of t he J2EE cont ainer environm ent . J2EE com ponent s, such as EJBs, init ially obt ain handles t o vendorspecific resources via JNDI . Vendor- specific resource references will be configurable via a elem ent ent ry in a J2EE XMLbased deploym ent descript or using sub- elem ent s such as elem ent s ( for exam ple, connector/MyResource) and elem ent s ( t hat is, t he class nam e of t he resource obj ect ) . J2EE com ponent s t hen look up such resources via an InitialContext.lookup() m et hod using t he . The J2EE cont ainer can t hen appropriat ely handle how such a resource will get allocat ed t o a request ing com ponent using t he resource m anagem ent connect ion pooling capabilit ies enabled by t he underlying st andard Connect or SPI . Aft er t he J2EE com ponent has a handle t o t hat resource, however, t he API is vendor- specific. That is, t he J2EE com ponent uses what ever vendor- specific API s t hey have defined for t hat resource when int egrat ing t he EI S wit h t he J2EE- based ent erprise applicat ion. The good news is, however, t hat J2EE com ponent s dependent on such EI S API s will be able t o be port ed from one J2EE- com pliant cont ainer/ server vendor product t o anot her if bot h cont ainer/ server vendors and your EI S vendor support t he Connect or SPI . Thus, building J2EE- based ent erprise applicat ions will be m ade even m ore - 1234 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

port able when J2EE Connect or t echnologies are em ployed for EI S int egrat ion.

Em be dde d Applica t ion s I n t e gr a t ion Not all applicat ions in an ent erprise sit inside of deskt op com put ers and workst at ions or inside of large server or m ainfram e plat form s. A current and growing need in m any ent erprise syst em s is t o also int egrat e t heir peripheral em bedded applicat ions int o t he m ix. Em bedded applicat ions drive such devices in t he ent erprise syst em as print ers, phot o copiers, PDAs, cell phones, scanners, fax m achines, ATMs, inform at ion kiosks, cash regist ers and checkout count ers, rem ot e aut om ot ive t erm inals, and t raffic light s, t o nam e a few. Em bedded applicat ions m ay be viewed as t he bridge bet ween t he inform at ional and physical universe of an ent erprise. They are t he I / O sensors and act uat ors of an ent erprise t hat connect people, physical asset s, and t he environm ent wit h t he ent erprise. Em bedded devices m ay connect wit h ent erprise applicat ions via st andard I nt ernet - based com m unicat ion paradigm s, CORBA, or perhaps via a wireless com m unicat ion paradigm . The very birt h of Java was driven by t he desire on t he part of Sun t o becom e involved in t he em bedded consum er elect ronics and associat ed em bedded soft ware m arket . Sun has cont inued wit h t he pursuit of it s int erest s and has as a result fost ered m any product s, API s, and plat form s t hat focus on em bedded Java applicat ions. Alt hough a det ailed discussion of em bedded Java t echnologies is beyond t he scope of t his book, we do want t o close t his chapt er wit h a brief descript ion of t hose Java t echnologies used in em bedded applicat ions t hat can be int egrat ed wit h Java ent erprise applicat ions. The following list cont ains a brief descript ion of t he core em bedded Java t echnologies t hat can be int egrat ed wit h ent erprise Java t echnologies: •



Ja va 2 Pla t for m , M icr o Edit ion ( J2 M E) : The J2ME is t he em bedded plat form count erpart t o t he large- scale J2EE plat form . The J2ME cont ains a JRE and a m inim al set of API s needed for em bedded applicat ions. Com m unit y- defined profiles are used t o specify addit ional API s and libraries needed for specific applicat ion t ypes. Two m ain classes of J2ME configurat ion are t he Lim it ed, Connect ed Device Configurat ion for em bedded applicat ions in t he 128KB t o 512KB m em ory range and t he Connect ed Device Configurat ion for em bedded applicat ions wit h 512KB+ m em ory. Pe r sona lJa va : PersonalJava was an em bedded applicat ion environm ent int roduced before t he J2ME and was specialized

- 1235 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE











t o sat isfy higher- end em bedded applicat ion needs such as t hose for PDAs, cell phones, and set - t op boxes. PersonalJava is now being m erged wit h t he J2ME t o represent one J2ME profile suit able in Connect ed Device Configurat ions for em bedded " Personal" and " Web" applicat ions. Em be dde dJa va : Em beddedJava, also int roduced before t he J2ME, provides a m eans t o configure exact ly which aspect s of a JRE and which API s are used by a part icular em bedded Java applicat ion. Em beddedJava accom plishes t his t ask by running t he Java code t hat you want t o em bed t hrough a set of filt ering and com pact ing t ools t hat generat e nat ive language code cont aining t ranslat ed versions of all JRE and Java API s used, as well as a t ranslat ed version of your Java code. The nat ive language code can t hen be com piled and linked int o a m inim alist binary execut able for your em bedded plat form . Em beddedJava was dependent on t he Java 1.1 plat form at t he t im e of t his writ ing. Ja va Ca r d: At t he lowest level of Java em bedding, t he JavaCard t echnology provides t he capabilit y t o em bed t he m ost m inim al JRE and API s int o a processor and m em ory space sm all enough t o fit ont o a credit card. Such cards are used for secure ident ificat ion of individuals and for com m erce t ransact ions such as are used for credit and debit cards. Jini: We have already described Jini in Chapt er 20, " Direct ory and Trading Services," as a t echnology useful in building t rading services for ent erprise applicat ions. Jini, in fact , is prim arily t out ed for it s applicabilit y t o em bedded applicat ion environm ent s as described by us in anot her paper ( ht t p: / / www.assuredt ech.com / papers/ j ini/ em bedded.pdf ) . When a Jini- based discovery and t rading service is provided for em bedded applicat ions, your ent erprise applicat ions can dynam ically discover when it s em bedded peripherals are available and negot iat e wit h a com m unit y of such devices for access t o t heir services from ent erprise applicat ions. For exam ple, your ent erprise applicat ions can dynam ically negot iat e access t o net work print ing devices using Jini. Ja va Com m unica t ions API : The Java Com m unicat ions API is a st andard Java ext ension defined in t he javax.comm package t o offer access t o serial ( RS- 232) and parallel ( I EEE 1284) com m unicat ion port s from Java applicat ions. M in im u m CORBA: CORBA v3.0 includes a specificat ion for m inim um CORBA. Minim um CORBA, as t he nam e im plies, defines a m inim um profile for CORBA t hat can be used in em bedded applicat ions. A real- t im e CORBA specificat ion is also being defined for enabling det erm inism in m anaged resources crit ical t o m any em bedded real- t im e applicat ions. Resources needing real- t im e det erm inism include connect ion

- 1236 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE





m anagem ent , t hread m anagem ent , st at e m anagem ent , and com m unicat ions prot ocol. W ir e le ss Acce ss Pr ot ocol ( W AP) : WAP defines a st andard com m unicat ions prot ocol suit e for dist ribut ed com m unicat ions bet ween wireless devices. WAP specifically addresses how wireless devices can int erface wit h t he I nt ernet . W ir e le ss M a r k up La ngua ge ( W M L) : WML is a m arkup language used for t ext ual display of Web pages on em bedded devices. WML is specifically designed t o be useful for represent ing dat a com m unicat ed over WAP.

Use of such t echnologies in em bedded applicat ions allows for m axim um ease of int egrat ion bet ween em bedded applicat ions and ent erprise- scale applicat ions. Ent erprise applicat ions can ut ilize TCP/ I P, HTTP, CORBA, and RMI t o direct ly com m unicat e wit h em bedded applicat ions t hat ut ilize such t echnologies. Thus, use of Java in em bedded applicat ions and int egrat ion wit h ent erprise applicat ions t ruly enable you t o perm eat e every vein of t he ent erprise t o provide a fully caffeinat ed ent erprise.

Con clu sion s Ent erprise Applicat ion I nt egrat ion ( EAI ) of Java ent erprise t echnologies wit h legacy/ auxiliary ent erprise applicat ions is well support ed by t he host of Java ent erprise t echnologies available t oday and is described t hroughout t his book. I nt ernal EAI solut ions m ay ut ilize JNI and cert ain dist ribut ed com m unicat ions enabling approaches such as CORBA, TCP/ I P, HTTP, RMI , and DCOM. Ext ernal EAI and B2B solut ions m ay pursue a m ore loosely coupled solut ion t hat involves JMS for asynchronous m essage com m unicat ions and XML for st andard m essage represent at ions and dialect t ransform at ions. J2EE connect ors wit h com m ercial ent erprise applicat ion vendor product s and t he int egrat ion of em bedded applicat ions wit h t he ent erprise are t wo ot her areas of EAI t hat ent erprise syst em archit ect s and developers m ust consider. As t his book and chapt er have t hus point ed out , not only can building Java ent erprise syst em s be m ade easy wit h Java ent erprise t echnologies and t he J2EE, but t he int egrat ion of ent erprise applicat ions wit h t hese sam e t echnologies also is at your fingert ips.

dd

- 1237 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Pa r t VI I I : Appe n dix e s I N TH I S PART A Soft ware Configurat ion B Addit ional Resources

- 1238 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Appe n dix A. Soft w a r e Con figu r a t ion This appendix cont ains descript ions of how t o configure t he com m ercial off t he shelf ( COTS) and sam ple soft ware equipped wit h t his book on t he accom panying CD. Because of t he highly dynam ic nat ure involved in vendor soft ware releases, t he inform at ion in t his appendix is perhaps t he m ost sensit ive- t o- change inform at ion in t he book. St ay t uned for any updat es t o t hese inst ruct ions post ed t o ht t p: / / www.assuredt ech.com / books/ j 2ee/ soft ware.ht m l. Also not e t hat m uch of t he m at erial in t his appendix is very dry and reference- orient ed by nat ure. We t hus recom m end t hat you not read t his inform at ion in one sit t ing but rat her refer t o each sect ion of t his appendix as you encount er exam ples t hat depend on t hat sect ion's cont ent s. We describe how each chapt er in t he book wit h associat ed sam ple code on t he CD relat es t o each sect ion in t his appendix ( in t he " Soft ware Configurat ion per Chapt er" sect ion of t his appendix) .

Soft w a r e on t h e CD The soft ware on t he CD is placed int o one of t he direct ories depict ed graphically in Figure A.1. At t he left m ost side of t his diagram , we see t he root direct ory for t he CD ( ) . is not an act ual direct ory nam e, but rat her represent s t he t op- level direct ory for all code on t he CD and will be referred t o t hroughout t his appendix. The cots direct ory cont ains all COTS soft ware equipped wit h t he book on t he CD. Ot her COTS soft ware used in t he book will be downloadable from various Web sit es. The webref direct ory cont ains links t o addit ional resources on t he Web. The examples direct ory cont ains all t he sam ple source code ( in a src subdirect ory) and COTS configurat ion script s ( in a config subdirect ory) . The src direct ory under t he examples direct ory represent s t he root of all Java source code ( prefixed wit h t he ejava package nam e) . Each chapt er wit h sam ple code st ored in soft form on t he CD has it s own direct ory below t he ejava direct ory. Finally, not e t hat a special classes direct ory has been est ablished on t he CD. No com piled Java class files are st ored in t his direct ory, but it is left as a placeholder in t he event t hat readers want t o t ransfer t he ent ire CD direct ory st ruct ure and cont ent s int o a working local direct ory on t heir host m achines. Not e also t hat a sam ple setenv.bat file is cont ained on t he CD in t he \examples\config direct ory t hat m ay be used t o set environm ent variables for your part icular environm ent . The

- 1239 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

setenv.bat file sim ply serves as a st art er file t hat m ust be m odified for your part icular environm ent based on t he inst ruct ions t hat follow in t his appendix. The CD also cont ains a nift y aut om at ic st art up feat ure and GUI for Windows plat form s. The GUI can also be st art ed by invoking t he \Start.exe applicat ion file. The result ing GUI window enables you t o explore t he CD exam ple code, explore t he COTS product s on t he CD, obt ain access t o online web resources, and discover ot her book, product regist rat ion, and support inform at ion. Figur e A.1 . The Building Ja va Ent e r pr ise Syst e m s w it h J2 EE CD st r uct ur e .

- 1240 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Soft w a r e Con figu r a t ion pe r Ch a pt e r This appendix describes general soft ware configurat ion procedures t hat m ust be perform ed t o run t he sam ple code associat ed wit h chapt ers in t he book. I n general, t he large m aj orit y of code exam ples in t his book will work only aft er t he following Com m on Soft ware Configurat ion sect ions of t his appendix have been successfully com plet ed: • • • •

J2SE Configurat ion J2EE Configurat ion Java Environm ent Variable Configurat ion Sam ple Soft ware Configurat ion

Addit ionally, Table A.1 m aps chapt ers of t he book t o t he sect ion t it les of t his appendix whose inst ruct ions are pert inent t o t hat chapt er. Not e t hat in Table A.1, we repeat t hose sect ions relevant t o a chapt er for each chapt er in t he book. Of course, aft er a part icular soft ware configurat ion st ep is perform ed for one chapt er, it will no longer be necessary t o perform m any of t he sam e configurat ion st eps for a subsequent chapt er t hat is also dependent on t hose st eps. Tabl e A. 1. Appendi x Sect i on( s) Rel evant t o a Chapt er

Chapter

Configuration Step(s) Required

Chapt er Com m on Soft ware Configurat ion JavaBeans Configurat ion 7 Chapt er Com m on Soft w are Configurat ion Dat abase Configurat ion 9 Chapt er Com m on Soft w are Configurat ion Dat abase Configurat ion 10 Chapt er Com m on Soft w are Configurat ion Dat abase Configurat ion 12 Chapt er Com m on Soft ware Configurat ion Dat abase Configurat ion CORBA ORB 15 Configurat ion RMI / I I OP Configurat ion Chapt er Com m on Soft w are Configurat ion Dat abase Configurat ion RMI / I I OP 16 Configurat ion Chapt er Com m on Soft w are Configurat ion Microsoft Java Configurat ion Dat abase 18 Configurat ion Chapt er Com m on Soft ware Configurat ion CORBA ORB Configurat ion CORBA 19 Services Configurat ion JNDI Configurat ion RMI / I I OP Configurat ion Chapt er Com m on Soft ware Configurat ion CORBA ORB Configurat ion CORBA 20 Services Configurat ion JNDI Configurat ion LDAP Configurat ion Jini Configurat ion Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion Dat abase Configurat ion CORBA ORB Configurat ion CORBA Services 22 Configurat ion JMS Configurat ion JavaMail Configurat ion Chapt er Com m on Soft ware Configurat ion 27

- 1241 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Chapt er Com m on Soft ware Configurat ion 30 Chapt er Com m on Soft w are Configurat ion XML Configurat ion 31 Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion 32 Web Configurat ion Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion 33 Web Configurat ion Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion 35 Applicat ion Server Configurat ion Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion 36 Dat abase Configurat ion Applicat ion Server Configurat ion Chapt er Com m on Soft w are Configurat ion BEA WebLogic Server Configurat ion 37 Dat abase Configurat ion Web Configurat ion Applicat ion Server Configurat ion JMS Configurat ion JavaMail Configurat ion

J2 SE Con figu r a t ion Most of t he exam ples in t his book require a Java 2 Plat form , St andard Edit ion ( J2SE) version 1.2 com pat ible Java runt im e environm ent ( JRE) and soft ware developm ent kit ( SDK) . I n fact , t he J2EE v1.2 is dependent on t he J2SE v1.2. The J2SE v1.2 SDK can be downloaded from ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ . Follow t he inst ruct ions provided on t hat sit e for downloading and inst alling t he J2SE v1.2 SDK for your part icular plat form . We should not e t hat our sam ple helper script s equipped wit h t he book are cat ered for Windows environm ent s but can be ext ended or m im icked for use wit h a Java SDK on any plat form . Our build script s equipped wit h t he CD t ypically assum e t hat you have set t he JAVA_HOME environm ent variable t o t he root direct ory of your J2SE inst allat ion. For exam ple, at a Windows DOS prom pt , you m ight set t his variable like t his:

set JAVA_HOME=C:\jdk1.2.2 The J2SE v1.3 cannot be used wit h t he J2EE v1.2, but it can be used for m any of t he st andalone Java applicat ions described in t his book. The J2SE v1.3 can be downloaded from ht t p: / / j ava.sun.com / product s/ j dk/ 1.3/ . Follow t he inst ruct ions provided on t hat sit e for downloading and inst alling t he J2SE v1.3 SDK for your part icular plat form .

J2 EE Con figu r a t ion Part VI , " Ent erprise Web Enabling," and Part VI I , " Ent erprise Applicat ions Enabling," provide exam ples of how t o run and deploy

- 1242 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Web and EJB com ponent s inside t he Java 2 Plat form , Ent erprise Edit ion version 1.2 reference im plem ent at ion server. Those part s of t he book also assum e t he use and availabilit y of t he J2EE version 1.2 API s and SDK. The J2EE v1.2 soft ware can be downloaded from ht t p: / / www.j avasoft .com / j 2ee/ j 2sdkee/ . Follow t he inst ruct ions provided on t hat sit e for downloading and inst alling t he J2EE SDK for your part icular plat form . Our build script s equipped wit h t he CD t ypically assum e t hat you have set t he J2EE_HOME environm ent variable t o t he root direct ory of your J2EE inst allat ion. For exam ple, at a Windows DOS prom pt , you m ight set t his variable as shown here:

set J2EE_HOME=C:\j2sdkee1.2 The [J2EE_HOME]\bin\j2ee com m and is used t o st art a J2EE server. The [J2EE_HOME]\bin\packager t ool is used t o creat e J2EE WAR, EJB JAR, EAR, and Applicat ion Client JAR files. The [J2EE_HOME]\bin\deploytool is used t o init iat e t he deploym ent of J2EE packaged m odules and ent erprise applicat ions using eit her a GUI or a com m and- line form of t he t ool. The docum ent at ion for how t o use such t ools wit h t he J2EE reference im plem ent at ion can be downloaded from ht t p: / / www.j avasoft .com / j 2ee/ j 2sdkee/ .

Ja va En vir on m e n t Va r ia ble Con figu r a t ion Aside from t he st andard Java environm ent variables defined previously, t he PATH and CLASSPATH environm ent variables m ust also be set . Our build script exam ples t ypically set t hese variables aut om at ically when building or running an exam ple. The PATH ident ifies t he pat h for execut able applicat ions, and t he CLASSPATH ident ifies t he pat h for class files and archive files ( t hat is, JAR files) t o be used when init iat ing t he JRE. See ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ t ooldocs/ t ools.ht m l for m ore inform at ion specific t o your part icular plat form .

M icr osoft Ja va Con figu r a t ion The Microsoft Java Virt ual Machine ( MSJVM) is used t o facilit at e t he creat ion of Java- based COM/ DCOM applicat ions. The MSJVM, also referred t o as jview, com es wit h t he Microsoft Java SDK version 3.2 or higher. You can download t he lat est Microsoft Java SDK from ht t p: / / www.m icrosoft .com / j ava. Follow t he inst ruct ions provided on t hat sit e for downloading and inst alling t he Microsoft JVM SDK for use wit h t he COM/ DCOM exam ples in t he book. To use our sam ple COM/ DCOM script s equipped on t he CD, t he MSDK_JAVA

- 1243 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

environm ent variable m ust be set t o t he root direct ory of a Microsoft SDK inst allat ion ( we have used t he Microsoft SDK for Java v3.2) . Microsoft Visual J+ + version 6.0 or higher can be used t o help creat e t he COM/ DCOM exam ples in t he book. The Microsoft Visual J+ + t ool of m ost use t o you will be t he Professional Edit ion, wit h bet t er support for building COM and DCOM applicat ions t han t hat found wit h ot her edit ions. An evaluat ion copy of Microsoft Visual J+ + is provided on t he CD in t he \cots\microsoft\visualj++ direct ory.

BEA W e bLogic Se r ve r Con figu r a t ion The BEA WebLogic Server v5.1 is equipped wit h t his book on t he CD in t he \cots\weblogic direct ory. The BEA WebLogic Server, in fact , cont ains m uch of t he J2SE- and J2EE- com pliant soft ware infrast ruct ure t hat can be used t o execut e m any of t he exam ples provided on t he CD. All BEA WebLogic docum ent at ion is root ed at ht t p: / / www.weblogic.com / docs50/ resources.ht m l. The specific inst ruct ions for inst alling t he BEA WebLogic Server are cont ained at ht t p: / / www.weblogic.com / docs50/ inst all/ . The root direct ory in which you inst all t he BEA WebLogic Server on your m achine corresponds t o a WEBLOGIC_HOME environm ent variable assum ed by t he configurat ion script s for our sam ple soft ware. On a Windows plat form , t his environm ent variable m ay be set as exem plified here:

set WEBLOGIC_HOME= D:\weblogic A special weblogic.properties Java propert ies file cont ained under t he WEBLOGIC_HOME direct ory defines m any of t he propert ies we will need t o m odify t hroughout t his book for proper operat ion wit h our exam ples. A com plet e descript ion of all BEA WebLogic Server propert ies configurable in t he weblogic.properties file is defined at ht t p: / / www.weblogic.com / docs50/ adm indocs/ propert ies.ht m l. A set of special script s is cont ained under t he WEBLOGIC_HOME direct ory for st art ing t he BEA WebLogic server. On a Windows NT plat form , t he script t o use is nam ed startWeblogic.cmd. For UNI X plat form s t he script t o use is nam ed startWeblogic.sh, and for Windows NT plat form s using t he Microsoft SDK t he script t o use is called startWeblogicJView.cmd. These script s can be configured t o easily st art a BEA WebLogic Server t hat references t he weblogic.properties file. You will specifically need t o set t he

- 1244 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

JDK_HOME environm ent variable defined in t he startWeblogic file t o reference your [JAVA_HOME] direct ory. More inform at ion on st art ing t he BEA WebLogic Server and on configuring t hese startWeblogic files can be found at ht t p: / / www.weblogic.com / docs50/ inst all/ st art server.ht m l.

Sa m ple Soft w a r e Con figu r a t ion Most of t he sam ple code on t his book's CD is com piled using st andard Java com pilat ion t ools. Furt herm ore, a subset of t he code on t his book's CD can be execut ed aft er com pilat ion using st andard Java runt im e execut ion t ools. This book assum es a basic abilit y on t he part of developers t o com pile and execut e regular st andalone Java code. Addit ional inform at ion on basic Java SDK usage can be found at ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ index.ht m l. Furt herm ore, specific inst ruct ions for use of t he various Java SDK t ools can be found at ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ t ooldocs/ t ools.ht m l. The direct ories under t he \examples\src direct ory cont ain t he source code for all exam ples in t his book. To com pile such code, you m ust copy t he direct ories from t he CD ont o your local working file syst em . Sam ple script s included on t he CD build t he code assum ing t hat you've copied t his direct ory st ruct ure t o m im ic t he st ruct ure shown in Figure A.1. The code root ed at in t hat diagram t hus m ust be copied t o your local working environm ent root ed at a direct ory of your choice. However, it is im port ant t hat t he direct ory root be ident ified by an EJAVA_HOME environm ent variable. Thus, for exam ple, if EJAVA_HOME is set as

set EJAVA_HOME=C:\books\j2ee t hen t he \examples\src direct ory should be equivalent t o C:\books\j2ee\examples\src on your local file syst em . All sam ple source code com pilat ion and class file execut ion, of course, m ust occur wit hin t his local file syst em environm ent root ed at EJAVA_HOME. We include m any .bat script files on t he CD for t he plet hora of soft ware exam ples equipped wit h t he book. I f you've set your environm ent variables described in t his appendix correct ly, you should be able t o use t he .bat script files " as is" on Windows plat form s. These script files can also serve as t em plat es t o creat e script s for ot her plat form s on which you are running t his code ( for exam ple, UNI X and Macint osh) .

- 1245 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

D a t a ba se Con figu r a t ion I n t his sect ion, we present an int egrat ed view of t he sam ple BeeShirts.com dat a m odel used t o configure our sam ple dat abase. We also describe how t o inst all and configure a dat abase wit h our sam ple BeeShirts.com dat a. Not e t hat because all of our exam ples in t his book use JDBC as a dat abase int erface t echnology, t he exam ples will work wit h any dat abase t hat support s a JDBCcom pliant driver int erface. We have creat ed dat abase configurat ion script s for use wit h bot h t he Cloudscape DBMS and Oracle8i DBMS. These script s can be used t o configure eit her dat abase wit h t he BeeShirts.com schem a and init ial set of sam ple dat a. Because Chapt er 10, " Advanced JDBC," describes t he lat est JDBC 2.0 st andard feat ures, som e of t he JDBC 2.0 feat ures dem onst rat ed in Chapt er 10 were not fully support ed by all vendors, including bot h Cloudscape and Oracle. Chapt er 9, " Basic JDBC," and all ot her chapt ers, however, ut ilize t he m ost com m on JDBC feat ures t hat m ost dat abase vendors support . BeeShirts.com D a t a M ode l Figure A.2 depict s t he dat a m odel used wit h t he exam ples in t his book. Chapt er 8, " Ent erprise Dat a," cont ains a descript ion of t he basic dat a m odel diagram convent ions used t o underst and t his diagram . These are t he basic ent it ies of t his m odel: •

• •













CUSTOMER: Cont ains BeeShirts.com cust om er dat a. STATE: Maps a st at e code t o a st at e nam e. AUTHENTICATION: Cont ains cust om er aut hent icat ion dat a. CREDIT: Cont ains keys t o all credit - relat ed dat a. CHARGE_CARD_TYPE: Cont ains cust om er charge- card dat a. ORDERS: Cont ains cust om er order dat a. ITEM: Cont ains order it em dat a. TSHIRT: Cont ains T- shirt it em dat a. SUPPLIER: Cont ains BeeShirts.com T- shirt supplier dat a. Figur e A.2 . The

BeeShirts.com da t a m ode l.

- 1246 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Clou dsca pe D a t a ba se Configur a t ion The Cloudscape dat abase is t he prim ary dat abase t hat we use wit h our exam ples t hroughout t his book prim arily because of it s ease of configurat ion, it s open int egrat ion wit h Java ent erprise environm ent s, and t he Cloudscape Corporat ion's open policy for m aking Cloudscape accessible t o developers and various SDKs. Cloudscape, in fact , com es equipped wit h bot h t he BEA WebLogic Server and t he J2EE reference im plem ent at ion used by t his book. The following st eps describe how t o use t he Cloudscape dat abase wit h our exam ples. Cloudsca pe Soft w a r e t o I nst a ll

You can use t he Cloudscape dat abase cont ained in t he \cots\cloudscape direct ory on t he CD, t he dat abase t hat com es equipped wit h t he BEA WebLogic soft ware provided wit h t he CD, or t he dat abase t hat com es equipped wit h t he J2EE

- 1247 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

reference im plem ent at ion down loadable from Sun Microsyst em s. Cloudscape v1.5 is equipped wit h BEA WebLogic, and Cloudscape v3.0 is used wit h t he J2EE reference im plem ent at ion. N ot e Not e t hat alt hough t he Cloudscape dat abase is equipped wit h t his book's CD as a separat e inst allat ion package, we only describe how t o configure t he Cloudscape dat abase equipped wit h t he BEA WebLogic Server and t he J2EE reference im plem ent at ion. This is because you will need t o configure such dat abases when you run our sam ple script s t hat use eit her t he BEA WebLogic Server or t he J2EE reference im ple m ent at ion server. However, you m ay also opt t o use t he st andalone Cloudscape dat abase provided on t he CD for use wit h t he st andalone Java ent erprise exam ples cont ained on t he CD.

Cloudsca pe Lim it a t ions

The Cloudscape version equipped wit h BEA WebLogic did not support any JDBC 2.0 feat ures as described in Chapt er 10. The Cloudscape version equipped wit h t he J2EE reference im plem ent at ion wit h t he book's CD could support JDBC 2.0 scrollable result set s and bat ch updat es, but it could not support any of t he new SQL t ypes t hat we use in our exam ples. We include script s on t he CD for configuring t he Cloudscape dat abase wit h sam ple BeeShirts.com dat a. These script s do not define dat a st ruct ures t hat exem plify how t o use Cloudscape wit h Chapt er 10's new SQL t ype exam ples, however. The configurat ion st eps for Oracle t hat follow t he Cloudscape configurat ion st eps present ed here can be used t o dem onst rat e Chapt er 10's new SQL t ype exam ples. Cloudsca pe Configur a t ion Tool St a r t u p w it h BEA W e bLogic

The CloudView GUI configurat ion t ool for Cloudscape equipped wit h BEA WebLogic requires t hat you set JAVA_HOME ( for root J2SE inst all) , WEBLOGIC_HOME ( for root WebLogic inst all) , and CLASSPATH environm ent variables before running it . As an exam ple of set t ing such environm ent variables for Windows, we have t his:

set JAVA_HOME=C:\jdk1.2.2 set WEBLOGIC_HOME=D:\weblogic

- 1248 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

set CLASSPATH=%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.ja r; set CLASSPATH=%CLASSPATH%; %WEBLOGIC_HOME%\eval\cloudscape\lib\cloudscape.jar set CLASSPATH=%CLASSPATH%;%WEBLOGIC_HOME%\eval\cloudscape\lib \tools.jar set CLASSPATH=%CLASSPATH%;%WEBLOGIC_HOME%\lib\weblogicaux.jar The CloudView GUI t ool is t hen invoked from t he com m and line via t his:

java COM.cloudscape.tools.cview Alt ernat ively, you can use t he sam ple startWebLogicCloudview.bat Windows script file cont ained on t he CD under t he \examples\config\dbscripts\cloudscape direct ory t o invoke CloudView. You m ust set only t he JAVA_HOME and WEBLOGIC_HOME environm ent variables before running t his script . Cloudsca pe Configur a t ion Tool St a r t up w it h t he J2 EE Re fe r e nce I m ple m e nt a t ion

You m ust first execut e a special cloudscape script equipped wit h t he J2EE reference im plem ent at ion. You m ust invoke t his com m and not only during inst allat ion, but also when you want t o use Cloudscape wit h our exam ples aft er it has been inst alled. First change t o t he [J2EE_HOME]\bin direct ory and invoke t he com m and as shown here:

cloudscape -start The CloudView GUI configurat ion t ool for Cloudscape equipped wit h t he J2EE reference im plem ent at ion requires t hat you set JAVA_HOME ( for root J2SE inst all) , J2EE_HOME ( for root J2EE reference im plem ent at ion inst all) , and CLASSPATH environm ent variables before running it . As an exam ple of set t ing such environm ent variables for Windows, we have t he following:

set JAVA_HOME=C:\jdk1.2.2 set J2EE_HOME=C:\j2sdkee1.2

- 1249 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

set CLASSPATH=%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.ja r; set CLASSPATH=%J2EE_HOME%\lib\j2ee.jar; %J2EE_HOME%\lib\cloudscape\RmiJdbc.jar;%CLASSPATH% set CLASSPATH=%J2EE_HOME%\lib\cloudscape\tools.jar; %J2EE_HOME%\lib\cloudscape\client.jar;%CLASSPATH% set CLASSPATH=%J2EE_HOME%\lib\cloudscape\cloudscape.jar;%CLAS SPATH% The CloudView GUI t ool is t hen invoked from t he com m and line via t his:

java COM.cloudscape.tools.cview Alt ernat ively, you can use t he sam ple startJ2EECloudview.bat Windows script file cont ained on t he CD under t he \examples\config\dbscripts\cloudscape direct ory t o invoke CloudView. You m ust set only t he JAVA_HOME and J2EE_HOME environm ent variables before running t his script . Cloudsca pe D a t a ba se , Sa m ple D a t a ba se Sche m a , a nd Sa m ple D a t a Configur a t ion

Aft er t he CloudView GUI t ool is launched, t he st eps for configuring a Cloudscape dat abase are generally t he sam e. The general st eps for Cloudscape dat abase configurat ion using t he CloudView GUI t ool follow: 1. Select File, New, Dat abase from t he CloudView GUI m enu. 2. Ent er t he nam e of t he dat abase t o creat e. For t he J2EE reference im plem ent at ion, we set t his value t o [J2EE_HOME]\cloudscape\beeshirtdb. For BEA WebLogic, we set t his value t o [WEBLOGIC_HOME]\eval\cloudscape\beeshirts. 3. Select Syst em on t he left hand t ree view of t he CloudView GUI and t he Connect ion t ab on t he right side, and add t he prefix, usernam e, and password. For t he J2EE reference im plem ent at ion, t he prefix should be set t o jdbc:rmi//localhost:1099/jdbc: cloudscape:. For t he BEA WebLogic server, t he prefix should be set t o jdbc: cloudscape. We set t he usernam e t o TSHIRTS and t he password t o TSHIRTS for our exam ples. Click t he OK but t on. 4. Select t he dat abase j ust creat ed in t he left hand t ree view. 5. Select t he Script s icon on t he dat abase t ab and t hen choose t o Open a Script .

- 1250 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

6. Select \examples\config\dbscripts\cloudscape\creat eshirtsdb.sql. 7. Execut e t his script by clicking t he Execut e icon on t he t ab. The Cloudscape dat abase should now be configured wit h t he BeeShirts.com schem a and dat a used wit h our exam ples t hroughout t he book. Not e t hat t he \examples\config\dbscripts\cloudscape\removeshir tsdb.sql script can also be execut ed t o rem ove t he dat abase t hat was creat ed. Cloudsca pe Libr a r y Envir onm e nt Va r ia ble

For all exam ples t hat use t he Cloudscape dat abase, t he CLOUDSCAPE_LIB environm ent variable m ust be set t o t he direct ory of your Cloudscape JAR files. For t he Cloudscape dat abase t hat com es wit h t he J2EE reference im plem ent at ion, t his direct ory is [J2EE_HOME]\lib\cloudscape. For t he Cloudscape dat abase t hat com es wit h t he BEA WebLogic Server, t his direct ory is [WEBLOGIC_HOME]\eval\cloudscape\lib. For exam ple, t o set CLOUDSCAPE_LIB on a Windows plat form wit h t he J2EE reference im plem ent at ion, you m ight have t his:

set CLOUDSCAPE_LIB=C:\j2sdkee1.2\lib\cloudscape To set CLOUDSCAPE_LIB on a Windows plat form wit h BEA WebLogic, you m ight have t his:

set CLOUDSCAPE_LIB=d:\weblogic\eval\cloudscape\lib Sa m ple Pr ope r t ie s File s for Cloudsca pe Configur a t ion

To use t he BEA WebLogic Server or t he J2EE reference im plem ent at ion wit h Cloudscape, you'll need t o set a few param et ers enabling t he applicat ion servers t o com m unicat e wit h t he Cloudscape dat abase. For BEA WebLogic, t he [WEBLOGIC_HOME]\weblogic.properties file needs t o have t he following ent ries for use wit h t he dat abase:

# This connection pool uses the sample Cloudscape database shipped # with WebLogic. Used by the EJBean, JHTML, JSP, and JMS examples.

- 1251 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

weblogic.jdbc.connectionPool.ejavaPool=} url=jdbc:cloudscape:D:\\weblogic\\eval\\cloudscape\\beesh irts,} driver=COM.cloudscape.core.JDBCDriver,} initialCapacity=1,} maxCapacity=2,} capacityIncrement=1,} props=user=TSHIRTS;password=TSHIRTS;server=none # Add a TXDataSource for the connection pool: weblogic.jdbc.TXDataSource.weblogic.jdbc.jts.ejavaPool=ej avaPool # # Add an ACL for the connection pool: weblogic.allow.reserve.weblogic.jdbc.connectionPool.ejava Pool=everyone Not e t hat t he url param et er in t he weblogic.properties file j ust shown m ust be set t o t he jdbc:cloudscape:[WEBLOGIC_HOME]\eval\cloudscape\beeshirts value as appropriat e for your environm ent and as configured in t he preceding sect ion. When you're using t he J2EE reference im plem ent at ion, t he following ent ry m ust be present in t he [J2EE_HOME]\config\default.properties file for use of Cloudscape:

jdbc.datasources= jdbc/Cloudscape|jdbc:rmi:jdbc:cloudscape:beeshirtsdb;crea te=true; Not e t hat t he J2EE reference im plem ent at ion assum es t hat t he beeshirtsdb dat abase configured in t he previous propert y is st ored under t he [J2EE_HOME]\cloudscape direct ory as described earlier in st ep 2. For chapt ers t hat do not use t he BEA WebLogic Server or t he J2EE reference im plem ent at ion and j ust use st raight JDBC t o t alk wit h t he dat abase in st andalone applicat ions ( t hat is, m ost chapt ers before Part VI and Part VI I of t he book) , you'll need t o ensure t hat any DRIVER_CLASS and DATABASE_URL propert ies assum ed by t hose exam ples are valid. These propert ies are defined in t he various Java propert ies files associat ed wit h each chapt er t hat has dat abase connect ivit y via JDBC. The following propert ies m ust be set for t he Cloudscape version equipped wit h BEA WebLogic:

- 1252 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

# JDBC Driver Class for Cloudscape DRIVER_CLASS=COM.cloudscape.core.JDBCDriver # Database URL for our example database with Cloudscape # Info supplied here relates to configuration steps described earlier DATABASE_URL=jdbc:cloudscape:D:\\weblogic\\eval\\cloudsca pe\\beeshirts Of course, t he DATABASE_URL previously defined m ust reference t he appropriat e root direct ory of your WebLogic inst allat ion given in t he jdbc:cloudscape:[WEBLOGIC_HOME]\\eval\\cloudscape\beeshir ts propert y value. Sim ilarly, t he DRIVER_CLASS and DATABASE_URL propert ies m ust be set as shown here when you're using t he Cloudscape version equipped wit h t he J2EE reference im plem ent at ion:

# JDBC Driver Class for Cloudscape DRIVER_CLASS=RmiJdbc.RJDriver # Database URL for our example database with Cloudscape # Info supplied here relates to configuration steps described earlier DATABASE_URL=jdbc:rmi:jdbc:cloudscape:beeshirtsdb Clou dsca pe D a t a ba se St a r t in g w it h t h e J2 EE Re fe r e n ce I m ple m e n t a t ion

Before running our st andalone Java applicat ion exam ples wit h t he J2EE reference im plem ent at ion's version of Cloudscape, you m ust first execut e a special cloudscape script equipped wit h t he J2EE reference im plem ent at ion. First change t o t he [J2EE_HOME]\bin direct ory and invoke t he com m and as shown here:

cloudscape -start Or a cle D a t a ba se Con figu r a t ion Oracle's lat est dat abase, Oracle8i, is an upgrade of t heir DBMS t echnology on t he part of Oracle and em ploys a very Java- cent ric and CORBA- orient ed ent erprise archit ect ure. We provide script s for configuring our BeeShirts.com dat a for use wit h Oracle8i. We also provide a few addit ional script s for configuring Oracle8i t o work wit h a few of t he advanced JDBC 2.0 feat ures described in Chapt er 10. Or a cle Soft w a r e t o I nst a ll

- 1253 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Before you download any Oracle dat abase soft ware, you will need t o j oin Oracle's free Technet m em bership. Sim ply go t o ht t p: / / t echnet .oracle.com and answer all of Oracle's quest ions t o becom e a regist ered Oracle Technet m em ber. The Oracle8i dat abase server soft ware t hat you m ay use wit h t he exam ples in t his book can t hen be downloaded from ht t p: / / t echnet .oracle.com . Not e t hat we have used t he Ent erprise Edit ion of Oracle8i, but t he St andard Edit ion and Personal Edit ions m ay also be used. Not e also t hat we have used t he Windows NT version of Oracle wit h our exam ples, but t hat ot her operat ingsyst em plat form s for your dat abase inst allat ion can also be used. Or a cle Lim it a t ion s

Oracle8i v8.1.5 had a few lim it at ions at t he t im e of t his writ ing. Cert ain JDBC 2.0 feat ures of Chapt er 10 did not yet funct ion, including scrollable result set s, updat able result set s, and bat ch updat es. Chapt er 10's advanced SQL t ype exam ples, all t he Chapt er 9 feat ures, and t he rem aining dat abase feat ures ut ilized t hroughout t he rest of t he book, however, do funct ion correct ly wit h Oracle8i v8.1.5. Oracle8i v8.1.6 uses a JDBC driver t hat report edly will funct ion wit h t he newer JDBC 2.0–com pliant feat ures described in Chapt er 10, including scrollable result set s, bat ch updat es, and all t he new SQL t ypes. Updat able result set s were report edly st ill not support ed by Oracle v8.1.6's JDBC driver at t he t im e of t his writ ing. Or a cle D a t a ba se I nst a lla t ion

I nst allat ion of t he Oracle dat abase can proceed according t o t he inst ruct ions at ht t p: / / t echnet .oracle.com . During inst allat ion, you will be asked t o ent er som e inform at ion t hat will affect how our exam ples can work wit h t he dat abase. These are t he m ain concerns wit h set t ing param et ers: •



Global Dat abase Nam e and SI D should be TSHIRTS. Ensure t hat default dat abase list ener uses port 1521.

The m ain st eps involved in inst alling an Oracle8i dat abase using t he Oracle GUI - based inst allat ion ut ilit y follow: 1. Select t he opt ion t o I nst all/ Deinst all Product s from wit hin t he Oracle inst all ut ilit y screen opt ions. 2. I t is accept able t o use t he default product inst all pat h and Oracle hom e nam e for our exam ples. However, you m ay want t o select a different inst allat ion pat h. 3. Select an act ual dat abase server t o inst all when prom pt ed.

- 1254 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

4. Not e t hat you can choose a m inim al inst allat ion for use wit h our exam ples if you want . 5. When prom pt ed, opt t o inst all a st art er dat abase. 6. I t is im port ant t hat your sam ple global dat abase nam e and SI D are ent ered as TShirts ( case- insensit ive) when prom pt ed. 7. A sum m ary of select ed opt ions is displayed. 8. The st at us of your inst all is event ually displayed. Writ e down any init ial passwords creat ed during inst allat ion. Or a cle D a t a ba se Sa m ple Sche m a a nd D a t a Configur a t ion

Before we configure t he dat abase wit h our sam ple schem a and dat a, you'll need t o set up an Oracle net work client ( t hat is, Net 8 client ) on your m achine since we use SQL- Plus during configurat ion. You m ay set up a SQL net work client as shown here: 1. I nvoke t he Net work Adm inist rat ion's Net 8 Easy Config applicat ion for configuring a SQL net work client . 2. When prom pt ed, m ake sure t hat you creat e a new net service nam e of TSHIRTS. 3. When prom pt ed, select TCP/ I P as your prot ocol. 4. When prom pt ed, ent er your m achine's host nam e ( it can be localhost) , and a port of 1521 ( which is t he default ) . 5. When prom pt ed, ent er a service nam e of TSHIRTS. Aft er configuring a SQL net work client , you can use SQL- Plus t o read t he dat abase configurat ion script s t hat we have packaged wit h t he CD t o aut om at ically creat e your dat abase schem a and load a set of sam ple dat a. The :\examples\config\dbscripts\oracle\createshirtsd b.sql file can be execut ed by SQL- Plus t o configure t he dat abase as shown here: 1. I nvoke t he SQLPlus applicat ion. Not e t hat SQLPlus can be run from t he com m and line using sqlplus. 2. When prom pt ed, ent er system as a usernam e, manager as a password, and tshirts as a host st ring. 3. Ent er @\examples\config\dbscripts\oracle\createsh irtsdb.sql and press t he Ent er key. Alt ernat ely, you m ay ent er @\examples\config\dbscripts\oracle\createsh irtsdbforch10.sql and press t he Enter key t o configure t he dat abase wit h t he schem a t o be used wit h Chapt er 10's new SQL t ype exam ples.

- 1255 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Your Oracle8i dat abase should now be ready for use wit h our exam ples. Not e t hat you can also rem ove t he dat abase by execut ing our < CD_ROOT>\examples\config\dbscripts\oracle\removeshirtsdb .sql script . You can rem ove t he special Chapt er 10 dat abase by execut ing our < CD_ROOT>\examples\config\dbscripts\oracle\removeshirtsdb forch10.sql script . Cha nging Pr ope r t ie s File s for Or a cle Configur a t ion

Our configurable Java propert ies files on t he CD for m any exam ples t ypically cont ain t wo dat abase ent ries, which m ay vary bet ween dat abase inst allat ions. The DRIVER_CLASS propert y can be set equal t o oracle.jdbc.driver.OracleDriver if you are using t he Oracle t hin JDBC driver. The DATABASE_URL propert y m ay vary depending on your inst all but can be configured in our propert ies files wit h jdbc:oracle:thin:@localhost:1521:TSHIRTS. I f you have inst alled your dat abase on a rem ot e m achine, you will need t o replace t he localhost value wit h t he host nam e or I P address of t he rem ot e m achine. Also not e t hat t he default dat abase port of 1521 is assum ed and t hat an SI D of TSHIRTS is also presum ed. Addit ionally, when using t he Oracle dat abase wit h t he BEA WebLogic Server, you'll also need t o configure t he [WEBLOGIC_HOME]\weblogic.properties file wit h t he following ent ries:

# This connection pool uses the Oracle database. # Used by the EJBean, JHTML, JSP, and JMS examples. weblogic.jdbc.connectionPool.ejavaPool=} url=jdbc:oracle:thin:@localhost:1521:TSHIRTS,} driver= oracle.jdbc.driver.OracleDriver,} initialCapacity=1,} maxCapacity=2,} capacityIncrement=1,} props=user=TSHIRTS;password=TSHIRTS; # Add a TXDataSource for the connection pool: weblogic.jdbc.TXDataSource.weblogic.jdbc.jts.ejavaPool=ej avaPool # # Add an ACL for the connection pool: weblogic.allow.reserve.weblogic.jdbc.connectionPool.ejava Pool=everyone

- 1256 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

When using t he Oracle dat abase wit h t he J2EE reference im plem ent at ion server, you'll need t o configure t he [J2EE_HOME]\config\default.properties file wit h t he following ent ry:

jdbc.datasources= jdbc/Cloudscape|jdbc:oracle:thin:@localhost:1521:TSHIRTS; create=true;

W e b Con figu r a t ion Various configurat ion variables and execut ion script s can be used t o build and execut e t he Web exam ples present ed in Chapt er 32, " Java Servlet s," Chapt er 33, " JavaServer Pages," and Chapt er 37, " Advanced Ent erprise JavaBeans Serving." These exam ples can be execut ed in eit her t he J2EE reference im plem ent at ion or t he BEA WebLogic Server. This sect ion describes t hese Web configurat ion procedures. W e b Configur a t ion Pr ope r t ie s for t he J2 EE Re fe r e nce I m ple m e nt a t ion For t he J2EE reference im plem ent at ion's Web server environm ent , a special [J2EE_HOME]\config\web.properties file needs t o be m odified. The HTTP port in t hat file needs t o be set t o 7001 for our exam ples as shown here:

http.port=7001 W e b Configur a t ion Pr ope r t ie s for t he BEA W e bLogic Se r ve r The BEA WebLogic Server's Web server is configured wit h configurat ion variables set inside of t he [WEBLOGIC_HOME]\weblogic.properties file. The root cont ext for running t he Chapt er 32 Java Servlet exam ples in t he book needs t o point t o t he [WEBLOGIC_HOME]/myserver/ servletsch32.war WAR file creat ed in Chapt er 32 as exem plified here:

weblogic.httpd.webApp.beeshirts= D:/weblogic/myserver/servletsch32.war The root cont ext defined in t he [WEBLOGIC_HOME]\weblogic.properties file for running t he Chapt er 33 JavaServer Pages exam ples needs t o point t o t he

- 1257 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

[WEBLOGIC_HOME]/myserver/jspch33.war WAR file creat ed in Chapt er 33 as exem plified here:

weblogic.httpd.webApp.beeshirtsjsp= D:/weblogic/myserver/jspch33.war Sim ilarly, t he root cont ext defined in t he [WEBLOGIC_HOME]\weblogic.properties file for running t he Chapt er 37 int egrat ed JavaServer Pages and EJB exam ples needs t o point t o t he [WEBLOGIC_HOME]/myserver/jspch37.war WAR file creat ed in Chapt er 37 as exem plified here:

weblogic.httpd.webApp.beeshirtsjsp= D:/weblogic/myserver/jspch37.war The Chapt er 32, 33, and 37 exam ples also need t o have a weblogic.httpd.documentRoot propert y from t he [WEBLOGIC_HOME]\weblogic.properties file configured as exem plified here:

weblogic.httpd.documentRoot=D:/weblogic/myserver/ The Chapt er 33 and Chapt er 37 exam ples also need t o have weblogic.httpd.register and weblogic.httpd.initArgs propert ies from t he [WEBLOGIC_HOME]\weblogic.properties file configured as exem plified here:

weblogic.httpd.register.*.jsp=} weblogic.servlet.JSPServlet weblogic.httpd.initArgs.*.jsp=} pageCheckSeconds=1,} compileCommand=c:/jdk1.2.2/bin/javac.exe,} workingDir=D:/weblogic/myserver,} verbose=true Not e also t hat we have included a WebLogic specific weblogic.xml file in t he examples/src/ ejava/ejbch37/webclient direct ory as well. This file cont ains JNDI nam e m appings for EJB references ut ilized by t he web applicat ion code. At t he t im e of t his writ ing, BEA WebLogic did not provide a PUBLIC URL for use from wit hin t he DOCTYPE t o reference t he st ruct ure of t his file and also did not provide a public nam e for t his DTD. Thus, we had t o use a SYSTEM URI t o reference t he DTD t hat sit s in t he

- 1258 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

[WEBLOGIC_HOME]/classes/weblogic/servlet/internal/ dd/weblogic-web-jar.dtd file equipped wit h t he BEA WebLogic inst allat ion. You t hus m ust m odify t he weblogic.xml file t o reference t he correct root WebLogic inst allat ion direct ory for your environm ent . For exam ple:

W e b Configur a t ion Scr ipt s for t he J2 EE Re fe r e nce I m ple m e nt a t ion Throughout t he Web chapt ers, we also include sam ple Windows script s for building and deploying J2EE Web applicat ions for use wit h t he J2EE reference im plem ent at ion. Before such J2EE reference im plem ent at ion–specific script s are run, you m ust change t o t he [J2EE_HOME]\bin direct ory in a separat e window and issue t he J2EE reference im plem ent at ion server st art up com m and ( t hat is, j2ee) . You m ust also st art up t he Cloudscape dat abase server ( t hat is, [J2EE_HOME]\bin\cloudscape -start) before running t he Web code used in Chapt er 37. The sam ple script s com pile all Java code, package t he Web m odule and EAR file, and deploy t he Web m odule t o a running J2EE server. Not e t hat you m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16, " RMI Com m unicat ions." This orb.properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. W e b Con figu r a t ion Scr ipt s for t he BEA W e bLogic Se r ve r Throughout t he Web chapt ers, we also include sam ple Windows script s for building J2EE Web applicat ions for use wit h t he BEA WebLogic Server. The sam ple script s com pile all Java code as well as package and deploy a Web m odule ( not e t hat BEA WebLogic Server v5.1 version did not support EAR file deploym ent , however) . Not e t hat Chapt er 37's examples/src/ ejava/ejbch37/webclient/buildweblogic.bat sam ple script independent ly copies our Serializable ent it y classes t o t he [WEBLOGIC_HOME]\myserver\serverclasses direct ory and does not package t hese files inside of t he deployable WAR file. This st ep was t aken due t o a class cast ing issue t hat occurs as we have

- 1259 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

experienced wit h t he BEA WebLogic v5.1 server when such classes are packaged inside of t he WAR file. The BEA WebLogic Server can t hen be st art ed wit h t he [WEBLOGIC_HOME]\startWeblogic. cmd script . Not e t hat in order t o enable t he BEA WebLogic Server t o com pile JSP classes ( used in Chapt er 37) , you m ust add t he [JAVA_HOME]\bin direct ory t o t he PATH environm ent variable t hat is set from wit hin t he [WEBLOGIC_HOME]\startWeblogic.cmd script as exem plified here:

SET PATH=C:\jdk1.2.2\bin;%PATH% Not e also t hat t he BEA WebLogic Server com es equipped wit h t he java.weblogic.jspc JSP com piler t ool t hat we use from wit hin our Chapt er 33 JSP build script s. I nst ruct ions for how t o use t he WebLogic JSP com piler can be found at ht t p: / / www.weblogic.com / docs50/ classdocs/ API _j sp.ht m l# com piler .

Applica t ion Se r ve r Con figu r a t ion Various configurat ion variables and execut ion script s can be used t o build and execut e t he applicat ion serving exam ples present ed in Chapt er 35, " Applicat ion Servers and Ent erprise JavaBeans," Chapt er 36, " Modeling Com ponent s wit h Ent erprise JavaBeans," and Chapt er 37, " Advanced Ent erprise JavaBeans Serving." These exam ples can be execut ed in eit her t he J2EE reference im plem ent at ion or t he BEA WebLogic Server. This sect ion describes t hese EJB applicat ion server configurat ion procedures. Applica t ion Se r ve r Con figu r a t ion Pr ope r t ie s for t he BEA W e bLogic Se r ve r The BEA WebLogic Server's EJB applicat ion server is configured via set t ing propert ies in t he [WEBLOGIC_HOME]\weblogic.properties file. The build script s used wit h our Part VI I exam ples for BEA WebLogic creat e EJB JAR files t hat are copied t o t he [WEBLOGIC_HOME]\myserver direct ory. At t he t im e of our creat ion of t hese exam ples, t he BEA WebLogic Server v5.1 could not deploy EJBs inside of EAR files. Deploying EJBs as EJB JARs in BEA WebLogic requires configuring t he weblogic.ejb.deploy propert y inside of t he weblogic.properties file as exem plified here for t he single EJB deployed in Chapt er 35:

# Deploys EJBeans. Add the following entries as appropriately

- 1260 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

# named with the root WEBLOGIC_HOME directory for your environment weblogic.ejb.deploy=} D:/weblogic/myserver/CreditManagerEJB.jar For Chapt er 36, t he [WEBLOGIC_HOME]\weblogic.properties file's weblogic.ejb.deploy propert y m ust be m odified t o reference t he new beans creat ed for t hat chapt er as exem plified here:

# Deploys EJBeans. Add the following entries as appropriately # named with the root WEBLOGIC_HOME directory for your environment weblogic.ejb.deploy=} D:/weblogic/myserver/CreditEJB.jar,\ D:/weblogic/myserver/CustomerEJB.jar, } D:/weblogic/myserver/TShirtEJB.jar,} D:/weblogic/myserver/ItemEJB.jar, } D:/weblogic/myserver/OrderEJB.jar, } D:/weblogic/myserver/BrowseEJB.jar, } D:/weblogic/myserver/OrderManagerEJB.jar, } D:/weblogic/myserver/ShoppingCartEJB.jar , } D:/weblogic/myserver/CreditManager36EJB.jar For Chapt er 37's int egrat ed EJB and JSP exam ple, t he [WEBLOGIC_HOME]\weblogic. properties file's weblogic.ejb.deploy propert y m ust be m odified t o reference t he t wo new beans creat ed for t hat chapt er as exem plified here:

# Deploys EJBeans. Add the following entries as appropriately # named with the root WEBLOGIC_HOME directory for your environment weblogic.ejb.deploy=} D:/weblogic/myserver/CreditEJB.jar,} D:/weblogic/myserver/CustomerEJB.jar, } D:/weblogic/myserver/TShirtEJB.jar,} D:/weblogic/myserver/ItemEJB.jar, } D:/weblogic/myserver/OrderEJB.jar, } D:/weblogic/myserver/BrowseEJB.jar, } D:/weblogic/myserver/OrderManagerEJB.jar, } D:/weblogic/myserver/ShoppingCartEJB.jar , } D:/weblogic/myserver/CreditManager36EJB.jar, } D:/weblogic/myserver/AuthenticationEJB.jar, } D:/weblogic/myserver/AuthSessionEJB.jar Finally, for Chapt er 37's int egrat ed EJB and JMS exam ple, t he [WEBLOGIC_HOME]\weblogic. properties file's

- 1261 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

weblogic.ejb.deploy propert y m ust reference t he t wo deployable beans for t hat exam ple as exem plified here:

# Deploys EJBeans. Add the following entries as appropriately # named with the root WEBLOGIC_HOME directory for your environment weblogic.ejb.deploy=} D:/weblogic/myserver/CreditEJB.jar,} D:/weblogic/myserver/CreditManager37EJB.jar Applica t ion Se r ve r Configur a t ion Scr ipt s for t he BEA W e bLogic Se r ve r Throughout t he EJB chapt ers, we also include sam ple Windows script s for building J2EE EJB and ent erprise applicat ions for t he BEA WebLogic Server. The script s com pile all Java code and package t he EJB m odules and Web m odule ( for Chapt er 37) . The BEA WebLogic Server can t hen be st art ed wit h t he [WEBLOGIC_HOME]\startWeblogic.cmd script . For Chapt er 35 and Chapt er 36, each EJB direct ory cont ains a buildweblogic.bat script t o build t he individual EJB associat ed wit h t hat direct ory. An associat ed runWebLogicClient.bat file can t hen be used t o run t he t est client for t hat bean. Alt hough each ent it y bean can be run and t est ed by it self, t he session beans require any ent it y beans t hey depend upon t o have already been deployed. Addit ionally, a buildweblogicall.bat file in t he \examples\src\ejava\ejbch36 direct ory can be used t o build all t he Chapt er 36 EJBs for BEA WebLogic. The \examples\src\ejava\ejbch37\webclient\buildweblo gic.bat file can be used t o build all t he EJBs and t he WAR file used by Chapt er 37's exam ples t hat ut ilize t he BEA WebLogic Server. Applica t ion Se r ve r Configur a t ion Scr ipt s for J2 EE Re fe r e nce I m ple m e nt a t ion We also include sam ple Windows script s for building and deploying J2EE EJB and ent erprise applicat ions for t he J2EE reference im plem ent at ion server. Before such a script is run, you m ust change t o t he [J2EE_HOME]\bin direct ory in a separat e window and issue t he J2EE reference im plem ent at ion server st art up com m and ( t hat is, j2ee) . You m ust also init iat e t he Cloudscape dat abase server using [J2EE_HOME]\bin\cloudscape -start. The J2EE reference im plem ent at ion script s com pile all Java code; package t he - 1262 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

EJB m odules, Web m odule ( for Chapt er 37) , and EAR file; and t hen deploy t he EAR file t o a running J2EE server. For Chapt er 35 and Chapt er 36, each EJB direct ory cont ains a buildj2ee.bat script t o build t he individual EJB associat ed wit h t hat direct ory. An associat ed runJ2EEClient.bat file can t hen be used t o run t he t est client for t hat bean. Alt hough each ent it y bean can be run and t est ed by it self, t he session beans require any ent it y beans t hey depend on t o have already been deployed. Addit ionally, a buildj2eeall.bat file in t he \examples\src\ejava\ejbch36 direc t ory can be used t o build all t he Chapt er 36 EJBs for t he J2EE reference im plem ent at ion. The buildj2eeall.bat file uses a buildj2eejar.bat file in each Chapt er 36 EJB direct ory. A runJ2EEClientWithAll.bat file in each Chapt er 36 EJB direct ory can also be used t o t est t he associat ed EJB encapsulat ed by t he deployed EAR file. The \examples\src\ejava\ejbch37\webclient\buildj2ee. bat file can be used t o build all t he EJBs and t he WAR file used by Chapt er 37's exam ples t hat ut ilize t he J2EE reference im plem ent at ion. Chapt er 37's buildj2ee.bat file uses a \examples\src\ejava\ejbch37\webclient\buildj2eej ars.bat file t o creat e all EJB JAR files before creat ing a WAR and t hen an EAR file. Not e t hat you m ay have copied an orb.properties file t o your [JAVA_HOME]\jre\lib direct ory if you have inst alled t he st andard RMI / I I OP ext ension per t he inst ruct ions of Chapt er 16. This orb.properties file m ust be rem oved in order t o properly run t he J2EE reference im plem ent at ion server. Not e also t hat at t he t im e of t his writ ing, t he J2EE v1.2 reference im plem ent at ion did not support t he use of com posit e prim ary keys. Thus, t he Credit EJB and it s CreditPrimaryKey com posit e prim ary key did not funct ion properly. Thus, t he Credit t est client code and CreditManagerSession EJB would not funct ion properly wit h t he J2EE reference im plem ent at ion. The J2EE v1.2.1 reference im plem ent at ion will report edly fix t his bug. The BEA WebLogic Server can be used t o fully dem onst rat e use of t he Credit and CreditManagerSession EJB code.

Ja va Be a n s Con figu r a t ion I n addit ion t o est ablishing your com m on soft ware configurat ion environm ent for Chapt er 7's sam ple code, you m ay opt ionally elect t o ut ilize a JavaBeans cont ainer environm ent . I nt egrat ed

- 1263 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Developm ent Environm ent s ( I DEs) such as Sym ant ec's Visual Café and I nprise/ Borland's JBuilder t ools provide cont ainer im plem ent at ions wit hin which your JavaBean can be m anipulat ed during design- t im e. The JavaBeans Developm ent Kit ( BDK) , downloadable from t he Sun Web sit e at ht t p: / / j ava.sun.com / beans/ soft ware/ bdk_download.ht m l, can also be used t o provide an environm ent for creat ing JavaBean com ponent s and includes a reference JavaBean cont ainer known as t he " BeanBox."

XM L Con figu r a t ion BEA WebLogic and t he J2EE reference im plem ent at ion bot h include XML parsers under t he hood t o int erpret J2EE XML- based deploym ent descript ors. However, t he st andard Java API for XML Parsing ( JAXP) im plem ent at ion can be downloaded from ht t p: / / j ava.sun.com / xm l/ download.ht m l. JAXP will com e in handy part icularly for code exam ples in Chapt er 31, " XML."

CORBA ORB Con figu r a t ion The Java I DL ORB com es equipped wit h t he J2SE inst allat ion and is ready t o use wit h our exam ples. We have also included t he I nprise Visigenics Visibroker for Java ORB on t he CD t o use wit h t he CORBA relat ed exam ples in t he book which ut ilize feat ures t hat are not support ed by Java I DL. The I nprise Visigenics ORB is included on t he CD in t he \cots\inprise direct ory and can be inst alled t o a root direct ory on your local m achine. You m ust sim ply set t he VISIGENIC_HOME environm ent propert y t hat we use wit h our exam ples t o t he root direct ory of your I nprise Visigenic inst allat ion as exem plified here:

set VISIGENIC_HOME=D:\visigenics

CORBA Se r vice s Con figu r a t ion The I nprise Visigenics ORB product com es equipped wit h t he CORBA Nam ing Service and CORBA Event s Service used by our exam ples in t he book. Addit ionally, Prism Technologies's OpenFusion suit e of CORBAservices ( including a CORBA Nam ing Service and CORBA Event s Service) on t he CD can be used wit h t he I nprise Visigenics ORB. I n part icular, we use OpenFusion's CORBA Trading Service wit h our exam ples. The OpenFusion product suit e is included on t he CD in t he \cots\prismtech direct ory. You m ust set t he OPEN_FUSION_HOME environm ent propert y t hat we use wit h our

- 1264 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

exam ples t o t he root direct ory of your Prism Technologies OpenFusion inst allat ion as exem plified here:

set OPEN_FUSION_HOME=C:\prismtech You will also need t o add t he following line t o t he [OPEN_FUSION_HOME]\bin\configure.bat file ( subst it ut ing t he [VISIGENIC_HOME] value shown wit h t he root direct ory of your I nprise Visigenic inst allat ion) :

SET CPATH=[VISIGENIC_HOME]\lib\vbjorb.jar; [VISIGENIC_HOME]\lib\vbjapp.jar;%CPATH% You'll need t o change t o t he [OPEN_FUSION_HOME]\bin direct ory and execut e t he configure.bat script file. A pop- up dialog t hen appears, and you m ust click t he Next but t on unt il you are given t he opt ion t o save your configurat ion t o t he regist ry. Thereaft er, you m ust execut e t he manager.bat file in t he [OPEN_FUSION_HOME]\bin direct ory. From wit hin t he result ing pop- up window, you t hen m ust click on t he Trading Service opt ion and subsequent ly elect t o st art t he server when prom pt ed. You can t hen use t he runtrading.bat file equipped wit h t he CORBA Trading Service sam ple code in Chapt er 20, " Direct ory and Trading Services."

RM I / I I OP Con figu r a t ion You m ust download and inst all t he RMI / I I OP st andard ext ension for use wit h t he J2SE v1.2 plat form , whereas RMI / I I OP com es equipped wit h t he J2SE v1.3 plat form . The RMI / I I OP download package and inst ruct ions can be found at ht t p: / / j ava.sun.com / product s/ rm iiiop/ index.ht m l. You also m ust set an RMI_IIOP_HOME environm ent variable t o t he root direct ory for your RMI / I I OP inst allat ion when running any exam ples. Not e t hat it is very im port ant t o m ake sure t hat t he orb.properties file generat ed during t his inst allat ion is copied properly t o your [JAVA_HOME]\jre\lib direct ory. The inst allat ion program m ay at t em pt t o copy t his file t o anot her direct ory t hat it perceives as t he JRE library direct ory, so st ep t hrough t he inst allat ion process carefully. Not e, however, t hat t his orb.properties file m ust be rem oved when at t em pt ing t o properly run t he J2EE reference im plem ent at ion server wit h t he ot her exam ples in t he book. The RMI / I I OP I DL- t o- Java com piler can be downloaded from ht t p: / / developer.j ava.sun.com / developer/ earlyAccess/ idlc/ index.ht m l. A single idlc1_0_1ea.zip file is downloaded which cont ains a

- 1265 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

single idlj.jar file t hat m ust be copied int o t he [RMI_IIOP_HOME]\lib direct ory.

JN D I Con figu r a t ion JNDI com es packaged wit h t he J2EE API s provided by bot h t he BEA WebLogic Server and t he J2EE reference im plem ent at ion. JNDI can also be downloaded separat ely and run in a st andalone J2SE v1.2 environm ent from ht t p: / / j ava.sun.com / product s/ j ndi/ . The J2SE v1.3 environm ent com es wit h JNDI but cannot be used wit h t he J2EE v1.2 environm ent s. JNDI SPI im plem ent at ions can be downloaded from ht t p: / / j ava.sun.com / product s/ j ndi/ serviceproviders.ht m l. To run our sam ple JNDI soft ware wit h t he book, you'll need t o set t he JNDI_HOME environm ent variable t o t he root direct ory of your JNDI inst allat ion as exem plified here:

set JNDI_HOME=C:\unzipped\jndi1_2_1 To run our sam ple soft ware t hat uses t he file- syst em JNDI SPI , you'll need t o set t he FSCONTEXT_HOME environm ent variable t o t he root direct ory of your file- syst em SPI inst allat ion as exem plified here:

set FSCONTEXT_HOME = D:\unzipped\fscontext1_2beta2 To run our sam ple soft ware t hat uses t he RMI regist ry JNDI SPI , you'll need t o set t he RMICONTEXT_HOME environm ent variable t o t he root direct ory of your RMI regist ry SPI inst allat ion as exem plified here:

set RMICONTEXT_HOME= D:\unzipped\rmiregistry1_2_1 To run our sam ple soft ware t hat uses t he CORBA Nam ing Service JNDI SPI , you'll need t o set t he COSCONTEXT_HOME environm ent variable t o t he root direct ory of your CORBA Nam ing Service SPI inst allat ion as exem plified here:

set COSCONTEXT_HOME=D:\unzipped\cosnaming1_2_1 You'll also need t o set t he RMI_IIOP_HOME environm ent variable t o t he root direct ory of your RMI / I I OP inst allat ion for bot h t he CORBA

- 1266 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Nam ing Service and t he RMI regist ry JNDI exam ples as exem plified here:

set RMI_IIOP_HOME=C:\rmi-iiop To run our sam ple soft ware t hat uses t he LDAP JNDI SPI , t he LDAP_HOME environm ent variable m ust be set t o t he root direct ory of your LDAP JNDI SPI inst allat ion as exem plified here:

set LDAP_HOME=C:\unzipped\ldap-spi

LD AP Con figu r a t ion Chapt er 20 ut ilizes an act ual LDAP server in addit ion t o an LDAP SPI t o provide direct ory service funct ionalit y exam ples t hrough JNDI . We used t he Net scape Direct ory Server v4.11 wit h our exam ples. The Net scape Direct ory Server can be downloaded from iPlanet .com at ht t p: / / www.iplanet .com / downloads/ download/ index.ht m l. Aft er you have downloaded and spawned t he Net scape Direct ory Server GUI set up program , you m ust proceed wit h a set of configurat ion st eps as described here: 1. Select t he opt ion t o inst all as a Net scape Server when prom pt ed by t he Net scape Direct ory Server GUI inst allat ion program . 2. Select t he Typical inst all opt ion when prom pt ed. 3. Select t he inst allat ion direct ory of your choice when prom pt ed. 4. Select t he product s t hat you want t o inst all when prom pt ed. The opt ional Net scape Direct ory Server Synch Service product is not necessary. 5. Select t he first t im e configurat ion when prom pt ed, unless you already have inst alled t he Net scape Direct ory Server. 6. I f t his is your first - t im e inst allat ion, you m ay not have any exist ing dat a t o im port when t he inst allat ion wizard prom pt s you for such dat a. No ext ra special dat a is needed t o run our exam ples. 7. Est ablish your localhost as t he server ident ifier and a port num ber of 389 when prom pt ed. Also be sure t o set t he suffix as o=Airius.com when prom pt ed. 8. Est ablish any adm inist rat ion I D and passwords t hat you like when prom pt ed. 9. Provide t he direct ory- m anager nam e and password when prom pt ed.

- 1267 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

The Net scape Direct ory Server should now be set up. When you first inst all t he Net scape Direct ory Server, no direct ory service dat a is loaded. For our exam ples in t he book, we use som e sam ple dat a t hat com es wit h Net scape Direct ory Server. This dat a is st ored in an Airius.ldif st ored file in t he [NETSCAPE_DIRECTORY_SERVER_HOME]\slapd-localhost\ldif direct ory. To load such dat a, follow t hese st eps: 1. I nvoke t he Net scape Console 4.1 applicat ion ( from t he Windows St art m enu) . 2. Select t he left hand t ree node direct ory server on t he localhost, and click t he Edit but t on on t he right side of t he window. 3. A new window t it led Netscape Directory Server localhost should now appear. 4. Select t he Console, I m port m enu it em from t hat window. 5. Select t he [NETSCAPE_DIRECTORY_SERVER_HOME]\slapdlocalhost\ldif\Airius.ldif file for im port . Our exam ples from Chapt er 20 m ay now be run, and t hey m ay ut ilize t his default direct ory service dat a.

Jin i Con figu r a t ion Jini is used in Chapt er 20 as a t rading service. The Jini Technology SDK can be downloaded from ht t p: / / developer.j ava.sun.com / developer/ product s/ j ini/ . We assum e t hat t he root direct ory of your Jini inst allat ion is ident ified by a JINI_HOME environm ent variable for Chapt er 20's exam ples as exem plified here:

set JINI_HOME=D:\jini1_0_1

JM S Con figu r a t ion We use t he JMS infrast ruct ure provided wit h t he BEA WebLogic Server wit h our Chapt er 22 and Chapt er 37 JMS exam ples. Thus, JMS will largely be configured for use aft er you have gone t hrough t he BEA WebLogic Server Configurat ion st eps defined previously. You m ust add t he [EJAVA_HOME]\examples\classes direct ory t o t he JAVA_CLASSPATH variable cont ained in t he [WEBLOGIC_HOME]\startweblogic.cmd script before st art ing t he BEA WebLogic Server for use wit h our JMS code. For exam ple:

- 1268 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

set JAVA_CLASSPATH=.\classes\boot;.\eval\cloudscape\lib\cloud scape.jar; [EJAVA_HOME]\examples\classes You will also want t o clean your [EJAVA_HOME]\examples\classes direct ory before running our sam ple JMS execut ion script s. Finally, t he BEA WebLogic Server is inform ed about t he use of a special st art up t hread handler class ( t hat is, JMSReceiver) in Chapt er 37's int egrat ed EJB and JMS exam ple and is configured t o pass in init ializat ion param et ers from wit hin t he weblogic.properties file for t he server as shown here:

# Define JMSReceiver as startup class with init parameters shown here weblogic.system.startupClass.JMSReceiver=} ejava.ejbch37.creditmgr.JMSReceiver weblogic.system.startupArgs.JMSReceiver=} JMS_TOPIC=JMS_CREDIT_TOPIC

Ja va M a il Con figu r a t ion Our sam ple JavaMail code in Chapt er 22 ut ilizes a POP3 provider. The POP3 v1.1.1 provider can be downloaded from ht t p: / / j ava.sun.com / product s/ j avam ail/ pop3.ht m l. The POP3_HOME environm ent variable used in our sam ple script s m ust be set t o t he root direct ory of your POP3 provider inst allat ion. Because t he POP3 v1.1.1 provider is com pat ible only wit h JavaMail v1.1.3, you'll also need t o download t he JavaMail st andard ext ension from ht t p: / / j ava.sun.com / product s/ j avam ail/ and t he Java Act ivat ion Fram ework v1.0.1 from ht t p: / / j ava.sun.com / beans/ glasgow/ j af.ht m l. The POP3 v1.1.1 provider t hat we ut ilize is not com pat ible wit h JavaMail v1.1.2 and t hus cannot be used wit h t he JavaMail API equipped wit h t he J2EE v1.2 reference im plem ent at ion. To run our exam ples, a MAIL_HOME and JAF_HOME environm ent variable m ust be set t o t he root direct ory of your JavaMail and Java Act ivat ion Fram ework inst allat ion, respect ively. We do, however, ut ilize t he JavaMail SMTP im plem ent at ion provided wit h t he J2EE reference im plem ent at ion wit h t he int egrat ed EJB and JavaMail sam ple code of Chapt er 37. The AuthenticationSessionEJBean class in t he examples\src\ejava\ejbch37\authenticationsession direct ory sends an em ail m essage via JavaMail. I n order t o support t his funct ionalit y, you will have t o set t he elem ent defined - 1269 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

in t he examples\src\ejava\ejbch37\authenticationsession\sunj2ee-ri.xml file t o an appropriat e SMTP server nam e ( for exam ple, sm t p.m yHost .com ) . The BEA WebLogic v5.1 Server does not support t he JavaMail funct ionalit y present ed in Chapt er 37.

Appe n dix B. Addit ion a l Re sou r ce s This appendix cont ains references t o addit ional resources t hat can be used t o augm ent t he m at erial present ed in t his book. For t he lat est list of such resources, cont act Assured Technologies, I nc.'s inform at ion t echnology resources sit e at ht t p: / / www.assuredt ech.com / resources. The accom panying CD also includes a collect ion of Web resources, st ored beneat h t he webref direct ory.

Obj e ct - Or ie n t e d a n d Com pon e n t - Ba se d Soft w a r e D e ve lopm e n t We list resources for addit ional inform at ion on obj ect - orient ed soft ware developm ent and com ponent - based soft ware developm ent here: Booch Gr ady; Obj ect - Or i ent ed Anal ysi s and Desi gn wi t h Appl i cat i ons , Second Edi t i on; Benj ami n- Cummi ngs; Redwood Ci t y, CA; 1994. Er i ksson Hans- Er i k Magnus Penker ; UML Tool ki t ; Wi l ey; New Yor k; 1998. Gamma Er i c ; Desi gn Pat t er ns: El ement s of Reusabl e Obj ect - Or i ent ed Sof t war e; Addi son- Wesl ey; Readi ng, MA; 1995. Hi l l si de Gr oup; Pat t er ns Home Page; ht t p: / / hillside.net / pat t erns/ . Jacobson I var ; Obj ect - Or i ent ed Sof t war e Engi neer i ng: A Use Case Dr i ven Appr oach, Revi sed Pr i nt i ng; Addi son- Wesl ey; Har l ow, Engl and; 1992. Jacobson I var ; The Obj ect Advant age: Busi ness Pr ocess Reengi neer i ng wi t h Obj ect Technol ogy ; Addi son- Wesl ey; Wor ki ngham, Engl and; 1995. Mar chukov Mar k; Component Sof t war e Resour ces ;

ht t p: / / www.geocit ies.com / m _a_r_c_h/ com ponent s.ht m l . Rumbaugh James ; Obj ect - Or i ent ed Model i ng and Desi gn; Pr ent i ce Hal l ; Engl ewood Cl i f f s, NJ; 1991.

- 1270 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Sof t war e Engi neer i ng I nst i t ut e, Car negi e Mel l on Uni ver si t y; Component - Based Sof t war e Devel opment / COTS I nt egr at i on; ht t p: / / www.sei.cm u.edu/ st r/ descript ions/ cbsd.ht m l .

Ja va Ba sics We list resources for addit ional inform at ion on t he Java language, basic Java API s, and t he J2SE here: Flanagan David; Java in a Nut shell, Second Edit ion; O'Reilly; Cam bridge, MA; 1997. Jaworski Jam ie; Java 1.1 Developer's Guide, Second Edit ion; Sam s.net Publishing; I ndianapolis, I N; 1997. Sun Microsyst em s, I nc.; Applet Tag; ht t p: / / j ava.sun.com / product s/ j dk/ 1.1/ docs/ guide/ m isc/ applet .ht m l. Sun Microsyst em s, I nc.; Java 2 SDK, St andard Edit ion; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ . Sun Microsyst em s, I nc.; Java 2 SDK, St andard Edit ion Docum ent at ion; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ index.ht m l. Sun Microsyst em s, I nc.; Java 2 Plat form , St andard Edit ion, v1.2.2 API Specificat ion; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ api/ index.ht m l. Sun Microsyst em s, I nc.; Manifest File Form at ; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ j ar/ m anifest .ht m l.

J2 EE Ba sics We list resources for addit ional inform at ion on t he J2EE and t he BEA WebLogic Server product here: BEA WebLogic; BEA WebLogic Server v5.1 Docum ent at ion; ht t p: / / www.weblogic.com / docs50/ resources.ht m l. Sun Microsyst em s, I nc.; Java 2 Plat form , Ent erprise Edit ion; ht t p: / / www.j avasoft .com / j 2ee/ . Sun Microsyst em s, I nc.; Java 2 Plat form , Ent erprise Edit ion, v1.2 Specificat ion; ht t p: / / www.j avasoft .com / j 2ee/ download.ht m l# specs. Sun Microsyst em s, I nc.; JSR- 000058 Java 2 Plat form , Ent erprise Edit ion 1.3 Specificat ion ( J2EE 1.3) ; ht t p: / / j ava.sun.com / about Java/ com m unit yprocess/ j sr/ j sr_058_j 2ee13.ht m l.

Use r I n t e r fa cin g

- 1271 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

We list resources for addit ional inform at ion on Java user int erfacing API s here: Sun Microsyst em s, I nc.; Abst ract Window Toolkit ( AWT) ; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ awt / index.ht m l. Sun Microsyst em s, I nc.; Java 3D API ; ht t p: / / j ava.sun.com / product s/ j avam edia/ 3D/ . Sun Microsyst em s, I nc.; Java Foundat ion Classes ( JFC) ; ht t p: / / j ava.sun.com / product s/ j fc/ index.ht m l. Sun Microsyst em s, I nc.; JavaHelp; ht t p: / / j ava.sun.com / product s/ j avahelp/ . Sun Microsyst em s, I nc.; Java Media API s; ht t p: / / j ava.sun.com / product s/ j avam edia/ index.ht m l. Sun Microsyst em s, I nc.; The Swing Connect ion; ht t p: / / j ava.sun.com / product s/ j fc/ t sc/ index.ht m l.

Ja va Be a n s We list resources for addit ional inform at ion on JavaBeans here: Sun Microsyst em s, I nc.; JavaBeans Com ponent API ; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ beans/ index.ht m l. Sun Microsyst em s, I nc.; JavaBeans Specificat ions for Java 2; ht t p: / / j ava.sun.com / beans/ glasgow/ . Sun Microsyst em s, I nc.; I nfoBus; ht t p: / / j ava.sun.com / beans/ infobus/ .

D a t a ba se D e ve lopm e n t a n d JD BC We list resources for addit ional inform at ion on dat abase developm ent and t he JDBC API here: Silberschat z Kort h; Dat abase Syst em Concept s; McGraw- Hill; New York; 1986. Sun Microsyst em s, I nc.; JDBC Dat a Access API ; ht t p: / / j ava.sun.com / product s/ j dbc/ . Sun Microsyst em s, I nc.; JDBC 1.X Specificat ions; ht t p: / / j ava.sun.com / product s/ j dbc/ download2.ht m l. Sun Microsyst em s, I nc.; JDBC 2.X Specificat ions; ht t p: / / j ava.sun.com / product s/ j dbc/ download.ht m l. Sun Microsyst em s, I nc.; JDBC 3.0 Specificat ion JSR; ht t p: / / j ava.sun.com / about Java/ com m unit yprocess/ j sr/ j sr_054_j dbc3.ht m l.

- 1272 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Sun Microsyst em s, I nc.; SQL t o Java Type Mapping; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ j dbc/ spec/ j dbcspec.fram e8.ht m l.

Ge n e r a l D ist r ibu t e d Com m u n ica t ion s a n d TCP/ I P We list resources for addit ional inform at ion on TCP/ I P and dist ribut ed com m unicat ions t opics in general here: Casad Joe Bob Willsey; Teach Yourself TCP/ I P in 24 Hours; Sam s; I ndianapolis, I N; 1999. FreeSoft ; I nt ernet Encyclopedia; ht t p: / / freesoft .org/ CI E/ Topics/ index.ht m . Spurgeon Charles; Et hernet Web Sit e; ht t p: / / www.ot s.ut exas.edu/ et hernet / . I nt ernet Engineering Task Force; ht t p: / / www.iet f.org. St allings William ; Dat a and Com put er Com m unicat ions, Sixt h Edit ion; Macm illan; New York; 1999. Sun Microsyst em s, I nc.; J2SE Net working Feat ures; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ net / index.ht m l.

CORBA We list resources for addit ional inform at ion on CORBA in general as well as on Java- relat ed CORBA t echnology here: Dist ribut ed Obj ect Com put ing Group, Washingt on Universit y in St . Louis; OMG CORBA Docum ent s in PDF; ht t p: / / t ao.cs.wust l.edu/ corba/ . McCart y Bill Luke Cassady- Dorion; Java Dist ribut ed Obj ect s; Sam s; I ndianapolis, I N; 1999. Obj ect Managem ent Group; CORBA/ I I OP Specificat ion; ht t p: / / www.om g.org/ corba/ corbaiiop.ht m l. Obj ect Managem ent Group; CORBA Services Specificat ion; ht t p: / / www.om g.org/ library/ csindx.ht m l. Obj ect Managem ent Group; I DL t o Java Language Mapping; ht t p: / / www.om g.org/ corba/ clchpt er.ht m l# ij lm . Obj ect Managem ent Group; Java t o I DL Language Mapping; ht t p: / / www.om g.org/ corba/ clchpt er.ht m l# j ilm . Obj ect Managem ent Group; OMG Hom e Page; ht t p: / / www.om g.org. Orfali Robert Dan Harkey

RM I

- 1273 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

We list resources for addit ional inform at ion on RMI via JRMP and I I OP here: McCart y Bill Luke Cassady- Dorion; Java Dist ribut ed Obj ect s; Sam s; I ndianapolis, I N; 1999. Sun Microsyst em s, I nc.; RMI Specificat ion; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ rm i/ spec/ rm iTOC.doc.ht m l. Sun Microsyst em s, I nc.; Java Rem ot e Met hod I nvocat ion ( RMI ) ; ht t p: / / j ava.sun.com / product s/ j dk/ rm i/ . Sun Microsyst em s, I nc.; RMI over I I OP; ht t p: / / j ava.sun.com / product s/ rm i- iiop/ .

COM / D COM We list resources for addit ional inform at ion on COM/ DCOM in general as well as on Java relat ed COM/ DCOM t echnology here: Adler Dan; " Using RMI and JDBC From Visual Basic" ; JavaReport ; Nov em ber 1998. Maso Brian; Visual J+ + 6 from t he Ground Up; Osborne/ McGraw Hill; New York; 1999. McCart y Bill Luke Cassady- Dorion; Java Dist ribut ed Obj ect s; Sam s; I ndianapolis, I N; 1999. Microsoft Corporat ion; DCOM; ht t p: / / www.m icrosoft .com / com / t ech/ dcom .asp. Sessions Roger; COM and DCOM; Wiley; New York; 1998.

JN D I , N a m in g, D ir e ct or y, Tr a din g, a n d Jin i Se r vice s We list resources for addit ional inform at ion on JNDI , nam ing services, direct ory services, t rading services, and Jini here: Edwards Keit h W.; Core Jini; Prent ice Hall PTR; Upper Saddle River, NJ; 1999. I nform at ion Technology Division, Universit y of Michigan; Light w eight Direct ory Access Prot ocol; ht t p: / / www.um ich.edu/ ~ dirsvcs/ ldap/ ldap.ht m l. I nt ernet Soft ware Consort ium ; I SC BI ND; ht t p: / / www.isc.org/ bind.ht m l. Jini Com m unit y; Jini Com m unit y Hom e Page; ht t p: / / www.j ini.org. Kosovic Douglas; Trader I nform at ion Service; ht t p: / / archive.dst c.edu.au/ AU/ research_news/ odp/ t rader/ t rader.ht m l. Microsoft Corporat ion; Act ive Direct ory Archit ect ure; ht t p: / / www.m icrosoft .com / windows2000/ library/ howit works/ act ivedirect ory/ adar ch.asp.

- 1274 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Net scape Com m unicat ions Corporat ion; The St ring Represent at ion of LDAP Search Filt ers; ft p: / / ft p.isi.edu/ in- not es/ rfc2254.t xt . Perrone Paul KrishnaChagant i; " Java Nam ing and Direct ory Service I nt erfaces" ; Dist ribut ed Com put ing; Oct ober 1999 ( online copy at ht t p: / / www.assuredt ech.com / papers/ j ndi/ dc99.pdf) . Perrone Paul Krishna Chagant i; " Jini in t he Box" ; Em bedded Syst em s Program m ing; Novem ber 1999; cover st ory ( online copy at ht t p: / / www.assuredt ech.com / papers/ j ini/ em bedded.pdf) . Prism Technologies, I nc.; OpenFusion Hom e Page; ht t p: / / www.prism t echnologies.com / product s/ openfusion/ m ain.ht m . Salam on András; DNS Resources Direct ory; ht t p: / / www.dns.net / dnsrd/ . Sun Microsyst em s, I nc.; Java Nam ing and Direct ory I nt erface ( JNDI ) ; ht t p: / / j ava.sun.com / product s/ j ndi/ . Sun Microsyst em s, I nc.; JNDI Service Providers; ht t p: / / www.j avasoft .com / product s/ j ndi/ serviceproviders.ht m l. Sun Microsyst em s, I nc.; JavaI DL Nam ing Service; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ idl/ j idlNam ing.ht m l.

M OM , JM S, a n d Ja va M a il We list resources for addit ional inform at ion on m essaging syst em s and t echnology in general, JMS, and JavaMail here: FreeSoft ; Mail; ht t p: / / freesoft .org/ CI E/ Topics/ 91.ht m . FreeSoft ; Post Office Prot ocol; ht t p: / / freesoft .org/ CI E/ RFC/ 1725/ index.ht m . FreeSoft ; Sim ple Mail Transfer Prot ocol; ht t p: / / freesoft .org/ CI E/ RFC/ 821/ index.ht m . Sun Microsyst em s, I nc.; JavaMail API ; ht t p: / / j ava.sun.com / product s/ j avam ail/ . Sun Microsyst em s, I nc.; Java Messaging Service API ; ht t p: / / j ava.sun.com / product s/ j m s/ .

D ist r ibu t e d Tr a n sa ct ion s, JTA, a n d JTS We list resources for addit ional inform at ion on t ransact ion services, t he OTS, JTS, and JTA here: Sun Microsyst em s, I nc.; Java Transact ion API ( JTA) ; ht t p: / / j ava.sun.com / product s/ j t a/ . Sun Microsyst em s, I nc.; Java Transact ion Service ( JTS) ; ht t p: / / j ava.sun.com / product s/ j t s/ .

- 1275 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Vogel Andreas Madhavan Rangarao; Program m ing wit h Ent erprise JavaBeans, JTS and OTS; Wiley; New York; 1999.

Ge n e r a l Assu r a n ce a n d Se cu r it y We list resources for addit ional inform at ion on assurance and securit y here: Gar finkel Sim son Gene Spafford; Web Securit y & Com m erce; O'Reilly; Cam bridge, MA; 1997. Oaks Scot t ; Java Securit y; O'Reilly; Cam bridge, MA; 1998. Russell Deborah G. T. Gangem i Sr.; Com put er Securit y Basics; O'Reilly & Associat es, I nc.; Cam bridge, MA; 1991. Perrone Paul; Global Safet y Assurance: Concept s and Applicat ion t o Train Cont rol Syst em s; Universit y of Virginia; Charlot t esville, VA; 1995. Perrone Paul; Pract ical Ent erprise Assurance; ht t p: / / www.assuredt ech.com / papers/ assurance/ pea.pdf. Venners Bill; I nside t he Java Virt ual Machine; McGraw Hill; New York; 1998. Sun Microsyst em s, I nc.; Java Securit y API ; ht t p: / / j ava.sun.com / securit y/ . Sun Microsyst em s, I nc.; Java Securit y Archit ect ure ( JDK1.2) ; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ securit y/ spec/ securit yspec.doc.ht m l. Sun Microsyst em s, I nc.; Java Crypt ography Ext ension ( JCE) ; ht t p: / / j ava.sun.com / product s/ j ce/ . Sun Microsyst em s, I nc.; Java Secure Socket Ext ension ( JSSE) ; ht t p: / / j ava.sun.com / product s/ j sse/ . Sun Microsyst em s, I nc.; Java Aut hent icat ion and Aut horizat ion Service ( JAAS) ; ht t p: / / j ava.sun.com / product s/ j aas/ . Sun Microsyst em s, I nc.; Perm issions in t he Java 2 SDK; ht t p: / / j ava.sun.com / product s/ j dk/ 1.2/ docs/ guide/ securit y/ perm issions.ht m l.

Ge n e r a l W e b, H TM L, a n d Scr ipt in g We list resources for addit ional inform at ion on general Web enabling and HTML here: GuysFrom Rolla.com ; General ASP Resources; ht t p: / / www.4guysfrom rolla.com / webt ech/ index.sht m l. Nat ional Cent er for Supercom put ing Applicat ions ( NCSA) at t he Universit y of I llinois at Urbana- Cham paign ( UI UC) ; NCSA ( at UI UC) Beginner's Guide t o HTML; ht t p: / / www.ncsa.uiuc.edu/ General/ I nt ernet / WWW/ HTMLPrim er.ht m l.

- 1276 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

Sun Microsyst em s, I nc.; Java Plug- I n Product ; ht t p: / / j ava.sun.com / product s/ plugin/ index.ht m l. World Wide Web Consort ium ; W3C Hom e Page; ht t p: / / www.w3.org/ . World Wide Web Consort ium ; HTML 4 Specificat ion; ht t p: / / www.w3.org/ TR/ RECht m l40/ . World Wide Web Consort ium ; HTTP—Hypert ext Transfer Prot ocol; ht t p: / / www.w3.org/ Prot ocols/ .

XM L We list resources for addit ional inform at ion on XML here: Sun Microsyst em s, I nc.; Java Technology and XML; ht t p: / / j ava.sun.com / xm l/ . Sun Microsyst em s, I nc.; Java API for XML Parsing ( JAXP) Downloads and Specificat ions; ht t p: / / j ava.sun.com / xm l/ download.ht m l. World Wide Web Consort ium ; Ext ensible Markup Language ( XML) ; ht t p: / / www.w3.org/ XML/ . World Wide Web Consort ium ; Ext ensible Markup Language ( XML) Specificat ion; ht t p: / / www.w3.org/ TR/ REC- xm l. World Wide Web Consort ium ; XML Linking Language ( XLink) ; ht t p: / / www.w3.org/ TR/ xlink/ . World Wide Web Consort ium ; Ext ensible St ylesheet Language ( XSL) ; ht t p: / / www.w3.org/ St yle/ XSL/ . World Wide Web Journal; " XML: Principles, Tools, and Techniques" ; O'Reilly; Cam bridge, MA; 1997.

Ja va Se r vle t s a n d JSP We list resources for addit ional inform at ion on Web enabling via Java Servlet s and JSP here: Sun Microsyst em s, I nc.; Java Servlet API ; ht t p: / / j ava.sun.com / product s/ servlet / . Sun Microsyst em s, I nc.; Java Servlet Specificat ion; ht t p: / / j ava.sun.com / product s/ servlet / 2.2/ . Sun Microsyst em s, I nc.; JavaServer Pages; ht t p: / / www.j avasoft .com / product s/ j sp/ . Sun Microsyst em s, I nc.; JavaServer Pages Specificat ion; ht t p: / / www.j avasoft .com / product s/ j sp/ download.ht m l.

Applica t ion Se r vin g a n d EAI

- 1277 -

Building Ja va Ent e r pr ise Syst e m s w it h J2 EE

We list resources for addit ional inform at ion on applicat ion serving fram eworks and EAI here: I T Toolbox; I T Toolbox for ERP; ht t p: / / www.erpassist .com / . I T Toolbox; I T Toolbox for EAI ; ht t p: / / eai.it t oolbox.com / . Microsoft Corporat ion; Microsoft Windows DNA; ht t p: / / www.m icrosoft .com / dna/ . Sun Microsyst em s, I nc.; JSR- 000016 J2EE Connect or Archit ect ure; ht t p: / / j ava.sun.com / about Java/ com m unit yprocess/ j sr/ j sr_016_connect .ht m l. Sun Microsyst em s, I nc.; Java 2 Plat form , Ent erprise Edit ion; ht t p: / / www.j avasoft .com / j 2ee/ .

En t e r pr ise Ja va Be a n s We list resources for addit ional inform at ion on Ent erprise JavaBeans here: Sun Microsyst em s, I nc.; Ent erprise JavaBeans; ht t p: / / j ava.sun.com / product s/ ej b/ . Sun Microsyst em s, I nc.; Ent erprise JavaBeans Specificat ion; ht t p: / / j ava.sun.com / product s/ ej b/ docs.ht m l. Sun Microsyst em s, I nc.; EJB t o CORBA Mapping Specificat ion; ht t p: / / j ava.sun.com / product s/ ej b/ docs.ht m l. Sun Microsyst em s, I nc.; JSR- 000019 Ent erprise JavaBeans 2.0 Specificat ion; ht t p: / / j ava.sun.com / about Java/ com m unit yprocess/ j sr/ j sr_019_ej b2.ht m l.

- 1278 -