THE LARGEST JAVA EVENT ON THE EAST COAST
TM
The World’s Leading Java Resource Java COM August 2001 Volume:6 Issue:8
Feature: Core J2EE Patterns John Crupi 16 Learning to design comes from experience Applet EJB XML Servlet JSP Guest Editorials Enterprise Java: Fitting the Pieces into the Tony Loton by Sanjay Sarathy pg. 7 by Rob MacAulay pg. 76 Enterprise Java Puzzle Adding functionality with EJBs PART 3 24
Book Review Authorization: J2EE Application Sanjay Mahapatra by Ajit Sagar pg. 30 Security Model A powerful security model that’s robust and reliable 32 J2ME API Rundown pg. 78 Frameworks: A J2EE Application Steven Randolph Framework Checklist Building portable, scalable, and robust apps 38 Product Reviews Jeode pg. 80 Feature: FavoritesComboBox Justin Hill & David Lesle iPAQ pg. 88 STRATRARA Keep each new class simple and flexible STRATRARATEGTEGIEGIE 46 STRRATEGTEGIEEGIE Cubist Threads S TEGG by Blair Wyman pg. 114 Feature: Strategies for Storing Java Objects Scott W. Ambler RETAILERS PLEASE DISPLAY in Relational Databases Apply these fundamentals for years to come 62 UNTIL OCTOBER 31, 2001 Industry Commentary:Wireless Apps Wanted Kimberly Martin A market for third-party J2ME applications is about to explode 84
MIDlets: The Missing Bits Jason Briggs A beginner’s guide to writing applications for the MID profile PART 2 92
Java Basics: A Deeper Look at Java Jacquie Barker Anatomy of a Java program, revisited 98 FROMF THE EDITORDI J2ME INTERNATIONAL ADVISORY BOARD • CALVIN AUSTIN (Lead Software Engineer, J2SE Linux Project, Sun Microsystems), • JAMES DUNCAN DAVIDSON (JavaServlet API/XMP API, Sun Microsystems), • JASON HUNTER (Senior Technologist, CollabNet), • JON S. STEVENS (Apache Software ALANWILLIAMSON EDITOR-IN-CHIEF Foundation), • RICK ROSS (President, JavaLobby), • BILLROTH (Group Product Manager, Sun Microsystems), • BILL WILLETT (CEO, Programmer’s Paradise) • BLAIR WYMAN (Chief Software Architect IBM Rochester)
EDITORIAL J2SE EDITOR-IN-CHIEF: ALAN WILLIAMSON We All Needa Week Off in the Sun EDITORIAL DIRECTOR: JEREMY GEELAN ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI t last we can return to sanity. The Looking up the coast from Sun to another J2EE EDITOR: AJIT SAGAR J2ME EDITOR: JASON BRIGGS speeches are over, the bunting is company’s trials and tribulations, this month PRODUCT REVIEW EDITOR: JIM MILBERY Adown, and the mad hysteria is at an we saw that Microsoft was saved from the FOUNDING EDITOR: SEAN RHODY end. After the chaos of JavaOne we can return chopping block and has been allowed to stay PRODUCTION to normal. I am of course paraphrasing that together as a single operating unit. I can’t really VICE PRESIDENT,PRODUCTION AND DESIGN: great literary character Edmund Blackadder. comment on whether this is going to be a good
JIM MORGAN J2EE EXECUTIVE EDITOR: M’LOU PINKHAM It has now been a month since I arrived home thing or a bad thing, but I’m getting a little para- MANAGING EDITOR: CHERYL VAN SISE from our annual pilgrimage to JavaOne and noid regarding Microsoft’s influence on the EDITOR: NANCY VALENTINE I’m still following up on all the business cards desktop market now that Windows XP is just ASSOCIATE EDITORS: JAMIE MATUSOW that were thrust in my general direction. around the corner. For example, have you been GAIL SCHULTZ JavaOne is a great opportunity to do some following the SmartTag debate? This is where BRENDA GREENE ASSISTANT EDITOR: LIN GOETZ serious catching up and general networking, Microsoft will put hyperlinks around special and it was a real treat as Blair Wyman and I keywords it finds in all rendered HTML pages to TECHNICAL EDITOR: BAHADIR KARUV, PH.D. Home took some time out to have a chat with James link you to another site with more information. WRITERS IN THIS ISSUE Gosling about what he’s been up to lately. You For example, say your Web page happened to SCOTT AMBLER, BILL BALOGLU, JACQUIE BARKER, JASON BRIGGS, JOHN CRUPI, can read what we spoke of elsewhere in this mention Sun Microsystems somewhere in the JEREMY GEELAN, JUSTIN HILL, TONY LOTON, ROB MACAULAY, SANJAY MAHAPATRA, KIMBERLY MARTIN, BILLY PALMIERI, STEVEN RANDOLPH, AJIT SAGAR, issue. It was interesting to talk with James con- text. A small link made out of the text would – if SANJAY SARATHY, ANTHONY SIMMONS, ALAN WILLIAMSON, BLAIR WYMAN cerning the overall direction of Java and dis- you were to position your mouse over a pop-up cover how he feels about many of the issues. – display more information and optionally take SUBSCRIPTIONS: We touched on the old debate regarding Java you to another site…all without the approval or FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, being open-sourced and his response was so knowledge of the original Web site producer. In PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT wonderfully practical that I can’t help feeling principle it’s a great idea, but one that is open to SUBSCRIPTION HOTLINE:[email protected] that maybe he resents all the bickering and so much abuse. The upshot is that Microsoft has COVER PRICE: $4.99/ISSUE politics that divert attention from the underly- postponed this feature’s appearance in IE for a DOMESTIC: $69.99/YR. (12 ISSUES) ing beauty that makes Java, well…Java. little while longer, but rest assured it’ll be there in CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. The industry is still struggling to find its feet some version, at some point. (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. after the dot-bomb exploded, and desperately That aside, what annoys me most about EDITORIAL OFFICES: trying to stave off redundancies is the very com- Microsoft’s newest addition to its operating sys- SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 pany behind Java: Sun Microsystems. Although tem suite is that there’s still no embedded Java TELEPHONE: 201 802-3000 FAX:201 782-9600 we probably shouldn’t read too much into this Virtual Machine. With Microsoft’s strong relation- JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly (as Scott McNealy keeps telling us), the core ships with the major PC manufacturers, Windows (12 times a year) for $69.99 by SYS-CON Publications, Inc., 135 Chestnut Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at business at Sun is still manufacturing and sell- XP will find its way into the homes of millions of Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address ing hardware, and the work Sun does with Java users who will simply never think of installing a changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., is still very much full steam ahead. That said, as JVM, let alone replacing the operating system. 135 Chestnut Ridge Road, Montvale, NJ 07645. you’ll read from our chat, James does comment Due to the high-level politics and strategies of two ©COPYRIGHT: on the fact that “all the cool stuff with Java isn’t companies, millions of users are affected, includ- Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. done at Sun,” so even if they are hitting a rocky ing a whole development community that won’t No part of this publication may be reproduced or transmitted in any form or by any patch in the road, Java isn’t going to suffer much. be able to service this new user base. means, electronic or mechanical, including photocopy or any information storage and retrieval system, without written permission. For promotional reprints, contact reprint coor- This was the month that Sun had their We need to start moving Java applications dinator. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its famous one-week nonpaid holiday – a move into the mainstream and have sites chockful of readers to use the articles submitted for publication. to save some pennies, which for an organiza- executable JAR files that users simply 6and run WORLDWIDE DISTRIBUTION BY: tion of Sun’s size and payroll would account without worrying about the requirements they CURTIS CIRCULATION COMPANY for quite a lot of pennies. But you can’t help face in the README.TXT file beforehand. NEW MILFORD NJ wondering how many of the engineers just Maybe if we had this, Microsoft wouldn’t went into work anyway. seem half so bad. Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. SYS-CON Publications, Inc., is independent of Sun Microsystems, Inc. All brand and product names used on these pages are trade names, [email protected] service marks or trademarks of their respective companies. AUTHOR BIO Alan Williamson is editor-in-chief of Java Developer’s Journal. In his spare time he holds the post of chief technical officer at n-ary (consulting) Ltd, one of the first companies in the UK to specialize in Java at the server side. Reach him at [email protected] (www.n-ary.com) and rumor has it he welcomes all suggestions and comments!
AUGUST 2001 5
Java COM GUEST EDITORIAL
WRITTEN BY SANJAY SARATHY The rational The RingIs Bloody alternative
With too many solutions looking for a business problem to solve Version 4.5 Introductory Offer he Thrilla in Manila: both the name and the of the month might be, all businesses want to cre- events of that steamy October day in 1975 ate tighter synergies throughout their entire value $2995 Tremain seared in the memory of all who chain that encompass customers, employees, for Teamwork Server watched it. Muhammad Ali and Joe Frazier, two of suppliers, and partners. the greatest boxers in heavyweight history, battled This is truer today than ever. These synergies have toe-to-toe for 14 rounds, until Frazier’s corner sur- taken on a whole new importance thanks to the rendered and threw in the towel. explosion in online personalization; a development Today the technology industry is in the midst that now touches individual consumers as well as All 9 UML diagrams of its own thrilling fight – one that is centered on larger business-to-business operations. Additional Features: the much-hyped world of Web Services. And just As vendors, we often get so distracted by the • Performs Java, C++ or CORBA IDL as with Ali and Frazier, the various combatants are technology details that we end up losing sight of code round-trip engineering (code treating each other to verbal jabs and taunts. this bigger picture. Worse yet, perhaps, this too generation and reverse engineering); Anyone who attended JavaOne this past June wit- often makes us adversaries, leading to wasted recognizes JavaDoc comments. This nessed this, particularly at some of the morning time and energy as we throw punches at each feature allows you to write code, reverse keynotes. Unfortunately, as companies continue other about which is the best way to proceed. We engineer, make changes to the model to spar over the issue, we are losing the necessary have to remind ourselves that organizations cre- and re-generate the code without losing any implementation specific information. focus on the business impact of Web Services as ate real value when they’re able to implement each vendor beats its own technology drum. • Supports UML 1.3 notation. One thing companies don’t seem to be fighting • Saves diagrams as bitmap PNG/JPG and about is the potential of Web Services to transform scalable WMF/SVG/EPS/DXF formats. how technology is used to inspire and create new • Provides XML interoperability — native revenue-generating opportunities for all sorts of model files are stored in XMI format. businesses. However Orwellian it might sound, • Integrated with Forte for Java (FFJ) IDE the idea of creating, assembling, and deploying versions 1.0 and 2.0. personalized services across a global network and Standard Edition: ...... $249 within a contextual framework – all based on who Professional Edition: . . . . $499 you are, where you are, and what you’re doing – is an enormously appealing prospect to many. The potential to eliminate technolo- Visit us at Java One gy and business silos within and across organizational boundaries provides Floating License . . $100 additional another compelling Upgrade for a $69 annual fee! argument for Web Services, especially when companies real-
ize they won’t have to C abandon the various I investments they’ve ✦ G already made. M ✦ ▲✦ Companies agree No Magic... on something else as Just Technology That Works well: no matter what the technology flavor Download fully functional demo at: www.magicdraw.com [email protected] AUTHOR BIO contact us at Sanjay Sarathy is director of product marketing at iPlanet. He holds a BA in [email protected] quantitative economics from Stanford University and an MBA from the Haas School of Business at the University of California. 100% Pure Java Application
AUGUST 2001 7
Java COM LETTERS TO THE EDITOR The Ring ’m a subscriber to JDJ and am very happy Hi Mohan, Is Bloody with the magazine (I’m from the U.K. liv- I hope the original article was useful to Iing and working in Germany). The digital you. To answer your question, an object may edition is an excellent bonus for me as the be passed from the server to the client only if post takes awhile. The content of the maga- it’s serializable, i.e., implements the zine is simply first class, both in quality and java.io.Serializable interface. Any object not choice of subject matter – I’ll definitely renew implementing Serializable cannot be passed. my subscription when the time comes! Serialized objects are passed “by value” Another publication that interests me is across the network so that the receiver sees a WBT, which I currently read online only. I’d duplicate version of the original rather than be interested in receiving subscription the original. So even if you could pass the J2SE information/pricing for oversea subscrip- HttpSession, it would no longer reflect the cur- tions for this publication (possibly just the rent session state as kept current on the server. digital edition). Presumably you want the client to see some of In the meantime, keep up the excellent the information held within the session. How work, and I look forward to reading the next about defining your own object to hold values issue(s) extracted from the session, make it
8 AUGUST 2001
Java COM J2EE EDITORIALOR J2EE INDEXX
J2ME J2EE Design Patterns: The 10 Next Frontier AJIT SAGAR J2EE EDITOR J2EE provides component APIs that are built on solid design principles. J2EE Design Patterns:The Next Frontier by Ajit Sagar
J2SE e live in a world where of experience of a multitude of developers J2EE FAQ 12 abstraction is the name of the are available for other developers to apply, Wgame. I used to be an avid use, and learn from. The best approach is reader of Asterix comics, and thinking of to consult the appropriate documentation Core J2EE Patterns abstraction reminds me of a couple of and other resources, and not reinvent the Without design patterns, 16 panels in the “Obelix & Co.” comic book. A wheel for each new application. One of the application development can Roman emissary tries to explain to the primary advantages of this approach is be an extremely chaotic task. (simpleton) Obelix the intricacies of that your design paradigm will be support- Turn the page and see how Roman economy in simple words: “Make ed by a larger community than just the design patterns in the realm J2EE much menhir, get much gold," or some- environment that you program in. In some of J2EE can help build thing to that effect. sense, design patterns are simply commu- robust, reusable applications. I don’t mean to say that we developers nication mechanisms for application by John Crupi are simpletons. But, as my colleagues in architects, designers, and developers to marketing say, the presentation needs to share information on best design prac- Fitting the Pieces into the be “dumbed-down” for the appropriate tices. Enterprise Java Puzzle, 24 crowd. As an enterprise architect, I don’t J2EE covers a lot of areas. It’s impossi- Part 3
Home want to deal with the details of system- ble for a single person, or a group of devel- The conclusion of a very level programming and operating system opers, to acquire expertise on all of them. exciting tour on designing implementations. That is one of the rea- This problem is magnified in distributed enterprise applications using sons I chose J2EE as my reference frame- development environments where com- Java. This article uses work for implementing applications. Yes, municating the different aspects of design servlets and Session EJBs to J2EE is an abstraction, a “dumbed-down” and coordinating the modules of the provide the final pieces of the framework for me to develop distributed application becomes an extremely daunt- Enterprise Java puzzle. applications. ing task. Design patterns help alleviate a by Tony Loton One of the really neat things about Java large portion of this pain. is that it’s made standard design patterns Sun’s J2EE Blueprints provide a great Book Reviews: household names for the developer com- starting point to help developers under- Designing Enterprise 30 munity. Java is built on standard design stand the rationale behind the design of Applications with the Java 2 patterns and implementation guidelines. the J2EE platform. The sample Pet Store Platform, Enterprise Edition Five years ago, the majority of the pro- application helps put this in the perspec- & J2EE Technology in Practice grammers I talked to didn’t know what tive of a real-world demo. However, when Reviewed by Ajit Sagar design patterns were. Now, almost all Java you design a real-world application, there developers are aware of Factories, are other aspects of design that you need J2EE Application Listeners, and Adapters. The reason? Core to address. With the acceptance of J2EE as Security Model 32 Java objects use the Factory patterns. the preferred platform for building distrib- A comprehensive and concise Observer-Observable and Producer- uted applications, you’ll see richer sources overview of the J2EE applica- Listener are a part of the language. of information on building these applica- tion security framework. A Adapters and Proxies are applied all over tions emerge. great source for readers who enterprise Java applications. want an introduction to J2EE Starting This Month… security basics. J2EE Design At JDJ, we want to address this higher by Sanjay Mahapatra J2EE provides component APIs that are level of abstraction. This month and in built on solid design principles. However, subsequent issues, you’ll see more cover- J2EE Application in order to apply these APIs to build enter- age on applying J2EE into actual applica- Framework Checklist 38 prise applications, you need a good design tions. In this issue, John Crupi starts a J2EE frameworks enhance base for developing robust and reusable the offerings of application components. The good news is that years –continued on page 74 servers to provide complete application design [email protected] environments. AUTHOR BIO by Steven Randolph Ajit Sagar is the J2EE editor of JDJ, and the founding editor and editor-in-chief of XML-Journal. A lead architect with VerticalNet Solutions, based in San Francisco, he’s well versed in Java,Web, and XML technologies.
10 AUGUST 2001
Java COM J2EE FAQQ J2EE ROADMAPP
The Java2 Platform, Enterprise Edition defines the APIs for building enterprise-level applications. J2SE...... v. 1.2 J2ME WHAT ARE THE COMPONENT TECHNOLOGIES OF THE J2EE ARCHITECTURE? Q The J2EE architecture consists of the following types of Java components: Web components, EJBs, A Enterprise JavaBeans API application clients, and Java applets. Web components consist of servlets and JavaServer Pages (JSPs)...... v. 1.1 The component technologies of J2EE facilitate the development of J2EE components. Java Servlets ...... v. 2.2 These technologies are offered as a set of distributed system APIs that are specified by Sun JavaServer Pages Technology via the Java Community Process (JCP) and are open to vendors, including Sun, for imple- ...... v. 1.1 mentation. These APIs include : • Enterprise JavaBean (EJB): For developing server-side business components JDBC Standard Extension J2SE • Java Database Connectivity (JDBC): For unified RDBMS access ...... v. 2.0 • Java Message Service (JMS): For distributed messaging Java Naming and Directory • JavaMail: For e-mail services Interface API ...... v. 1.2 • Java Native Directory Interface (JNDI): For distributed naming services • JavaServer Pages (JSP): For generating dynamic HTML or XML for Web clients RMI/IIOP ...... v. 1.0 • Java Servlet: For generating dynamic HTML or XML for Web clients Java Transaction API..v. 1.0 • Java Transaction API (JTA): For managing distributed transactions • Remote Method Interface (RMI): For distributed object communications JavaMail API ...... v. 1.1
J2EE Java Messaging Service Enterprise JavaBeans are the central theme for J2EE. EJBs comprise Java’s middle-tier serv- ...... v. 1.0 er-side component model. All the other APIs exist to provide connectivity to and from EJBs. Useful URLs: WHERE DO ALL THE J2EE COMPONENTS EXIST IN A DISTRIBUTED APPLICATION? Q Java 2 Platform Enterprise Edition J2EE is a true n-tier architecture; however, the different components developed on the J2EE A http://www.java.sun.com/j2ee/ framework can be grouped into server-side and client-side components. Applets and application J2EE Blueprints clients are basically pure client-side components and execute in a virtual machine on the client http://www.java.sun.com/j2ee/ blueprints
Home machine. Applets execute in a browser, while applications can execute in other client-side processes. J2EE offers two types of Web components: servlets and JSPs. The purpose of both types J2EE Technology Center of components is the same: to serve up dynamic content to Web clients. In fact, JSPs are http://developer.java.sun.com/developer/prod- compiled into servlets during execution. This means that JSPs and servlets get requests ucts/j2ee/ from Web clients and serve back HTML (or XML). Servlets and JSPs provide the connec- J2EE Tutorial tivity between the client- and server-side components in a J2EE application. To generate http://java.sun.com/j2ee/ the right response, they can communicate with back-end data sources through JDBC, tutorial/ RMI, JMS, or JavaMail, as well as to middle tier Java components, namely, EJBs. In turn, EJBs can communicate with back-end sources.
EJBs are Java’s server-side components. EJB components are developed to model busi- ness logic for an application. EJBs can leverage other APIs to connect to and communicate with back-end systems. There are two types of EJBs – session beans, which are associated with the lifetime of a user session, and entity beans, which are associated with server-side business objects that are persisted in a database and live beyond the life of user sessions.
WHAT ARE J2EE CONTAINERS AND WHAT IS THEIR RELATION TO APPLICATION SERVER VENDORS? Q A J2EE component needs an execution environment to run in. J2EE containers are A runtime hosts for J2EE components. Since there are basically two types of middle-tier J2EE components (Web components and EJBs), there are two types of J2EE containers – Web component containers and EJB containers. Web component containers are basically servlet engines, JSP engines, and Web con- tainers. A servlet container provides network services for servlet execution, such as sup- port for HTTP, and other request-response protocols. JSP containers are basically servlet containers with the additional functionality of compiling JSP pages into servlets. As men- tioned above, JSPs become servlets at runtime. Web containers provide the additional functionality of access to other J2EE APIs, such as RMI and JDBC. EJB containers provide the runtime life-cycle management environment for EJB com- ponents. This includes EJB instantiation, communication, persistence, and transaction management, as well as access to other J2EE APIs, such as RMI and JDBC. Application server vendors such as WebSphere, BEA, iPlanet, and ATG provide implemen- tations of the J2EE service APIs and the containers in which components built on these APIs can execute. Since there are different types of J2EE containers, there are different J2EE contain- er providers. This means that you can buy the Web and EJB containers from different sources and make them communicate by using standard J2EE services. For example, a JRun servlet engine from Macromedia should be able to work with an EJB container from WebLogic.
12 AUGUST 2001
Java COM J2ME J2SE J2EE Home
to the first installment of the “Core been designing mission-critical J2EE solutions since J2EE J2EE Patterns” column by the Sun Java Center technology was introduced. (www.sun.com/service/sunps/jdc). Every other month, we In our work, we often encounter situations where, because (Deepak Alur, Danny Malks, myself, and other architects from technology is moving so quickly, designers and developers are the Sun Java Center) will discuss various topics from our book, still struggling to understand the technology, let alone how to Core J2EE Patterns, Best Practices and Strategies (Alur, Crupi, design with the technology. It’s not good enough to tell design- Malks, Prentice Hall/Sun Press, 2001). These topics include ers and developers to write good code, nor is it sufficient to each of the 15 J2EE patterns in our catalog, design strategies, suggest using servlets and JavaServer Pages (JSP) technology bad practices, refactorings and pattern-driven design in the for developing the presentation tier and EJB components for Java 2 Platform, Enterprise Edition (J2EE). developing the business tier. Since its inception, SJC architects have been working with Applying the Technology clients all over the world to successfully design, architect, Today, as in the past, many of us naively assume that learn- build, and deploy various types of systems based on Java and ing a technology is synonymous with learning to design with J2EE technology and platforms. the technology. Certainly, learning the technology is impor- Recognizing the need to capture and share proven designs tant for success in designing with the technology. Many exist- and architectures, we started to document our work on the ing Java books are excellent at explaining technology details, J2EE platform in the form of patterns in 1999. Although we such as API specifics and so forth, but at the same time they looked in the existing literature, we couldn’t find a complete give no insight on applying the technology. catalog of patterns that dealt specifically with the J2EE plat- Learning to design comes from experience and from shar- form. We found many books dealing with one or more of the ing knowledge on best practices and bad practices. The expe- J2EE technologies, which do an excellent job of explaining the riences we’ll convey in this column are derived from the work technology and unraveling the nuances of the specifications, we have done in the field. We are part of Sun Microsystems, but many of these books fall short on design. Inc.’s, Sun Java Center (SJC) consulting organization and have After two years of work on capturing J2EE patterns and
16 AUGUST 2001
Java COM documenting them in the proper pattern form, at the JavaOne levels of abstraction and in numerous domains. Numerous 2001 Conference we launched our book, which includes the categories have been suggested for classifying software pat- SJC J2EE Pattern Catalog. We also announced that four com- terns, with some of the most common patterns being:
J2ME panies and allies, Rational, TogetherSoft, Forte, and iPlanet, • Design have all agreed to bundle the SJC J2EE Pattern Catalog in their • Architectural respective tools (http://java.sun.com/pr/2001/06/pr010604- • Analysis 25.html). • Creational This is important in our eyes because patterns lend them- • Structural selves to tools so nicely. As a matter of fact, the pattern-driven • Behavioral design concept in J2EE technology is difficult without tool support. More about this later. Even within this brief list of categories, we see numerous J2SE levels of abstraction and orthogonal classification schemes. The Essence of Patterns Thus, while many taxonomies have been suggested, there is First, let’s start with a brief overview of patterns – starting no one right way to document these ideas. with some expert definitions. In our J2EE pattern catalog, each pattern hovers some- In A Pattern Language, Christopher Alexander says each where between a design pattern and an architectural pattern pattern is a three-part rule which expresses a relation between while the strategies document portions of each pattern are at a certain context, a problem, and a solution. a lower level of abstraction. The scheme we have introduced is Richard Gabriel discusses this definition in more detail in to classify each pattern within one of the following three logi- A Timeless Way of Hacking. Gabriel offers his own version of cal architectural tiers: J2EE Alexander’s definition as applied to software: each pattern is a • Presentation three-part rule that expresses a relation between a certain • Business context, a certain system of forces that occurs repeatedly in • Integration that context, and a certain software configuration that allows these forces to resolve themselves. Identifying a Pattern This is a fairly rigorous definition, but there are also much We have successfully completed and deployed many J2EE looser ones. For example, Martin Fowler, in Analysis Patterns, technology projects at the Sun Java Center, and over time have
Home offers the following definition: a pattern is an idea that has noticed that similar problems recur across these projects. We been useful in one practical context and will probably be use- have also seen similar solutions emerge for these problems. ful in others. While the implementation strategies varied, the overall solu- As you can see, there are many definitions for a pattern, tions were quite similar. Let’s discuss, in brief, our pattern but they all have a common theme relating to the recurrence identification process. of a problem/solution pair in a particular context. Some of the When we see a problem and solution recur, we try to iden- common characteristics of patterns: tify and document its characteristics using the pattern tem- • They’re observed through experience • Are typically written in a structure • Prevent reinventing the wheel • Exist at different levels of abstraction • Undergo continuous improvement • Are reusable artifacts • Communicate designs and best practices • Can be used together to solve a larger problem Categorizing Patterns Patterns, then, represent expert solutions to recurring problems in a context and thus have been captured at many
FIGURE 1 J2EE pattern relationships FIGURE 2 Pattern framework
18 AUGUST 2001
Java COM Home J2EE J2SE J2ME 20 A UGUST 2001 ed. to thehigher-level structure pattern inwhichtheyare includ- most clearlycommunicatestherelationship ofthestrategies however,right; we feelthatourcurrent templatestructure umented someofthesestrategies intheirown aspatterns solution atmultiplelevelsofabstraction. We couldhavedoc- details. Through thestrategies, documentsa eachpattern ous strategies thatprovide lower-level implementation of abstraction. At thesametime, includesvari- eachpattern made thedecisiontodocumentthematarelatively highlevel Patterns vsStrategies combination. tion by distillingthesimilarideasintoapattern/strategy the otherhand,itmightbebettertocommunicatesolu- menting twosimilarsolutionsasdifferent patterns. On munication amongdevelopers. If so, thenconsiderdocu- the solution.Sometimes, aseparate nameimproves com- it’stern, toconsiderhow important tobestcommunicate sent asinglepattern. When decidinghow thepat- toform identification. Often,similarsolutionsmayrepre-pattern suchasthis,with rules buttheyhelpprovide acontextfor systems. Certainly, there ismuchroom forinterpretation inatleastthree untilithasbeenverified pattern different catalog. guide fortransitioning intothepattern acandidatepattern Three, asitisknown community. inthepattern isa This rule inimplementedsolutions.terns miningby theprocess ofpattern undertake lookingforpat- their usagemultipletimesondifferent projects. We also cataloguntilwe are anddocument the pattern abletoobserve didate patterns. However, we don’t to addcandidatepatterns plate. At first,we considertheseinitialdocumentstobecan- Service To Worker Combines a Dispatcher componentwiththeFront CombinesaDispatcher Controllerand View HelperPatterns. thehandlingofarequest. Providesacentralizedcontrollerformanaging anaggregate subcomponents Creates View fromatomic View Dispatcher Service To Worker Composite View Facilitates preprocessingandpost-processingofarequest. View Helper Intercepting Filter SYNOPSIS PATTERN NAME Service Activator Activator Facilitates asynchronousprocessingforEJBcomponents Activator sources; providestransparent accesstodata. Abstractsdata Service Activator Data Access Object SYNOPSIS PATTERN NAME factories businessservice locates lookupandcreation; complexity ofbusinessservice Encapsulates andresultsprocessing. results caching, execution, query Manages Locator Service Facilitates exchangebetweentiersbyreducingnetworkchattiness. data handling. Hidesbusiness objectcomplexity;centralizesworkflow Value ListHandler Value Object Assembler handling. Hidesbusiness objectcomplexity;centralizesworkflow Composite Entity Value Object Session Facade andprovides tiers, andservice Decouplespresentation Business Delegate SYNOPSIS PATTERN NAME TABLE 1 TABLE 3 TABLE 2 When we started documentingtheJ2EEpatterns, weWhen we started According tothisrule, asolutionremains acandidate validation process, ofthepattern As part we usetheRule of Presentation-tier patterns Integration-tier patterns Business-tier patterns Combines a Dispatcher component with the Front Controller and View Helper Patterns, deferring many activitiesto deferringmany View processing componentwiththeFrontCombines aDispatcher Controllerand View HelperPatterns, Assembles a composite value object from multiple data sources. Assembles acompositevalueobjectfrommultipledata a facadeandproxyinterfacetotheservices stack oftiers. with theadjacenttier. We represent thewholesystemasa cally separated from oneanother. Eachtierislooselycoupled unique responsibility inthesystem. We vieweachtieraslogi- separation inthesystem.Eachtierisassignedits ofconcerns oftiers.the systeminterms ofthe Atierisalogicalpartition (andapplication)isamultitieredplatform system,we view andsinceaJ2EE on theJ2EEplatform, applications thatrun ApproachThe Tiered tion foreachtier. technology.Connectivity (JDBC) related andJava totheJava Database Message (JMS) Service related totheEJBtechnology. The integration-tier are patterns andJSPtechnology.servlets areThe business-tierpatterns approach. The presentation-tier are patterns related to according tofunctionality, catalogfollows andourpattern this J2EE Patterns Strategies promote bettercommunicationby providing • Developers discover andinventnewwaystoimplement the • Strategies provide anextensibilitypointforeachpattern. • includethemostrecommended Thepatterns ormostcom- • existatahigherlevelofabstraction Thepatterns thanthe • of thestrategies tothepatterns: have notedsomeoftheissueswithrespect totherelationship for now, believingthecurrent documentationtobe clear. We these strategies topatterns, we havedeferred thesedecisions names forlower-level solution. aspectsofaparticular patterns, producing newstrategies forwell-known patterns. mon implementationsasstrategies. strategies. Since this article describes patterns thathelpyouSince build patterns describes thisarticle While we continuetohavelivelydebatesaboutconverting Table descrip- andabrief 1,2,and3eachlistthepatterns We usedthetiered approach todividetheJ2EEpatterns J ava COM Home J2EE J2SE J2ME 22 A UGUST 2001 diagrams toexplaineachstrategy. withmultiplestrategiestion, patterns useclassandsequence diagram thatshows theinteractions In forthepattern. addi- gram thatshows thestructure ofthesolutionandasequence • • • ly asfollows: Using UML Hall/Sun Press, 2001) and is currently concentrating on pattern-driven designinJ2EE. concentrating onpattern-driven 2001)andiscurrently Hall/Sun Press, He iscoauthorof scalable architecturesfor J2EEtechnology. objectcomputingandremainsfocused oncreatingreusable, in distributed experience of Hehasmorethan15years isthechiefJava architectoftheSunJava Center. John Crupi columns, [email protected]. are topicsyou wantustoaddress anyJ2EEpattern infuture intherealences withapplyingJ2EEpatterns world.If there to exchange andshare withyou ourideas, vision,andexperi- columns. We thinkthiswillbeagreat andforum opportunity In Upcoming Issues ascanbeappliedtoabusinessproblem.(across eachtier)patterns ipants ofeachpattern. The diagram identifiestheend-to-end isrepresentedpattern by aUMLpackagethatcontainsthepartic- commonly usedtogether. We frameworks. callthesepattern thataretext ofabusinessproblem andalsodiscussthepatterns each otherasshown inFigure 1. language)tovisuallyseehowpattern relate thepatterns to together tosolveacommonbusinessproblem? Even more so, whatare thatare thepatterns commonlyused the isolatedpatterns, butinhow work together. thepatterns value increating catalogisnotjustunderstanding apattern togethertosolveabusiness problem. Iagree.patterns The that theydidnothaveagoodhandleonhow andwhentouse indevelopment?” problems withusingpatterns answer wasyes. Next, theywere asked, “Do you haveany useful?” wasposedtothegroup. Almostunanimously, the section,thequestion, the pattern “Do are you thinkpatterns focus group togatherdataabouttoolsandpatterns. During A Patterns NeedPatterns UTHOR interaction diagrams. ferent typesofobjectsandroles in theclassand Stereotypes: of thesolution. or astrategy. This provides thedynamicview between different inasolution participants these diagrams toshow theinteractions Sequence (orinteraction) diagrams: This provides thestaticviewofsolution. structure oftheimplementation strategies. the structure solutionandthe ofthepattern Class diagrams: Each pattern in the pattern catalogincludesaclassdia- inthepattern Each pattern We catalog,particular- useUMLextensivelyinthepattern I wantedtogiveyou aflavorofwhat’s tocomeinfuture In Figure 2,we show framework. anexample of apattern Each In inthecon- eachcolumnwe willattepttoputeachpattern We created relationship apattern guide(alsoknown asa The numberoneproblem identified by thedeveloperswas About ayear ago, Sun ran aJava technologydeveloper B IO We usestereotypes toindicatedif- We usetheclassdiagrams toshow [email protected] We use Crupi andDanCrupi Malks (ISBN0-13- Patterns, 064884-1) Copyright 2001.Sun with permission from with permission Core J2EEPatterns Microsystems, Inc. article containexcerptsarticle Portions of this by Deepak Alur, John ak fSnMcoytm,Ic,i h ntdSae n te onre.SnMcoytm,Inc. SunMicrosystems, andothercountries. intheUnitedStates Inc., marks ofSunMicrosystems, JDBCandJMSaretrademarksorregisteredtrade- andJ2EE, EJB, EnterpriseJavaBeans, Java, theSunlogo, SunMicrosystems, Sun, AllRightsReserved. Inc. Copyright 2001SunMicrosystems, fig otiuig oyn,ordistributingtheinformation. copying, contributing, ifying, Reviewed by James McGovern F. Libraries Professional JSP Tag Book Review: by ThomasHammell Drop into JavaDrag ‘n’ by Mark Dykstra Java Recognizing andeliminatingerrors in Multithreaded Errors Eliminating by Jose Barrera Using theJava Reflection classes Reflecting onJava by Alan Williamson JavaOne JDJ J2EE Panel Discussion Next Month Core J2EE (Prentice ete u o h uhr hl elal o n aae ufrda euto sn,mod- sufferedasaresultofusing, damages Neither Sunnortheauthorsshallbeliableforany suitability, truth, accuracy, or completeness of any oftheinformation. orcompletenessofany accuracy, truth, suitability, may have intellectual property rights relating to implementations ofthetechnology toimplementations intellectualpropertyrightsrelating may have chairs majorappvendorsat h uhr aeayrpeettos arnis orguarantiesastothequality, warranties, representations, the authorsmakeany ecie nti ril,adn ies faykn sgvnhr.Pleasevisit kindisgivenhere. andnolicenseofany described inthisarticle, h xetta uhdsliesaehl ob eal nai.NeitherSunnor suchdisclaimersthe extentthat areheldtobelegallyinvalid. www esfrapriua ups,o o-nrneet–aedslie,exceptto ornon-infringement–aredisclaimed, ness foraparticularpurpose, in,adwrate icuigayipidwrat fmrhnaiiy fit- andwarranties–including impliedwarrantyofmerchantability, any tions, o icsinproe ny l xrs ripidcniin,representa- Allexpressorimpliedconditions, for discussionpurposesonly. .sun.com/software/communitysource/ The information inthisarticleThe information (the isprovided “Information”) “as is,” J ava for licensinginformation. COM ENTERPRISE JAVA
J2ME Fitting the Pieces into the Enterprise Java Puzzle
J2SE Adding functionality with EJBs
The story so far: In Part 1 (JDJ Vol. 6, issue 4), I covered Part 3 of 3 servlets and gave a practical demonstration of how a basic access control mechanism for intranet applications could be built using Servlet Session Tracking and HTTP Authentication. In Part 2 (Vol. 6, issue 5), I introduced a couple of applets into the architecture J2EE WRITTEN BY and showed how a communication channel could be established TONY LOTON between the applets and servlets that comprised the application.
The next version of my application delegated the construction of the HTML ceeds and is committed – or it fails and will include the ability for an engineer to form to a separate displayForm() func- is rolled back. Either way, transactional transfer tasks to another engineer when tion to facilitate the representation of integrity is assured. he goes on vacation or when he’s sick. the form in the case of user error. The When presented like this, EJBs look
Home This added functionality requires a first time around, the form is displayed easy, so to spice things up I’ll suggest servlet to present the transfer form and with a null error message via the call another way of achieving exactly the subsequently to process the form sub- displayForm(out.user,null). same functionality. mission. An Enterprise JavaBean (ses- When the user submits the form, the submission is handled by the same The Alternative EJB Solution servlet’s doPost() method given in This time, I’ll use an entity bean to Listing 2. This method first gets hold of represent each individual engineer and the engineer to which the transfer I’ll rework the TaskManager session should be targeted. If no engineer was bean to coordinate the two entity beans specified, it redisplays the form with an that represent the two engineers. The error message – displayForm(out,user, remote interface for an engineer (entity) “You must specify an engineer”) – other- bean has the method definitions shown FIGURE 1 Task Transfer Form wise the transfer goes ahead courtesy of in Listing 4. For any given engineer you an Enterprise JavaBean. can count his tasks, get his tasks, delete sion) will perform the actual transfer them, and assign new ones. function. Simple EJB Solution In case you’re wondering, the AUTHOR BIO I’ve created the simplest possible sometimesFail parameter on the Tony Loton works Task Transfer Servlet Enterprise JavaBean to perform the assignTasks() method was my way of through his Figure 1 shows what the Task transfer of tasks from one engineer to testing this. If set to true, this parameter company, Transfer Form looks like. You can type another. The TaskManager EJB is refer- causes the method to throw an excep- LOTONtech Limited the name of a recipient engineer and enced by name via JNDI, and its home tion once in a while, which triggers the (www.lotontech.com), submit the form to initiate the transfer. interface is obtained. The home inter- entire transfer operation to be rolled as an independent If the transfer succeeds, the user is pre- face is used to create an instance of the back. consultant, course sented with a confirmation page (not bean, and this instance is instructed to The TaskManager session bean now instructor, and shown). transfer the tasks. I said that this is the has a revised version of the transferTasks technical author. He I will be using a single servlet to sup- simplest possible EJB, and it is: the method, given in Listing 5. It looks up has a degree in port two functions: presenting the remote interface has only one method – the two entity beans representing the computer science transfer form, and handling the form transferTasks(…). from- and to- Engineer(s), gets the tasks and management submission. One servlet, two uses, dis- The EJB implementation in Listing 3 of the fromEngineer, deletes them, and and has spent 10 tinguished by invoking the servlet is a minimal session bean with no trans- then adds them one-by-one to the years in IT. His last through its doGet() or doPost() method. actional attributes, and a single method toEngineer. five years have been The initial form presentation is per- with a single JDBC statement to manip- Adopting this approach introduces devoted almost formed by the doGet() method of the ulate the usertasks database table. I’ve many points at which the transactional exclusively to Java, new servlet, which I’ve called kept it simple not only for illustration, integrity might be compromised. The UML, and related TransferServlet. Listing 1 provides the but also because it’s often the best deleteTasks call – or any one of the technologies. code for this method, and for clarity I’ve approach. The sole SQL statement suc- assignTask calls – might fail, leaving the
24 AUGUST 2001
Java COM ENTERPRISE JAVA
considerably easier to implement – and fits of the EJB model come through more reliable – and the other showing using the standard services for transac- the power and complexity of EJBs. In tions, security, and so on. So if you’re general, my suggestion would be: not going to use these services – in the Applet EJB beware the consultant who dives name of keeping it simple – you might XML straight into the second approach with- be better off sticking with simple RMI.
J2ME Servlet out considering the simpler solution, In a nutshell, don’t treat EJBs as a half- JSP although, of course, there are times hearted solution; either find an easier when only a complex solution will do. method or commit to the EJB approach with all your heart. Fitting the Pieces into the Puzzle I’ve not yet mentioned CORBA as a FIGURE 2 Java puzzle Having presented the three major candidate for client/server communica- architectures offered by the J2EE (the tion or even as an alternative to EJBs. In GLOSSARY servlet, applet, and EJB) in a way that the time that it took RMI to mature and J2SE hopefully shows that these three EJB to take off, CORBA – in the form of API Application Programming Interface approaches may be complementary the Visigenic (Visibroker) or Iona (Orbix) AWT Abstract Windows Toolkit rather than competitive, you might now Java ORB implementations – provided a CGI Common Gateway Interface have some good ideas about the direc- solution that was more comprehensive CORBA Common Object Request Broker Architecture tion in which to take your project. But than RMI and ahead of EJB. Now that EJB Enterprise Java Beans you might still be a little unsure about niche has been filled by pure Java tech- HTML HyperText Markup Language the answer to the essential question: nologies and I see CORBA as being lim- HTTP HyperText Transfer Protocol Which horse for which course? ited to the one remaining niche for J2EE Java 2 Enterprise Edition I can only give an opinion, but the which it is uniquely suited – legacy inte- J2EE JDBC Java DataBase Connectivity order in which I have covered these gration. JNDI Java Naming and Directory Interface technologies is no accident. For any JSP Java Server Pages Internet/intranet application, I would, The Three Approaches RMI Remote Method Invocation by default, assume the servlet-only I’ve taken a tour of the three major URL Uniform Resource Locator approach initially as providing the architecture styles for application devel- WAR Web ARchive thinnest possible clients and the lowest opment that are available to Enterprise XML eXtensible Markup Language common denominator for compatibility Java developers – namely servlets,
Home with client Web browsers. applets, and EJB – and I’ve presented my For very limited client-side valida- ideas on how applications may be built database in an inconsistent state. Rest tion and control, I might stick with the comprising all three approaches, with assured that you could make it work by HTML/servlet approach, add some some interesting diversions into areas setting the transactional properties of JavaScript, and stop there. In all other such as access control. I’ve fitted the big the participating session and entity situations that necessitated highly inter- pieces into the puzzle by offering my beans, in which case the EJB container active or graphical clients, I would use advice on which pieces should be insert- will call the ejbLoad and ejbStore meth- applets with the straightforward ed first and which later, if at all. ods (assuming bean-managed persist- applet–servlet communication mecha- I’ll leave you with one final thought. ence) on the entity beans at appropriate nism based on serialized objects. There are a few smaller pieces such as times to assure the transactional In situations that demand true, XML and JSP that could be placed into integrity. stateful, remotely referenced server- the gaps between the big ones to com- This leaves us with (at least) two side objects I would consider plete the final puzzle, as shown in ways to implement the transferring of Enterprise JavaBeans. I would try to Figure 2. tasks between engineers using keep my EJBs as simple as possible, and Enterprise JavaBeans; one way being that’s where the irony is. The real bene- [email protected]
Listing 1: TransferServlet "doGet" Method if (user==null) public void doGet(HttpServletRequest req { /* -- write error message -- */ } , HttpServletResponse res) throws IOException else { { // -- get the current http session -- // -- handle the transfer form submission -- HttpSession session=req.getSession(true); res.setContentType("text/html"); String user=(String) PrintWriter out = res.getWriter(); session.getAttribute("user"); String toEngineer= if (user==null) req.getParameter("toEngineer"); { /* -- write error message -- */ } else if (toEngineer==null) { { // -- display the transfer form displayForm(out,user res.setContentType("text/html"); ,"You must specify an engineer"); PrintWriter out = res.getWriter(); } else displayForm(out,user,null); { } out.println(""); } out.println("
26 AUGUST 2001
Java COM .narrow(initial.lookup("TaskManager") } ,TaskManagerHome.class); public TaskManagerEJB() {} TaskManager taskManager= public void ejbRemove() {} taskManagerHome.create(); public void ejbActivate() {} public void ejbPassivate() {} taskManager.transferTasks(user,toEngineer); public void setSessionContext(SessionContext sc) {} } out.println("Transfer to "+toEngineer +" succeeded. "); Listing 4: Engineer Entity Bean } public interface Engineer extends javax.ejb.EJBObject catch (TransferException ex1) {
J2ME { public int getTaskCount() throws java.rmi.RemoteException; out.println("Transfer to "+toEngineer public String[] getTasks() throws java.rmi.RemoteException; +" failed with an application error. "); public void deleteTasks() throws java.rmi.RemoteException; } public void assignTask(String task, boolean sometimesFail) catch (Exception ex2) throws java.rmi.RemoteException; { public String getKey() throws java.rmi.RemoteException; out.println("Transfer to "+toEngineer } +" failed with a system error. "); } Listing 5: transferTasks Method with Entity Beans public void transferTasks out.println(""); (String fromEngineerID, String toEngineerID) out.println("