ANNOUNCINGWEBSERVICESEDGE 2001P.103
TM
The World’s Leading Java Resource Java COM April 2001 Volume:6 Issue:4
Sept 23–26, 2001 New York, NY
98
Oct 22–25, 2001 Santa Clara, CA 2001
104
Editorial by Sean Rhody pg. 5 App Server Focus: Best Practices for Sandra L. Emerson, From the Editor If you write EJBs Michael Girdley & Rob Woollen for aapp servers, these best by Alan Williamson pg. 7 Writing EJB Applications practices are for Avoid reinventing the wheel yJou 8 Enterprise Java 1 2 by Tony Loton pg. 60 J2EE: Guaranteed Messaging with JMS David Chappell Make sure your business-critical data & Richard Monson-Haefel Product Reviews 3 WebSphere 3.5 pg. 84 reaches its destination PART 2 18 n? Borland AppServer 4.5 pg. 100 4 App Server Focus: From Web Sites to Phil Costa VisualAge Repository How can app servers ease the transition? 26 by Tim deBoer, Steve Francisco Web Services and Wireless E1 A2 C2 B3 & Ellen McKay pg. 88 Server Replica S E2 CORBA Corner: OMG’s New Fault Tolerant 1 D3 Jon Siegel Java Code CORBA Specification Online redundancy can save the day 32 by Anthony Meyer pg. 92 create a foundation App Server Focus: Create a Foundation N Matt Creason First Look CocoBase pg. 106 Build an application server infrastructure EJB JSP 40 create a foundation HTTP
RETAILERS PLEASE DISPLAY
r
e r u t c u r t s a r f n i app JLink: Creating Reusable Enterprise e Mani Malarvannan UNTIL JUNE 30, 2001 v r e $4.99US $6.99CAN Components Using J2EE Cybelink’s Jlinks architecture PART 2 44 E Applications ce and Scalability
App Server Focus: Building J2EE Apps for EEWRITTEN BY MISHA DAVIDSON Misha Davidson Performance and Scalability Techniques, optimizations, and examples 50 App Server Focus: Application Server Sudhakar Ramakrishnan Metamorphosis & Christopher G. Chelliah 9 3 The essential capabilities 6 66 EDITORIAL SEAN RHODY, FOUNDING EDITOR/CHIEF CORPORATE EDITOR
EDITORIAL ADVISORY BOARD JEREMY ALLAIRE, TED COOMBS, ARTHUR VAN HOFF, JIM MILBERY, GEORGE PAOLINI, KIM POLESE, SEAN RHODY, RICK ROSS, AJIT SAGAR, BRUCE SCOTT, RICHARD SOLEY, ALAN WILLIAMSON FOUNDING EDITOR/CHIEF CORPORATE EDITOR: Living on SEAN RHODY EDITORIAL DIRECTOR: JEREMY GEELAN EDITOR-IN-CHIEF: ALAN WILLIAMSON EXECUTIVE EDITOR: M’LOU PINKHAM ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI MANAGING EDITOR: CHERYL VAN SISE EDITOR: NANCY VALENTINE the Edge ASSOCIATE EDITORS: JAMIE MATUSOW GREGORY LUDWIG KEN SILVER his is my first note to let everyone know JMS, JDBC, and so on. In particular, EDITORIAL INTERN: NIKI PANAGOPOULOS about the plans for our very own, SYS- we’ll cover the latest EJB standards, TECHNICAL EDITOR: BAHADIR KARUV, PH.D. PRODUCT REVIEW EDITOR: JIM MILBERY CON–sponsored JavaEdge2001 Inter- patterns for EJB design, deployment T ference, we’ve also scheduled conferences for “Testing and Deploying Appli- SUBSCRIPTIONS r e r u t c u r t s a r f n i app e andv Scalability FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, XML (XMLEdge2001), wireless (Wireless- cations” will enlighten managers r e PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT s EEWRITTEN BY MISHA DA Edge2002), Linux (LinuxEdge2002), and and senior technologists. SUBSCRIPTION HOTLINE:[email protected] ColdFusion (ColdFusionEdge2002). It’s our Practical Business Solutions, our COVER PRICE: $4.99/ISSUE DOMESTIC: $69.99/YR. (12 ISSUES) plan to offer developers, managers, and busi- final track, showcases the use of Java CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. nesspeople additional choices and opportuni- in industry and the availability of (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. ties to meet vendors, understand technology, products and solutions along any PUBLISHER,PRESIDENT,AND CEO: FUAT A. KIRCAALI VICE PRESIDENT,PRODUCTION & DESIGN: JIM MORGAN network with their peers, and leverage the number of lines. A variety of vendors SENIOR VICE PRESIDENT,SALES & MARKETING: CARMEN GONZALEZ resources of the entire Java community. will present on topics ranging from VICE PRESIDENT,SALES & MARKETING: MILES SILVERMAN VICE PRESIDENT,SYS-CON EVENTS: CATHY WALTERS This year I have the honor of serving as “Financial Services” and “CRM” to TRADE SHOW MANAGER: DONA VELTHAUS technical chairman for the JavaEdge2001 “Supply Chain.” Also included will be Java solu- SALES EXECUTIVE,EXHIBITS: MICHAEL PESICK ADVERTISING ACCOUNT MANAGERS: ROBYN FORMA conference. We’ve decided to present five ses- tion vendors for subjects like “Content MEGAN RING sion tracks designed to maximize your ability Management,” “Personalization,” and “Port- RONALD J. PERRETTI ASSOCIATE SALES MANAGERS: CHRISTINE RUSSELL to learn and leverage. The tracks are Wireless als.” CARRIE GEBERT Java and J2ME, J2SE, J2EE, Working with I- In each track we plan to have a mix of sev- ALISA CATALANO VICE PRESIDENT,CIRCULATION: AGNES VANEK Technology, and Practical Business Solutions. eral experience levels in order to accommo- NEWSSTAND SALES MANAGER: CHERIE JOHNSON Obviously, the first three tracks strongly mir- date the beginner, the experienced developer, ART DIRECTOR: ALEX BOTERO ASSOCIATE ART DIRECTORS: CATHRYN BURAK ror the way Java itself is structured. the expert, and the project manager or CIO. RICHARD SILVERBERG With the explosion of cell phones, the grow- The conference will also have an exhibit ASSISTANT ART DIRECTORS: ABRAHAM ADDO AARATHI VENKATARAMAN ing presence of networked PDAs, and an floor, where you can interact with numerous WEBMASTER: ROBERT DIAMOND increase in the sophistication of non-PC vendors to discuss their products and solu- WEB DESIGNERS: STEPHEN KILMURRAY GINA ALAYYAN devices, J2ME is positioned to become an inte- tions in a traditional setting. We’re looking WEB DESIGNER INTERN: PURVA DAVE gral part of the post-PC world. The J2ME track forward to an authors day, where we’ll have JDJSTORE.COM: ANTHONY D. SPITZER ASSISTANT CONTROLLER: JUDITH CALNAN will explore wireless technology, including WAP the authors of a number of current Java CREDIT & COLLECTIONS: CYNTHIA OBIDZINSKI and other protocols. We’ll also have sessions on books, as well as our own authors, available ACCOUNTS PAYABLE: JOAN LAROSE some of the KVMs available, and information to meet with you and sign autographs. EDITORIAL OFFICES on porting applications to small devices. As the technology chair, I’m interested in SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 TELEPHONE: 201 802-3000 FAX:201 782-9600 Important issues such as memory constraints what you have to say. The reality is, this is your JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly and display limitations will also be covered. conference, and I want to make sure you get (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 The J2SE track will focus on application the most you can out of it. We have a call for Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., development using Java. There will be some papers open at the moment on our Web site 135 Chestnut Ridge Road, Montvale, NJ 07645. overlap with J2EE, but this track will focus on (www.sys-con.com/javaedge/papers. ©COPYRIGHT aspects of Java programming that are more cfm) where industry professionals can submit Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any pertinent to pure Java applications. Topics will possible topics. We’re also actively working means, electronic or mechanical, including photocopy or any information storage and retrieval system, without written permission. For promotional reprints, contact reprint coordi- include AWT and Swing, 2D and 3D program- with a variety of sources to line up the most nator. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its readers to use the articles submitted for publication. ming, speech and telephony, mail, and that appropriate content for the conference. But I W ORLDWIDE DISTRIBUTION BY dreaded topic – multithreaded programming. want to know what you, our community, need. CURTIS CIRCULATION COMPANY Our J2EE track will focus on the core tech- Please drop me a line with your suggestions at 730 RIVER ROAD, NEW MILFORD NJ 07646-3048 PHONE: 201 634-7400 nologies of the Enterprise Edition – EJB, JSP, [email protected]. See you on the Edge. 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, service marks or trademarks of their respective companies. [email protected] AUTHOR BIO Sean Rhody is the founding editor of Java Developer’s Journal. He is also a respected industry expert and a consultant with a leading Internet service company. APRIL 2001 5 Java COM FROM THE EDITOR ALANWILLIAMSON, EDITOR-IN-CHIEF Shouldn’t It Be dot.org Instead? ’m sitting here cross-legged on a fresh San As you know, we’re pushing toward a new Francisco afternoon, 8,000 miles away from release of your beloved Java Developer’s Imy family, wondering how the industry we Journal with JDJ2.0 penciled in for the JavaOne live and breath in is shaping up. When I left issue. At this moment in time the team and I Scotland, it was the weekend and the American are working very hard to collate all the materi- markets didn’t have too much to report. After a als required to make this happen. One of the 9-hour flight, lane jumping on Highway 101, I first things I set about doing was to assemble arrived at my apartment to discover the news is an Advisory Panel. Its purpose will be to steer raging about how the markets have taken a the magazine through the changes and ensure serious downturn. How tech stocks have gone that we’re offering content that is relevant. And way out of favor, with even the blue chips from time to time we’ll peer into a crystal ball struggling. Should we worry? This is a question to see what’s around the corner. people keep asking me, and to be honest my Each month we’ll publish the remarks from answer up to now has been: “Nah, things are the Advisory Panel and invite you all to give okay for us Java dudes.” But are they? your input. I’m proud to say that the Panel has I’m over here on a pilgrimage, you might now been chosen and a dialog has begun. say. I’m here to meet and talk with some of the Success is so much easier to achieve when makers and shakers of the Java universe. I want you have a good team around you, and I am to know what they think. Is it media hype or is fortunate enough to have a great team with me. there indeed a little fire where the smoke is? • First and foremost I’d like to introduce you to Sometimes a good sign of how well an industry our editorial director, Jeremy Geelan. Jeremy is doing is to take a look at what the recruit- is a constant inspiration to me, and keeping ment world is up to. I had a chat with some of up with this man’s thought processes is a these people and they told me that it’s business full-time job. as usual, except the high packages on offer • A name that’s already familiar to the readers aren’t quite the same as they used to be in the of JDJ is, of course, Ajit Sagar. Ajit, the new good old days. I chortled at this, and inquired J2EE editor, is working on building the J2EE what period were we referring to when we content for JDJ2.0 – let me tell you, it’s in mentioned “good old days.” Only 12 months great hands. ago was the answer. Damn, this industry moves • A name that’s virtually synonymous with fast… “product review” is Jim Milbery. As our new, While I stared out at the Golden Gate Bridge official product editor, Jim will coordinate all I had a wee thought regarding the term dot- the reviews for JDJ. com. If you remember, the initial domain struc- ture was to have profit-making companies use I’ll introduce the rest of the people on the the .com domain whereas nonprofit compa- team next month. To do so now would make nies had to use the .org name. I think some this look more like an Oscar ceremony than an companies perhaps indulged in a little wishful editorial. thinking…maybe we should be pointing our • • • browsers toward amazon.org instead! There is, of course, one other member of But don’t panic just yet. By all accounts we the team I haven’t mentioned: you, the most still have a major shortage of people who actu- important member. Without your input we’re ally can do a day’s development as opposed to merely killing time here. So make yourself those who just think they can. I’ll have more to heard. Join our mailing list at http://myjdj.sys- report next month once I’ve had my chats with con.com/mailman/listinfo/myjdj and let us various people around the Bay area. If indeed know what you think. there is writing on the wall, I’ll find it! Your JDJ needs you. [email protected] AUTHOR BIO Alan Williamson holds the reins at n-ary (consulting) Ltd, one of the first companies in the UK to specialize in Java at the server side. APRIL 2001 7 Java COM Best Practices for Writing EJBs Written by Sandra L. Emerson, Michael Girdley & Rob Woollen “Almost every EJB application uses transactions at some point” If you write EJBs avaSoft defined the Enterprise JavaBeans specification to give Java for app servers, developers a foundation for these best building distributed business practices components. EJBs are Java components that implement are for business logic and follow a contract you designated in the EJB specification. Enterprise JavaBeans live inside an EJB container that provides a set of standard services, including transactions, persistence, security, and concurrency. This means that the application programmer is freed from developing these services from scratch. 8 APRIL 2001 APRIL 2001 9 Java COM Java COM To get the most out of using EJBs in an enterprise-level distributed User Interactions and Transaction Performance application supported by a J2EE-compliant application server, pro- Transactions can cause performance problems if they span too grammers should: many operations. In particular, a transaction should never encom- • Closely conform to the EJB specification. pass user input or user think time. If a user starts a transaction and • Use available tools for bean development and compliance check- then goes to lunch or even visits another Web site, the transaction isn’t ing. committed. Instead, it continues to hold valuable locks and resources • Learn to benefit from the experiences of others. within the server. In general, all transaction demarcation should occur within the As outlined in this article, best practices for EJBs are based on server. There are a number of well-known techniques to avoid keep- experience gained through implementing J2EE for BEA WebLogic ing long-running transactions open. When you ask a user to submit a Server and helping BEA’s customers develop or migrate their multiti- form, break up the operation into two transactions. The Web page er applications to the J2EE platform. should read the data in a single transaction along with a version stamp. This transaction is committed before the form is returned to EJB Overview the user. The user can now modify the data as desired. The form There are four types of Enterprise JavaBeans in EJB 2.0: update occurs in a new transaction. 1. Stateless session beans: Provide a service without storing a conver- Transactions should never encompass user input or think time. sation state between method calls. 2. Stateful session beans: Maintain state; each instance is associated Container-Managed vs Bean-Managed Transactions for Entity Beans with a particular client. The EJB specification allows a session bean to choose either con- 3. Entity beans: Represent an object view of persistent data, usually tainer-managed or bean-managed transactions. In the former the rows in a database. They have a primary key as a unique identifier. bean writer declares transaction attributes in the deployment descrip- There are two operational styles for entity beans: container-man- tor. The EJB container then automatically starts and commits transac- aged persistence (CMP) and bean-managed persistence (BMP). tions as requested. The bean writer doesn’t have to write any code to 4. Message-driven beans: Added in EJB 2.0. These EJBs, the integra- manage transactions. In the latter the bean writer uses the user trans- tion between JMS (Java Message Service) and EJB, are used to per- action interface to explicitly start and commit transactions. Container- form asynchronous work within the server. managed transactions should always be the bean writer’s first choice. In bean-managed transactions the bean writer must ensure that the Best Practices transaction is committed or rolled back. While the BEA WebLogic For your coding pleasure…here are selected best practices for cre- Server includes a transaction timeout, the bean writer shouldn’t rely ating EJBs for an enterprise-level distributed application supported on this feature, but release transaction resources as soon as possible. by a J2EE-compliant application server such as the BEA WebLogic In the case of container-managed transactions this is handled auto- Server. Our assumption is that the developer is an intermediate-to- matically by the EJB container. expert Java programmer who’s familiar with writing EJBs for an appli- Use container- instead of bean-managed transactions. cation server. We present best practices for: • Transactions Best Practices for EJB Security • EJB security EJB provides a declarative security support as well as a simple pro- • Creating a primary key class grammatic interface for explicit security checks within the bean code. • When not to use stateful session beans In practice, EJB security settings need to be considered within the • Coding business interfaces entire application’s security model. It’s common for Web-based appli- • Using message-driven beans in transactions cations to handle authentication within the Web tier. In this environ- ment the EJB tier may contain few security constraints. This arrange- Best practices are shown in summary form as tinted text following ment simplifies the EJB design, and since the security checks are the relevant section. localized to the presentation layer, the application may modify secu- rity policies without modifying the EJB tier. Tips for Transactions Applications with stand-alone programmatic clients often access Almost every EJB application uses transactions at some point. session beans directly. Since there is no intermediate tier, the security Transactions ensure correctness and reliability and are essential to e- access control must be handled in the EJB tier. commerce applications. Misuse, however, can affect performance Declarative security control is preferred for simple applications. and even produce incorrect results. It’s important to understand that Since the security constraints are declared in the deployment descrip- session beans themselves can’t be transactional. tor, the bean classes’ business logic is not polluted with security A common misperception is that the member variables of the checks. The declarative security model is based on security roles that session bean will be rolled back when their transaction aborts. are declared in the deployment descriptor. Declarative security works Instead, session beans merely propagate their transaction to any best when the number of roles is fixed and doesn’t depend on the resource they acquire. For instance, at the beginning of a transac- number of clients. For instance, an application might include a user tion a session bean has a member variable with a value of zero. role and an administrator role. Since there are only two access During the transaction, the member variable is set to two, and a row domains, it’s feasible to declare these roles in the deployment is inserted into the database. If the transaction rolls back, the mem- descriptor. ber variable won’t be reset to zero. However, the row will no longer However, declarative security shouldn’t be used when each user be in the database. Since a database is a transactional resource, it requires individual security constraints. Such applications require will participate in the session bean’s transaction, and a rollback will programmatic security checks within the EJB code. It’s also common abort any associated work. to combine both security models. For instance, an Account bean Session bean state is not transactional. may use declarative security to ensure that only registered users access any methods. The bean code then includes additional con- This article is adapted from Chapters 8–10 of the straints to ensure that each user gains access only to his or her forthcoming book J2EE Applications and BEA WebLogic Server, account. to be published by Prentice Hall. Use declarative security checks when an application contains few roles. Choose programmatic security when each user needs individual security checks. 10 APRIL 2001 Java COM How to Write a Primary Key Class for Entity Beans Applications should always call remove after finishing with a state- The EJB primary key class serves as its unique identifier both in ful session bean instance. This allows the EJB container to release the persistent store and in the EJB container. Usually, the primary key container resources as soon as possible. If the remove call is omitted, class fields map directly to the primary key fields in a database. If the the EJB container will eventually passivate the bean, but this involves primary key is only a single entity bean field that is a Java primitive extra disk access. class (such as java.lang.String), the bean writer doesn’t have to write a Stateless session beans are easier to scale than stateful session beans. custom primary key class. Instead, in the deployment descriptor, the bean writer specifies the name of the class and the name of the pri- Stateful session bean writers must also be careful when inte- mary key field. grating their stateful session beans with Web applications. These If the primary key maps to a user-defined type or to multiple beans should not allow concurrent method calls. As mentioned fields, the bean writer must write a custom primary key class. The earlier, it’s possible for multiple requests to cause concurrent calls class must implement java.io.Serializable and contain the primary on a stateful session bean. Unfortunately, this error usually shows key fields. For CMP entity beans the field names must match the cor- up under load, so it’s often missed in testing. For this reason use responding primary key field names in the bean class. This allows the stateful session beans only within the scope of a request. Use enti- EJB container to assign the appropriate CMP fields to their corre- ty beans or servlet sessions for applications that need to store data sponding fields in the primary key class. between requests. For instance, we might define an employee’s primary key as a com- pound key using the first name, last name, and office number. Our Coding Business Interfaces compound key would look like Listing 1. Many new EJB programmers are confused by the relationship The primary key class consists of the primary key fields, which between the remote interface and the EJB class. This arrangement is must be public, and a no argument constructor. The class must also necessary for the container to intercept all method calls to the EJB. implement the hashCode and equals methods. The EJB container One confusing aspect is that the EJB class implements the methods uses a number of data structures internally, many of which are defined in the remote interface, but the EJB class doesn’t implement indexed by the primary key class. It is vital that hashCode and equals the remote interface itself. In fact, the EJB class should never imple- be implemented correctly and efficiently in the class. ment the remote interface. While the EJB specification allows this The hashCode method is implemented by returning an integer practice, it can cause serious but subtle bugs. The problem with hav- using the primary key fields. The goal of this function is to produce an ing the EJB class implement the remote interface is that the class can integer that can be used to index tables. The hashCode for a primary now be passed as a parameter to any method that expects the remote key should never change. Therefore, the hashCode should be con- interface as a parameter. structed only from immutable values. Remember that the remote interface exists to allow the con- A common strategy is to XOR the hashCode of the primary key ele- tainer to intercept method calls in order to provide necessary serv- ments together. OR should never be used, since ORing several values ices such as transactions or security. If the Bean class is used, the will generally have most or all bits set to 1. Similarly, AND should not method calls arrive directly on the bean object – creating a dan- be used since most or all bits will converge to 0. gerous situation in which the container cannot intercept method The hashCode method must be implemented such that two equal calls or intervene in case of error. If (as recommended) the EJB objects have the same hashCode. However, two objects with the same class doesn’t implement the remote interface, this problem hashCode aren’t necessarily equal. This hashCode implementation becomes apparent at compile time. The Java compiler will reject stores the hashCode in a member variable to avoid computing it every the attempt to pass the bean class as a parameter of the remote time hashCode is called. interface’s type. It can also be tricky to implement equals correctly. The first line of Never implement the remote interface in the EJB class. any equals method should check the passed reference against this. This optimization simply checks whether equals has been called –continued on page 16 against itself. While this sounds strange at first, it is a common opera- tion when the container has a primary key object and is checking to Listing 1: Defining a compound primary key see if it already exists in a data structure. public final class EmployeePK implements java.io.Serializable { Next, the equals method should ensure that the passed parame- public String lastName; ter is its own type. If the primary key class is final, a simple instance- public String firstName; of check can be used. If the primary key class isn’t final, the passed public int officeNumber; parameter might be a subclass of our primary key class. In this case private int hash = -1; the equals method must use getClass().equals to ensure that the class types match exactly. It is recommended that primary key class- public EmployeePK() {} es be final, since using instanceof is cheaper than comparing classes. public int hashCode() { Primary key classes should be final. if (hash == -1) { hash = lastName.hashCode() ^ firstName.hashCode() ^ officeNumber; When Not to Use Stateful Session Beans } return hash; Stateful session beans represent a stateful conversation between a } single client and a bean instance. Stateful session beans can’t be public boolean equals(Object o) { shared between multiple users. You shouldn’t model a shared cache or if (o == this) return true; any shared resource as a stateful session bean. If multiple clients need if (o instanceof EmployeePK) { to access a single EJB instance, use an entity bean. EmployeePK other = (EmployeePK) o; return other.hashCode() == hashCode() && Stateful session beans are not shared by multiple users. other.officeNumber == officeNumber && other.lastName.equals(lastName) && other.firstName.equals(firstName); Since each client requires its own stateful session bean instance, the number of bean instances and the associated resource require- } else { ments can grow quickly. If an application can tolerate the stateless return false; } programming model, stateless session beans are easier to scale than } stateful session beans. } 12 APRIL 2001 Java COM The WebLogic Server provides an EJB compliance checker to catch Like session beans, message-driven EJBs may specify either bean- any methods that are defined in the remote interface but not imple- managed or container-demarcated transactions in their ejb-jar.xml mented in the EJB class. deployment descriptor. With container transactions a message-driven EJB may specify either Required or NotSupported. (Since there is no Using Transactions with Message-Driven Beans client transaction, there is no reason to support the other transaction Message-driven EJBs are the integration between EJBs and the JMS. attributes.) If the transaction attribute is NotSupported, the message- Like other EJB types, message-driven EJBs live within an EJB container driven EJB will not participate in a transaction. and benefit from EJB container services such as transactions, security, If the Required attribute is specified, the EJB container automatical- and concurrency control. However, a message-driven EJB doesn’t inter- ly starts a transaction. The message receipt from the JMS Queue or Topic act directly with clients. Instead, message-driven EJBs are JMS Message is included in this transaction. The message-driven bean’s onMessage Listeners. A client publishes messages to a JMS destination. The JMS method is then called in the transaction context. When the onMessage provider and the EJB container then cooperate to deliver the message to method returns, the EJB container commits the transaction. If the trans- the message-driven EJB. action aborts, the JMS message remains in the JMS destination and is Like other EJBs, message-driven beans make use of the EJB contain- delivered again to the message-driven EJB. er’s transaction service. Since these beans never interact directly with clients, they never participate in the client’s transaction. Error Handling in Message-Driven Bean Transactions Message-driven beans with the Required transaction attribute need to be careful when aborting transactions. A transaction aborts either because it was explicitly marked for rollback or because a system exception was thrown. One potential issue is known as the “Poison Message.” In this scenario a message-driven EJB receiv- ing stock trade orders from an order queue might encounter a stock symbol that doesn’t exist. When the message-driven EJB receives the error message, the underlying logic might be to abort the transaction because the symbol is invalid. When the JMS implemen- tation delivers the message again in a new transaction, the process repeats. Clearly, this is not the desired behavior. A good solution for this potential problem is to sepa- rate application errors from system errors. An applica- tion error, such as an invalid stock symbol, should be handled by sending an error message to an error JMS destination. This allows the transaction to commit, and the “Poison Message” leaves the system. A system error might be that the back-end database has failed. In this case our transaction should roll back so that this mes- sage is still on the queue when the database recovers. Conclusion EJBs are server-side Java components that leverage the standard transaction, persistence, concurrency, and security services provided by the EJB container. What we’ve described here are best practices for coding to the J2EE standard, based on experience with the BEA WebLogic Server. AUTHOR BIOS Sandra L. Emerson is a technical writer and consultant with 20 years’ experience in the software industry. She is a coauthor of The Practical SQL Handbook (Addison-Wesley). Michael Girdley is senior product manager for BEA WebLogic Server at BEA Systems, Inc. He has extensive experience programming with Java, HTML, C, and C++, and is a coauthor of Web Programming with Java (SAMS); Java Unleashed, 2nd ed. (SAMS); and Java Programming for Dummies (IDG Books). Rob Woollen is a senior software engineer at BEA Systems, Inc. He is currently the lead developer for the BEA WebLogic Server EJB Container and is a coauthor of the forthcoming book J2EE Applications and BEA WebLogic Server (Prentice Hall). 16 APRIL 2001 Java COM J 2 E E Guaranteed Messaging with JMS How to make sure your business-critical data reaches its destination Part 2 of 3 he notion of guaranteed delivery of Java Message Service messages WRITTEN BY T has been lightly touched on in other recently published articles on DAVID CHAPPELL & JMS. But what really makes a JMS message “guaranteed”? Should you RICHARD MONSON-HAEFEL just take it on faith, or would you like to know what’s behind it? This article answers these questions “Provider failure” refers to any failure sender. The storage mechanism is used via a detailed discussion of message per- condition that is outside the domain of for persisting messages to disk to ensure sistence, internal acknowledgment the application code. It could mean a that the message can be recovered in the rules, and message redelivery. Using hardware failure that occurs while the event of a provider failure or a failure of excerpts condensed from the book we provider is entrusted with the process- the consuming client. The forwarding coauthored, Java Message Service, we’ll ing of a message, an unexpected excep- mechanism is responsible for retrieving explain how JMS guaranteed messaging tion, the abnormal end of a process due messages from storage, and subse- works – including once-and-only-once to a software defect, or network failures. quently routing and delivering them. delivery semantics, durable subscrip- tions, failure and recovery scenarios, Message Autonomy Message Acknowledgments and transacted messages. Messages are self-contained auto- The message acknowledgment pro- nomous entities. A message may be sent tocol is key to guaranteed messaging, JMS Guaranteed Messaging and re-sent many times across multiple and support for acknowledgment is There are three key parts to guaran- processes throughout its lifetime. Each required by the semantics of the JMS teed messaging: message autonomy, JMS client along the way will consume API. The acknowledgment protocol store-and-forward, and the underlying the message, examine it, execute busi- allows the JMS provider to monitor the message acknowledgment semantics. ness logic, modify it, or create new mes- progress of a message so that it knows Before we discuss these parts, we need sages in order to accomplish the task at whether the message was successfully to review and define some new terms. A hand. produced and consumed. With this JMS client application uses the JMS API. Once a JMS client sends a message, knowledge the JMS provider can man- Each JMS vendor provides an imple- its role is completed. The JMS provider age the distribution of messages and mentation of the JMS API on the client, guarantees that any other interested guarantee their delivery. which we call the client runtime. In parties will receive the message. This The acknowledgment mode is set on addition to the client runtime, the JMS contract between a sending JMS client a JMS session when it is created, as indi- vendor provides some kind of message and the JMS provider is much like the cated below: “server” that implements the routing contract between a JDBC client and a and delivery of messages. The client database. Once the data is delivered, it is tSession = runtime and the message server are col- considered “safe” and out of the hands tConnect.createTopicSession(false, lectively referred to as the JMS provider. of the client. Session.CLIENT_ACKNOWLEDGE); This article is adapted from Java Message Store-and-Forward Messaging qSession = Service by Richard Monson-Haefel and David When messages are marked persist- qConnect.createQueueSession(false, Chappell (O'Reilly) and appears here by per- ent, it is the responsibility of the JMS Session.DUPS_OK_ACKNOWLEDGE); mission of the publisher. provider to utilize a store-and-forward AUTO_ACKNOWLEDGE mechanism to fulfill its contract with the Let’s start by examining the 18 APRIL 2001 Java COM J 2 E E AUTO_ACKNOWLEDGE mode. In the sage is intended for a disconnected loosely coupled asynchronous environ- durable subscriber, the message server 5 Receive ment of JMS, senders and receivers (pro- saves the message to disk as though it 1 Send ducers and consumers) are intentional- were a persistent message. In this case JMSJMSS ly decoupled from each other. Hence, the difference between persistent and SServereveervererve 6 Ack the roles and responsibilities are divided nonpersistent messages is subtle, but 3 Ack among the message producer, the mes- very important. For nonpersistent mes- JMSMS JMSM sage server, and the message consumer. sages the JMS provider could fail before Producerodu 2 Persist Consumeronsumsu it’s had a chance to write the message The Producer’s Perspective out to disk on behalf of the disconnect- Remove from publish() 7 persistent store Under the covers, the ed durable subscribers. Messages may 4 method returns Persistentersisten TopicPublisher.publish() or Queue- be lost (see Figure 3). Store Sender.send() methods are synchro- With persistent messages a provider nous. These methods are responsible for may fail and recover gracefully, as illus- FIGURE 1 Send and Receive are separate operations. sending the message and blocking until trated in Figures 4 and 5. Since the mes- an acknowledgment is received from the sages are held in persistent storage, message server. If a failure condition they’re not lost and will be delivered to occurs during this operation, an excep- consumers when the provider starts up Receive 5 tion is thrown to the sending application again. If the messages are sent using a 1 Send and the message is considered undeliv- p2p queue, they’re guaranteed to be JMSJMSS ered. delivered. If the messages were sent via SServereveervererve 6 Ack publish/subscribe, they’re guaranteed 3 Ack The Server’s Perspective to be delivered only if the consumers’ JMSMS JMSM The acknowledgment sent to the subscriptions are durable. Producerodu 2 Persist Consumeronsumsu producer (sender) from the server means that the server has received the The Consumer’s Perspective Remove from publish() 7 persistent store message and has accepted responsibili- There are also rules governing 4 method returns Persistentersisten ty for delivering it. From the JMS server’s acknowledgments and failure condi- Store perspective, the acknowledgment sent tions from the consumer’s perspective. to the producer is not tied directly to the If the session is in AUTO_ACKNOWL- FIGURE 2 Message removed from persistent store delivery of the message. They are logi- EDGE mode, the JMS provider’s client cally two separate steps. For persistent runtime must automatically send an messages, the server writes the message acknowledgment to the server as each out to disk (the store part of store-and- consumer gets the message. If the server Durable Subscriber forward), then acknowledges to the pro- doesn’t receive this acknowledgment, it 1 Send JMSJMSS ducer that the message was received considers the message undelivered and SServereveervererve (see Figure 1). For nonpersistent mes- may attempt redelivery. 2 Ack sages this means the server may JMSMS JMSM acknowledge to the sender as soon as it Message Redelivery Producerodu 5 Persist Consumeronsumsu has received the message and has the The message may be lost if the message in memory. If there are no sub- provider fails while delivering a message publish() 4 Provider Fails 3 method returns scribers for the message’s topic, the to a consumer with a nondurable sub- Persistentersisten message may be discarded. scription. If a durable subscriber receives Store In a publish/subscribe model, the a message, and a failure occurs before the message server delivers a copy of a mes- acknowledgment is returned to the Message is Lost! 6 sage to each of the subscribers. For provider (see Figure 6), the JMS provider FIGURE 3 When a nonpersistent message can be lost. durable subscriber, the message server considers the message undelivered and doesn’t consider a message fully deliv- will attempt to redeliver it (see Figure 7). ered until it has received an acknowledg- In this case the “once-and-only-once” ment from all of the message’s intended requirement is in doubt. The consumer Send recipients. It knows on a per-consumer may receive the message again, because 1 basis which clients have received each when delivery is guaranteed, it’s better to JMSJMSS message and which have not. risk delivering a message twice than to SServereveervererve Once the message server has deliv- risk losing it entirely. A redelivered mes- 3 Ack JMSMS JMSM ered the message to all of its known sub- sage will have the JMSRedelivered flag Producerodu 2 Persist Consumeronsumsu scribers and has received acknowledg- set. A client application can check this ments from each of them, the message is flag by calling the getJMSRedelivered() publish() 5 Provider Fails removed from its persistent store (see method on the Message object. Only the 4 method returns Persistentersisten Figure 2). most recent message received is subject Store If the subscriptions are durable and to this ambiguity. 6 Message retained in persistent store the subscribers aren’t currently connect- ed, the message will be held by the mes- Point-to-Point Queues FIGURE 4 Persistent messages won’t be lost during a provider failure. sage server until either the subscriber For point-to-point queues, messages becomes available or the message are marked by the producer as either expires. This is true even for nonpersis- persistent or nonpersistent. If the for- tent messages. If a nonpersistent mes- mer, they are written to disk and subject 20 APRIL 2001 Java COM J 2 E E to the same acknowledgment rules, fail- tion to the client if a provider failure ure conditions, and recovery as persist- occurs during the acknowledgment ent messages in the publish/subscribe process. The provider failure results in model. the message being retained by the JMS 2 Receive From the receiver’s perspective the server for redelivery. rules are somewhat simpler since only JMSJMSS one consumer can receive a particular Transacted Messages SServereveervererve 3 Ack instance of a message. A message stays JMS transactions follow the conven- in a queue until it is delivered to a con- tion of separating the send operations JMSMS JMSM sumer or expires. This is somewhat anal- from the receive operations. Figure 8 Producerodu Recover from Consumeronsumsu ogous to a durable subscriber in that a shows a transactional send in which a 1 persistent store receiver can be disconnected while the group of messages are guaranteed to get Remove from 4 persistent store message is being produced without los- to the message server, or none of them Persistentersisten ing the message. If the messages are will. From the sender’s perspective the Store nonpersistent they aren’t guaranteed to messages are cached by the JMS survive a provider failure. provider until a commit() is issued. If a FIGURE 5 Persistent messages are delivered on recovery of the provider. failure occurs or a rollback() is issued, DUPS_OK_ACKNOWLEDGE the messages are discarded. Messages Specifying the DUPS_OK_ACKNOW- delivered to the message server in a LEDGE mode on a session instructs the transaction are not forwarded to the Receive 5 JMS provider that it is okay to send a consumers until the producer commits 1 Send message more than once to the same the transaction. JMSJMSS destination. This is different from the The JMS provider won’t start delivery SServereveervererve Consumer 6 fails once-and-only-once or the at-most- of the messages to its consumers until 3 Ack JMSMS JMSM once delivery semantics of the producer has issued a commit() on AUTO_ACKNOWLEDGE. The DUPS the session. The scope of a JMS transac- Producerodu Persist Consumeronsumsu 2 _OK_ACKNOWLEDGE delivery mode is tion can include any number of mes- publish() based on the assumption that the pro- sages. 4 method returns Persistentersisten cessing necessary to ensure once-and- JMS also supports transactional Store only-once delivery incurs extra over- receives, in which a group of transacted head and hinders performance and messages are received by the consumer 7 Message still in persistent store throughput of messages at the provider on an all-or-nothing basis (see Figure 9). FIGURE 6 Failure occurs during delivery of a message to a durable subscriber. level. An application that is tolerant of From the transacted receiver’s perspec- receiving duplicate messages can use tive the messages are delivered to it as the DUPS_OK_ACKNOWLEDGE mode expeditiously as possible, yet they are to avoid incurring this overhead. held by the JMS provider until the Receive 2 In practice, the performance receiver issues a commit() on the ses- improvement you gain from sion object. If a failure occurs or a roll- JMSJMSS DUPS_OK_ACKNOWLEDGE may be back() is issued, the provider will SServereveervererve 3 Ack something you want to measure before attempt to redeliver the messages, in designing your application around it. which case the messages will have the JMSMS JMSM redelivered flag set. Producerodu Recover from Consumeronsumsu 1 persistent store CLIENT_ACKNOWLEDGE Transacted producers and transact- With AUTO_ACKNOWLEDGE mode ed consumers can be grouped together Remove from 4 persistent store the acknowledgment is always the last in a single transaction if they are created Persistentersisten thing to happen implicitly after the from the same session object, as shown Store onMessage() handler returns. The client in Figure 10. This allows a JMS client to receiving the messages can get finer- produce and consume messages as a FIGURE 7 Durable subscriber recovers grained control over the delivery of single unit of work. If the transaction is guaranteed messages by specifying the rolled back, the messages produced CLIENT_ACKNOWLEDGE mode on the within the transaction won’t be deliv- consuming session. ered by the JMS provider. The messages The use of CLIENT_ACKNOWLEDGE consumed within the same transaction 1 Send allows the application to control when won’t be acknowledged and will be rede- the acknowledgment is sent. For exam- livered. JMSJMSS Receive SServereveervererve 5 ple, an application can acknowledge a Unless you’re doing a synchronous 2 Send message – thereby relieving the JMS request/reply, you should avoid group- JMSMS JMSM provider of its duty – and perform fur- ing a send followed by an asynchronous Producerodu Consumeronsumsu ther processing of the data represented receive within a transaction. There could 3 commit() by the message. The key to this is the be a long interval between the time a acknowledge() method on the Message message is sent and the related message FIGURE 8 Transactional messages are sent in an all-or-nothing fashion. object, as shown in Listing 1. is asynchronously received, depending The acknowledge() method informs on failures or downtime of other the JMS provider that the message has processes involved. It’s more practical to been successfully received by the con- group the receipt of a message followed sumer. This method throws an excep- by the send of another message. 22 APRIL 2001 Java COM J 2 E E lowing JMS objects : Creating a JMS Transaction XAConnectionFactory, XAQueueCon- Enabling a JMS transacted session nection, XAQueueConnectionFactory, XA- happens as part of creating a Session QueueSession, XASession, XATopicCon- 3 Receive object, as shown in Listing 2. nection, XATopicConnectionFactory, and Send The first parameter of createTopic- XATopicSesion. 1 Session() or createQueueSession() meth- JMSJMSS 4 Receive od is a Boolean indicating whether this is Conclusion SServereveervererve a transacted session. That is all we need to Our discussion of message acknowl- 2 Send JMSMS 5 commit() JMSM create a transactional session. There is no edgment shows that producers and con- Producerodu Consumeronsumsu explicit begin() method. When a session is sumers have different perspectives on transacted, all messages sent or received the messages they exchange. The pro- using that session are automatically ducer has a contract with the message FIGURE 9 Message can be received on all-or-nothing basis. grouped in a transaction. The transaction server that ensures that the message will remains open until either a session.roll- be delivered as far as the server. The back() or a session.commit() happens, at server has a contract with the consumer which point a new transaction is started. that the message will be delivered to it. An additional Session method, is- The two operations are separate, which 1 Receive Transacted(), returns a Boolean true or is a key benefit of asynchronous mes- false indicating whether the current ses- saging. It is the role of the JMS provider JMSJMSS Receive SServereveervererve 4 sion is transactional. to ensure that messages get to where JMSMS 2 Send they are supposed to go. Producer/ JMSM Distributed Transactions Through message acknowledgment, Consumeronsum Consumeronsumsu Having all producers and all con- message persistence, and transactions, commit() 3 sumers participate in one global trans- JMS provides a strict set of rules that action would defeat the purpose of guarantees that your business critical FIGURE 10 When transacted producer and consumers are grouped as one. using a loosely coupled asynchronous data will travel reliably throughout your messaging environment. global enterprise. Note: This material is Sometimes it’s necessary to coordi- condensed from our book, which con- nate the send or receipt of a JMS trans- tains full working examples with action with the update of another non- detailed explanations of the concepts JMS resource, like a database or an EJB presented here. entity bean. This typically involves an underlying transaction man- AUTHOR BIOS ager that takes care of coordi- David Chappell is chief technology evangelist for Progress nating the prepare, commit, or Software’s SonicMQ and coauthor of O’Reilly’s Java Message rollback of each resource par- Service. ticipating in the transaction. JMS provides JTA transaction Richard Monson-Haefel is the author of Enterprise interfaces for accomplishing JavaBeans and coauthor of Java Message Service, both from this. O’Reilly. He is also the lead architect of the OpenEJB server. JMS providers that imple- ment the JTA XA APIs can partici- pate as a resource in a two-phase [email protected] commit. The JMS specification provides XA versions of the fol- [email protected] Listing 1: CLIENT_ACKNOWLEDGE mode requires an explicit acknowledge() public void onMessage(javax.jms.Message message){ int count = 1000; try{ // perform some business logic with the message ... message.acknowledge(); // perform more business logic with the message ... }catch (javax.jms.JMSException jmse){ // catch the exception thrown and undo the results // of partial processing ... } } Listing 2: Creating transected jms session // pub/sub connection creates a transacted TopicSession javax.jms.TopicSession session =connect.createTopicSession(true,Session.AUTO_ACKNOWLEDGE); // p2p connection creates a transacted QueueSession javax.jms.QueueSession = connect.createQueueSession(true,Session.AUTO_ACKNOWLEDGE); ... } 24 APRIL 2001 Java COM Java COM allaire> allaire> allaire> allaire> New Demands for Developers presentation services (i.e., pages that provide the formatting of data allaire> From a business perspective, these changes are exciting but they and handle things such as state management). allaire> also introduce a new level of complexity into the developer’s life. Thus, a browser request sent to www.mysite.com would receive allaire> Supporting two implementations of DHTML is difficult enough. Now, the HTML home page, but a WAP phone would receive the WML home with Web services and wireless devices coming online, the develop- page and a Palm cHTML. This type of handler architecture is one that allaire> ment team also has to make sure the application they’re building many Web developers have been forced to implement in order to sup- allaire> today can support the dozens of wireless devices as well as expose port different browsers. Given the physical differences between a allaire> parts of its functionality as a Web service. For the online travel service, computer monitor and a PDA screen, the different home pages are allaire> this means the code that checks a flight’s estimated arrival time must unlikely to be mirrors of each other. However, forcing users to remem- allaire> be able to format its data so that it can be viewed in a PC browser, dis- ber different URLs for each device is an unnecessary burden, espe- allaire> played on a mobile device, or passed to another application. cially for consumer sites. Fortunately, many of the same design principles that have served allaire> Web developers well in the past few years are also applicable to this allaire> Any individual piece of computer hardware or software can fail. That’s why we back up our hard drives.When the hard drive on my laptop failed last year, the tape backup got me up and running in a WRITTEN BY few days – the time it took to get a replacement drive and reload JON SIEGEL my files. But some systems can’t afford to be client should produce a response with have a single point of failure. down for a few days…or even a few the correct result (subject to the limita- FT systems provide this degree of hours…or sometimes even a few min- tions listed in the last section of this assurance through utes. For example: article). • Redundancy (replication) • Medical monitoring systems deal with OMG’s FT CORBA specification • Fault detection and notification health-critical information constant- enables products that support a wide • Logging and recovery ly. range of fault tolerance from simple • Fly-by-wire systems must act in real one-copy redundancy of key objects to The FT CORBA infrastructure allows time and must not fail (as you’ll attest highly reliable, geographically dis- individual object instances to be repli- if you’ve ever flown in an airplane). persed, multiply connected servers. FT cated on multiple processors at different • When widely used e-commerce sys- CORBA applications are transparent to locations on the network – even in dif- tems fail, companies lose thousands the user, to the operation of the client, ferent cities or on different continents – of sales, and possibly thousands of and, to some extent, to the application in a very flexible way. Even when calls customers. programmer. are cascaded, with replicated objects • Financial trading applications may It’s perhaps a little more surprising calling other replicated objects, propa- lose unbelievable amounts of money that the transparency extends partially gation is controlled so that no copy exe- for both customers and the responsi- to the application programmer who cutes the resulting call more than once. ble company if they go down at a crit- codes his or her usual CORBA program Faults are detected by a number of ical moment – usually when the load with the same set of objects that would mechanisms, including both push is highest and potential for failure is have been coded for a nonfault-tolerant (heartbeat) and pull monitoring. To greatest. system, adding to each application avoid scalability problems, a Fault object a few interfaces that let the FT Detector on each host monitors the Online redundancy provides the infrastructure synchronize the state of individual objects on it, and a global timely robustness that meets these sys- each set of object replicas. Running this (replicated, of course) Fault Detector tems’ needs. And to enable users of same code on reliable, redundant hard- monitors the individual host Fault these systems to take advantage of ware under the control of a fault-toler- Detectors. CORBA, OMG members have recently ant infrastructure makes it fault toler- standardized Fault Tolerant (FT) ant. Replication and Object Groups CORBA, which provides entity redun- The transparency doesn’t extend to The replicas of an object are created dancy to CORBA systems. the system administrator, who must and managed as an object group. To ren- The difference between running an install and configure the fault-tolerance der this replication transparent to the application under normal conditions product, provide redundant hardware client, the copies are created and man- and under fault-tolerant conditions is and software, and configure the applica- aged by a Replication Manager and simple: under normal conditions an tion to run redundant copies of its addressed by a single Interoperable application will fail occasionally. objects. As you’ll discover, fault toler- Object Group Reference (IOGR). I won’t Under fault-tolerant conditions it ance results from the way the applica- present details of the IOGR here – should never fail. Every invocation by a tion uses the redundant hardware to run they’re hidden from the application and redundant copies of its software. serve only to allow the ORB and FT This article is abridged from the forthcoming infrastructure to work together to deliv- book Quick CORBA 3, by Jon Siegel, copyright FT Basics er FT support. 2001 by the Object Management Group and FT CORBA supports applications Fault Tolerance Domains make it published by John Wiley & Sons. that require a high level of reliability. practical to create and manage large FT Under FT CORBA, applications must not systems. An FT Domain may contain a 32 APRIL 2001 Java COM C0RBA CORNER host Active vs Passive Replication Styles There are two major styles of replica- 6 tion: active and passive. Passive then h subdivides into two styles of its own, but os ORB without hos h let’s look at the difference between t ost os support for 3 E1 active and passive first. fault tolerance Los AngelesAn eleleses t D2 5 • Every active replica executes every Fault ToleraTo errance invocation independently, in the Doomao aina New Yorkk B2 C1 Fault Tolerananceaan same order as every other replica. The A Domaiainaiin replication mechanism inhibits dupli- IIOPPTCP CP/IPC C3 D1 E2 1 cate invocations when one replicated st D3 object invokes another. Active replica- host Hawaii tion is faster and cheaper when the Location B C2 Wide-area 7 cost of computation is less than the 1 B3 Fault Tolerancencennc DomainDomaDDommai cost of saving/restoring state, and host necessary when recovery has to be 2 4 t st instantaneous. • Only one passive replica of a replicat- host host ed object, the primary member, exe- FIGURE 1 Structure of fault-tolerance domains cutes invoked methods, saving its state periodically. When a fault number of hosts and many object vidual instance. Hosts may participate in occurs, a backup member is promot- groups, although a single host may sup- one (Host 2) or more (e.g., Hosts 3 and 4) ed to primary, and its state is restored port multiple domains. There is a single domains, but all objects in a group must from a log and the replaying of (replicated) Replication Manager for be in the same domain because they are request messages. each domain. all created and managed by that In Figure 1 lightly shaded ovals domain’s Replication Manager. Warm passive replication lessens the denote the extent of FT domains, darker Every object group has a set of FT recovery delay somewhat by loading ones denote hosts, and circles denote properties – ReplicationStyle, Member- state into backup objects periodically object instance replicas. Capital letters shipStyle, ConsistencyStyle, FaultMon- during execution; cold passive replica- within an object’s circle denote its object itoringStyle, and six others – that may be tion does no loading until the primary group; the set of circles with the same set either domain-wide, per type, or per member fails. letter is thus the set of replicas of an indi- group. Unlike, for example, POA proper- Another mode, Stateless, applies to ties, some of these may be modified objects that have no dynamic state. after the group is created. ACTIVE_WITH_VOTING, the only set create Invoked by properties object() Application replication style we haven’t covered yet, is interesting for two reasons: Replication Manager 1. It isn’t fully supported by the current specification and represents a possi- Property Object Group Manager Manager notification ble future extension. Generic Factory Fault Fault 2. This mode (and the fact that it’s not Notifier Detector supported) points out a limitation: Invoked by Replication the current specification protects only create fault Manager on is_alive() object() reports Factory Objects against crash faults, that is, when an object issues no response. host host host The specification doesn’t protect against what it terms commission faults, H1 H2 H3 where an object generates incorrect results, or against what it terms byzantine faults, where an object or host generates incorrect results intentionally. The Client Object Server Replica Server Replica ACTIVE_WITH_VOTING replication style, used with sophisticated algorithms, can C S1 S2 protect against both types of faults, albeit at considerable cost in network traffic. Strong Replica Consistency is the prin- Fault Fault Factory Factory Detector ciple of FT CORBA that guarantees that Detector objects have identical state. Supported by the specification, it guarantees that for ORB ORB ORB passive replication all members of an Logging Recovery Logging Recovery object group have the same state follow- Mechanism Mechanism Mechanism Mechanism ing each state transfer, and that for active replication all members have the same state at the end of each operation. FIGURE 2 Possible architectural configuration of fault-tolerant system For this to work, applications must 34 APRIL 2001 Java COM C0RBA CORNER be deterministic, or must be sanitized to bly using a GUI. Of the properties the primary member or to promote a give the appearance of being determin- defined, two are especially relevant here: backup member to primary. istic: for a given starting state a given MembershipStyle and ConsistencyStyle. At this point the primary member invocation with a given set of parame- MembershipStyle defines whether the needs to have its state restored. If you’ve ters must produce the same output and infrastructure or application controls chosen the application-controlled con- the same internal state. (Sanitize means membership in an object group, and sistency style, the application must fetch to clean up a set of replicas so that all ConsistencyStyle defines whether the and restore the state of the new primary give the identical answer to an invoca- infrastructure or the application controls member. This is easy to describe: it’s tion, removing all sources of nondeter- consistency of state for members of an application-dependent, and you have to ministic behavior. Although this may be object group. code it yourself. If you’ve chosen infra- simple for a routine that queries a data- structure-controlled consistency style, base row or performs a calculation, it’s Fault Detector and Fault Notifier things are more automatic: using the not so easy to sanitize an object against Figure 3, copied from the specifica- Checkpointable interface with its opera- a query whose result varies with even tion, shows diagrammatically the tions set_state( ) and get_state( ), the slight differences in invocation delivery sequence of events that ensues when a system keeps state current in a log and timing, or depends on a hardware serial fault is detected. uses the most recent values to restore the member during recovery. If you’ve chosen active replication, Fault Notification none of this applies at failure/recovery time; the system just has one less dupli- cate response than usual and goes on Replication with its processing without missing a Fault Manager Notifier beat. However, the logging and recovery Fault Reports Fault mechanisms still use get_state( ) and Analyzer set_state( ) to maintain a log that is used Fault to synchronize new instances that Detector Fault might be added to an object group at Detector Fault runtime. Pings Detector Fault Analyzer Application The Fault Analyzer registers with the Fault Notifier to receive fault reports. It then correlates fault reports and gener- Application Application Application Application ates condensed fault reports using an Object Object Object Object application-specific algorithm. Even though reporting is orthogonal to recovery and your system is (hopeful- ly) chugging along without missing a beat even when redundant copies or hosts fail, you’ll still want to know every- FIGURE 3 Interactions among Fault Detectors, Fault Notifier, Fault Analyzer, and Replication Manager thing that’s gone wrong during execu- tion. The Fault Analyzer is the system number or some other value that differs As mentioned before, at least one component that takes care of this. from one machine to another.) Fault Detector on each host periodically Although a simple fault analyzer may The specification requires that the FT pings each object replica on that host to report every fault it receives, it’s much infrastructure deliver the same set of see if it’s functioning. Applications can better if it performs correlations and invocations in the same order to every configure additional Fault Detectors as condenses several thousand nearly member of an object group. The deter- needed. When a Fault Detector detects a simultaneous instance fault reports into ministic behavior of the object fault, it pushes a report to the Fault a single host fault report! instances, combined with the consistent Notifier using the FaultNotifier inter- behavior of the FT infrastructure, guar- face, a subset of the Notification Service Limitations and Conformance antees strong replica consistency. interface. Some limitations to FT CORBA are given in the following abbreviated list. The Replication Manager Logging and Recovery By analyzing them you’ll gain additional Figure 2 shows a sample configura- Everything covered so far was an insight into the workings of an FT sys- tion for a fault-tolerant system. I’ll use introduction to this part. Here’s where tem. this configuration to discuss the way the service fixes up your application • Legacy client ORBs: An unreplicated each element works. when an object crashes. client hosted by a CORBA 2.3 or earli- The Replication Manager, itself repli- If you’re running in one of the pas- er ORB can invoke methods on a cated as the figure shows by the nested sive replication styles (either warm or replicated server, but won’t partici- boxes, inherits three interfaces defined cold), only the primary member of each pate fully in FT (for reasons that space separately in the specification: Prop- of your object groups actually executes constraints preclude discussing). ertyManager, ObjectGroupManager, and an invocation and sends back replies. • Common infrastructure: For this first GenericFactory. The PropertyManager When the Fault Detector suspects that release of the specification, all hosts interface lets you define fault-tolerance the primary member has failed, it sig- within a FT domain must use the properties for your object groups, possi- nals the Replication Manager to restart same FT product and ORBs from the 36 APRIL 2001 Java COM C0RBA CORNER CORBA provides no protection against such faults. Strong“ Replica Consistency is the principle of FT CORBA defines two conformance points. An implementation must sup- port at least one, and may support both: FT CORBA 1. Passive replication FT CORBA prod- ucts support only the COLD_PASSIVE, WARM_PASSIVE, and STATELESS that guarantees replication styles. 2. Active replication FT CORBA products that objects have identical state support only the ACTIVE and STATE- LESS replication styles. same vendor to ensure FT behavior. occur when an object or host’’ gener- That’s all the fault tolerance we have Between domains, full FT behavior is ates incorrect results, and byzantine space for here. I know it isn’t enough to get guaranteed only if all employ the faults occur when this happens inten- you programming in FT mode, but I think same FT product and the same ORB, tionally or maliciously. These fault it’s more than enough to trigger an inves- although some improvement can be types are neither detected nor cor- tigation into whether FT CORBA can pro- expected even when different prod- rected by FT CORBA, although the vide your enterprise with the assurance ucts are used. ACTIVE_WITH_VOTING replication you need to survive in today’s world of AUTHOR BIO • Network partitioning faults: A net- style provides a mechanism that can business dependence on computing. Jon Siegel, director of work partitioning fault divides the be used to build a solution. The solu- technology transfer at system into two parts, each able to tion, however, will be expensive in Acknowledgment Object Management operate and communicate within terms of resource. I’d like to thank Dr. Louise Moser and Group, also writes articles itself but unable to communicate with • Correlated faults: These faults cause Dr. Michael Melliar-Smith of Eternal and presents tutorials and the other. The inherent nature of the the same error to occur simultaneous- Systems, Inc. (www.eternal-systems. seminars about CORBA. problem doesn’t allow assured detec- ly in every replica or host, and typical- com), for technical review of this article His book, CORBA 3 tion and recovery from these, which ly result from failures in design or and for their contributions to the Fault Fundamentals and are therefore not covered by FT coding. They can happen anywhere: Tolerant CORBA specification on which Programming, was CORBA. application, operating system, stor- this article is based. published last year by • Commission and byzantine faults: As age, network, hardware, or any other John Wiley & Sons. mentioned earlier, commission faults replicated part of the system. FT [email protected] 38 APRIL 2001 Java COM SYBASE SYBASE SYBASE SYBASE create a foundation SYBASE SYBASE SYBASE SYBASE SYBASE SYBASE REATE A FFOUNDATION SYBASE C SYBASE SYBASE build an application SYBASE SYBASE server infrastructure SYBASE SYBASE SYBASE SYBASE SYBASE SYBASE SYBASE create a foundation SYBASE SYBASE SYBASE r SYBASE written by matt creason e r u t c u r t s a r f n i app SYBASE e SYBASE v SYBASE r SYBASE e SYBASE s SYBASE • Scalability: The ability to meet system demands • Robustness: Confidence in being efficient, stable, and proven SYBASE • Security: The competence to reduce loss of information and YBASE S quash customer fear SYBASE s most of you reading this article know, the SYBASE To remain focused on these benefits that will create the foun- SYBASE dation for your application server infrastructure, you must con- SYBASE application server market is growing and every company, large or tinue to answer three simple, yet complex, questions: • Who is the target audience? SYBASE • What is the agreed or implied level of service expected? SYBASE small, can visualize the benefits an application server infrastructure • What level of security must you maintain in your environment? SYBASE SYBASE These questions can usually be answered definitively, but only SYBASE could bring to their organization. But why then, even with the vast for a certain point in time. Therefore, to ensure that you maintain SYBASE a strong foundation, your company must revisit these questions SYBASE to keep up with a moving target. Every time you pose these ques- amount of benefits available, have companies not adopted an appli- tions to your organization there will most likely be negotiation SYBASE and compromise, but remember that a solid foundation is a bal- SYBASE anced one. Keeping this in mind, let’s discuss three application SYBASE cation server as the foundation for their organization? server infrastructure models that your company could use: SYBASE development, small-business, and enterprise. SYBASE SYBASE The reason is they’re making it more complex than it really is. Development Model The development model is an all-in-one solution, literally. SYBASE The Web server, the JSP engine, and the application server all run SYBASE Though it’s by no means a small chore, it is a large puzzle, but one on the same box. Though this model works, it tends to construct SYBASE more roadblocks than remove them. The only positive argument SYBASE is a financial one. It’s cheap and your company only has to invest SYBASE that can be pieced together by maintaining focus. The focus should in one piece of hardware and in a limited amount of CPU- or SYBASE MHz-priced software licenses to house and run the different SYBASE pieces of the infrastructure mentioned above. be on the three major inherent benefits an application server infra- Because everything runs on one box, points of failure begin SYBASE to compound as the development model is built. First, there’s no YBASE S contingency for software or hardware redundancy. Without Web SYBASE structure will bring to a company. server redundancy, should the Web server go down, there’s no SYBASE SYBASE 40 APRIL 2001 SYBASE SYBASE Java COM SYBASE SYBASE SYBASE SYBASE SYBASE point of entry into the application(s), given the premise that these are one and has been shown to balance fiscal responsibility with an abili- SYBASE browser-based application(s). ty to be highly scalable, robust, and secure. SYBASE This same theory applies if the application server software process should fail, but with even more severe consequences. Instead of just Enterprise Model SYBASE affecting browser clients, all the application(s) become unusable, Now we come to the granddaddy of the infrastructure models, the YBASE S therefore disabling all supported client models for the affected appli- enterprise model. The enterprise model is the one that every compa- SYBASE cation(s). Not only is this model risky on the surface, the risk is com- ny strives to achieve, but can’t always afford. This model is often large SYBASE pounded by the high memory and I/O intensive processes these and complex, and therefore places a high fiscal demand on a compa- SYBASE servers place on one piece of hardware. These discrepancies directly ny, which must be taken into consideration. Though theoretically SYBASE impact an infrastructure’s ability to be scalable and reliable. there is only a single hardware addition of a firewall between the In addition, this model lacks any implementation of a firewall. As a application server and the database, the complexity of being able to SYBASE result, there’s no allowance for a demilitarized zone, which makes this manage this behemoth grows exponentially because it usually SYBASE infrastructure highly vulnerable to hackers. Security must come from involves multiple clusters and redundancy. SYBASE either a custom authentication application or utilization of the appli- SYBASE cation server vendor’s security protocols. Though vulnerable and SYBASE maybe not the most scalable or robust application server infrastruc- he enterprise model SYBASE ture, this configuration is a solid and cost-effective development envi- ronment. It could even be run as a successful departmental infrastruc- SYBASE is the one that every ture designed to serve a small target audience that expects a reason- SYBASE able level of service, and requires minimal security. company strives to SYBASE “ SYBASE Small-Business Model achieve,t but can’t SYBASE A small-business model divides tasks among multiple pieces of SYBASE hardware to gain high throughput and redundancy capabilities. In always afford SYBASE this configuration, the Web server and the application server have been separated, and the JSP engine can reside with either one based SYBASE upon the chosen vendor’s software ability to integrate a JSP engine This growth affects your bottom line by dramatically increasing YBASE S into their respective product. Though to get the highest reliability, your need for manpower to manage and monitor” this infrastructure. SYBASE scalability, and security, the JSPs should be run within your applica- In addition, there’s the additional hardware cost of adding a firewall. SYBASE tion server in order to take full advantage of the inherent pooling and With this said, and though these costs can be significant, most organ- SYBASE security mechanisms provided. This is the most common model used izations that are in the enterprise space already know that in order to SYBASE when companies choose to build an application server infrastructure. play, you must pay. The popularity of this model is a direct result of a balance of main- The benefits this model brings to an organization are simple. It SYBASE taining scalability, robustness, and security with the financial impact incorporates and provides the same level of high reliability and scala- SYBASE of purchasing and supporting additional hardware. bility that the small business model would, but wraps a stringent SYBASE The first and most obvious benefit of separating the Web and security framework around the application server infrastructure. By SYBASE application server processes across at least two pieces of hardware is adding this security “wrapper,” the enterprise model creates the high- SYBASE that you now have the ability to implement a firewall between the two. ly sought-after demilitarized zone. This is a transition zone from one SYBASE This provides your organization and customers with the necessary world to another, or from the Internet to inside your organization, security to protect both entities in the e-business space. A second which allows only certain protocols on specific listeners to enter into SYBASE benefit of this model is that you alleviate the stress placed on the “all- your environment. An enterprise model provides a company with the SYBASE in-one” or development model of those high I/O and memory-inten- most scalable, robust, and secure infrastructure available that can SYBASE sive processes by splitting them across separate pieces of hardware. As serve any space, provided your organization can justify the financial SYBASE a result, your infrastructure eliminates the Web and application serv- costs. SYBASE er processes from “stepping” on each other, thereby greatly reducing As presented, these models hinge not only on the technical aspects SYBASE the possibility of the aforementioned catastrophic failure. Finally, this of scalability, robustness, and security, but have a high dependency on SYBASE configuration allows your organization to easily scale your infrastruc- financial requirements. This is emphasized in no short order due to ture to meet system demands. Ease of scalability directly stems from the “dot-bombs” that have fallen by the wayside lately. Yes, some of the SYBASE the inherent increase in manageability and the ability to monitor with companies were doomed from the start, but most did not plan and YBASE S finite precision the appropriate Web or application server process. build a scalable infrastructure that was fiscally feasible. Because even SYBASE With this enhanced sense of infrastructure awareness your organ- for “techies” this is a reality, and I thought it important that you know SYBASE ization can remove the finger of blame being thrown around between not only how to build your company’s application server infrastruc- SYBASE the two processes, which usually correlates directly to organizational ture, but that you also have some understanding of the financial SYBASE structure, and focus on solving the problem rather than discussing investments required to implement this foundation. whose problem it is. By concentrating on the issues, your organization In closing, keep your eye on the ball while you build and maintain SYBASE will be able to react to a projected or actual loss of level of service by an application server infrastructure by continually revisiting and SYBASE bringing online only those additional server resources that are focusing on: SYBASE required. • Who is the target audience? SYBASE The drawbacks to the small-business model are financial and • What is the agreed or implied level of service expected? SYBASE security. There’s an increased financial burden in terms of the addi- • What level of security must you maintain in your environment? SYBASE tional capital expenditures of hardware and the manpower to main- SYBASE tain these systems. In terms of security, even though this model incor- AUTHOR BIO porates a firewall, it does not build a demilitarized zone required by Matt Creason is a system consultant with the Internet Applications Division of Sybase, Inc. He is a SYBASE some organizations. But by maintaining the focus on our target audi- current member of the IEEE and the IEEE Computer Society. SYBASE ence of a small business, most do not require such a strict security SYBASE construct. Despite these facts, the small-business model is a proven [email protected] SYBASE SYBASE 42 APRIL 2001 SYBASE SYBASE Java COM J L I N K Jlink:Cybelink’s Framework for Creating Reusable Enterprise Components Using J2EE Create scalable enterprise-wide Web architecture Part 2 of 3 In Part 1 of this article (JDJ, Vol. 6, issue 2) we discussed the problems associated with J2EE’s Servlet/JSP container. In Part 2 WRITTEN BY we’ll discuss Cybelink’s Jlink architecture and how it solves those MANI MALARVANNAN problems. Jlink Architecture uted component-based applications. It Mapping MVC with Servlets and JSP Jlink is built on various architectural facilitates the division of the application In Part 1 we discussed the problems and software design patterns. In this into logical components that can be associated with Sun’s Servlet/JSP con- section we’ll discuss the software pat- designed and developed independently. tainer; in the previous section we dis- terns, specifically, the Model-View- This division increases the reusability of cussed the MVC pattern. Now that we Controller (MVC) patterns. components by reducing the couplings understand the Servlet/JSP Container between them. model and the MVC pattern, we can MVC Architectural Pattern In the MVC pattern the Model com- start applying the MVC to the MVC is an architectural pattern that’s ponents represent the business logic Servlet/JSP Container model. Tra- been widely used in architecting distrib- (e.g., JavaBeans and EJBs), the View ditionally, the MVC pattern was used to components represent the build client/server applications; in this UI that displays the process- section we’ll see how we can use it to ing results of the business develop Web-based applications using Controller Componentsomponents logic, and the Controller Servlets/JSP. In our Jlink we’ll use the JSP 1. Maps User Acctionsons to components manage the and JavaBean as the Controller compo- Model Componenents coordination between the nents, the JSP pages as the View compo- 2. Selects the Vieww Components for User Model and View compo- nents, and JavaBeans as Model compo- Actions on the View Components Notify State Changes nents. Figure 1 shows the nents. relationship between the various components of the JSP and JavaBeans as MVC pattern. The Model Controller Components components maintain the The AppController.jsp (see Listing 1) state of the business object and AppController bean (see Listing 2) are User Action Events and when the state of the used as Controller components that are Model Commponentsponents Model object changes, they responsible for accepting the HTTP notify the View compo- requests and passing them to the appro- nents, which update the UI priate RequestHandler object. (Listings 1. Contains Object State 2. Notifies State Changes with new data. It’s also pos- 1–7 can be found on the JDJ Web site, to Views sible for the View compo- www.JavaDevelopersJournal.com.)The nents to request state RequestHandler objects are designed Select View Components Select View State Changes Requests changes directly from the using JavaBeans. These beans strip the Model components. The browser requests and send them to the View Componentsonents View components enable appropriate Command JavaBean compo- the Controller components nents. The Command beans are modeled 1. Displays the ModelModel Component's Datata to change the display after Command Design patterns. Before 2. Sends User Actictionsns tot according to the user’s handling the request to the Controller Componentsnents 3. Allows Controller request. The Controller RequestHandler objects, the App- Components to select new Suite Change Notification Event View Components components map the user’s Controller.jsp creates a ClientContext (see actions from the View to the Listing 3) object for each request and pass- FIGURE 1 MVC architecture Model components. es it to the RequestHandler object. The 44 APRIL 2001 Java COM J L I N K Controller Components HTTP HTTP Request AppController.javapController.java AppController.jsppControlle Request RequestHandler JavaBeans Submits the Requests to process Selects appropriate View Components and Other EJBBusiness Services Carries the Request info to process in Extracts thee Results Business Services View JSPComponents Command JavaBean Components FIGURE 2 Jlink architecture ClientContext contains javax.servlet In our Jlink all HTTP requests go to ual classes and interfaces. Figure 3 shows .HttpRequest, javax.servlet.HttpResponse, the AppController.jsp, which creates the the UML class diagram of the Jlink. and javax.servlet.http.HttpSession objects. AppController JavaBean for the first Thus the ClientContext encapsulates the request (see Figure 2). The javax.serv- AppController.jsp Client state by maintaining the necessary let.ServletContext object is set in the As mentioned earlier, the App- objects in one place, eliminating the AppController JavaBean. For a Web Controller.jsp (see Listing 1) creates the spaghetti code discussed in Part 1. Other application the AppController.jsp cre- AppController JavaBean the first time the objects should get parameters, such as ates one AppController JavaBean that HTTP request comes from the browser. Request and Query, from the Client- will be shared by all the Model and View After creating the bean, it sets the Context object. components in the Jlink. The App- ServletContext object to the AppController Controller.jsp acts as a bridge between bean. For each request, the AppController JSP as View Components the browser and the AppController creates a new ClientContext object by In our Jlink, JSP pages represent the JavaBean. For each HTTP request, it cre- passing the HttpServletRequest, Http- View components. These pages interact ates a ClientContext object and prompts ServletResponse, and HttpSession objects. directly with the JavaBean Model com- the RequestHandler to call the Using the ClientContext object it gets the ponents to get the results to display on handleRequest method by passing the RequestHandler object from the App- the Browser. ClientContext object. Controller JavaBean and calls the Figure 2 shows the architecture of the handleRequest method by passing the Model Components Jlink. If you compare Figure 1 with ClientContext object. The RequestHandler The Jlink has been architected in Figure 2 you can see how Jlink is mod- computes the result and selects a JSP page such a way that we can use JavaBeans, eled after the MVC pattern. that’s appropriate for displaying it. The EJB, C++, or any other component as Now that we’ve discussed the high-level AppController.jsp retrieves the JSP page the Model. The Controller and View workings of Jlink, we’ll look at individual and passes it to the browser. Note that nei- components are not affected when we classes and interfaces in more detail. ther the Controller components (App- change our Model components from Controller.jsp and AppController bean) JavaBeans to EJBs. The Command Jlink Classes and Interfaces nor the View components (JSP pages) JavaBean objects shield the Controller This Jlink is built on JSP, Java inter- know how the results are computed in the and View components from the Model faces, and abstract and concrete classes. RequestHandler object. components. In this section we’ll discuss the individ- Controller Interface Command JavaBean This interface (see Listing 4) provides AUTHOR BIO The Command JavaBean shields the basic methods that all AppControllers Mani Malarvannan is Controller and View components from the RequestObjectuestObje need to implement in order to qualify as CEO and cofounder Model components. They get the requests an AppController. of Cybelink from the handler objects and pass them to (www.cybelink.com), a the Model components located either in AppController JavaBean Minnesota-based the same machine as the Command The AppController JavaBean imple- company that specializes JavaBean or in a different one. Once the ments the Controller interface (see SessionObjectssionObje in e-business consulting Model components execute the requests, ClientContext Listing 2). One AppController object is and training. Mani has they collect the results, which are then created per Web application the first several years of OO retrieved by the View components. The time an HTTP request comes to that analysis and design RequestHandler objects or the JSPs will application. This AppController man- experience and has been worry about issues such as transactions, ages application-wide objects. The working in Internet and the Model object’s location, and more. The AppController JSP sets the Servlet- Java technologies since Command JavaBean shields these issues ResponseObjectponseOb Context object to the AppController their inception. He holds a from the Controller and View compo- bean, which is used to store application- BS and an MS in nents, thereby increasing the reusability wide objects and can be accessed by all computer science. and coupling of the components. FIGURE 3 ClientContext object structure the JavaBeans within the application. 46 APRIL 2001 Java COM RequestHandler already exists for the and putSessionObject retrieve the session in which the ClientContext objects using the HttpSession object. As object was created. If the Request- explained earlier, the HttpSession object Handler doesn’t exist, a new Request- and all other objects added to the Handler is created. It uses the forName HttpSession become potential candi- static method from the class to get the dates for garbage collection if the brows- Class object and the newInstance er that created the HttpSession object is method on the Class object to create the timed out. The methods getRe- appropriate RequestHandler object. The questObject and setRequestObject forName method takes the name of the retrieve the HttpServletRequest. In- class as a parameter. The class name is cluding the HttpServletRequest object, obtained from the property file using all other objects that are added to it the key obtained from the query param- become potential candidates for eter, which is passed from the browser. garbage collection when a new HTTP This design solves our problem of map- request comes from the browser. The ping browser requests to proper methods getRequestParameterNames() Servlet/JSPs and avoids the big if-then- and getRequestParameterValues() re- else statement in the AppController trieve the names and values of the bean. Thus we can add more Request- parameters set by the browser. The Handler objects as the Web site grows. method getQueryString() returns the query parameter that’s set by the brows- Request Handler Interface er. As explained earlier, the Query string This interface (see Listing 6) provides is used to find the appropriate Class basic methods that all RequestHandler Name to create the RequestHandler classes must implement to qualify as a object. FIGURE 4 UML class diagram for Jlink RequestHandler. Thus the ClientContext object (see Figure 4) provides a wrapper for GenericRequestHandler HttpServletRequest, HttpServletRe- This is an abstract class (see Listing sponse, and HttpSession objects and the 3) that implements the RequestHandler outside world can access them through interface and provides a generic imple- the ClientContext object. This design mentation for handling HTTP requests. avoids spaghetti code in the JSP and The Constructor is called from the JavaBean source code described in Part 1. AppController JSP for each HTTP Figure 4 shows the structure of the request. The Constructor creates a ClientContext object. For each HTTP java.util.ResourceBundle object. The request a new ClientContext object is name for the ResourceBundle object created. comes from the method getName, an abstract method in the GenericRequest- Jlink Class Diagram Handler object. The subclasses of In any Java-based framework Java GenericRequestHandler must provide interfaces play a critical role in creating the actual name for the Resource- the frameworks that provide tools for the Bundle. This approach provides the sub- architects, designers, and developers to classes of the GenericRequestHandler create reusable components. Jlink is no with the flexibility to have their own different; Figure 5 shows the class dia- ResourceBundle names. The methods gram for the Jlink interfaces and classes getClientContext and setClientContext described earlier. The AppController retrieve and set the ClientContext implements the Controller interface and object. The method getNextPage returns we can create several application-specif- FIGURE 5 UML sequence diagram for Jlink the JSP page (View component). The ic AppController classes by implement- handleRequest method does nothing in ing it. The Controller interface provides The java.util.ResourceBundle object this abstract class. The subclasses of the coordination among all the AppCon- is used to read the resource names and GenericRequestHandler must provide troller objects within the framework. This paths from a property text file. The the actual implementation for this mechanism allows us to add more appli- methods getAppObject and putApp- method. This approach allows Jlink cation-specific AppController classes, Object retrieve and add application- users to have their own project-specific thereby making the framework adaptable wide objects to the ServletContext. This implementation for the RequestHandler to various types of Web applications. provides any JSP or JavaBean within the objects and still use the infrastructure The GenericRequestHandler imple- Web application with the flexibility to provided by Jlink. ments the RequestHandler interface add or retrieve the objects. The impor- and provides an abstract behavior for all tant method in this class is ge- ClientContext the handler classes in a particular Web RequestHandler, which we’ll discuss in The ClientContext is a crucial object application. Depending on the Web detail. Listing 5 shows the implementa- in our Jlink (see Listing 7). The application’s needs, we can create sever- tion of the getRequestHandler. Constructor takes HttpServletRequest, al application-specific GenericRequest- getRequestHandler accepts a HttpServletResponse, and HttpSession Handler classes by implementing the ClientContext and checks if a objects. The methods getSessionObject RequestHandler interface. 48 APRIL 2001 Java COM J L I N K How Jlink Works bean creates an object of the class it RequestHandler object is created, it In the previous section we discussed inherits from the GenericRequest- remains as long as the corresponding the static aspects of Jlink. In this section Handler class. When the AppCon- browser connection is valid. we’ll discuss the dynamic aspects. An troller.jsp asks for a RequestHandler, the HTTP request comes from a browser to AppController bean gets the Session ID Conclusion the AppController.jsp (see Figure 5). On from the ClientContext and checks if the In Part 2 we discussed the Jlink’s the first request for a Web application the RequestHandler already exists by pass- architecture and how it solves the prob- AppController.jsp creates an App- ing the Session ID to the lems of creating scalable enterprise- wide Web architecture. Jlink was built using industry best practices such as OO ...creating“ the frameworks that provide tools for the methodology and software design pat- terns. Using Jlink, organizations can cre- ate reusable component-based archi- architects, designers, tecture that will evolve with the technol- ogy and the organization. and developers References to create reusable components • Sun J2EE Blueprint: http://java.sun. com/j2ee/blueprints • Gamma, E., Helm, R., Johnson, R., and Controller bean and sets the getSessionObject method ’’on the Vlissides, J. (1995). Design Patterns – ServletContext object. This Servlet- ClientContext. If the RequestHandler is Elements of Reusable Object-Oriented Context object lives as long as the Web already created, getSessionObject Software. Addison-Wesley. application is alive in the Servlet/JSP con- retrieves it from the HttpSession object • Buschmann, F., et al. (1996). Pattern- tainer. Next, the AppController JSP creates stored in the ClientContext. Even Oriented Software Architecture. John a ClientContext for every HTTP request by though a new ClientContext is created Wiley & Sons. passing the HttpRequest, HttpResponse, for each new HTTP request in the • Fields, D.K., and Kolb, M.A. (2000). and HttpSession objects. Then it uses the AppController.jsp, the HttpSession is Web Development with JavaServer ClientContext to get the RequestHandler the same for a single browser connec- Pages. Manning Publications. from the AppController bean. tion. Only the HttpServletRequest and • Servlet/JSP API: http://java.sun.com/ At this level the AppController.jsp HttpServletResponse objects are created products/servlet/2.2/javadoc/index.html deals only with the interface every time an HTTP request comes to [email protected] RequestHandler, but the AppController the AppController.jsp. Finally, once a APRIL 2001 49 Java COM lverStream lverStream lverStream lverStream lverStream Building J2EE Applications lverStream lverStream lverStream for Performance and Scalability lverStream lverStream lverStream lverStream WRITTEN BY MISHA DAVIDSON lverStream J2EE lverStream techniques, lverStream lverStream lverStream lverStream optimizations, and lverStream lverStream lverStream lverStream examples lverStream lverStream lverStream lverStream lverStream lverStream lverStream lverStream lverStream lverStream he highly structured nature of applications latency and high throughput under a wide range of loads. This built using J2EE technologies lends itself article examines techniques for building such applications. lverStream well to design patterns for performance lverStream optimization. This article examines a num- Structure of J2EE Applications lverStream ber of such patterns and suggests optimal J2EE applications are comprised of three tiers of components – lverStream ways of using them to improve latency, throughput, and overall client, server, and enterprise information system (EIS) resources. lverStream Tscalability of J2EE applications. The client can be a static page or an applet running in a browser lverStream Application Performance Defined lverStream (HTML or WML), or a J2EE client application running inside a The standard performance metrics for computer systems are J2EE client container. On the server tier, servlets and JavaServer lverStream latency and throughput. In the context of J2EE applications, laten- Pages (JSPs) that run inside a Web container generate the applica- lverStream cy is the time that elapses between the moment a client request is tion Web UI. EJBs that run in an EJB container encapsulate appli- lverStream received by the server and the moment a response is sent back. cation logic and data access. A typical J2EE application uses a rela- lverStream Throughput is the number of client requests that are handled per tional database as its EIS-tier. Figure 2 shows the relationship lverStream second. between J2EE components. lverStream Both latency and throughput are important. To achieve high This article presents techniques that affect the performance of performance, you want to minimize the latency of your applica- Java and database-backed systems in general, optimizations that lverStream tion while increasing throughput. In practical terms, subsecond apply to individual J2EE component types, and a number of J2EE lverStream latency is usually sufficient for Web systems. Acceptable through- application patterns that improve performance. lverStream put rates vary depending on the application; however, throughput lverStream of hundreds of e-commerce (e.g., shopping cart) transactions per J2EE Application Performance Basics lverStream second is considered quite good. At their core, J2EE applications are Java programs that utilize a lverStream Both latency and throughput define the performance of a sys- database. As such, J2EE applications are subject to all performance lverStream tem under a particular load. However, J2EE systems operate under principles that apply to traditional Java and database program- rapidly changing loads, at times coping with an influx of client ming. Good coding techniques and efficient use of the database are lverStream requests an order of magnitude greater than normal. The system’s a prerequisite for writing high-performance J2EE applications. lverStream ability to cope with such an increased load is called scalability. lverStream Typically, system performance degrades with increased client Database Usage Basics lverStream load: latency increases and throughput falls. When a poorly Databases can be huge – thousands of tables and millions of lverStream designed system is confronted with an unexpectedly high load rows of data. Improper use of a database in a J2EE application lverStream (see Figure 1), its latency grows nonlinearly and becomes unac- drastically affects performance. Keep the following points in mind ceptably high while throughput falls sharply. An ideal system when architecting the database portion of the application: lverStream maintains a constant latency regardless of the load level, while its • Avoid n-way joins: Every join has a multiplicative effect on the lverStream throughput scales linearly with the load. While ideal systems don’t amount of work the database has to do to execute a SQL state- lverStream exist, a well-designed system should scale well, maintaining low ment. Multiway joins degrade the performance of an applica- lverStream lverStream 50 APRIL 2001 lverStream lSt Java COM lverStream lverStream lverStream lverStream class can be used at the same time, marking a lverStream c servlet with a SingleThreadModel doesn’t guaran- lverStream Poor tee thread-safety of an application. Multiple lverStream Good instances of the servlet class may still be accessing onses/se p the same underlying classes and data at the same lverStream time. Managing multiple instances of the servlet lverStream ut res p does, however, incur significant overhead for the lverStream Web container. Therefore, instead of writing bad Latency sec/response lverStream Good hrough servlet code and covering it up with a Single- T lverStream Poor ThreadModel, it’s preferable to write thread-safe lverStream code to begin with. Clients Clients lverStream In some cases, it may be possible to speed up the writing of the output from a servlet by using an lverStream Scalability in terms of throughput Scalability in terms of latency OutputStream instead of a PrintWriter (both can lverStream FIGURE 1 Scalability in terms of latency and throughput be obtained from the ServletResponse). In general, lverStream a PrintWriter should be used to ensure that all lverStream tion once the data set becomes sufficiently large. You may not character set conversions are done correctly. However, if you know lverStream notice the performance hit on a development system using a sam- that your servlet returns only binary or ASCII data, you can use an lverStream ple database, but it’ll manifest itself in production. Make sure any OutputStream instead. An OutputStream writes data directly to the multiway joins your application is using are really needed. wire, thus forgoing the character set conversion overhead. lverStream • Avoid bringing back thousands of rows of data: If you don’t, your Using the getRemoteHost()method on a ServletRequest can dra- lverStream server will spend an inordinate amount of resources and time stor- matically increase the latency of your application. This call performs lverStream ing them in memory. The user whose actions caused the query will a remote DNS look-up on the IP address of the client. This operation lverStream get a sluggish response, and everyone else’s ability to do work will typically takes seconds to complete and should be avoided at all costs. lverStream be impaired. If you absolutely have to bring back such a large data lverStream set, consider bringing back just the primary keys first and fetching JSP Performance Hints individual rows on-demand. This approach doesn’t reduce the total Even though JSPs provide an elaborate functionality built on top of lverStream amount of work, but, it spreads it out, greatly reducing the immedi- servlets, the performance of JSPs is roughly comparable to that of lverStream ate response time. servlets. JSPs compile to servlets; compilation introduces a trivial lverStream • Cache data when reuse is likely: Accessing a database is by far the amount of initialization code. Compilation happens only once and lverStream most expensive operation an application server can perform. Thus, JSPs can be precompiled, eliminating any runtime overhead. JSPs are lverStream the number of such accesses should be minimized. In particular, if slower than servlets only when returning binary data, since JSPs lverStream an application frequently refers to a certain subset of values from always use a PrintWriter, whereas servlets can take advantage of a lverStream the database, those values should be cached. faster OutputStream. JSP custom tag libraries can encapsulate arbitrarily complex Java lverStream Java Coding Guidelines functionality in a form that can be easily used by Web designers who lverStream Coding techniques affect the performance of J2EE applications, aren’t that knowledgeable about Java. Thus, JSP custom tag libraries lverStream though not as much as database usage. Here are a few basic points to are an effective tool for dividing the work between programmers and lverStream keep in mind when writing J2EE applications: Web designers. However, every time a custom tag is used on a page, lverStream • Avoid unnecessary object creation: Current implementations of the Web container has to create a new TagHandler object or fetch it lverStream JVMs are much more efficient in managing object creation. Still, it’s from the tag cache. In either case, excessive use of custom tags may one of the more expensive operations that JVMs perform. create unnecessary processing overhead. lverStream • Minimize the use of synchronization: Synchronization blocks BodyTags are a special kind of custom tag. They have access to, and lverStream reduce scalability of applications by forcing serialization of all con- can do transformations on, the contents of their bodies. The use of lverStream current threads of execution. Setting up synchronization also BodyTags causes the contents of the page between the start and the lverStream requires a nontrivial amount of resources from the JVM. Therefore, lverStream serialized blocks should be kept small and used only when absolute- lverStream ly needed. The same rule applies to using standard Java classes. The JDK usually provides at least two implementations for each data Servlets lverStream structure, one with synchronization and one without (e.g., Vector is lverStream synchronized and ListArray is not). When using JDK classes, pick JSPs Web Container lverStream synchronized implementations only when synchronization is actu- lverStream ally needed; use unsynchronized versions in all other cases. Databaseatabas lverStream HTML, WML lverStream J2EE Component Performance Browser lverStream Now that we’ve defined the basics of writing performant J2EE applications, let’s look at specific performance techniques for writing lverStream servlets, JSPs, and EJBs. lverStream J2EE Client EJBs lverStream Servlet Performance Hints J2EE Client Container EJB Container lverStream The first thing to note about writing servlets for performance is lverStream that the use of a SingleThreadModel interface should be avoided. lverStream SingleThreadModel is a marker interface that tells a Web container that the code inside the service() method of the servlet class is not Client Server EIS lverStream thread-safe. Typically, the container will create and possibly cache lverStream multiple instances of the servlet class to handle the concurrent invo- Tier Tier Tier lverStream cations of the service() method. Since multiple instances of the servlet FIGURE 2 J2EE application components lverStream lverStream 52 APRIL 2001 lverStream lSt Java COM lverStream lverStream lverStream lverStream end portions of the tag to be copied in memory. They can be nested complexity. This shortcut is acceptable because data access is read- lverStream and iterate over their bodies. Using multiple levels of BodyTags com- only and there’s little processing logic. This approach isn’t suitable for lverStream bined with iteration will likely slow down the processing of the page applications that require complex processing or write to the database. lverStream significantly. Infrequently Changing Shared Data lverStream EJB Performance Hints On the other end of the application spectrum are applications that lverStream Conversational session beans that write to the database should be share a small subset of infrequently changing data. A typical example lverStream designed to prevent conflicts when doing the update. The simplest of such application functionality is a list of top stories or most popular lverStream way of achieving transactionality in this case is to lock the whole table, items on a shopping site. Stateless session EJBs can be used to effi- lverStream or just the rows that are being updated. However, this approach incurs ciently cache and manage such data. lverStream high overhead and greatly reduces the scalability of EJBs written this lverStream way. Instead, optimistic concurrency control may be used, so there ood coding practices and efficient would be no need to lock the data that’s being updated. Instead, all the lverStream updates to the database receive an additional WHERE clause contain- J2EE components are only a part lverStream ing the old values of all columns in the row being updated. In case of lverStream contention, the first writer succeeds while everyone else fails, because “G of writing high performance J2EE lverStream the WHERE clause doesn’t match after the first update. The result is applications. Architecture has a critical lverStream the same as when strict locking is used. However, optimistic locking lverStream involves smaller overhead and allows multiple updates to proceed in effect on application performance” parallel, thus increasing the scalability of the system. Note that, as lverStream with most database operations, the benefits of optimistic locking lverStream degrade when there are many collisions and the application spends a There are three types of objects involved in this scenario: stateless lverStream lot of time dealing with failed updates. session EJBs that access and store the data; clients, for example, JSPs lverStream Entity EJBs may form a “graph” of related beans. Not all parts of that use this data; and a special remote Cursor class that’s owned by lverStream such an object graph may be needed by an application at all times. To the client and used to keep track of which rows were read by that lverStream reduce the overhead of loading such object graphs, a technique of client. To cache the data, the session EJB in its ejbCreate() method per- “lazy-loading” dependent EJBs can be used. forms a SQL query, reads in the result, and stores the individual rows lverStream For example, suppose we have an insurance policy bean that refers as elements in a ListArray. To read a row of data, clients execute a busi- lverStream to holder and vehicle beans, and we’re interested only in the identifi- ness method, readNextRow(), on that session EJB. However, different lverStream cation of the vehicle in that policy, not the identity of the policyhold- clients need to access different rows stored by that session bean. To do lverStream er. In this case, loading the holder bean at the same time the policy that, clients pass in a special cursor object that holds the number of lverStream bean is loaded would be wasteful. Instead, we load the dependent the last row read by that client. The session bean uses that number to lverStream beans only when they’re actually needed (see Listing 1). find the next row to give to the client. It then increments the row lverStream Some application servers use optimistic locking and lazy loading inter- counter inside the cursor before returning the row (see Listing 2). A nally in their container-managed persistence (CMP) implementations. more efficient implementation results if the client manages the row lverStream number inside the cursor. lverStream J2EE Application Performance To prevent the data from going stale, readNextRow() must imple- lverStream Good coding practices and efficient J2EE components are only a ment a refresh mechanism. In the above example, the data is refreshed lverStream part of writing high-performance J2EE applications. Architecture has after it’s been accessed a certain number of times. Alternatively, data lverStream a critical effect on application performance. Here are some examples. can be refreshed after it’s been cached for a certain duration. lverStream Read-Only Web Applications Minimizing the Number of Network Round-Trips for J2EE Clients lverStream Many real-world J2EE applications such as on-line reservation sys- J2EE client applications may call EJBs directly. Each call involves a lverStream tems and catalogs provide read-only access to a large set of data. These JNDI look-up and a network round-trip, both of which can be expen- lverStream applications handle a large number of queries from different users; sive. When a J2EE client contains all the processing logic, it has to per- lverStream some of the query results are large, but all are short-lived. Using entity form multiple JNDI look-ups and network round-trips to access the lverStream EJBs is overkill for this type of application, as they individually read data presented by entity EJBs on the server. This overhead can be lverStream each row of data and the server expects to keep that data in memory for reduced to a single look-up and round-trip if the processing logic is a while. Instead, this type of read-only Web application lends itself well encapsulated in a single session bean. That bean, in turn, encapsu- lverStream to the following optimization. Embed SQL statements that access the lates all the entity beans that would otherwise be accessed directly by lverStream data in JavaBeans. Use these beans directly from JSPs to fetch the data. the J2EE client. In this case, a J2EE client acts as a rendering engine for lverStream Going from JSPs to the database without involving the EJB layer the results contained in a single object returned by the session bean. lverStream significantly speeds up the application. It also reduces the overall lverStream Deployment Strategies lverStream Application design and coding techniques determine the perform- lverStream ance of the resulting systems. The way in which an application is onse deployed has an effect as well. lverStream p Too many resources, mgmt • Minimize interprocess communication: If possible, run the Web lverStream overhead server and the application server in the same process. Separating sec/res lverStream y the two can significantly increase the response time of your appli- lverStream atenc Well-tuned cation. L system lverStream Insufficient • Use clustering to increase scalability: As long as your application lverStream resources, doesn’t require the servers in your cluster to communicate with contention each other, adding more servers keeps latency low while increasing lverStream Resources throughput. lverStream • Provide at least the minimal set of resources needed to run an lverStream FIGURE 3 Latency as a function of server resources under constant load application. This includes setting a sufficient size for the JVM’s lverStream lverStream 54 APRIL 2001 lverStream lSt Java COM lverStreamlverStream lverStreamlverStream lverStreamlverStream lverStreamlverStream heap, providing a reasonable number of database connections, Listing 1: Lazy-loading dependent entity EJBs lverStreamlverStream and setting a reasonable size for thread, servlet, and bean pools. public class PolicyBean implements javax.ejb.EntityBean { lverStreamlverStream Failure to provide enough resources results in contention and public Vehicle vehicle; // data we re interested in public Holder holder; lverStreamlverStream severely degrades application performance. However, unreason- ably high resource settings will degrade performance as well. For lverStreamlverStream public void ejbLoad() {} // Load nothing by default example, if the heap size is greater than the physical memory lverStreamlverStream available, the JVM will thrash instead of doing useful work. public String getVehicleId() { lverStreamlverStream Similarly, if the size of the database connection pool is greater loadVehicle(); // insure that dependent beans are loaded return vehicle.getVIN(); lverStreamlverStream than the number of connections allowed, the application will } lverStreamlverStream spend a lot of time dealing with what it perceives as database fail- ures (see Figure 3). private void loadVehicle() { // do this in-line for better per- lverStreamlverStream formance lverStreamlverStream Summary if (vehicle != null) { lverStreamlverStream // get initCtxt here J2EE applications, like any application, should be architected for home = (VehicleHome) initCtxt.lookup("VehicleHome"); lverStreamlverStream performance and scalability. J2EE application designers can take vehicle = home.findByPolicy (policyID); } lverStreamlverStream advantage of the following common principles. } lverStreamlverStream • Entity beans are too heavy to use with read-only data, use JDBC } lverStreamlverStream instead. lverStreamlverStream • Stateless session EJBs can be used to efficiently represent infre- Listing 2: Using a stateless session EJB to cache shared data quently changing shared data. lverStreamlverStream public class SharedData implements SessionBean { • Minimize the network overhead for J2EE clients by locating the pro- private ListArray m_data; // cached data lverStreamlverStream cessing logic in a session bean on the server. private int m_accessCnt; // access counter public void ejbCreate() { lverStreamlverStream reloadData(); // get data for the first time lverStreamlverStream In building individual J2EE components, the following rules apply. } For servlets: private void reloadData() { lverStreamlverStream // do sql query, store result in m_data lverStreamlverStream • Avoid using a SingleThreadModel interface } • Use print OutputStream instead of PrintWriter to output bi- public String[] readNextRow (Cursor curs) { lverStreamlverStream nary/ASCII data if (m_accessCnt++ > 1000) { // refresh? lverStreamlverStream m_accessCnt = 0; • Don’t use a getRemoteHost() method on a ServletRequest reloadData(); // re-get the data lverStreamlverStream } lverStreamlverStream For JSPs: int i = curs.incRow(); // update row • Be careful when using nested BodyTags return (String[]) m_data.elementAt(i); lverStreamlverStream } lverStreamlverStream } lverStreamlverStream For EJBs: • Use optimistic locking to improve performance when doing data- lverStreamlverStream base updates lverStreamlverStream • Use lazy-loading to efficiently handle dependent beans lverStreamlverStream lverStreamlverStream Because J2EE applications are Java programs that use databases, lverStreamlverStream common programming principles are applicable to J2EE apps as well. lverStreamlverStream Specifically, for JDBC access: • Avoid n-way joins lverStreamlverStream • Avoid bringing back thousands of rows of data lverStreamlverStream • Cache data when reuse is likely lverStreamlverStream lverStreamlverStream For Java programming: lverStreamlverStream • Avoid unnecessary object creation lverStreamlverStream • Minimize the use of synchronization lverStreamlverStream Finally, when deploying J2EE applications, provide them with suf- lverStreamlverStream ficient resources and use clustering to achieve higher scalability. lverStreamlverStream lverStreamlverStream References lverStreamlverStream 1. J2EE Blueprints: http://java.sun.com/j2ee/blueprints/ lverStreamlverStream 2. Larman, C., and Guthrie, R. (2000). Java 2 Performance and Idiom lverStreamlverStream Guide. Prentice Hall. 3. Professional Java Server Programming J2EE Edition. (2000). Wrox lverStreamlverStream Press. lverStreamlverStream 4. Roman, E. (1999). Mastering Enterprise JavaBeans and the Java 2 lverStreamlverStream Platform, Enterprise Edition. Wiley. lverStreamlverStream 5. Halter, S., and Halter, S.M. (2001). Enterprise Java Performance. lverStreamlverStream Prentice Hall. lverStreamlverStream AUTHOR BIO lverStreamlverStream Misha Davidson is a product manager for SilverStream Software, Inc. lverStreamlverStream lverStreamlverStream [email protected] lverStreamlverStream lverStreamlverStream 56 APRIL 2001 lverStreamlverStream lStlSt Java COM ENTERPRISE JAVA Fitting the Pieces into the Enterprise Java Jigsaw Providing an access control infrastructure for intranet applications Part 1 of 3 The choices can be overwhelming for a development team embarking on an Enterprise Java project.You’ve read the books, attended the classes, and now know the individual Java technolo- gies pretty well, but how do you choose between them? Should WRITTEN BY your project be based on servlets, applets, EJBs, any two, or all TONY LOTON three? In this series I try to show how each servlet session tracking. By the end of server provokes the user’s browser into technology can be used as part of an this article, the security framework for displaying an authentication dialog box enterprise application to fit the pieces my application will be in place and I’ll (see Figure 1). The target page will be into the Enterprise Java jigsaw. For a have covered some simple JDBC along displayed or the servlet executed only if practical perspective, I’ll present an the way. the user supplies a valid username as example that starts with a single Java The access control solution that I the password. This is completely auto- servlet and finishes with a small working offer is intended for use with in-house matic; all you need to do is provide the application that’s composed of applets, intranet applications with security server with a list of valid usernames and servlets, EJB, and JDBC, and has a basic requirements that are limited to authen- passwords. access control mechanism. My inten- tication (asking a user to log in) and Some servers allow you to use the tion is not to provide a comprehensive authorization (propagating the user’s same method but vary the way the tutorial on any individual technology, identity so application components can authentication is actually done, maybe but to give just enough information to allow or deny their functionality to the via an HTML form or using certificates. demonstrate some of the possible com- user). If you’re developing Internet Bear that in mind when you build a real binations. applications that handle sensitive data, system; however, for my example I’ll stick The emphasis will be placed firmly such as credit card numbers, you’ll also with the basic HTTP authentication. on the three major architectures – need to think about encryption. For authentication I’ll use a servlet as applet, servlet, and EJB – that provide Getting a user to log in by supplying the protected resource and call it three alternative styles for enterprise a username and password is quite LoginServlet. When the user tries to run application development. I’ll mention straightforward with HTTP authentica- the LoginServlet via its URL, he or she some of the other J2EE technologies – tion. Every application server that I’ve will be prompted to authenticate. If such as XML and JSP – in passing, but authentication succeeds, the servlet will not in detail. be executed. Listing 1 shows an extract The code listings highlight the of the code for the LoginServlet, which important techniques, and some rou- possesses no code for authentication tine statements were removed for clari- since this is handled automatically by ty. Although you can’t necessarily run the application server and Web browser. these code snippets as presented, rest First I get the remote user name from assured they’re all based on applications the HttpRequest. If the user hasn’t that are known to work. authenticated because a valid username FIGURE 1 HTTP authentication dialog box and password were not supplied, or HTTP Authentication and a Login Servlet because I forgot to protect the servlet In this article I start with a single used allows you to flag the URL path to URL in the first place, the get- servlet and use this as the basis for a any resource as being protected. When a RemoteUser() method returns null. This simple but effective access control sys- user tries to access the HTML page or means that authorization (propagating tem based on HTTP authorization and servlet that the URL represents, the the user identity to allow or deny certain 60 APRIL 2001 Java COM ENTERPRISE JAVA applets as long as you invoke each applet via a corresponding servlet rather Possibly,“ it represents the simplest approach to than from a static HTML page. Each applet should have a servlet that creates the HTML containing the 62 APRIL 2001 Java COM ENTERPRISE JAVA On the presentation side, at this and WebLogic Server, and something irrespective of the URL context in AUTHOR BIO point I’ll add an initial HTML page that similar in the distant past with Oracle WebLogic, the J2EE demands that all Tony Loton works through has a frame for the login page (and Application Server and Java Web servlets sharing the same HttpSession his company – options menu) and a separate frame for Server. Possibly, it represents the sim- must be deployed in the same Web LOTONtec Limited the initial splash screen and subsequent plest approach to providing an access archive (WAR) file, and hence share the (www.lotontech.com) – as content. control infrastructure for intranet same URL context. an independent Figure 2 demonstrates that when applications, taking advantage of the Finally, with the basic security mech- consultant, course “bill” logs in, he sees two authorized mechanisms already provided by the anism in place and a promise that it can instructor, and technical options – getTasks and transferTasks. application server and adding just one be used with applets as well as servlets, author. He’s spent the The underlying database table con- additional component, the Login- tune in next time to find out how to past 10 years in IT, the tains the data shown in Table 1, so when Servlet. incorporate one or more applets into last five devoted almost another user, “ben,” logs in he sees only Every one of the application servers the architecture and set up a communi- exclusively to Java, UML, the getTasks option. Take my word for it. I’ve mentioned supports HTTP authen- cation channel between the servlets and and related technologies. tication and session tracking via cook- the applets that comprise the enhanced He holds a Conclusion ies. One difference you might need to be application. degree in computer I’ve implemented these ideas with aware of, however, is that while session science and management. the J2EE Reference Implementation tracking across servlets seems to work [email protected] { Listing 1 // -- find out who the remote user is -- public class LoginServlet extends HttpServlet String user=req.getRemoteUser(); { public void doGet(HttpServletRequest req // -- get the current http session -- , HttpServletResponse res) throws IOException HttpSession session=req.getSession(true); { // -- find out who the remote user is -- res.setContentType("text/html"); String user=req.getRemoteUser(); PrintWriter out = res.getWriter(); // -- get the current http session -- if (user==null) HttpSession session=req.getSession(true); { // -- print the unauthorized message here -- res.setContentType("text/html"); } PrintWriter out = res.getWriter(); else { if (user==null) // -- save the user name for future servlets -- { session.setAttribute("user", user); // -- authentication failed, show error -- } out.println(""); else out.println("
// -- respond with HTML including -- try // -- this link to an application -- { out.println("Click here to run an applica- // -- get DB connection from a datasource -- tion."); InitialContext ic = new InitialContext(); } } DataSource ds = (DataSource) } ic.lookup("java:comp/env/jdbc/LOTONtech");
Connection con = ds.getConnection(); Listing 2 public class AppServlet extends HttpServlet // -- select user s menu options -- { Statement st=con.createStatement(); public void doGet(HttpServletRequest req , HttpServletResponse res) throws IOException ResultSet results=st.executeQuery { ("SELECT username, useroption // -- get the current http session — FROM useroptions WHERE username=’"+user+"’"); HttpSession session=req.getSession(true); while (results.next()) res.setContentType("text/html"); { PrintWriter out = res.getWriter(); String useroption=results.getString(2); options.addElement(useroption); // -- get the current user -- } String user=(String) } session.getAttribute("user"); catch (Exception e) { if (user==null) out.println("ERROR: Connecting to database!"); { } // -- not authenticated, show message -- } //-- write the options out as html -- else if (user.equals("bill")) out.println("Welcome "+user+", choose an option:");
{ for (int opNum=0; opNum
out.println(""); Listing 3 out.println(""); public void doGet(HttpServletRequest req } , HttpServletResponse res) throws IOException
64 APRIL 2001
Java COM The Java 2 Platform, Enterprise Edition (J2EE), defines the This enabled ubiquitous access to computing resources. A standard for developing and deploying multitier enterprise shift toward server-centric IT development took shape to applications. At the core of J2EE architecture are applica- leverage these resources efficiently, and resulted in Web tion servers – containers for your J2EE components. servers that could run various kinds of applications.This This article explains the architecture of an application gave birth to the application server. server that embraces standards such as J2EE, and focus- Later, application servers provided proprietary inter- es on ways to leverage the application server platform for faces such as NSAPI and ISAPI that enabled developers to caching, load balancing, scalability, and clustering servic- access a server’s internal services. However, these tech- es. It also provides an understanding of how to build J2EE niques were not standard across application servers, lim- applications, by looking at both design and runtime sce- iting flexibility and deployment choices. Developers facing narios. It concludes with some best practices for design- these challenges embraced standards such as J2EE that ing and implementing enterprise applications. enabled them to focus on business logic, and not the underlying plumbing and proprietary interfaces. This cre- The Metamorphosis:From Web Servers to Application Servers ated a drive for the next-generation application server that During the early ’90s, the advent of the Internet gave supported standards such as J2EE for building e-business birth to myriad programming models like CGI and FastCGI. applications.
66 APRIL 2001
Java COM ORACLE ORACLE ORACLE ORACLE Application Server Architectures Scalable Execution Environment for Java Programs ORACLE Few companies have been able to create an application server that A JVM is an abstract machine that runs compiled Java programs. ORACLE addresses the different functionalities necessary in a multitiered archi- Every application server vendor that supports J2EE has to provide a ORACLE tecture in a cohesive way. In general, application servers should provide: concrete implementation that conforms to the JVM specification. • Programming standards and models such as J2EE A platform is scalable if it provides consistent performance regard- ORACLE • Access to all tiers less of the number of concurrent users. As the load on standard VMs ORACLE • Application partitioning increases, congestion of requests can take place. As a result, more ORACLE • Messaging, transactional, and distributed services VMs have to be started to handle the increasing number of user ORACLE • Manageability requests. A few of these VMs can become overloaded and server ORACLE response can start to fail. Oracle Enterprise Java Engine (EJE) address- ORACLE Additionally, application servers are required to provide support es this problem with a session-oriented VM that reduces the response for multiple platforms, including Linux, Solaris, and Windows NT. time by making sure each session has its own virtual Java VM, Java ORACLE This article uses Oracle9i Application Server (Oracle9iAS) (see global variables, threads, and garbage collector. The underlying run- ORACLE Figure 1) to describe the basic building blocks of an application serv- time provides the needed scalability and threading, enabling the VM ORACLE er including: to efficiently perform memory management utilizing a low session ORACLE • Mechanism to handle HTTP requests footprint. ORACLE • Scalable execution environment for Java programs Oracle9iAS includes a scalable EJE to provide an execution envi- ORACLE • Containers for J2EE components ronment for Java components. It supports use of the standard JDK ORACLE • Performance optimizations, such as caching, load balancing, fault JVM for lightweight components and the Oracle EJE for heavy-duty tolerance, and clustering applications. The Oracle EJE is the same engine featured in the data- ORACLE base and has been proven for concurrency (see “Enterprise Java: ORACLE Mere support of J2EE alone is not sufficient. Advanced features Oracle8iJVM,” JDJ, Vol. 5, issue 10). ORACLE such as wireless integration, portals, business intelligence, Web ser- ORACLE vices, collaboration, and process integration can make it easier for Containers for Various J2EE Components ORACLE developers to create e-business applications. We’ll describe these con- The J2EE runtime environment is composed of containers and ORACLE cepts using Oracle9iAS in an upcoming issue of JDJ. components. A container acts as a vessel to hold the component, and provides a J2SE runtime environment and implementation of J2EE APIs ORACLE Mechanism to Handle HTTP Requests for services like transactions, messaging, and distributed protocols. In ORACLE Oracle HTTP Server is powered by Apache, a popular Web server. addition, application servers come with a number of tools to create, ORACLE The HTTP server not only serves files, but also provides functionality assemble, deploy, and manage applications to support J2EE roles. ORACLE to execute programs to generate dynamic content. To facilitate e- Containers play a critical role in hosting J2EE components by ORACLE business, HTTP engines support the HTTPS protocol, thereby provid- shielding users from the complexities of the middle tier. Containers ORACLE ing a safe and secure transport. In choosing an HTTP server, one must take away the necessity of writing plumbing code and allow developers ORACLE pay attention to its ability to handle high loads. to focus on business logic, delegating the container to handle transac- Oracle9iAS builds on Apache’s extensible architecture by adding tion management, scalability, persistence, and security services. ORACLE modules to extend the core functionality. The modules abstract the Oracle9iAS has a complete implementation of J2EE containers for ORACLE server’s operations to improve performance. Oracle HTTP Server enterprise APIs, including Servlet, EJB, JSP, XML, JMS, and JNDI. The ORACLE comes with additional modules including mod_ssl, mod_perl, Oracle EJE programming environment supports SQL data access ORACLE mod_ose (OracleServlet engine), and mod_plsql. Oracle9iAS has SSL through JDBC and SQLJ, distributed applications through EJB, and ORACLE support for both 40-bit and 128-bit encryption. Oracle provides cus- dynamic Web site development using JavaServer Pages and servlets. tomer support for all Apache modules shipped with Oracle9iAS. ORACLE Performance Optimizations ORACLE Performance of an application ORACLE server hinges on caching, load bal- ORACLE Oracle Servlet ancing, fault tolerance, and clus- Engine IAS ORACLE m tering. odul ORACLE HTTTPTT es Caching ORACLE (Apaache) DATABASE One of the notable properties of ORACLE OracleJSPJ Dispatchers the Internet is that, at times, an ORACLE Listener HTML page can get popular quick- 12 CACHE ORACLE IIOP (IIOP redirect) ly, creating a hot spot on your Web requests 9 3 CLUSTER ORACLE site. These hot spots are dynamic Load Database balancer 6 in nature and keep moving around ORACLE Cache ORACLE JNDI with time. A key performance measure for the Web is the speed ORACLE HTTP Cache requests EJBContainer management with which content is served to ORACLE engine EJBHomemem users. As traffic on the Web increas- ORACLE EJB Interfafacec EJBHome es, users are faced with increasing ORACLE delays and failures in data delivery. Remotee ORACLE Object Oracle Anyy Caching is one of the key strategies Interfafaceac EJB Enterprise ORACLE Cache pages Java Engine JDBC to improve performance. Solutions should include a Web ORACLE Web Cache compliant Portable Wireless Forms Reports Business Imtelligence Unified Messaging, data store cache to improve application ser- ORACLE Notifications, Workflow, and Applications Interconnect ver performance and a database ORACLE cache to improve the data access ORACLE FIGURE 1 Oracle9i Application Server architecture performance. Both technologies ORACLE ORACLE 68 APRIL 2001 ORACLE
ORAC E Java COM ORACLE ORACLE ORACLE ORACLE are necessary and work to complement each other. Oracle9iAS has mines how frequently the origin database is replicated to all mid- ORACLE both Web cache and database cache technologies. dle-tier caches. The database cache stores tables, packages, proce- ORACLE dures, and functions. Cache management is highly configurable ORACLE Improving Application Server Performance Using Web Cache and hit/miss statistics are available through the Oracle Enterprise An important issue in many caching systems is how to cache fre- Manager console. ORACLE quently changing data and provide fast response to users. The Oracle9iAS Database Cache is both an in-memory and disk- ORACLE Oracle9iAS Web Cache solution includes: backed cache. This combination doesn’t limit the cache size of the ORACLE • Dynamic content caching and content invalidation: A popular memory footprints and also means that the cache is not “cold” imme- ORACLE myth is that dynamic data is uncachable. However, Oracle9iAS Web diately after a machine reboot. ORACLE Cache allows cachability rules for both static and dynamic content ORACLE created by J2EE components. Cache invalidation can be time- based, or triggered by sending XML messages in an HTTP post Advanced features such as ORACLE request. For example, if a column in a table is updated, a database ORACLE trigger can send an invalidation request to the cache. “wireless integration, ORACLE • Personalization of cached data: To provide personalization fea- portals, ORACLE tures, Oracle9iAS Web Cache embeds session IDs in every URL to business intelligence, ORACLE make them unique for each user. Using these IDs and a substitution ORACLE mechanism, the Web cache can insert personalized information Web services, ORACLE into cached objects. For example, a Welcome page with the greeting collaboration, “Hello Sudhakar” is generated by a JSP. When the page is served ORACLE through Web cache, it parses out the parameter and caches a “tem- and process integration ORACLE plate.” When the next site is accessed, the parameter is substituted can make it easier for developers to create ORACLE into the template and served by Web cache. The second request e-business applications ORACLE won’t even hit the application server. ORACLE • Server acceleration: In this technique, cache servers are placed in Load Balancing, Fault Tolerance, and Clustering ” ORACLE front of a cluster of Web servers to intercept all HTTP requests. The Load balancing deals with response times and the act of distribut- cache stores objects returned by an origin server, handles thou- ing connection loads across multiple servers. Fault tolerance ensures ORACLE sands of concurrent users, and frees processing resources on the no single point of failure. Clustering involves grouping together inde- ORACLE origin server. pendent nodes to work together as a single system, and architecting ORACLE • Quality of service: To prevent an overload on origin servers, caching for high availability and scalability. Clustering is used to load balance ORACLE systems assure performance by setting a limit on the number of and provide fault tolerance. ORACLE concurrent connections that servers can handle. Oracle9iAS Web Oracle supports many ways of load balancing: ORACLE Cache helps distribute the load to origin Web servers using a • Round-robin DNS for distributing HTTP requests across the clus- ORACLE heuristic algorithm and request queues. ter: This simple mechanism works well for Web traffic in which multiple IP addresses are assigned the same name in the DNS name ORACLE Improving Database Tier Performance Using Database Cache space. Requests are alternated between the hosts that are present- ORACLE Many applications rely on EJB components for heavy-duty trans- ed in rotational order. ORACLE action operations. Acquiring JDBC connections is usually the slowest • Use of hardware load-balancing devices and IP sprayers: To ORACLE part of the process. To circumvent this problem, most EJB servers per- address the scalability problem, a router or “IP-Sprayer” is placed ORACLE form connection pooling and caching through JNDI and data sources. between the clients and a cluster of application servers to spread JDBC drivers that support connection pooling are useful, but this the load evenly over the nodes. ORACLE alone is not enough for better performance. • Spawning a number of HTTP processes to handle load: This ORACLE Minimizing the number of round-trips between the middle tier increases the ability of the server to handle thousands of client ORACLE and data tier can influence the response time. The relative percentage requests. Load balancing is used to distribute the load among the ORACLE of read-only data in the middle-tier application can have an effect on running instances. ORACLE the number of round-trips your application has to perform. Database • Using Oracle HTTP Servers in reverse proxy mode: Oracle HTTP ORACLE caches are effective in multitier environments where databases are Server can be used in front of origin servers simply configured as a ORACLE located on separate nodes. These caches reduce the load on the data- reverse proxy (i.e., proxy for content servers). This mechanism base tier by processing the most common read-only requests to data relieves the origin server load by taking advantage of the caching ORACLE sets on the application server tier. features of the proxy server. ORACLE A database cache should be an operational aspect of the Web ORACLE site and transparent to the application developer. Oracle9iAS Routing Requests to Improve Response Times ORACLE Database Cache keeps track of queries and can intelligently route to In addition, Oracle9iAS offers techniques to improve the perfor- ORACLE the database cache or to the origin database without any applica- mance of servlets, EJBs, and J2EE components delivering dynamic ORACLE tion code modification. A flexible synchronization policy deter- content. J2EE components rely on “HTTP” for communication ORACLE APPLICATION REQUIREMENTS IMPLEMENTATION REQUIREMENTS ORACLE Access from different browsers/devices Presentation tier: Components to render the application for different browsers/devices ORACLE An interactive experience to create an itinerary Application tier: Session management components to dispatch user’s requests and control flow through the application ORACLE Validation to create a “valid” itinerary Business tier: Business logic validation based on ticketing rules, user’s profile, etc. ORACLE Manage user profiles Data tier: Components to query and store persistent business objects ORACLE Make secure purchases/refunds Security and transaction management services Interact with other itinerary services Messaging and transaction services that span the business and data tiers ORACLE (e.g., hotel and rental car reservations) ORACLE Fault tolerant, minimize downtime No single point of failure ORACLE ORACLE TABLE 1 Logical partitioning of components ORACLE ORACLE 70 APRIL 2001 ORACLE
ORAC E Java COM ORACLE ORACLE ORACLE ORACLE between Web clients and servers, and “RMI/IIOP” for communication because of the listener’s ability to inspect IIOP headers for session IDs ORACLE between objects requesting service from each other in a distributed and redirect them to the appropriate node. Incoming IIOP connec- ORACLE computing environment. tions are redirected to dispatchers on the node with least load. The ORACLE When an HTTP request arrives, the load-balancing device redis- load is computed based on a number of parameters including CPU tributes the load over Web caches that sit in front of the application utilization and number of sessions in progress. With load balancing ORACLE server farm. Oracle9iAS Web Cache distributes HTTP requests you can split the load across multiple servers. The Listener process ORACLE according to the relative capacity of each application server, which within Oracle9iAS performs load balancing by distributing EJB lookup ORACLE is configurable. If one of the application servers in the farm were to across multiple application servers. Services that are located in a ORACLE fail, Web cache automatically redistributes the load among the number of places can be grouped together by specifying a service ORACLE remaining servers. Oracle9iAS Web Cache reduces application ser- name in the URL. Listener handles HTTP connections by transferring ORACLE ver load not only on Oracle9iAS, but on other application servers such requests to configured dispatchers on a node. too. ORACLE ORACLE Balancing the Load of Servlet Processes Ideally, a developer balances the trade-off between ORACLE Oracle HTTP Server load-balances servlet processes that use the “ ORACLE Apache JServ servlet engine. Several JServ processes can serve single ORACLE or multiple instances of Oracle HTTP Server using a weighted load- data transfer/network ORACLE balancing algorithm that can be configured, depending on the load- ORACLE handling capability of the target machines. overheads and fault ORACLE Providing Fault Tolerance Using Listeners ORACLE Oracle9iAS listener/dispatcher architecture provides a fault-tol- tolerance/scalability ORACLE erant, resilient environment without a single point of failure. With ORACLE this architecture, each physical machine has a listener on a desig- ORACLE nated port and a number of dispatchers to service J2EE container requirements ORACLE requests. The bridge in this paradigm is that each dispatcher regis- ters itself with any number of nodes in the application server farm. ORACLE by distributing the components accordingly Thus, if a particular node is no longer able to service requests, the ORACLE listener will send incoming requests to another dispatcher on ” ORACLE another node. It’s important that an application server redirect both A Glimpse into J2EE Best Practices ORACLE HTTP and IIOP requests intelligently for the purpose of load balanc- This section covers some of the best practices to keep in mind ORACLE ing. Redirection is essential to load balance at a protocol level; how- when writing J2EE applications. Using a flight reservations system ORACLE ever, there’s no concept of “redirection” in HTTP – but there is one deployed on an application server, several issues central to J2EE ORACLE for IIOP. Oracle leverages its listener/dispatcher architecture with application development are addressed. The goal is to present a Apache modules to provide HTTP redirection. For example, design based on the J2EE blueprint (http://Java.sun.com/ ORACLE mod_ose load balances servlet requests across nodes by redirecting j2ee/blueprints/) and to demonstrate the simplicity with which you ORACLE HTTP requests. can leverage the underlying application server for infrastructure ORACLE Oracle9iAS provides mechanisms to load balance incoming services. ORACLE requests be they in IIOP or other network formats in multithreaded ORACLE server mode. This has great benefits to enterprise components resid- Design Architecture ing on multiple nodes. The listener process has the ability to load bal- To meet these requirements, the application should be carefully ORACLE ance across these nodes using IIOP redirection. This is possible designed using interfaces and design patterns (for example, Model- ORACLE View-Controller, façade, proxy). It should be ORACLE logically partitioned as components in dif- ORACLE Oracle9ii Application Server ferent tiers (see Table 1). ORACLE Cache Invalidation Message Figure 2 depicts the components for the ORACLE end-to-end design of this J2EE application.
ORACLE Orac
Transparently Presentation Tier J From Cac ORACLE XML Asynchronous Reso Queries SP Refresh XML is used as a standard for informa- l
ORACLE e Contro l
9 tion exchange. For example, given the XML
ve Oracle9i
s DatabaseDatabas ORACLE i d AS Web Cache A App he content for the “Pick a Flight” screen, it can
Content Cache Wire
ORACLE ll be transformed (using XSLT) into HTML for l icatio
HTTPTP er Serv Query/Insert/ l a Web browser or WML for a WAP device.
ORACLE es HTML Update/Delete / s
n For Web users, JSPs are ideal to render ORACLE Messagin l e this content as a rich HTML presentation. t ORACLE Dev. K Porta PSI Compliant Oracle9iAS includes an XML Development ORACLE Session Entity Any
g DataData SSourceource Kit (XDK) with a DOM/SAX parser, XSLT l
it Bean Bean ORACLE Persistence Manager processor, Oracle XML Schema Processor, ORACLE and other utilities. Oracle9iAS also includes XML/JMS Message Components C Presentat Components C C
ORACLE App a wireless and portal framework to seam- omponent omponent Bus
ORACLE D lessly transform content to be part of a por- l at icatio i
nes Disparate
a tal or rendered for any number of wireless ORACLE System i s Browsers o devices (Palm, WAP, Rim). Thus, the “Pick a n n s ORACLE s & Devices Flight” screen is generated once, but is ORACLE available through a Web interface, user-cus- ORACLE FIGURE 2 Flight reservations application design tomizable portal, and wireless devices. ORACLE ORACLE 72 APRIL 2001 ORACLE
ORAC E Java COM ORACLE ORACLE ORACLE ORACLE Application Tier Data Tier ORACLE Regardless of which browser/devices are used to access the appli- The persistent objects underlying Flight Reservations (e.g., ORACLE cation, requests from concurrent users should be coordinated and PassengerManager and FlightsController) are entity beans. These ORACLE tracked by the application tier. This tier manages the state of each user objects are stored as rows in database tables, but leverage the con- in the system and logically guides them through the process of build- tainer to look up, store, and manage a read-consistent cache of this ORACLE ing their itineraries. For example, this tier will know that after a user persistent data in the middle tier. ORACLE has selected an itinerary, he or she should be offered “discount Most J2EE implementations would use a database cache in the ORACLE rentals,” before being taken to the “checkout” screen. middle tier to minimize the overhead of fetching data from the data- ORACLE Servlets are suited to dispatch browser requests and perform con- base tier. For example information about Daily Flight Specials, Airport ORACLE troller functions (MVC pattern). In its post() method, the servlet Locations, and City Tour Spots (i.e., relatively static data) should be ORACLE should accept an XML message and evaluate the message in a Finite cached ideally in the middle tier to avoid frequent network round- State Machine (FSM). For example, when a customer accesses the trips. ORACLE site, the servlet receives an XML message and establishes an HTTP Entity bean containers typically support container-managed per- ORACLE session for this user. It then uses an FSM to handle the message, and sistence (CMP) for relational data sources. But what if some of the ORACLE responds with an XML document containing the list of flights for persistent data (e.g., Flights) comes from nonrelational data sources ORACLE those sectors. This is rendered as HTML and presented as a list of (e.g., a hierarchical database)? Oracle offers Persistence Service ORACLE flights from which the user selects a single entry. Interface (PSI), a Java API that allows CMP providers such as Oracle ORACLE Typical servlet engines use threads to isolate concurrent users. Business Components for Java to manage O/R mappings from entity ORACLE This becomes a bottleneck when there are a large number of users beans to database entities. Using such an interface makes it possible and a stateful application. A good design will limit session state to to map entity beans to any data source including other relational ORACLE only the essentials; however, even this can cause resource (thread) databases and even nonrelational databases. Thus these legacy ORACLE contention within the container. Oracle’s approach is to use a JVM sources can still benefit from the look-up, transaction, and caching ORACLE architecture that isolates concurrent users. The result is less con- simplicity provided by the container. ORACLE tention and a container that’s more resilient to application failures A common criticism against entity beans is the processing over- ORACLE within an individual session. head imposed by the container, especially for fine-granularity beans. ORACLE The Oracle9iAS container resides in the same shared memory and Business Tier address space as the middle-tier application cache. This minimizes ORACLE When creating the itinerary, the Application Tier will make calls the container-imposed and network overheads since the relevant per- ORACLE such as validateCustomer(Customer customer) and handleRes- sistent data can be cached in the middle tier using the Oracle9iAS ORACLE ervationEvent(ReservationEvent re) to the Business Tier to validate Database Cache. ORACLE the user’s entry. ORACLE These methods will evaluate against business rules stipulating Deployment and Runtime Architecture ORACLE what constitutes a valid reservation for a particular customer. When Figure 2 depicts all the components residing within a single ORACLE the itinerary is finished, a session bean will make the reservation via a instance of the application server. This is one possible deploy- method call such as createBooking(Itinerary itinerary). ment scenario, but is usually not the case in a production envi- ORACLE In certain business scenarios the session bean may interact with ronment, where it’s best to distribute the components across ORACLE remote systems through XML messages. Making a JMS call from a session many nodes to avoid scalability bottlenecks, and cater to fault tol- ORACLE bean frees the developer from worrying about the distributed transaction erance. ORACLE spanning these remote systems. The container will provide this service. Factors to consider when distributing components should be ORACLE Business processes today involve getting many types of informa- the proximity of components to the underlying data (i.e., avoid tion to multiple people according to constantly changing rules. The network round-trips) and how to distribute any resource bottle- ORACLE Oracle Workflow engine is integrated into Oracle9iAS to automate and necks (i.e., CPU, memory, I/O) across the different nodes. Ideally, a ORACLE route information according to business rules. Workflow supports developer would balance the trade-off between data transfer/net- ORACLE both synchronous and asynchronous processes. For example, when work overheads and fault tolerance/scalability requirements by ORACLE the booking has been completed, postnotification function executes distributing the components accordingly. For example, the servlet ORACLE to send an itinerary to the user. components may be CPU intensive, while the session bean and ORACLE entity bean may be typi- ORACLE cally memory and I/O intensive. Should these ORACLE Har A C components reside on
d E ORACLE Web ware Loa B DatabaseDatabas the same node or be dis- Cachee D ORACLE CacheCCa tributed across different ORACLE HTTP Entity ones? Since the balance is Bean d JSP Servlet Session sometimes hard to find,
ORACLE Ba Bean the application server l
ORACLE ancer an CClientClien must be flexible enough ORACLE Dispatcher Dispatcher Dispatcher Dispatcher to seamlessly distribute ORACLE Oracle9i components to different ORACLE d/ or We Session nodes as necessary. ORACLE Bean Figure 3 shows an HTTP Entity ORACLE b JSP extreme example of Cac Servlet Bean Web deploying each compo- ORACLE DatabaseDatabas he Cache nent on a separate tier to ORACLE F I Cache show the granularity to ORACLE Application Server Farm G H J which the application ORACLE server scales and provides ORACLE FIGURE 3 A potential Oracle9i AS deployment architecture fault tolerance. We’ve ORACLE ORACLE 74 APRIL 2001 ORACLE
ORAC E Java COM ORACLE ORACLE ORACLE deployed the components into five tiers, across 10 physical nodes in routed automatically to the servlet instance on Machine H (using ORACLE the application server farm: sess_iiop protocol). ORACLE • Two nodes for HTTP listeners The dispatcher architecture will similarly route this request to ORACLE • Two for JSP components Machine D for business processing and to Machine E to query data ORACLE • Two for servlet components from the entity beans. As the application queries persistent data (e.g., ORACLE • Two for session bean components through the FlightController entity beans), the Database Cache ORACLE • Two for entity bean components Management Engine intelligently resolves the query by fetching data sets from the cache. ORACLE In this example the dispatcher on Machine C will register itself Similarly, changes to the underlying persistent data in the data- ORACLE with the listeners on Machines B and G. The dispatcher on Machine I base tier (e.g., flight schedules) trigger an XML invalidation message ORACLE registers itself with the listeners on Machines C and H, and so on. An to the Oracle9iAS Web Cache so that a subsequent request goes to the ORACLE instance of the Web cache is placed in front of this “farm” to serve as origin server to avoid serving stale data. ORACLE a reverse-proxy, load balancer, and request router. Thus each tier can ORACLE tolerate a machine failure and continue to service incoming applica- Conclusion ORACLE tion requests. This article discussed the essential capabilities of application When a user accesses the flight reservations Web site, servers. To understand application design principles and ways in ORACLE http://flights.oracle.com/, to make a travel reservation, the request which J2EE applications can leverage the underlying application ORACLE first hits the Web cache listening on that host/port combination. If the server infrastructure, we walked you through a simple J2EE flight ORACLE request matches a recently cached item (based on predefined cacha- reservations system. Using Oracle9iAS as an example, you’ve seen ORACLE bility rules), it’s served directly from the Web cache and doesn’t even how to design, develop, assemble, and deploy J2EE enterprise appli- ORACLE hit any of the application server nodes. cations. ORACLE If it were a “new” request, then the Oracle9iAS Web Cache, based on its predefined load-balancing criteria, would hand the request to a UTHOR IOS ORACLE A B particular HTTP instance (i.e., Machine A or F). The HTTP Server then Christopher G. Chelliah is a principal solutions architect at Oracle Corporation. He has been a project ORACLE needs to invoke the JSP to render the user interface. Assuming the leader and active member on many projects involving distributed object-oriented systems based on a ORACLE request hits Machine A, the HTTP listener on that machine will try to CORBA/Java/EJB/Internet platform. ORACLE route it to any of the dispatchers serving JSPs (i.e., Machine B or ORACLE Machine G). If Machine B is not available, the request will be sent to Sudhakar Ramakrishnan is a principal member of the technical staff at Oracle Corporation. He is a ORACLE Machine G and vice versa. member of the Internet Platform group, and has more than six years of development experience in ORACLE The JSP then invokes the servlet to start the Flight Reservations areas of user interface, protocols, distributed computing, and component frameworks. application and keep track of the users’ itinerary (i.e., HTTP session) ORACLE as they build it. This request will be routed either to Machine C or H. [email protected] ORACLE Once the request has been routed to a Machine (say, H), and an HTTP ORACLE session is established, all future requests from the same client will be [email protected]
76 APRIL 2001
Java COM APP SERVERS 2001: The Year of Web Services History,trends,players,predictions...
The year 2000 saw J2EE compliancy move out of the realm of marketing and into nine shipping products. The threat of com- moditization of J2EE application servers forced vendors to switch WRITTEN BY gears in 2001 toward leveraging J2EE servers as platforms for Web FLOYD MARINESCU services, wireless, and EAI development.
The dominant players in the game petitive advantage as the J2EE specifica- so why would you pay extra for surfaced, but a variety of strategic tion provider, Sun was the first to ship a WebLogic when they can use jBoss? takeovers may reshape the J2EE app J2EE-compliant server with its IPlanet Scott Dietzen, CTO of BEA, believes server market in 2001. This article walks Application Server in June 2000. Other that “It is hard for a complex software you through the events, trends, and vendors engaged in an amusing battle of stack to commoditize.” Just because two players of last year and describes the press releases, during which they all servers implement the same specifica- changes in the application server mar- fought to be remembered as the first tions doesn’t mean that the two servers ket landscape today. independent company outside of Sun to will be considered identical. Dietsen pass the J2EE compliancy test suite. points to SQL servers as an example. 2000:Year of the J2EE-Compliant Arms Race The first such announcement came “SQL was a standard, but SQL servers For the app server market 2000 will from BEA on July 31, 2000. On Sep- did not become commodities.” The be remembered as the year of the J2EE- tember 8 ATG made a similar claim emergence of the SQL specification did compliant arms race. The first step regarding its own application server. On not allow cheap SQL databases to steal toward compliance was offering a com- October 19 Sybase announced it too had market share from the giants. Rather, it plete suite of J2EE products. The second: passed the tests, with Iona issuing a sim- was the underlying quality and stability these products had to pass Sun’s J2EE ilar press release on November 15. of implementation that won, resulting compliancy test suite, which consists of Silverstream followed on November 17, in Oracle’s becoming the leader in the about 5,000 tests designed to certify that Borland on December 15, and Bluestone database industry. the compliant application server can on December 19. run any J2EE application. 2001:The Year of Web Services,Wireless, Allaire, owner of the popular servlet Commoditization of the Servers:The Great Debate EAI,and Commerce Servers engine product JRun, purchased an EJB In August 2000 a new debate flared “The application server days are application server vendor and an- up on TheServerSide.com: How do you over. The future is integrated offerings. nounced the new complete JRun J2EE choose between vendors once all the J2EE compliancy will just be one of the server in June 2000. Oracle Corporation vendors are J2EE compliant? many check boxes on the list,” says Dave became a J2EE licensee at the end of Once a J2EE application has been Brown, technical director of GemStone May 2000 and announced full JSP, written, what would differentiate the Systems. servlet, and EJB support in July 2000. $1,500 Orion Application Server from In 2001 the focus of vendors is mov- Also in July Bluestone, a traditional the $30,000 Bluestone Total-e-Server? ing away from the J2EE server and into middleware powerhouse, announced The unpopular opinion was that, essen- complementary products that will be servlet and JSP support to complement tially, shopping for J2EE servers would built as J2EE applications, running on its popular Sapphire/Web EJB server become like buying apples from a gro- top of their existing J2EE servers. These with its new Total-E-Server product cery store. That is, small vendors who new applications will leverage built-in launch. Unify corporation began ship- couldn’t afford to produce the best qual- support for transaction handling and ping the full suite of J2EE products ity or who had small marketing budgets scalability provided by J2EE servers, around the same time. would disappear in a matter of time, providing a fully integrated platform for By the end of summer, vendors that leaving two or three industry giants as development. ColdFusion is one such hadn’t yet integrated complete J2EE the sole providers of J2EE servers. exciting example. Macromedia/Allaire offerings were not even on the radar of Another theory was that if J2EE plans to port the ColdFusion develop- most analysts and project managers, servers commoditize, open-source ment platform to a generic J2EE applica- and at this point catching up was very servers like jBoss or low-cost commer- tion that can run on top of any J2EE- difficult. cial application servers like Orion and compliant application server. The race was on. Now that J2EE ven- Unify eWave would be in a position to The trend toward supporting comple- dors had complete and integrated J2EE bring down companies like BEA. From a mentary offerings built on top of J2EE product offerings, the focus switched to purely J2EE API perspective, jBoss, began in 2000 with the emergence of the J2EE compliancy. Leveraging its com- Orion, and BEA WebLogic are identical, commerce server. Commerce servers,
78 APRIL 2001
Java COM APP SERVERS
such as those provided by BEA and that is, a requirement for enterprise- BEA a 56% market share, 33% for IBM, SilverStream, are out-of-the-box B2B and scale applications. Essentially, EAI prod- 3% for IPlanet, and 7% for all others B2C frameworks combined with simpli- ucts are message-oriented middleware combined. However, since the survey fied rules-based development environ- (MOM) products (IBM MQSeries, MS was Web-based and not controlled, ments targeted at business analysts and BizTalk) that tie together heterogeneous these figures are probably not reflective script-level programmers. These products systems within an enterprise by sup- of real market share. allow rapid visual development with a porting custom protocols and docu- All of the surveys are consistent in focus on personalization and customer ment exchange, often based on XML. placing BEA as the market leader in relationship management features (CRM). The final major trend to capitalize on 2000, followed by IBM. A clear third Given recent predictions that the for 2001 is the wireless explosion. Most place isn’t apparent at this time, but it’s B2B market could reach anywhere from vendors have added the word wireless to likely a close tie between Sybase, $1.5 trillion to $8 trillion in revenue by their Web sites, with WAP gateways and iPlanet, SilverStream, Iona, and HP/ 2004, B2B-enabling technologies such component frameworks for supporting Bluestone. as Web services and enterprise applica- wireless devices. tion integration (EAI) will be a key area Three Major J2EE Vendor Acquisitions Level for vendors to support. App Server Market Share at the End of 2000 the Playing Field for 2001 In a nutshell, Web services are a way With no one clear survey on applica- Three acquisitions that began in for businesses to expose their services tion server market share, it’s difficult to 2000 added three new giants to the J2EE programmatically over the Internet, lever- properly gauge the market share of J2EE arena: Brokat Infosystems/Gemstone, aging standards-based protocols and doc- application server vendors. In August HP/Bluestone, and Macromedia/Allaire. ument interchange formats to execute any 1999 the Giga Information Group pub- Brokat is a European software giant, kind of online transaction. Web services lished a report that predicted that BEA a powerhouse in the European financial, initiatives such as ebXML and UDDI are and IBM would share the market lead at integration, and wireless markets. Last currently the realm of early development, 24% market share each, with iPlanet July Brokat strategically expanded its but should serve as viable deployment third at 9%. offerings by acquiring Blaze Software, options by the end of this year. Vendors Recent vendor presentations, how- maker of rules engines for enterprise with investments in XML and Web-based ever, have pegged the market at applications, and GemStone Systems. protocols stand to ride that wave when it WebLogic 32%, WebSphere 16%, and The Gemstone/J application server mushrooms at year’s end. Sybase 15%. The most recent statistics product was bleeding market share loss. Unlike Web services, EAI is a funda- came from a Web-based survey run by However, the product itself stood in a mental complement to J2EE products, Giga in December 2000. The survey gave league of its own, recognized by many as one of the most advanced application servers available due to its powerful object database-based background and multi-VM clustering features. This year Brokat plans to focus on being the wire- less champion, utilizing its new software platform to build industry-specific wire- less applications, with an initial focus on software for Brokat’s strong financial services client base. Last October technology giant Hewlett-Packard entered the middle- ware market by acquiring Bluestone software, a longtime veteran in the application server market. HP and Bluestone were the ultimate marriage. HP brought trusted and established hardware and software deployment platforms combined with an extensive sales and marketing force, while Bluestone brought a mature and power- ful J2EE platform to the table. Le- veraging this new complete offering, HP announced the Net Action campaign (a competitor of similar offerings from Microsoft, Sun, and IBM) in February. Net Action is an integrated platform for enterprise and Web services develop- ment. Macromedia, the undisputed leader in Internet presentation layer tools (Dreamweaver, which has 70% market share in visual HTML tools) and rich media (Flash, which has 96% market share), announced its acquisition agree-
80 APRIL 2001
Java COM APP SERVERS
ment with Allaire in January of this year. will be maintained in 2001. Its server The No. 3 position in the Enterprise Allaire owns the JRun application server was bundled with comprehensive docu- Java space is controversial. Last year, and ColdFusion, a popular server-side mentation and running examples. Its depending on whom you asked, another development platform that is a prede- application server was the first to be company had the honor. Whoever gets it cessor of J2EE. The acquisition of Allaire bundled on a CD with popular Java this year – it could be Brokat, combines a client base of approximately magazines back when high-speed, SilverStream, HP/Bluestone, IONA, 2 million users comprising client-side home-based Internet was not readily Sybase, Macromedia, ATG, Borland, or Macromedia developers, ColdFusion available. Being the first to implement iPlanet – is unlikely to lead the competi- developers, and JRun developers. If many J2EE APIs has made the WebLogic tion by much of a margin. Macromedia can properly integrate its application server a favorite among Of all the products listed, I believe offerings into a single platform for client- thousands of independent software ven- HP/Bluestone has the greatest chance of and server-side development, combined dors (ISVs). taking over the No. 3 spot in server-side with a strategy for migrating its existing All other factors aside, the ISV client market share. Bluestone has learned client base to this new platform, it can base alone could keep BEA on top in from WebLogic and GemStone by pro- become an overnight market-share terms of market share. Not only has viding comprehensive J2EE trail maps shark. Unfortunately, the merger won’t WebLogic achieved a critical mass of and reference implementations to help be complete until mid-2001, placing acceptance, BEA has also invested heav- get developers up and running. Running Macromedia at a time-to-market disad- ily in the technologies that will differen- on top of a mature app server with pow- vantage with its competitors. tiate vendors from one another in 2001: erful success stories (such as American XML integration (eventually leading to Airlines’ Sabre System), Bluestone has The Application Server Market Outlook for 2001 Web services support) and commerce invested in all of the trends that became AUTHOR BIO The market share winners for 2001 server offerings, personalization, apparent in 2000, with product offerings Floyd Marinescu is an will be composed of companies that process/workflow automation and wire- for XML, wireless, commerce, personal- Enterprise Java educator provide J2EE-compliant servers with less support. Only a company with very ization, and EAI. at The Middleware support for the latest standards, such as deep pockets and strong developer The HP acquisition of Bluestone will Company, a EJB 2.0 and JCA 1.0, but also earn recog- incentives will succeed in driving ISV place this new company in a unique J2EE training company. nition for powerful, complementary, support away from BEA. position to take on the giants. HP will Floyd designed and and integrated offerings above and I believe that IBM WebSphere will likely mobilize its massive sales/market- implemented beyond J2EE – EAI and commerce serv- retain its position as the No. 2 enterprise ing force around its new middleware TheServerSide.com er offerings, Web services support, or development platform. Contrary to popu- offering, as well as invest significant J2EE community, and is wireless support. lar opinion, I don’t think IBM will trail as amounts of money in Bluestone prod- currently working on an BEA WebLogic was the market share far behind BEA as many think. On June 29, ucts. If HP/Bluestone can execute prop- EJB design patterns book. leader for 2000. I believe this position 2000, IBM announced that it would invest erly, it has a chance at gaining market $1 billion in the WebSphere share in 2002 and perhaps take on the platform, in technology as well giants in 2003. as the WebSphere consulting, sales, and marketing arms. The Conclusion:The Future of J2EE Application Servers effects of this will be felt in this In 2001 J2EE will be used as the year, since IBM will hopefully underlying platform for developing ver- invest significant resources into tical-niche applications and frameworks finally keeping up with the lat- for specialized applications such as Web est specs. services, wireless, CRM, process/work- IBM has traditionally been flow automation, and EAI. and will likely remain the The job of the ISV and component champion in EAI and pro- developer will be to write these niche cess/workflow automation frameworks to be as portable as possi- space. What is required is for ble. An explosion in the J2EE compo- IBM to invest in J2EE hooks to nent market is thus likely this year. The tie its existing proven products job of the project manager will turn into J2EE. IBM recently toward deciding which of these applica- announced an all-Java version tions should be combined to solve busi- of its own commerce server ness problems faster. In the best-case offering. IBM also was one of scenario, project managers will still be the first companies to provide able to choose the underlying applica- wireless and XML support tion server on which these portable through its alphaWorks initia- frameworks will be deployed. However, tives and the Wireless Trans- many companies working on enter- coding Server. prise-scale projects will turn toward Finally, IBM will likely proprietary vendor-integrated solu- become the first-to-market in tions. Web services product offer- By the end of the year, the application ings, as the company is inti- server market will be dominated by ven- mately involved in the specifi- dors who can provide one-stop integration cation process of Web services of tools, frameworks, and applications. initiatives, including UDDI, ebXML, XAML, and more. [email protected]
82 APRIL 2001
Java COM pplication servers are the one catego- VisualAge for Java, JSP developers and Web site ry of software product that seems to designers may find VisualAge a little difficult to WebSphere Abe on everyone’s mind these days. No learn. To address this market requirement, IBM longer is there any doubt in my mind that n- provides a simpler development environment tier applications are the future. Certain for Web site development called WebSphere applications will benefit from a heavy-client Studio. architecture, such as desktop publishing, The reviewer’s guide for WebSphere dis- Advanced but most will have at least some portion of cusses both products in detail, and I recom- their logic running on the middle tier. mend that you use WebSphere Studio if you While data-intensive tasks will still run plan on working with the WebSphere Server. more efficiently in the database tier, key WebSphere Advanced Edition and WebSphere Edition 3.5 business rules and HTML-client genera- Studio are packaged as separate installation tion will undoubtedly be handled by the kits on individual CDs. WebSphere’s installa- application server. Every major software tion program allows you to accept a default vendor has thrown the proverbial hat into installation process, or you can choose custom by IBM the app server ring. Leaders are starting installation. The former overwrote my existing to emerge, but it’s important to note that Apache Server installation on port 80 – which is the market penetration for application my biggest gripe with every application server REVIEWED BY JIM MILBERY servers is still less than 10%. I’ve ever worked with. We learned a valuable lesson count- Despite this small hiccup, the installation ing votes in Florida: it’s not smart to was painless and simple. The only problem I declare any winners until more encountered was that the installer failed to precincts have turned in their totals. create the administration user ID and pass- However, IBM is aggressively targeting word for the server. I was able to correct the the application server market with their problem right away by reviewing the installa- WebSphere line of products, which is tion manual. In fact, the most obvious how I came to spend the past several improvement in this release of WebSphere is weeks working with their WebSphere the enhanced installation and administration Advanced Server and WebSphere tools. The IBM HTTP server that comes with
REVIEW AUTHOR BIO Studio. WebSphere can be managed through a brows- Jim Milbery, a software consultant with Kuromaku Partners LLC er interface that’s crisp and well organized, as (www.kuromaku.com), based in Easton, Pennsylvania, has over IBM WebSphere Editions shown in Figure 1. 17 years of experience in application development and IBM sells a fairly large number of Both IBM and Oracle are embracing the relational databases. He is the applications editor for Wireless technologies under the WebSphere Apache server as the HTTP server of choice for Business & Technology and the product review editor marketing umbrella, which are bundled their application server products. While the for Java Developer’s Journal. into three versions of the application choice is excellent, configuration isn’t always server: easy. The browser-based administration tools [email protected] • Standard Edition: Supports static make the management task relatively sim- HTML pages, servlets, JavaServer ple, compared to using Apache’s arcane config- Pages, and XML uration files and syntax. • Advanced Edition: Standard Edition IBM also supports other popular HTTP features plus Enterprise JavaBeans servers, including iPlanet Enterprise Web • Enterprise Edition: Advanced Edition Server, Microsoft Internet Information Server, features plus CORBA and Lotus’s Domino Application Server. Once I had the Apache server configured, I installed WebSphere Standard Edition com- WebSphere Studio, which is tightly integrated petes directly with other low-end into the WebSphere Server. I highly recom- dynamic Web server technology such as mend that you use these products in tandem, iPlanet’s recently announced Web Server as it’s much easier to work with WebSphere IBM Software Solutions Enterprise Edition and Application through the Studio interface. IBM Corporation Server 6.0 Standard Edition. WebSphere The entire application server market has PRODUCT Route 100 Standard Edition and WebSphere rallied around the J2EE platform, and IBM Advanced Edition are based on the same WebSphere is no exception. Despite IBM and Somers,NY 10589 code line and are written in Java. While Sun’s much publicized spat over J2EE licensing, the Enterprise Edition shares many of the I fully expect IBM to tackle J2EE certification Web:www.ibm.com/websphere same features, it’s constructed from a dif- for the WebSphere Application Server. The J2EE ferent code line that’s based on IBM’s is chockful of required programming inter- Test Environment: Component Broker technology. The faces, but most developers will be concentrat- WebSphere Advanced Edition version 3.5 is ing on the big three: JavaServer Pages, Java Dell 4800 1GB RAM,30GB disk,NT 4.0 likely to be the most popular of the three servlets, and Enterprise JavaBeans. packages, and this is the software I took a The WebSphere Advanced Edition is all Pricing: look at. about J2EE programming. If you haven’t had Standard:$795/server much experience working with J2EE, you may IBM WebSphere Advanced Edition find it easier to start with JSP and servlets. Advanced:$7,500/CPU Although IBM offers an enterprise-class Through them you get access to application Enterprise:$35,000/CPU Java development environment in the form of data within a relational database using a sim-
84 APRIL 2001
Java COM WebSphere Advanced Edition 3.5 by IBM
ple programming paradigm. JSPs and servlets generate standard HTML pages from this data, so the resulting applications are compatible with even the lowest-common-denominator Web browsers. (You can even use servlet technology to generate browser pages for wireless devices using WML.) IBM organizes logical groups of similar content into WebSphere “applications,” which can consist of servlets, JSPs, or Enterprise JavaBeans. According to the J2EE specification, servlets and JSPs are used as the tools for generating the user interface layer of the appli- cation. Core business rules and transactions are implemented by using Enterprise JavaBeans – session beans and container beans. The for- mer handle the business rules and transaction logic; the latter han- dle the data persistence (e.g., storing records in a database). While Sun’s J2EE specification describes the various Java APIs
REVIEW that a vendor is required to support, actual implementation is left to the individual application server vendor. For example, vendors are required to support “stateful” session beans to implement transac- tions, but the actual transaction layer is up to the vendor. The speed and robustness of a vendor’s EJB implementation is completely FIGURE 1 IBM HTTP Server Management console dependent on the transaction layer that the application server is based on. ing with these products for a while before you make a selection. The WebSphere 3.5 offers a strong transaction layer on which its J2EE devil is definitely in the details. foundation is based. IBM supports both bean-managed persistence for EJBs – which leaves the detailed programming in the hands of Summary developers – and container-managed persistence for DB2, Oracle, IBM offers the Advanced Edition for most of the popular server plat- and Sybase. WebSphere 3.5 leverages JDK 1.2 and transaction forms, including AIX, Solaris, Windows NT/2000, and HP-UX. If you’re
PRODUCT enhancements such as failover and load balancing. looking for an enterprise-class application server, IBM has put together WebSphere supports additional standards in this release, such as a comprehensive package worth considering under the WebSphere LDAP (Lightweight Directory Access Protocol), and a copy of IBM’s umbrella. However, if you’re interested in building JSP/servlet applica- SecureWay Directory Server is bundled into the Advanced Edition to tions and don’t need directory services integration, EJBs, mainframe support LDAP. IBM’s goal is to provide a complete, integrated stack of access, and advanced failover capabilities, WebSphere Advanced may be products from the database to the application server all the way to more than you’re looking for. application development tools. In order to manage application servers more carefully, WebSphere 3.5 includes Tivoli Ready modules that allow the server to be managed by IBM’s Tivoli tools. IBM has made improvements in other areas of the server in this release as well, including integration with Domino, VisualAge for Java, and WebSphere Commerce Suite. Choosing an Application Server Platform Overall, WebSphere’s biggest strength is probably its integration with the DB2 database and the rest of the IBM product stack. While the ulti- mate goal of the J2EE is standardization and interoperability, the reality of this vision as far as commercial products is concerned tends to vary. Vendors such as IBM that market a database, application server, and development tools will tend to have greater integration within their own stack. It’s the classic “best of breed” versus “integrated suite of products” problem. That’s why I recommend that any organization looking to standard- ize on an application server take a very close look at the various prod- ucts on the market. While they all tend to have the same set of features, implementation of those features tends to vary widely, even within the realm of the J2EE. For example, IBM provides the WebSphere Studio product that features a simplified interface for developing servlet- based Web applications. Developers who are looking for a simple plat- form for managing servlet-based applications will likely find the com- bination of WebSphere Studio and WebSphere Advanced Edition to be compelling. Conversely, programmers who are building cross-database applica- tions may find BEA’s WebLogic more compelling, and corporations that want to leverage their PL/SQL programming skills will lean toward Oracle’s 9i Application Server. I don’t mean to suggest that these are the only reasons to select one particular product over another, and there are lots of reasons for choos- ing IBM’s WebSphere product line. However, I highly recommend work-
86 APRIL 2001
Java COM VISUALAGE REPOSITORY
Advanced Source Control in VisualAge for Java More source control tips
Part 2 of 2
Using a software configuration management (SCM) system is WRITTEN BY an integral part of any development project. Source code is your most valuable resource and must be protected. However, with the TIM DEBOER, large number of products available from many different vendors, STEVE FRANCISCO & it’s essential that you choose an SCM system that will work with ELLEN MCKAY your favorite development tools.
The External Version Control tool in refresh operation, such as file deletions, Manipulating Path Prefixes VisualAge for Java, version 3.5, allows new versions of files created by your When you import Java source or you to interact with several external teammates, and potential conflicts in compiled class files into the IDE, SCM systems from within the integrated which changes have occurred both they’re loaded into the appropriate development environment (IDE). Once inside the IDE and on the SCM server. package in the workspace. Resources, you’ve used the tool to associate a proj- You control how these inconsistencies however, are handled differently. ect in VisualAge for Java with a group of are dealt with and choose the course of They’re loaded into the associated proj- files in the SCM system, you can add and action in each case. ect_resources/
88 APRIL 2001
Java COM VISUALAGE REPOSITORY
means labels.properties will appear on project_resources\projectname\mypac cally imported directly into your project disk as: kage.properties. If you’re using the SCCI and placed into packages. The path pre- handler, you must also type the name of fix doesn’t affect the names of these file ide/project_resources/
90 APRIL 2001
Java COM JAVA CODE
Interfaces vs Abstract Classes in Java How to decide which to use
Have you ever wondered why you should use interfaces instead of abstract classes, or vice versa? More specifically, when dealing WRITTEN BY with generalization, have you struggled with using one or the ANTHONY MEYER other? I’ll shed some light on what can be a very confusing issue.
To start, I’ll identify two pieces of the You’re not modeling every aspect and Your company has several different development puzzle: the behavior of an nuance of a motor, but instead model- types of motors, but given our particular object and the object’s implementation. ing what’s important for the company application, this behavior is the only rule When designing an entity that can and the process you’re automating. (You that applies to all of them. You look at have more than one implementation, find out what’s important by talking to both interfaces and abstract classes, but the goal is to describe the entity’s behav- the users of a system. In this case it’s for purposes of illustration the motors ior in such a way that it can be used your sales department. Good luck!) will be modeled as an abstract class. without knowing exactly how the enti- Your sales department says that ty’s behavior is implemented. In every motor has a horsepower rating, public abstract Motor{ essence, you’re separating the behavior and this feature is the only attribute abstract public int getHorsepower(); of an object from its implementation. they’re concerned with. }
You make a handful of concrete imple- “ You can avoid mentations of this class, and version 1.0 of the application enters production. Time passes and you’re called to cre- accidentally implying an ate version 2.0. While reviewing the requirements for the second version, implementation pattern if you find that a small subset of motors is battery-powered, and that these batter- ies take time to recharge. The sales you model behavior using interfaces department wants to be able to view the time to recharge from the computer screen. From their statement, you derive But is this separation best achieved by Based on this statement,’’ you a behavior: way of an interface or by way of an describe the following behavior of a abstract class? Both can define methods motor: Behavior: Someone can ask a battery- without saying how they work. So which powered motor for its time to recharge one do you use? Behavior: Someone can ask the motor and the motor will return its time as an for its horsepower rating, and the motor integer. Modeling Behavior in an Abstract Class will return its rating as an integer. As a rule, pure behavior is always public int getTimeToRecharge(); modeled by interfaces and not in At this point you don’t know where abstract classes. This example will the horsepower comes from, but you do Translated into a method signature model behavior in an abstract class to know that this behavior must exist. this behavior becomes: illustrate why. Translated into a method signature Pretend you’re designing a “motor” this behavior becomes: public abstract BatteryPoweredMotor entity for an application that your sales extends Motor{ department will use to sell motors. public int getHorsepower() abstract public int getTimeToRecharge();
92 APRIL 2001
Java COM JAVA CODE
} But business is changing, and soon Throughout your application, mo- solar-powered motors are introduced. tors are treated the same in 90% of the The new battery-powered motors are The sales department tells you that code. When you’re checking if you have implemented inside the application as solar-powered motors require a mini- a solar- or battery-powered motor, use concrete classes. It’s important to note mum amount of light energy to operate. instanceof. that these classes extend Battery- This light energy is measured in lumens. PoweredMotor as opposed to Motor. The customers want to know this infor- if (instanceof SolarPoweredMotor){ } The changes are released as version 2 mation. There’s a fear that on cloudy if (instanceof BatteryPoweredMotor){ } and the sales department is happy once days some solar-powered motors won’t again. operate. The sales department requests You find out that horsepower is cal- that the application be changed to sup- culated for each type of motor so the port the new solar-powered motors. getHorsepower() method is overloaded From listening to their plight, a behavior in each of the derived abstract classes. Motoror is derived. So far, this design looks good… {abstract} That is, until you find out that the getHorsepower() : int Behavior: Someone can ask a solar- sales department wants to sell a new powered battery for its lumens required type of motor that has both battery and to operate and the motor will return an solar power! The behaviors associated integer. with solar- and battery-powered motors SolararPoweredMotorPower haven’t changed. The only difference is BatterryPoweeredMotor public int getLumensToOperate(); you have a handful of motors that exhib- {abstract} it both behaviors. {abstract} getLumensToOperate() : int In an Abstract class getTimeToRecharge() : int The Problem with Modeling Behavior public abstract SolarPoweredMotor extends in an Abstract Class FIGURE 1 A UML diagram showing both behavior and implementation inheritance Motor{ Here’s where the difference between abstract public int getLumensToOperate(); an interface and an abstract class } becomes apparent. <
<
<
FIGURE 2 A UML diagram showing only behavior inheritance <
<
getTimeToRecharge() : int SpecificMotoorImpl DualPooweredMMotor getHorsepower() : int
SpecificSololarPoweredImplPPo myCustomMethod() : int SpecificBattteryteryPoweredImpl getHorsepower() : int getTimeToRecharge() : int getHorsepower() : int getHorsepower() int getLumensToOperate() : int getLumensToOperate() : int getTimeToRecharge() : int
FIGURE 3 A UML diagram showing behavior inheritance from two different sources FIGURE 4 A UML diagram showing behavior inheritance and implementation inheritance derived from separate hierarchies
94 APRIL 2001
Java COM though the behavior in the hierarchy “Using abstract classes you can was accurate. Modeling Behavior in an Interface You can avoid accidentally implying an implementation pattern if you model enforce an behavior using interfaces. Let’s review the behavior: implementation Behavior: Someone can ask the motor for its horsepower rating, and the motor will return its rating as an integer.
hierarchy and avoid duplicate code public interface Motor(){ public int getHorsepower(); } AUTHOR BIO ered motors is well tested and has no The reason you’re having problems’’ Anthony Meyer is a known bugs. is that by using abstract classes you Behavior: Somone can ask a battery- technical director and a You can make a new abstract class implied not only a behavior hierarchy powered motor for its time to recharge Java developer at that’s SolarBatteryPowered but then but a pattern of implementation as and the motor will return its time as an Flashline.com. His your motor won’t trigger your instanceof well! You modeled how the motors integer. experience includes the when you check for solar- and battery- receive their behavior instead of just design, development and powered motors. The other option is to saying the motors have a specific public interface BatteryPoweredMotor implementation of make the new motor extend either the behavior. extends Motor(){ large-scale, Java-based, SolarPowered or BatteryPowered ab- While the phrase “Someone can ask public int getTimeToRecharge(); Internet applications in stract class. But if you do that, the new the motor for its horsepower rating, and } the corporate Web motor will lose the functionality of the the motor will return the rating as an development environment. abstract class it didn’t extend. integer” implies something about the Behavior: Somone can ask a solar-pow- He has also created and Technically your new motor needs to behavior of an object, it doesn’t deny ered motor for its lumens required to implemented extend both abstract classes, but you any behavior. Nevertheless, when you operate, and the motor will return its corporate-focused reuse painted yourself into a corner that can modeled with abstract classes, you cre- lumens as an integer. strategies in the be solved only with a lot of special-case ated an implementation pattern that financial industry. coding. later was found to be incorrect, even public interface SolarPoweredMotor extends
SHOP ONLINE AT JDJSTORE.COM FOR BEST PRICES OR CALL YOUR ORDER IN AT 1-888-303-JAVA BUY THOUSANDS 0F GUARANTEED BEST PRICES PRODUCTS AT FOR ALL YOUR GUARANTEED JAVA-RELATED