WEB SERVICES EDGE 2001 SANTA CLARA, CA OCT 24–25
TM
The World’s Leading Java Resource Java COM October 2001 Volume:6 Issue:10
OCTOBER 24–25, 2001 ª
OCTOBER 22–25, 2001
ª
SANTA CLARA CONVENTION? CENTER, SANTA CLARA, CA EJB 2.0: Local Entity Beans and Relationships Alex Pestrikov Exploring the many-to-many relationship 12 Guest Editorial 2 by George Grey pg. 50 Feature: MVC Steven Sweeting, Aaron Rustad, & Clive Jones Integrating and mapping a Web application MVC pattern 20 Product Reviews Source Integrity 8.1 pg. 40 Patterns: Core J2EE Patterns Dan Malks JBuilder 5 pg. 62 Presentation tier patterns and refactoring 32 Nokia 9210 pg.84 2 Portability Tips: Build to Spec! Liz Blair Ask Doctor Java Avoiding pitfalls in the Application Portability Series 44 pg. 66 Java & Translation: Using the Façade Pattern David Gallardo Cubist Threads for the Java Internationalization API by Blair Wyman pg. 114 Produce globally enabled software 52
RETAILERS PLEASE DISPLAY David Hardin & Mike Frerking UNTIL DECEMBER 31, 2001 Feature: A Storm in a Coffee Cup Embedded real-time Java components for hardware interfacing 72
Feature: Java for Embedded Computing – Vincent Perrier & A Reality It’s more productive as a language, and as a Steven Schwarz programming environment, than C/C++ PART 2 88
Java Basics: Extreme Performance Tuning James McGovern Uncommonly good solutions to common application problems PART 2 98 FROMF THE EDITORDI J2ME INTERNATIONAL ADVISORY BOARD • CALVIN AUSTIN (Lead Software Engineer, J2SE Linux Project, Sun Microsystems), • JAMES DUNCAN DAVIDSON (JavaServlet API/XMP API, Sun Microsystems), • JASON HUNTER (Senior Technologist, CollabNet), • JON S. STEVENS (Apache Software ALANWILLIAMSON EDITOR-IN-CHIEF Foundation), • RICK ROSS (President, JavaLobby), • BILLROTH (Group Product Manager, Sun Microsystems), • BILL WILLETT (CEO, Programmer’s Paradise) • BLAIR WYMAN (Chief Software Architect IBM Rochester)
EDITORIAL J2SE EDITOR-IN-CHIEF: Java XP ALAN WILLIAMSON EDITORIAL DIRECTOR: JEREMY GEELAN ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI ast month I wrote on the Microsoft and Compaq shareholders, 40%. J2EE EDITOR: AJIT SAGAR issues with their impending release of As with the XP stories, there’s already a J2ME EDITOR: JASON BRIGGS Windows XP. I intended to go a whole raft of postings concerning what’s going on PRODUCT REVIEW EDITOR: JIM MILBERY L editorial without mentioning that software behind the scenes. Most of it is nonsense, FOUNDING EDITOR: SEAN RHODY company, but because of the amount of e- I’m sure. One thing that is true, though, is a PRODUCTION mail I received, I have to do something. consolidation of both companies’ Java offer- J2EE VICE PRESIDENT,PRODUCTION AND DESIGN: JIM MORGAN It appears that, as with any good news ings. It’s way too early to be talking of such EXECUTIVE EDITOR: M’LOU PINKHAM story, it comes with a fair share of disinfor- things, but be assured, we’ll keep you up to MANAGING EDITOR: CHERYL VAN SISE mation. Every news source was reporting date with any information we receive. EDITOR: NANCY VALENTINE some aspect of the XP–Java saga and what it • • • ASSOCIATE EDITORS: JAMIE MATUSOW meant for the Java community. A lot of it was It’s been a bad month for the embedded GAIL SCHULTZ simply nonsense and I have to thank you for world, especially the Japanese market, which BRENDA GREENE sending me posts from the “we-love- lost somewhere around 60,000 jobs from the ASSISTANT EDITOR: LIN GOETZ Home TECHNICAL EDITOR: BAHADIR KARUV, PH.D. Microsoft” sites that were just downright major chip manufacturers. Apparently, the comical. If you had the misfortune to read slowdown in demand for mobile phones, WRITERS IN THIS ISSUE any of them, you’d get the idea that Java is on coupled with falling PC sales, is beginning to BILL BALOGLU, LIZ BLAIR, JASON BRIGGS, MIKE FRERKING DAVID GALLARDO, its way out, and that it was just a marketing make its mark at all ends of the manufactur- GEORGE GREY, DAVID HARDIN, THOMAS INGLIS, CLIVE JONES, DAN MALKS. gimmick from Sun. Gosh, that would be one ing process. Gateway recently announced the JAMES MCGOVERN, SCOTT MCNEALY, JIM MILBERY, BILL PALMIERI, hell of a gimmick! Even by Sun’s standards. closing of its European operation in Ireland. VINCENT PERRIER, ALEX PESTRIKOV, AARON RUSTAD, AJIT SAGAR, Fortunately, nothing is ever as bad as it I asked our resident J2ME guru, Jason STEVEN SCHWARZ, STEVEN SWEETING, ALAN WILLIAMSON, BLAIR WYMAN sounds, and we here at JDJ want to make Briggs, what this means for the J2ME mar- SUBSCRIPTIONS: sure our readers are kept informed of the ketplace. His reply was that we wouldn’t see FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, whole debacle. You deserve the truth, and a great pickup of Java-enabled devices for a PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT we’re here to deliver. We needed someone to while yet. He did note that it would probably SUBSCRIPTION HOTLINE:[email protected] tell our readers what the future of Java holds sneak up on us. We’ll suddenly turn around and cut through all the Microsoft marketing and discover that the device we’re using runs COVER PRICE: $5.99/ISSUE DOMESTIC: $49.99/YR. (12 ISSUES) anti-Java hype. on Java and we didn’t even know it. Which is CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. Who else but Scott McNealy, CEO of Sun exactly what you’d expect. (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. Microsystems, Inc., could tell you how it is? At the end of the day we should be mar- Scott has never been one to shy away from a keting our solutions, not the fact that they’re EDITORIAL OFFICES: little Microsoft bashing, but when we asked implemented in Java. Who cares? As long as SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 him to write our Guest Editorial, he kindly it does what we want it to, the underlying TELEPHONE: 201 802-3000 FAX:201 782-9600 agreed and put together a rational and won- technology shouldn’t matter to us as con- JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly (12 times a year) for $49.99 by SYS-CON Publications, Inc., 135 Chestnut derfully level-headed word of comfort for sumers. (Oh, before I forget, Jason, can you Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at our readers. Read what Scott has to say on put me down on the list for one of the Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address the next page. devices you mentioned in your editorial?) changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., On another note of Java news, I see that Java is going through an interesting time 135 Chestnut Ridge Road, Montvale, NJ 07645. we might be losing one of the heralded J2EE in its development life. More and more peo- ©COPYRIGHT: licensees. This morning HP and Compaq ple are now enjoying its benefits without Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. announced they would be merging, creating ever knowing that their devices are Java pow- No part of this publication may be reproduced or transmitted in any form or by any a company that would be just slightly small- ered. This is the way it should be, and we means, electronic or mechanical, including photocopy or any information storage and er than IBM. Early reports indicate that Carly need to start moving away from simply retrieval system, without written permission. For promotional reprints, contact reprint coor- dinator Carrie Gebert, [email protected]. SYS-CON Publications, Inc., reserves the right Fiorina, present CEO of HP, will head up the heralding “Java-powered” whatevers in our to revise, republish and authorize its readers to use the articles submitted for publication. consolidated company, with HP sharehold- marketing and focus more on the solutions ers taking a 60% share of the new company Java is attempting to deliver. Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. SYS-CON Publications, Inc., is independent of Sun Microsystems, Inc. All brand and product names used on these pages are trade names, [email protected] service marks or trademarks of their respective companies. AUTHOR BIO Alan Williamson is editor-in-chief of Java Developer’s Journal. In his spare time he holds the post of chief technical officer at n-ary (consulting) Ltd (www.n-ary.com), one of the first companies in the UK to specialize in Java at the server side. Rumor has it he welcomes all suggestions and comments.
OCTOBER 2001 5
Java COM GUEST EDITORIAL
WRITTEN BY SCOTT MCNEALY The rational The Platform of Choice alternative
t’s becoming more obvious to me every day between now and 2005 on these new devices. that Java technology is the platform of choice, In the server market we’re seeing choice like Iin more ways than one. never before. There are 17 different applications In the traditional sense of the phrase, it’s the servers available today that are compatible with Version 4.5 answer to the questions all developers ask them- the Java platform. Some are the underpinnings of Introductory Offer selves: Which platform should I develop to? Which IDEs, but even then IT professionals can choose has the biggest market and the most influence? the implementation that best suits their needs. $2995 Which provides me with a means to demonstrate And if the ISV they choose falls behind, they can for Teamwork Server my skills and creativity? replace one app server with another at a dramati- There’s a second meaning as well, another ques- cally lower cost of switching. tion to answer: Which platform provides develop- More than 400 major corporations are working ers, customers, and users with more choice? together through the Java Community Process to In this second meaning, “platform of choice” indi- innovate, enhance, and expand Java technology. All 9 UML diagrams cates one that runs on multiple operating systems, Offerings from Sun, IBM, HP, BEA, and Oracle, to Additional Features: addresses a wide spectrum of hardware, and can name a few, are all built around the platform of choice. • Performs Java, C++ or CORBA IDL spawn multiple implementations so users are free to The lonely exception, of course, is Microsoft. code round-trip engineering (code select the one that works best (yours, of course). Unless you’ve been totally out of touch since mid- generation and reverse engineering); By either definition Java technology is still the July, you’re aware that Microsoft is not shipping a JVM recognizes JavaDoc comments. This platform of choice, and this works to your benefit with Windows XP. The reason? Microsoft has used feature allows you to write code, reverse – big time. The Java platform addresses opportu- every excuse from “the lawsuit settlement required us engineer, make changes to the model nities ranging from the biggest servers available to to do this” to my personal favorite, “We don’t want and re-generate the code without losing any implementation specific information. the desktop to millions of new client devices – Windows to have too much code.” The real reason, smart cards, mobile phones, pagers, PDAs, TV set- I suspect, is that Microsoft is anti-choice. • Supports UML 1.3 notation. top boxes, and automotive systems. (Clearly the But, at the end of the day, you’ll want to know • Saves diagrams as bitmap PNG/JPG and definition of “client” is due for an update, too.) whether this move will lessen the market for your scalable WMF/SVG/EPS/DXF formats. Java technology is really hitting its stride now. products and impact your livelihood. Rest assured • Provides XML interoperability — native Within six months more than six million phones that we will provide XP support. It will be the latest model files are stored in XMI format. enabled with Java technology have been sold in Java technology, not something old. We’ll distribute it • Integrated with Forte for Java (FFJ) IDE Japan, where the three largest wireless providers – via PC manufacturers, Web sites, ISVs – whatever it versions 1.0 and 2.0. NTT DoCoMo, J-Phone, and KDDI – have deployed takes to ensure that your Java apps will run anywhere. Standard Edition: ...... $249 interactive wireless services. One analyst estimates So keep on writing to the platform of real choice, Professional Edition: . . . . $499 that more than 700 million JVMs will be deployed the one that’s here today: the Java platform.
[email protected] Visit us at Java One READERS’ RESPONSE AUTHOR BIO Scott McNealy is the chief executive of Sun Microsystems. Floating License . . $100 additional Early online reactions to Scott McNealy’s Microsoft Shoots Self in Foot Upgrade for a $69 annual fee! Guest Editorial. Add your feedback online ava is the ideal platform for software because a program written in at JavaDevelopersJournal.com. JJava can run on multiple platforms with little or no modifications. Since Microsoft is not including a JVM in Windows XP, a void beckons
Keep Up the Good Fight to be filled. Personally, I view Microsoft’s obsolete implementation of C
s the JVM still in the IE6 brows- the JVM as an impediment to furthering the Java platform. I Ier? If not, that would break a lot Computer builders would be wise to include an up-to-date JVM ✦ G of Web sites and cause much with the systems they sell. M ✦ ▲✦ (more) anti-Microsoftism... Computer buyers should ask for the JVM on the machines they No Magic... I’m a multimedia developer buy. If the computer makers don’t include a JVM, they’re short- Just Technology That Works currently learning Java and changing the customer and the customer should take his or her Java3D. Keep up the good fight. business to one that does. Download fully functional demo at: The relentless always win. Including the JVM is a great way for computer manufacturers to www.magicdraw.com differentiate themselves from those who don’t. Wallace Jackson CEO contact us at Mind Taffy LLC Peter English [email protected] [email protected] [email protected] 100% Pure Java Application
OCTOBER 2001 7
Java COM LETTERS TO THE EDITOR
New Format designers because we couldn’t expect them to Sanjay writes: DJ is a wonderful publication and the new learn JSP; they would give us HTML instead The scenario you mention: “restrict the Jformat makes it even better. I’d like to see a and we would have to turn that into JSP “and” customer ‘Bob Hoozit’ to viewing only his section in each issue devoted to new and less- do the back-end logic. Velocity does seem to orders...,” is relatively easy to implement using experienced Java programmers. “Interfaces vs provide a very nice alternative to this so I’m the current J2EE security model. Abstract Classes” by Anthony Meyer was a won- going to look into it now. Thanks for taking the derful example of this type of article [Vol. 6, issue time to write a straightforward comparison. 4]. I handed it out to students in my last Java class because it really explained many things. Kabriel Robichaux [email protected] J2SE J2EE J2ME
Let’s say the customerID/loginID (also the Some proposals are: name of the security Principal) for customer 1. How and where to do validity checking on Chat with James Gosling Bob Hoozit is: bhoozit. data that’s entered through Swing compo- hanks for the good interview with James nents. TGosling [“Real-World Java with James 1. Order creation 2. Which Layout managers do programmers Gosling,” Vol. 6, issue 8]. He references a book, When creating a new order, we’ll need to “really” use? Do they use the Swing classes Effective Programming, but I can’t find it any- persist to the database, the loginID field, or a bought-in Layout Manager? where. Are you sure you have the correct title? along with the other fields that comprise Home 3. Do experienced programmers really use the order. To accomplish this with contain- threads? J.David Beutel er-managed persistence, code similar to the [email protected]] snippet below should be used within the Douglas Maughan ejbCreate() method of OrderEJB. [email protected] Alan writes: The book is Effective Java Programming this.loginId=theContext.getCallerPrinci Language Guide (The Java Series) by Joshua pal().getName() ; // Bloch, Addison-Wesley Professional; ISBN: 0201310058. The above saves bhoozit in the loginID field, if bhoozit was logged in and created this J2EE Security Model new order. read Sanjay Mahapatra’s article, “J2EE IApplication Security Model,” [Vol. 6, issue 2. Order retrieval 8]. While implementing some projects using Now let’s say the CustomerServicesEJB has some of the more popular app servers, we’ve a method retrieveOrders() and the OrderEJB run into some limitations of the security (entity) has a findByCustomer() method. The model. While the container security descrip- CustomerServicesEJB::retrieveOrders() tors are declarative, we find we need finer- method will in turn need to make a method Comments on Jon Stevens’Article grained support. It’s one thing to protect cer- call similar to: just read Jon Stevens article about JSP, tain apps based on the user’s generic role, IStruts, Velocity, etc., [“JSP: You Make the but our apps tend to have user-specific per- findByCustomer(theContext.getCallerPrin Decision,” Vol. 6, issue 7]. I was really pleased missions, and the declaration isn’t flexible cipal().getName() ) that I’m not the only one who doesn’t like enough. JSPs. Great article! In your example in Listing 3, you restrict on the remote reference for OrderEJB. The Couldn’t have said it better... :-) the use of the CustomerServicesEJB to enti- above will cause the invocation of ties in the role of “customer.” We want to go findOrdersByCustomer with the argument Andreas Prohaska the next step. For instance, we would want to (bhoozit), if bhoozit was logged in and [email protected] restrict the customer “Bob Hoozit” to viewing attempted this order retrieval. only his orders and his invoices. This will result in each customer being just finished reading Jon Stevens’ article and Are we expecting too much from the J2EE able to see only his or her own orders, with just II wanted to write you a quick thanks. You security model or should we be looking at a couple of lines of code. did a great job of explaining the differences this in a different way? Hope this helps. between JSP and Velocity and it was a great read. I’ve been using JSP from the beginning Steve Suehs Sanjay Mahapatra and have been frustrated when working with [email protected] [email protected]
8 OCTOBER 2001
Java COM J2EE EDITORIALOR J2EE INDEXX J2ME AJIT SAGAR J2EE EDITOR
Plug and Plug and Plug and Play Plug and Plugand Plug and Play In the software world plug- and-play is a great concept. J2SE recently got the security card for enter- vides connectivity via resource adapters to However, overzealous devel- 10 ing our Pennsylvania offices. The legacy, ERP, and CRM systems. However, opers often have a tendency Ibadge attaches to a hook that’s linked this only supports synchronous commu- to overdesign for reuse. to the string that goes around my neck so I nications. Support for asynchronous com- by Ajit Sagar can carry the badge at all times. I’m sure munications is expected in the next you know the type of setup I’m talking release of the spec. An alternative for asyn- about. The JavaOne badges handed out chronous interaction is to use message- Local Entity Beans and this year were of the same type. As I exam- driven beans, that is, JMS. This is the Relationships ined this “gadget” more closely, I noticed advantage of open, pluggable APIs. Exploring the many-to-many 12 J2EE that the hook is attached to a clasp, and However, mixing the two paradigms will relationship the clasp snaps into a socket at the other have repercussions on the application. by Alex Pestrikov end. Another piece allows me to tighten or Issues such as performance and transac- loosen the string around my neck. tion management will have to be 2 For a simple security badge holder, this addressed by the application designer. The MVC – Integrating and gadget is really quite sophisticated. All the alternative in the market is to use a direct Mapping a Web pieces fit together so well. At first I was ERP adapter, such as one from Application MVC Pattern
Home quite impressed by the design. You can WebMethods or Attunity. While WebLogic A look at the MVC design detach the badge, the clasp, the string – all and WebMethods are working on a rela- pattern and its implementa- 20 the pieces that connect so well to each tionship that enables WebLogic’s imple- tion in Struts other. Then I started wondering why the mentation of J2EE CA to utilize by Steven Sweeting, Aaron Rustad, manufacturer had designed such a com- WebMethods’ platform, in addition to the and Clive Jones plex system for such a simple application. issues of performance, transaction integri- In the software world plug-and-play is ty, and security, application designers will a great concept. Good architectures also have to consider the licensing and Core J2EE Patterns should always be designed with compo- total cost of ownership (TCO) of using two Presentation tier patterns and nent reuse in mind. However, overzealous application environments. refactoring and how they 32 ones often have a tendency to overdesign Another example is the EJB model. relate to one another for reuse. It’s very important to rein in the Until EJB 2.0, whether a component was by Dan Malks design into the context of the real business local or remote, it was addressed via problem that applications built on the remote interfaces, which meant there was architecture try to solve. J2EE is a great always a network hop (or RMI call) to get Product Review platform for component-based develop- to an EJB component. Although applica- Source Integrity ment and promotes the design of reusable tion server vendors offered optimization Enterprise Edition 8.1 components. Along with the APIs, it offers for local component access, the spec did- by MKS 40 guidelines and best practices for plugging n’t enforce this. In other words, you could The latest version of MKS’s together components to build complete plug in any component and it would act as source code management applications. Design patterns should be a remote component. Luckily the local product line carefully examined before applying them interfaces in EJB 2.0 address this problem. Reviewed by Jim Milbery to a particular application. In the real Speaking of local interfaces, we have world, performance, timing constraints, an excellent article in this issue by Alex high availability, and other factors become Pestrikov. In addition to our bimonthly Build to Spec! additional criteria for designing a feasible column on Core J2EE Patterns, the fea- Avoiding pitfalls in the 44 solution. ture this month is an article on the MVC Application Portability Series For example, recall last month’s discus- pattern in a Web application. Add to this by Liz Blair sion on the connectivity to EIS sources our regular J2EE FAQs and some top- from the J2EE platform. The J2EE notch articles and you have another great Connector Architecture (J2EE CA) pro- issue.
[email protected] AUTHOR BIO Ajit Sagar is the J2EE editor of JDJ and the founding editor and editor-in-chief of XML-Journal. A senior solutions architect with VerticalNet Solutions, based in San Francisco, he’s well versed in Java,Web, and XML technologies.
10 OCTOBER 2001
Java COM E J B 2 . 0
J2ME Local Entity Beans and Relationships
J2SE Exploring the many-to-many relationship
A s the EJB 2.0 specification has entered its final stage, many companies are in the process of building server-side J2EE applications.The final draft of the specification has made contain- WRITTEN BY er-managed persistence (CMP) of entity beans complete and ALEX PESTRIKOV more powerful. J2EE
Significant changes that were made • The bean is collocated in the same this later.) to the specification in the area of entity JVM and its method parameters are Another important feature of CMP beans include: passed by reference. is declarative entity bean relation- • Local entity beans are lightweight ships. The specification allows a decla- entity beans that exist only locally, Although the last item exposes the ration of the following things about a inside the EJB container, and there- implementation details about the relationship:
Home fore don’t need to be marshaled. object, this optimization is well • Cardinality: One-to-one, one-to- • EJB QL helps create specialized deserved. Indeed, it’s only logical that many, and many-to-many relation- queries declaratively. some objects are never accessed ships are supported. • Declarative entity bean relationships remotely and therefore shouldn’t incur • Direction: Unidirectional and bidirec- have been added. the overhead associated with the remote tional relationships are supported. • Dependent object classes were call. Often the local entity bean may be • Cascade deletes: If a relationship is removed from the latest draft in favor accessed through a facade session bean. marked for cascade delete, the of local entity beans. In this case the remote clients will pass dependent entity beans are removed value objects to the facade session bean. when the main entity bean is These features are essential for real- This bean will then perform business removed. life applications. Another exciting devel- logic that may involve other session opment is that the latest version of BEA beans and entity beans. The facade bean You still have to provide abstract get WebLogic application server supports will call the local entity beans when the and set methods in the bean class to the draft specification in all of the pre- data needs to be persisted. (More about reflect cardinality and direction. For ceding features. In this article I will go through an example application to demonstrate local entity beans and enti- ty bean relationships; namely, a many- to-many relationship. I’ll also create deployment descriptors for BEA Web- Logic Application Server 6.1 and write a build-script to generate a deployable archive. Remote entity beans encapsulate coarse-grained persistent objects, whereas local entity beans target fine- grained persistent objects. Local entity beans differ from remote entity beans in this manner: • The bean interface extends javax. ejb.EJBLocalObject; the home inter- face extends javax.ejb.EJBLocal- Home. • The bean is never transmitted over the network. Thus its methods will not throw a java.rmi.RemoteException. FIGURE 1 Class diagram for the example application classes (remote and home interfaces for facade beans not shown)
12 OCTOBER 2001
Java COM E J B 2 . 0
example, if an Order bean has many The Group Manager bean is respon- a lot of different pieces to them, it’s a Order Line Items, then you must provide sible for adding and removing Users good idea to create a build script as soon abstract getLineItems and setLineItems from Groups. Adding a User to a Group as the skeleton of the project is in place. methods in the Order class to specify a is as simple as adding a user bean to a I use a utility Ant to do all my builds. Ant unidirectional, one-to-many relation- collection. This is done in the can create directories, move files, com- ship. addUserToGroup method. I had to pile, JAR, and deploy your J2EE applica-
J2ME declare this method to require a transac- tion. It can even create database schema How It’s Done tion in the ejb-jar.file because the collec- and run unit tests for you. Let’s write a small application that tion must be retrieved and altered in the Another good thing about Ant is that utilizes local entity beans and relation- same transaction. the scripts are written in XML, which ships. My example will run on BEA seems quite natural since we spent all WebLogic 6.1 Server and an Oracle data- UserBean userBean = this time with XML writing the deploy- base. I’ll have two entity beans – User userHome.findByPrimaryKey(userName) ment descriptors. WebLogic Server 6.1 and Group. User can belong to multiple ; comes with a number of examples that J2SE groups and a Group can have multiple GroupBean groupBean = have Ant build scripts and can serve as users. Both beans are local entity beans home.findByPrimaryKey(groupName); templates. Listing 4 shows the fragment and have two session facade beans: Collection users = of the Ant script that calls the WebLogic UserManager and GroupManager. I also groupBean.getUsers(); EJB compiler to create a final deployable want to navigate in both directions. users.add(userBean); .jar file for our beans. Thus our entity beans have a many-to- Finally, I copy the output .jar file to many, bidirectional relationship. Once I have the classes, I can write the WebLogic applications directory and Additionally, I’ll have two value objects the deployment descriptors. First I write run the Java client. The client creates the that are sent to clients by the facade ejb-jar.xml the same as for any EJB con- UserManager session bean and calls J2EE beans: UserValueObject and Group- tainer. Listing 1 describes a Group–User UserManager to create a User, passing a ValueObjects. The value objects allow relationship. User value object (see Listing 5). Groups clients to cache and use objects multiple Ejb-jar.xml descriptor declares the are created in a similar way. After a times without remote calls. Figure 1 entity beans and relationships, whereas Group is created, I can add a User to it illustrates the classes. the actual mapping-to-storage mecha- with just one call. In Figure 1 the entity beans’ inter- nism is done in the EJB container–spe- faces extend javax.ejb.EJBLocalObject cific deployment descriptors. BEA groupManager.addUserToGroup("alex",
Home "testgroup");
Under the hood, the container inserts a row in the table USER_GROUP A framework is of the greatest that points to tables SYSUSER and SYS- GROUP connecting them. use when an application is able When testing my applications on “ WebLogic 6.1 I used a utility P6Spy avail- to pick and choose those able from Provision6 (www.pro- vision6.com/) to analyze the SQL gener- features that are most important ated by the container. P6Spy driver is configured to log all SQL statements before they get to the real JDBC driver. One thing I’d see from the SQL log is that for every get method called on an AUTHOR BIO and the entity beans’ home interfaces WebLogic 6.1 uses two files for that pur- entity bean, the container generates a Alex Pestrikov, a extend the javax.ejb.EJBLocalHome pose. The first file, weblogic-ejb-jar.xml, SELECT statement. To improve that you programmer for interface. Another important aspect is specifies a persistence descriptor as a can use different concurrent strategy more than five that the value object must implement part of the Weblogic-enterprise-bean” flags in the WebLogic descriptor. For years, has spent the the java.io.Serializable interface for it to element. It also specifies the name of the example, if you set concurrency strategy last three years be sent over the network. second descriptor file where the field to be Exclusive, then the SELECT state- working on Java The entity beans have abstract get mapping is done. Listing 2 shows the ment is issued only once, the first time projects. He and set methods for all fields that complete Weblogic enterprise bean ele- the bean is loaded. The assumption currently writes J2EE need to be persisted. The business ment. here is that all updates are going applications for the logic to create, update, and delete the I specify how the fields are mapped through the bean, so the bean doesn’t Middleware Lab, entity beans resides in the facade ses- to the table columns in the other have to be synchronized with the data- government of sion beans. Here’s how the User WebLogic descriptor, weblogic-cmp- base for every get method. (See Ontario, Canada. Manager bean creates a User in the rdbms-jar.xml. I also specify how the WebLogic documentation for more on Alex holds a degree createUser method: Group–User relationship is mapped to other concurrent strategy flags and in finance and the database through a USER_GROUP entity bean optimization.) computer science InitialContext ctx = new table. Listing 3 shows the relationship Similarly, for every set method on the from the University InitialContext(); portion. entity bean, the container issues an of Bridgeport UserBeanHome home = Once I’ve written the deployment UPDATE statement. The reason is that (Connecticut), and is (UserBeanHome)ctx.lookup("User"); descriptors and implemented the every set method is performed in a new a master’s candidate UserBean bean = beans, I write a build script to build my transaction, and at the end of each trans- in computer science. home.create(user.getUserName()); application. Since EJB applications have action the container commits the data to
16 OCTOBER 2001
Java COM E J B 2 . 0
storage. Again, we can improve that if all Declarative relationships take another For More Information set methods are called in the same trans- step to abstract object developers from 1. EJB 2 Proposed Final Draft 2: action. Since they’re called inside the the database schema. http://java.sun.com/products/ejb/d facade session bean, we can mark the These features of CMP have the ocs.html bean to require a transaction in the ejb- potential to increase the productivity of 2. BEA Weblogic Server Release 6.1 jar.xml deployment descriptor. Further the enterprise application developers. Documentation: http://e-docs.bea.
J2ME optimizations are possible as required by The situation will further improve once com/wls/docs61/index.html a specific application. EJB container vendors create or improve 3. Jakarta Ant Project: http://jakarta. Entity beans separate business logic graphical tools to write deployment apache.org/ant/ from persistence code. Local entity descriptors for CMP and relationships. 4. P6Spy Driver: www.provision6.com beans cover the area of fine-grained For now the example deployment /index.htm objects making necessary syntactical descriptors given in this article can help changes to optimize performance. you get started. [email protected] J2SE Listing 1: ejb-jar.xml
18 OCTOBER 2001
Java COM J2ME J2SE J2EE
As Java technology has matured over the last few years so have we. We’ve learned that building complex enterprise applications that respond to change requires more than standardized APIs and virtual machines. Fortunately, we’re now starting to see the widespread adoption of best practices, patterns, and even frameworks with templates and prebuilt
Home components. This article looks at the MVC design pattern and reviews its implementa- tion in Struts, a presentation-tier application framework, as well as recog- nizing analogies of MVC to a well-formed, EJB-tier framework that Struts can be integrated with. MVC for J2EE Struts is an implementation of the presentation tier using MVC. The Struts controller encapsulates the presentation logic, handling the interac- tion of the JSP pages view with the JavaBeans model, which might access a database through JDBC. When we integrate with a business tier, the recommended pattern is to access a Session Façade or Business Service – analogous to an MVC view. The model could be thought of as our data access objects or entity beans. The model can be queried by the view, but updates occur through the controller, which would then represent our business logic. When we consider the applicability of the MVC pattern to the business tier, it enables us to recognize the separation of responsibilities between the interface, model, and business logic. It demarcates responsibilities across our infrastructure components. We see, for example, how to use different interfaces or views for the same model or controller. Struts Implementation of MVC Struts delivers on its promise of a framework that follows the MVC design pattern by effectively segregating the various components into a small set of extendable classes. Also note the declarative nature of its XML-based action mappings and JSP tags. Figure 1 illustrates the interaction between the key Struts components as they relate to editing user information. Figure 2 illustrates how each major component of Struts maps into the MVC.
The Model The Struts implementation of the Model comes by way of the abstract class, ActionForm. It manages the data required by the View (JSP) and changes its state according to the Controller (Action). In its simplest terms, the ActionForm is a standard JavaBean with getters and setters used to
20 OCTOBER 2001
Java COM J2ME
Client ActionServlet EditUserAction EditUser.jsp UserActionForm SaveUserAction
1:request J2SE
1.1:dispatch 1.1.1:populate
1.1.2:forward
2:submit
2.1:request
2.1.1:dispatch J2EE 2.1.1.2: URIs and how the ActionServlet 2.1.1.1:retrieve UserDelegate should dispatch them. A typical mapping is provided in Listing 4. When the ActionServlet receives the request such as http://my- 2.1.1.3:persist user app/SaveUser.do from the Edit- User.jsp, it understands that its map-
Home ping corresponds to the path attri- Figure 1:Struts sequence diagram bute defined in the XML configura- tion file, and that it should invoke the access its state. It defines no abstract methods, but you have perform method of the SaveUserAction class. The attribute the option of overriding the validate method to perform serv- “name” defines the ActionForm (model) that the action will er-side validation of the application data. receive and the scope attribute defines where the form will be An ActionForm used to maintain data about a user may found (request, session, context). It also defines URI mappings look like Listing 1. that the Action will use to determine where to forward. By keep- ing the application mappings external, the Struts framework The View can be easily modified without recompiling classes. The extensive Struts tag libraries combine to create a Online Business Systems has used the Struts application mechanism of presentation and interaction that allows devel- framework on many successful projects including Viewtrak.com, opers to develop, and designers to design. The JSP will use the an integrated food source management tool that tracks produc- ActionForm (Model) as a means of allowing the client to inter- tion of cattle from producer to consumer. The architect, Curtis act with the application. Linton of Online Business Systems, used Struts as the Web appli- Listing 2 provides an example of a JSP page with Struts tags. cation framework and the Versata Logic Suite for business logic development and management. Example code from this project The Controller has been used in this article, and updated to current versions. Two Struts classes make up the Controller, ActionServlet and Action. Both work in concert to manage the flow of the Business-Tier Pattern Framework application, but have distinct differences. The ActionServlet is Naturally there are many approaches to implementing responsible for mapping URI requests to specific Actions, business-tier design patterns such as developing infrastruc- while the Actions are responsible for interacting with the ture components and business components. Model (ActionForms). First, to develop the business components we should con- The developer extends the Action class to implement logi- sider a declarative approach, a business rules approach. cal units of work that will be invoked by the ActionServlet Barbara von Halle in her book, Building Business Rule Systems, upon receiving a request. Saving user information may be states, “It is no longer desirable to bury rules in specifications part of the SaveUserAction (see Listing 3). and program code where they are locked away, requiring cost- UserDelegate is a class based on the J2EE Business ly intervention and overhead to effect change.” Delegate design pattern. It hides the implementation of the Second, we need to pay careful attention to J2EE best prac- business-tier’s view of the model and will be explained in tices to avoid those performance pitfalls we’ve read about: too detail later in this article. The important thing to note is how many fine-grained entity beans, caching, use of CMP, and so on. the Struts model interacts with the business-tier’s view – the action is the bridge that joins the two. Business-Tier Design Pattern Framework The ActionServlet is made aware of the URI to Action map- Figure 3 illustrates a well-formed design pattern frame- pings via an XML configuration file. This file describes request work for the business tier.
22 OCTOBER 2001
Java COM Home J2EE J2SE J2ME 24 O Figure 2: Struts mapsintotheMVC Struts Figure 2: CTOBER View State Query 2001 JSP perhaps through SOAPperhaps toa Web service. be through RMItoanEJB, through messaging withJMS,or actual businessfunctionalitytothe outsideworld. This could Business Service presentation-tier MVC pattern. onthebusinesstier. pattern Service remote methodinvocationandinteraction withtheBusiness Business Delegate (presentation tier)andJava (clienttier) Web applications. themodel-baseddevelopmentofHTMLservlet which supports alsoincludestheoptional Server Versata Presentation Engine, that follows below. we describe thepatterns The Versata Logic or through the Versata thatincludesthe framework LogicServer JavaBeansEnterprise through the Versata Transaction LogicEngine deployment descriptors, andtestdatascripts. as well asdeployment artifacts, suchasdatabaseschemas, ty andsessionbeans),dataaccessobjects, are produced value objects, value objectassemblers, businessobjects(enti- fications, especiallybusinessrules. Java artifacts, suchas built withthe Versata LogicStudio from business-logicspeci- nance. ate andsimplifybusinesslogicdevelopmentmainte- leverage andhow andimplementthesepatterns theyacceler- we’ll alsolookathow products withinthe Versata LogicSuite ofthecoreterms J2EEdesignpatterns. Using thisframework, As an interface intoourbusinesslogicwe wouldconsider As aninterface The Business isthecomponent that presents Service the The Business represents Delegate pattern theModel ofour Business Delegates withinthepresentation tierhidethe The businesscomponentsmaybeaccessedasregular Within the Versata LogicSuite, businesscomponentsare What follows framework isadiscussionofthispattern in Change Notification Model View S electio Ac t i n o User Gestures nF o r m Controller State Change Dispatch Action Action cially foraccessing large setsofdata. The value objectwillpull optimization, espe- asaperformance times seethispattern only accessingthe controller forupdates. In fact,we some- objects wouldaccessthemodel directly state, for querying tions, sotheywouldbeequivalent toaviewcomponent. Object Assemblerstypicallyare opera- involvedonlyinquery business objects. Assembler thatbuildsandaggregates themfrom underlying Value Object Assembler models.senting internal re-pre-itself totheoutsideworldasopposednecessarily create value objectsthatrepresent how asystempresents pendent, notencapsulatebusinesslogic. We should lookto view. This suggeststousthattheyshouldbemodel-inde- objects. data value objectsaccessedsomewhatlikejavax.sql.RowSet across differenttributed businessobjects. They’re alsometa- forcompositeobjects–updatesmaybedis- This isalsotrue Business Service, suchasupdate, create, delete, andrefresh. behavior thatallows themtointeract directly with the by default. tionships. Value objectsare alsocreated foreachentityobject and creating compositeobjectsby joiningacross objectrela- butes tobeselectedfrom objectsintheentityobjectmodel, declaratively through the Versata LogicStudio, allowing attri- retrieve orupdateasetofrelated data. allowingbe serialized, theclienttomakeoneRMIcall S ervlet If we were more faithfulto the MVC theview pattern, Would thiscomponent beavieworcontroller? Value Value objectsare by atruntime supported the Value Object Considering theMVC value objects represent pattern, the These value objectsare alsoupdatable, encapsulating The Versata Suite enablesvalue objectstobecreated an encapsulationofbusinessdatathatcan approach isexpensive. A “value object” is methods, inpractice thisconversational getterandsetter via RMIcallstoattribute Value Objects nents ofourMVC-like pattern. Business oneofthe Service compo- View While aclientmayaccessEJBsdirectly J ava COM Home J2EE J2SE J2ME 26 O
CTOBER Delegate Business
2001 Tier Presentation term term entity beans, anddependentobject JavaBeans. We usethe applications, thesecomponentswill usuallybesessionbeans, late thebusinesslogicofour system. For J2EEenterprise Business Objects MVC-like business-tierpattern. ing hand-codedBMP. great withoutrequir- dealofflexibilityandhighperformance size, connectionpooling,andlockisolationlevels, givinga to useprepared statements, theprepared statementcache- the datasource andtuneoptions, atruntime suchas whether and transaction requirements. The administrator canchange configurationbased onobjectmetadata,runtime properties, the dataaccesslayer. Access objectsare created atruntime sources ranging from DB2toCICS. Access Builder allows you tocreate dataaccessobjectsfor example isIBM’s for JavaVisualAge (VAJ). VAJ’s Enterprise same API nomatterwhere thedataiscomingfrom. business objects. This allows thebusinessobjectstouse encapsulation ofthedatabetween thedatasource andthe example. anabstraction Data accessobjectsform layer andan sources, SQLdatabases, andlegacysystems, LDAPservers, for Object Data Access whether businesslogicneedstobeexecuted. retrieve datastraight backfrom thedataaccessobjector areattributes persistedorcalculated,itinferswhethercan operations whenithasto.objects forquery Since itknows The Versata Value ObjectAssemblerinstantiatesonlybusiness the needtoinstantiateanentitybeanforeachobjectinstance. data straight from thedataaccessobjectorJDBC,alleviating The componentsoftheBusiness encapsu- Objectpattern Data accessobjectsclearlyrepresent theModel ofour The Versata hasapowerful LogicServer implementationof You dataaccessobjects or usetools. canwrite Agood applicationsneedto access datafrom multiple Enterprise Our implementationusesthisoptimizationtransparently. Business business objects Business Tier Service Figure 3 Well-formed framework forthebusinesstier designpattern Object Value to describe these.to describe rec-The J2EEpattern Value Object Assembler Business Objects Data Access Object the data (the model) and from business services (the view). the data(themodel)andfrom businessservices objects handlebusinesslogic,providing acleanseparation from vides thepresentation logic. For thebusinesstier, thebusiness troller. Recall thatforthepresentation tier, thecontroller pro- sents. We prefer thinkingaboutbusinessobjectsasthecon- is. In awaythoughthat’s whatthewholebusinesstierrepre- representationof themodel,intrinsic ofwhatthebusiness to themodelorcontroller? You couldargue thatthey’re part 98–99% oftheJava componentbuiltdirectly from rules. class oraddcodetoJava components. We typicallyseeabout might beentered directly orusedtosub- into businessrules nents. Typically somecustomJava codingisrequired, which intothebusiness objects–theJavabusiness rules compo- optimizes, andtranslates thesespecificationsorwhatwe call business objectsfrom specifications. The systemsequences, ed transaction managementandpersistence, forexample. forcoordinat- andusetheservices the J2EEapplicationserver oftheData Accesspart Objectpattern. objects orJDBChelpers. For ourframework thesewould be ognizes thatbusinessobjectscould alsobedataaccess procedural approach, codetoupdatethe we couldthenwrite ance istotalbilled invoiceslesspaymentsreceived. Taking a Automation ofBusinessRules definitions asdeclarative approaches. today. We’ve also seentheStruts actionmappingsandview ships; somethingyou havetomanageprogrammatically adding declarative forcontainer-managed support relation- sistence managedby thecontainer. by EJB2.0goesfurther ment descriptor, specifyingwhatfieldsshouldhavetheirper- letting thesystemwork outthebestwayofdoingit. – justsaying the stepsof there’s amove awayfrom procedural programming –coding What NotHow –Declarative NotProcedural Declarative BusinessLogic Looking attheMVC patterns, wouldbusinessobjectsbeakin The Versata LogicSuite theautomatedcreation supports of The businessobjectsoperate withintheEJBcontainerof Consider thebusinessrequirement thattheaccount bal- An exampleofdeclarative programming istheEJBdeploy- As elaborated by C.J.Date inhisbook, how what we accomplishsomething–tothedeclarative we wanttoaccomplishinthefirstplaceand J ava What Not How COM , Home J2EE J2SE J2ME 28 FIGURE 4 O CTOBER Business RulesDesigner Constraints 2001 .Total Payments=sum (Payment.Total where3. PaymentStatus Total Billed=sum (Invoice.TotalFee2. where InvoiceStatus Account Balance=Total Billed–Total Payments 1. another, butonlyiftheinvoicehasbeenbilled. changes? You needtosubtract from oneaccountandaddto procedural approach. What aboutwhentheinvoice’s account We needtobeconsciousofanumbersideeffects witha deleting apayment? What aboutwhenapaymentbounces? What aboutacancelledinvoicethat’s reinstated? What about invoice issentout. What aboutwhenaninvoiceiscancelled? timeapaymentisreceivedaccount balanceevery oran • business rules. Some approach oftheadvantages are: ofarules that businessanalystsquicklyidentifywith.Afterall,they’re world,andone easier shiftthanwe madetotheobject-oriented procedural tothedeclarative isrequired. Fortunately, it’s an Business RulesParadigm Shift count. areplicate,grid: acalculation,default,twosums, anda Billed sumrule. Additional typescanbeseeninthe derivation the Account businessobject, providing detailfrom the Total- other attributes. Figure 5shows for several rules derivation derivation rules shows constraints fortheCustomer object. sent thepoliciesunderwhichabusinesscanoperate. Figure 4 of anaccount. of TotalFinalFee ofaninvoiceandtheimpacton TotalBilled implements logictodealwithachangeintheInvoiceStatus Logic Suite asitappearsintheInvoice object. The code provides ofthecodebuiltusing asmallportion Versata across theAccount, Invoice, andPayment objects. Listing5 side effects, require theserules over 300linesofJava code =“Active”) =“Billed”) Business logic isnothiddenincode: These are called Declaratively we mightexpress thislogicas: To aparadigm developwithbusinessrules shiftfrom the In we callthesecalculations terminology businessrules Constraints are theyrepre- anothertypeofbusinessrule; – the attribute definitionsare– theattribute from derived business rules FIGURE 5 Business RulesDesigner – Derivations . Taking intoaccountall Business canbe rules 8. 7. Geary, D.M. (2001). 6. Sucharitakul, A.(2001). “Seven Rules forOptimizing Entity 5. Alur, D., J.,andMalks, Crupi, D. (2001). 4. vonHalle, B. (2001). 3. 2. Date, C.J.(2000). 1. References not how. from specifications,driven notcode–moving toward what ment we alsosawhow changeisenabledthrough systems work andthe Versata LogicSuite forbusinesslogicdevelop- components. Through thediscussionofStruts frame- a cleardelineationofwork todevelopersandinfrastructure canalsoguideuswithinthebusinesstier,pattern providing Although typicallyappliedatthepresentation tier, theMVC defined butlooselycoupledcomponents, enablingchange. powerful abstraction totheJ2EEarchitect, creating well Summary • • • est,Inc.: Versata, Struts: nicalAr Beans.” nessr The originalGUIDEpaperandcontinuingwork: Hall. PracticesBest Strategies andDesign Wiley &Sons, Inc. Approach toApplication Development quickly productive withJ2EEtechnology. Enables newJava developers whoknow thebusinesstobe ment andmaintenance. ofbusinesslogicdevelop- gration, notonthesupervision J2EE architects canconcentrate oninfrastructure andinte- Naturally separates business logicfrom presentation logic: reduced. automatically. The testingcycle isalsosignificantly as thesystemtranslates specificationsintoprocedural code signed-off by businessuserswithnoimplementationerrors Reduces errors: ably modified. quickly foundandunderstoodthusspeedilyreli- The Model-View-Controller continuestooffera pattern ulesgr http://jakar ticles/ebeans/sev http://dev oup www .or Business canbeunderstoodand rules g .v www ta.apache ersata.com htNtHw TheBusiness Rules What Not How: eloper Advanced JavaServerAdvanced Pages Building Business Rule Systems .buildingbusinessr enr J .jav ava ules/ .or a.sun.com/dev g/str . May. . Prentice Hall. uts . Addison-Wesley. Core J2EEPatterns: ulesystems eloper/tech- www . Prentice . John .com .busi COM - Home J2EE J2SE J2ME 30 .. ..
HttpServletRequest req) J2ME Core J2EE Patterns J2SE Presentation tier patterns and refactoring J2EE atterns are expert solutions – recurring designs that have WRITTEN BY P proven effective over time. This month’s article will provide you DAN MALKS with a bit more detail on the subject. When applying patterns to the Catalog. The patterns and their tier cessing and postprocessing a Web presentation tier, we address the fol- categorizations are shown in Table 1. request. Here are some common lowing: Because of the focus of this column, examples of preprocessing: Home • Pre- and postprocessing of a request we’ll describe just one of the presenta- • Decrypting an input stream: The and/or response tion patterns in detail. First I want to incoming data may have been • Request handling, navigation, and provide some context on how the encrypted for security purposes. dispatch presentation tier patterns fit within a • Decompressing a stream: The • View preparation and creation common J2EE architecture, starting incoming stream may have been • Application partitioning with a basic description of a system. compressed for more efficient When a client makes a Web request transfer over the network. In other words, how do we handle for a particular resource, the request is • Translating various encoding a Web request, managing any neces- processed, a view is generated, and a schemes to a common format: sary data access and generating pres- result is returned to the client. To provide Multiple encoding schemes require entation content for the user? How more detail, we can define several logical different handling. If each encoding might we transform the incoming or components and subcomponents of a is translated to a common format, outgoing stream? How do we deter- typical Web-based architecture: the core request-handling mecha- mine what processing to perform to • Request handler: nism can treat every request simi- fulfill this request? What view should – Pre- and postprocessing be used to service the request and – Request processing TIER PATTERN NAME how do we generate it? What are the – Command processing Presentation Tier Intercepting Filter logical abstractions and how do we • Navigation and dispatch: Front Controller design and decompose our software – Navigation resolution View Helper to take advantage of these abstrac- – Request dispatching Composite View tions? • View processor: Service to Worker Six presentation tier patterns are – View preparation Dispatcher View documented in the Core J2EE Patterns – View creation Business Tier Business Delegate Every other month in this column we These components and subcom- Value Object (Deepak Alur, John Crupi, Dan Malks, and other ponents are shown visually in Figure Session Facade architects from the Sun Java Center 1. Let’s have a look at the Intercepting Composite Entity (www.sun.com/service/sunps/jdc) will discuss Filter pattern, which addresses issues Value Object Assembler various topics from our book, Core J2EE Patterns: in the request-handling portion of the Value List Handler Best Practices and Strategies (Alur, Crupi, Malks, architecture, as outlined above and in Service Locator Prentice Hall/Sun Press 2001). These topics the figure. include the 15 J2EE patterns in our catalog, Integration Tier Data Access Object design strategies, bad practices, refactorings, Intercepting Filter Service Activator and pattern-driven design in J2EE technology. The Intercepting Filter pattern documents issues relating to prepro- TABLE 1 J2EE Patterns by tier 32 OCTOBER 2001 Java COM P A T T E R N S either in a filter or as part of the providing pluggable behavior that can core processing flow, typically as be used to decorate core request pro- part of the controller. cessing. Another benefit of using this pattern is that it promotes the reuse of What constitutes postprocess- these various filtering components ing of a request? Here are some across different requests, in different J2ME common examples: combinations, and even in different • Encrypting an output stream: applications. The outgoing data may be There are several implementation encrypted for security purposes. strategies for this pattern, the most • Compressing a stream: The out- powerful of which leverages the stan- going stream may be com- dard filtering supported in the Servlet pressed for more efficient trans- specification 2.3. Vendor support for fer over the network. this revision of the specification will J2SE • Transformation of data for dif- be widespread in the not too distant ferent clients: Transformation future. into HTML, XML, or WML. Listings 1 and 2 are excerpts from Additionally, one of the forces the Standard Filter Strategy code that motivates us to consider this example in the book. The example J2EE The fact is that wherever there is FIGURE 1 Request-handling architecture “coding, there may be refactoring Home pattern is the desire to add and describes using filters to preprocess remove these processing compo- requests, checking their encoding nents independently – independ- schemes, and translating these differ- ent of other filtering components ent schemes to a common” format. and of the underlying core process- The common format is to store all ing that fulfills the client’s request. request states within request attri- Let’s look at the class diagram butes. Subsequently, any control code (see Figure 2) that describes this that checks for incoming values will FIGURE 2 Intercepting Filter class diagram pattern’s structure. In the figure get these values from request attri- the actual resource that is the tar- butes, regardless of the original get of the client request, such as a encoding. servlet or JavaServer Page technol- Figure 3 is the sequence diagram ogy, is represented by the Target that shows the basic collaboration of class. The individual pre- or post- the objects in the example. Note that processing components that per- in this implementation the role of the form filtering functionality, as FilterManager from the class diagram described above, are shown as is fulfilled by the Container in the Filter One, Filter Two, and Filter sequence diagram. We hope this pro- Three. One important thing to vides you with a basic understanding notice in this diagram is that of the benefits and some implement- there’s no direct association ing options for the Intercepting Filter between any of the filters and the pattern. target resource. Additionally, there’s no direct association from Refactoring any filter to one of the other filters. There’s more than one way to FIGURE 3 Filter sequence diagram This is an important point, approach any task. This is as true with since it clarifies that the filters are software development as with any- larly. Some common examples of loosely coupled both to the target thing else. So when I tell you that peo- encoding schemes are: resource and to other filters. This ple approach the task of developing – application/x-www-form-urlencoded allows the filters to be easily added software in different ways, you cer- – multipart/form-data and removed unobtrusively, as men- tainly won’t be surprised. Some folks • Performing authentication or tioned. feel that most design work should pre- authorization: Authentication and Filters are an excellent way to cede implementation, while others authorization may be performed layer functionality onto your system, like to jump in, write some code, and 34 OCTOBER 2001 Java COM P A T T E R N S PRESENTATION TIER REFACTORINGS of a J2EE technology-based Introduce a controller system and the relevant steps Introduce synchronizer token involved. The format and style Localize disparate logic is based on that in Fowler’s Hide presentation tier-specific details from the business tier book, which we find extremely PUBLISHER,PRESIDENT,AND CEO Remove conversions from view valuable. Based on Fowler and FUAT A. KIRCAALI [email protected] J2ME Hide resource from a client Beck’s definition, the J2EE ADVERTISING SENIOR VICE PRESIDENT,SALES AND MARKETING refactorings included in our CARMEN GONZALEZ [email protected] BUSINESS AND INTEGRATION TIER REFACTORINGS book might be called “medium VICE PRESIDENT,SALES AND MARKETING Wrap entities with session refactorings” based on their MILES SILVERMAN [email protected] Introduce business delegate level of abstraction. The refac- ADVERTISING SALES DIRECTOR ROBYN FORMA [email protected] Merge session beans torings are listed in Table 2, cat- ADVERTISING ACCOUNT MANAGER Eliminate inter-entity bean communication egorized by tier. MEGAN RING [email protected] Move business logic to session We find these refactor- ASSOCIATE SALES MANAGER J2SE ings to be excellent com- CARRIE GEBERT [email protected] GENERAL REFACTORINGS SALES ASSISTANT panions to the patterns and ALISA CATALANO [email protected] Separate data access code bad practices described in EDITORIAL Refactor architecture by tiers the rest of our book. In fact, EXECUTIVE EDITOR Use a connection pool you can think about the M’LOU PINKHAM [email protected] refactorings as often provid- EDITOR TABLE 2 Refactorings ing the steps that help guide NANCY VALENTINE [email protected] MANAGING EDITOR the developer from a less opti- CHERYL VAN SISE [email protected] start to think about how these bits of mal solution, or bad practice, to a ASSOCIATE EDITOR J2EE implementation fit together. The dif- more optimal one, suggested by a pat- JAMIE MATUSOW [email protected] ference is basically that of top-down tern. ASSOCIATE EDITOR GAIL SCHULTZ [email protected] design versus bottom-up design. In a future article we’ll provide ASSOCIATE EDITOR Refactoring applies to either more information on these refactor- BRENDA GREENE [email protected] approach, though it’s typically applied ings and their relationship to the pat- ASSISTANT EDITOR in an environment where there is an terns in the catalog. We’ll also go into LIN GOETZ [email protected] understanding that design is spread greater detail on the presentation, PRODUCTION VICE PRESIDENT,PRODUCTION AND DESIGN Home across the life of the project. That said, business, and integration tiers, as well JIM MORGAN [email protected] the fact is that wherever there is cod- as communication across these tiers. ART DIRECTOR ing, there may be refactoring. Martin Thank you for reading, and please e- ALEX BOTERO [email protected] ASSOCIATE ART DIRECTOR Fowler, in his great book Refactoring: mail us at [email protected] LOUIS F. CUFFARI [email protected] Improving the Design of Existing Code to provide feedback on this article and ASSISTANT ART DIRECTOR (Addison-Wesley), describes refactor- to suggest other topics of interest. CATHRYN BURAK [email protected] ing as “improving the design of the GRAPHIC DESIGNER ABRAHAM ADDO [email protected] code after it has been written.” His AUTHOR BIO GRAPHIC DESIGNER book identifies many common design Dan Malks, a senior Java architect with Sun Microsystems, is RICHARD SILVERBERG [email protected] flaws and describes the incremental currently focusing on distributed, service-based designs, GRAPHIC DESIGNER AARATHI VENKATARAMAN [email protected] coding changes that result in improved patterns, and implementations. He has developed in a variety WEB SERVICES of environments, including Smalltalk and Java, while focusing design. The issues are typically general WEBMASTER and not specific to any particular area on OO technologies. Dan has published articles on Java in ROBERT DIAMOND [email protected] of Java or software development. leading industry periodicals, and holds bachelor’s and master’s WEB DESIGNER The lion’s share of Fowler’s degrees in computer science. STEPHEN KILMURRAY [email protected] book is devoted to what WEB DESIGNER Copyright 2001 Sun Microsystems, Inc. All Rights PURVA DAVE [email protected] he calls “small refac- Portions of Reserved. Sun, Sun Microsystems, the Sun logo, WEB DESIGNER INTERN torings,” meaning this article contain Java, J2EE, Java Center, and JavaServer Pages CAROL AUSLANDER [email protected] are trademarks or registered trademarks of the design changes excerpts with permission from Sun Microsystems, Inc., in the United States A CCOUNTING are at a very low Core J2EE Patterns by Deepak Alur, and other countries. Sun Microsystems, CHIEF FINANCIAL OFFICER Inc., may have intellectual property rights BRUCE KANNER [email protected] level, each involv- John Crupi, and Dan Malks (ISBN 0- relating to implementations of the tech- ASSISTANT CONTROLLER ing several dis- 13-064884-1) Copyright 2001. Sun nology described in this article, and no JUDITH CALNAN [email protected] license of any kind is given here. Please crete coding mod- Microsystems, Inc. ACCOUNTS RECEIVABLE visit www.sun.com/software/communi- JAN BRAIDECH [email protected] ifications, such as tysource/ for licensing information. adding a parameter The information in this article SYS-CON EVENTS (the “information”) is provided “as is,” for VICE PRESIDENT,SYS-CON EVENTS to a method. A small discussion purposes only. All express or CATHY WALTERS [email protected] portion of the book, implied conditions, representations, and war- ranties, including any implied warranty of mer- CONFERENCE MANAGER coauthored by Kent Beck, chantability, fitness for a particular purpose, or non- MICHAEL LYNCH [email protected] is devoted to “big refactorings,” infringement, are disclaimed, except to the extent that such dis- SALES EXECUTIVE,EXHIBITS claimers are held to be legally invalid. Neither Sun nor the authors MICHAEL PESICK [email protected] which exist at a higher level of make any representations, warranties, or guaranties as to the SALES EXECUTIVE,EXHIBITS abstraction and have steps that aren’t quality, suitability, truth, accuracy, or completeness of the infor- RICHARD ANDERSON [email protected] as well defined or as concrete. mation. Neither Sun nor the authors shall be liable for any dam- SHOW ASSISTANT ages suffered as a result of using, modifying, contributing, copy- NIKI PANAGOPOULOS [email protected] In our book we include some J2EE ing, or distributing the information. JDJSTORE.COM technology–specific refactorings, describ- ANTHONY D. SPITZER [email protected] ing opportunities to improve the design [email protected] 36 OCTOBER 2001 Java COM filterChain) Listing 1: Intercpting Filter Implementation Example: Standard Encode Filter throws java.io.IOException, public class StandardEncodeFilter javax.servlet.ServletException { extends BaseEncodeFilter { String contentType = // Creates new StandardEncodeFilter servletRequest.getContentType(); public StandardEncodeFilter() {} // Only filter this request if it is multipart // encoding public void doFilter(javax.servlet.ServletRequest if (contentType.startsWith("multipart/form-data")){ try { servletRequest,javax.servlet.ServletResponse String uploadFolder = servletResponse,javax.servlet.FilterChain getFilterConfig().getInitParameter("UploadFolder"); J2ME filterChain) throws java.io.IOException, javax.servlet.ServletException { if (uploadFolder == null) uploadFolder = "."; String contentType = /** The MultipartRequest class is: servletRequest.getContentType(); * Copyright (C) 2001 by Jason Hunter if ((contentType == null) || * 38 OCTOBER 2001 Java COM PRODUCT REVIEW espite the “slowdown” in technolo- ured properly before you can connect to the by MKS gy, the developers and project man- server. MKS offers both “named user” and Dagers who I speak with continue to “floating” licenses for SIE 8.1, which is a plus, be under enormous pressure to deliver new but I’m not a big fan of FlexLM as a license applications and technology at a frenetic manager. pace. It can be incredibly difficult to juggle Once you get the server installed the real J2ME all the various development tasks when fun begins. SIE 8.1 is loaded with features and team members are working on multiple functions for source code control and securi- projects. ty. I can’t imagine any configuration that SIE Source Developers often find themselves would not be able to support with its vast working with different teams for each array of functions. For example, the server autonomous project – and each project provides for five different security-realm con- is often at a different stage of the project figurations (Unix, NT, LDAP, flat file, and development life cycle. This combina- WebLogic Server). However, configuring the J2SE tion is a breeding ground for all sorts of security realm requires you to edit a series of disasters including lost code, recurring property files and manually restart the server Integrity bugs, missed deadlines, and question- using the Windows NT Services Manager. able product quality. An important line (There’s no GUI server manager.) This is typi- of defense for project managers, devel- cal of IM and SIE in general. The products are opers, and quality-assurance engineers loaded with functionality, but it can be diffi- Enterprise Edition 8.1 alike is a source-code control system. cult to figure out just how to implement a cer- For large, geographically dispersed tain feature or function. In all fairness, the project teams, MKS Source Integrity client installation goes much smoother, since J2EE Enterprise Edition 8.1 might just be the there’s very little configuration that you need REVIEWED BY JIM MILBERY perfect solution. to worry about once you have the server up MKS has been in the source code and running. [email protected] integrity business since 1984. SIE 8.1 represents the very latest version of Working with IM and SIE their source code management product MKS provides a Java client application that line, and it integrates with MKS Integrity you can use to connect to the Integrity Server. Home Manager 4.2 to tie in source code control When you install the client interface it auto- with defect tracking and workflow man- agement. SIE 8.1 uses a completely new architecture that is based on an applica- specs MKS Inc. tion server layer. Users can connect to the 410 Albert St. server using a Java-based client/server application and to IM through a thin-client Waterloo, ON browser-based interface. Canada, N2L 3V3 Phone: 519 884-2251 Installing and Configuring SIE 8.1 Fax: 519 884-8861 MKS ships the software on two separate CDs – one for the Integrity Server and one for Phone: 800 265-2797 the client installation. I tested SIE on a e-mail: [email protected] Windows 2000 server, but SIE Web: www.mks.com supports a variety of different server platforms including Test Platform Linux, Solaris, and HP-UX. SIE Toshiba Satellite Pro 4600, uses a database to store security 866MHz Intel Pentium III and change package data. But the real repository data (projects processor, 20GB Disk, 256MB and archives) is stored on the of Memory, Windows 2000 w/ filesystem. The current release Service Pack 2 supports Oracle, Microsoft SQL Server, and PointBase as the Specifications database. Platforms: Windows NT/2000, I used the built-in PointBase 98/95, Linux, Solaris, HP-UX, database as the repository and followed the simple Install- and AIX Anywhere instructions to install Pricing: SIE Server is $4,000, Integrity Server. The installation SIE Client License is $750 per is simple, but you may run into a named user, IM Client License problem with the FlexLM license manager. MKS ships out is $750 per named user a license file with the software, and you’ll need to get the FlexLM license manager config- 40 OCTOBER 2001 Java COM PRODUCT REVIEW highly distributed teams (including teams that might include contractors who are working off- site). by MKS by Once you connect to a server, you’ll be work- J2ME ing with three basic source code objects: proj- ects, sandboxes, and members. A project is a group of related files (source code, design spec- ifications, graphic images, Web pages, etc.). As a developer, you’ll work with project files through an interface known as sandbox. Through the sandbox you can add new members, which are the individual program files that make up your J2SE project. I was able to add Java source files and Jtest project test files to my local sandbox, and then synchronize the whole lot back into my project. SIE provides a wealth of security fea- tures and management functions for managing projects including lock management, check- in/out procedures, and revision tools. Source Integrity Enterprise Edition 8.1 Enterprise Integrity Source One of the more powerful features of the FIGURE 1 Source Integrity Manager Java client MKS product line is its ability to integrate source J2EE code control with defect tracking through Integrity Manager. Integrity Manager provides tools for tracking defects, builds, and enhance- ments through a powerful workflow layer. IM works with the “change packages” that are creat- ed within SIE. For example, a change package can be associated with a group of Java source Home files, and IM can associate this same change package with a defect report. Thus project man- agers and customer service teams can track problem resolution all the way back to individ- ual source modules. Team members can access the Integrity Manager database through a Java client inter- face, or they can use a standard Web browser as shown in Figure 2. The combination of SIE 8.1 and the Integrity Manager provides a complete environment for managing source code and tracking defect resolution. Summary FIGURE 2 MKS Integrity Manager Web interface I found MKS Source Integrity Enterprise Edition 8.1 to be a very powerful and comprehensive source- matically detects the various IDEs you may have installed. SIE code control solution. SIE 8.1 is clearly the “Cadillac” in its supports many of the popular IDEs, but I noticed that it didn’t product category and I believe that teams of enterprise devel- always support the most recent versions. For example, SIE opers will find it to be a compelling solution. Geographically supports Borland’s JBuilder 3.0 Java IDE, but it failed to detect dispersed teams will find the remote-access features to be par- the JBuilder 4.0 or 5.0 releases I had installed on my desktop. ticularly enticing, though smaller development teams and However, it will support JBuilder 5.0 by the end of the year. workgroup developers may find SEI 8.1 to be overkill for their One of the advantages of SIE is that it does support a com- needs. However, MKS also offers Source Integrity Standard mand-line interface as well as the more familiar GUI. Thus Edition for smaller, localized development teams. you can easily create command scripts to work with SIE from your own development environment as necessary. The GUI JDJ Product Snapshot interface is useful to get the gist of the SIE environment (see • Target Audience: Project managers, Q/A team, program- Figure 1). mers The SIE client connects to the server using WebLogic’s pro- • Level: Advanced developer prietary protocol. I was able to connect from my laptop to the • Pros: Feature-rich product, support for client/server and newly installed Integrity Server that was running on a separate Web interfaces, workflow integration with Integrity machine. However, MKS also allows you to connect to a Manager 4.2, integration with popular development IDEs, remote server with SIE. Using the list of sample users and the flexible licensing policy, and command line interface demonstration password (from the MKS Web site) I connected • Cons: Complex server configuration, overwhelming feature through my NetScreen firewall to an SIE server that was run- set, can be expensive: IM and SIE together are $1,400 per ning on MKS’s remote site. This feature makes SIE ideal for named user 42 OCTOBER 2001 Java COM PORTABILITY TIPS Build toSpec! J2ME Part 2 Avoiding pitfalls in the Application Portability Series J2SE While J2EE technology is designed to support portabil- ity, it’s always possible to write nonportable code. In Part 2 of this series, we (the BluePrints development team) offer recommenda- WRITTEN BY tions on how to avoid specific design, implementation, and deploy- LIZ BLAIR ment pitfalls that can compromise portability. A comprehensive collection of the Web application, relative to the server’s that requests can be clearly channeled J2EE BluePrints application program- base URL. For example, if your server’s to the appropriate application Web J2EE ming model can be found at base URL is http://j2eeserver.com:8000 page. http://java.sun.com/j2ee/blueprints. and the context root is apps/myapp, This month, our recommendations then all components of the Web applica- Store Enterprise Bean Handles or Remote are: tion will be accessed relative to References in HttpSession • Deploy each Web application with a http://j2eeserver.com:8000/apps/myap It’s perfectly legal to store either han- unique context root to avoid colliding p. The Home • Use handles or remote object refer- tor (web.xml) specifies the application Every enterprise bean remote refer- ences to store session state in context root. ence extends EJBObject. A remote refer- HttpSession. Server behavior can be unpre- ence’s method EJBObject.getHandle() • Be aware of changes in taglib DTD dictable if two applications are deployed returns a handle, which is a persistable from J2EE 1.2 (JSP 1.1) to J2EE 1.3 (JSP to the same context root since it isn’t reference to the object. A handle can be 1.2). clear which application should receive serialized and persisted, and then at • Always import all classes used in a JSP. an incoming request. Servers and some later time deserialized and con- • Never throw resource-specific excep- deployment tools will differ in how they verted back into a remote reference to tions from BMP code. handle context root collisions. A good the original bean (if the bean still • Wrap authentication code in helper deployment tool will detect context root exists). classes. collisions at deployment time and allow Some application developers believe • Always completely specify security the deployer to choose a different con- that a handle is the only way to store a roles. text root. Selecting a unique context root reference to an enterprise bean in • Uses of EJBContext.getCallerPrincipal for every application will prevent this HttpSession, but this isn’t the case. In ().getName(). problem from ever occurring. For exam- fact, an enterprise bean reference ple: (acquired from a home interface create Unique Context Roots or finder method) can be stored directly Always specify a unique context root App1.ear: war_runtime.xml in HttpSession without first converting for every Web application you deploy to 44 OCTOBER 2001 ” Java COM mat. The TLD file DTD has changed tions (such as SQLException) from BMP errors with subclasses of Ac- from J2EE 1.2 (using JSP 1.1) to J2EE 1.3 code; instead, they should define and countDAOAppException (such as Ac- (JSP 1.2 ). use application exceptions to report countDAODBUpdateException). An Here’s an excerpt from a JSP 1.1 persistence errors. application-level exception is typically taglib.tld file: Bean providers should be especially thrown when a recoverable error has careful to avoid including back-end occurred, such as an incorrect user J2ME 46 OCTOBER 2001 JJavaava COMCOM PORTABILITY TIPS port the application or change your user Define Method Permissions When authentication mechanism. The J2EE platform’s Security Roles Are Used in EJBs long-term expectations are that developers If your application uses security roles, won’t be writing authentication functionality always specify method permissions with the directly into their applications; however, devel- OCTOBER 2001 47 Java COM PORTABILITY TIPS In short, the call itself is portable but Listing 1 the return value isn’t. public class AccountDAOImpl implements AccountDAO { One portable example might be sim- ply as a display value in the Web tier, for public void remove(String id) throws AccountDAODBUpdateException, example: AccountDAOSysException { J2ME deleteAccount(id); "Hello <%= } request.getUserPrincipal().getName( ) %>" private void deleteAccount (String userId) throws AccountDAODBUpdateException, AccountDAOSysException { Another possibility is as a log mes- String queryStr = "DELETE FROM Æ"; sage in the EJB tier for auditing, for PreparedStatement stmt = null; example: J2SE Debug.println("queryString is: "+ queryStr); "8:15 AM: User " + try { ejbContext.getCallerPrincipal().get getDBConnection(); Name() + " withdrew money." //stmt = dbConnection.createStatement(); //int resultCount = stmt.executeUpdate(queryStr); Until the return values are standard- stmt = createPreparedStatement(dbConnection, queryStr); ized from this API, its use to produce int resultCount = stmt.executeUpdate(); values that must be compatible with val- ues that may be produced by other con- if (resultCount != 1) J2EE tainer vendors isn’t a recommended throw new AccountDAODBUpdateException ("ERROR deleteing account from ACCOUNT_TABLE!! resultCount = portability practice. Look for this item "+ to be addressed in future versions of the resultCount); J2EE platform specification. } catch(SQLException se) { throw new AccountDAOSysException("SQLException while removing " We Want to Hear from You + The J2EE BluePrints team is interest- "account; id = " + userId + " :\n" + se); Home ed in hearing about your experiences } finally { developing applications for the J2EE closeStatement(stmt); platform and your experiences with closeConnection(); BluePrints. Send feedback and com- } ments to j2eeblueprintsinterest@sun. } com. Special thanks goes to the J2EE } development community for their con- Listing 2 tinued commitment to the J2EE plat- 48 OCTOBER 2001 Java COM J2SESE GUGUEST EDITORIALOR J2SE INDEXX J2ME Calls and J2SE Swings What will the next few years 50 bring for Java? by George Grey WRITTEN BY GEORGE GREY Using the Façade Pattern for the Java Internationalization API 52 J2ME Calls and J2SE Swings Produce globally enabled software ava has come a long way in its short life. CLDC offers a viable platform for devices by David Gallardo J2SE Linux just celebrated its 10-year with processor speeds around 50MHz, and Janniversary; for Java that milestone is memory footprints well under 1MB. Product Review still more than three years away. Who real- For more powerful wireless appliances, JBuilder 5 from Borland ly understood, seven years ago, that Java there are many options: accelerated Software Corporation would become the standard platform for PersonalJava and J2ME CDC JVM tech- We, as a community of Java 62 delivering content over the Internet and nologies for Windows CE, Palm OS, Wind developers, must applaud for running applications on mobile River, and others; various flavors of Java on and commend some of the phones – even the de facto platform for various flavors of Linux; and now a full available tools Borland offers future smart-card technology? And what J2SE-based OS from SavaJe. The Java with this latest release... will the next few years bring for Java? bandwagon in the IA space is sturdy. And by Thomas Inglis In the information appliance space we it’s rolling with recent announcements by see a proliferation of different devices: PDAs, major players such as DoCoMo, Motorola, Ask Doctor Java smart phones, Web tablets, in-car Internet Nokia, and Sharp, which have started ship- The doctor will help JDJ access, games consoles, set-top boxes, home ping or have announced wireless devices readers find a cure for their 66 servers, wireless enterprise devices for verti- with J2ME and PersonalJava capabilities. Java system ills. Homecal markets, J2EE and countless embedded What J2ME of the future, and should you write by Dr. Java devices with Internet access. Emerging wire- to J2ME CLDC, J2ME CDC, or J2SE? Moore’s less and display technologies are driving the Law suggests that wireless handheld devices capabilities of these devices forward. will get more and more powerful. Today’s As a result, application demands on the iPAQ contains the computing power of a networks, personal wireless networks, and corpo- underlying operating system and platform are three-year-old PC. Will everything eventual- rate LANs. Certainly a number of J2SE increasing dramatically. Multitasking is no ly run J2SE (or will it be Java 3 by then)? subset/J2ME superset profiles are moving along longer optional; future devices must be capa- Unlikely. Only you know whether your the JSR process, but I want a full version of Java and ble of simultaneously handling 1–100 megabit application needs J2ME or J2SE. It’s as much complete applications portability, not a subset. wireless data streams, providing immediate about what the target device is capable of as We shouldn’t proliferate multiple flavors of response to a user action while smoothly play- it is about your application’s functionality. J2ME. It hurts application portability and it dilutes ing a background multimedia stream. And all J2ME is the right choice for many applica- the powerful message of the Java platform. this using a featherlight battery pack – no tions running on phones, embedded Looking to the future I see a huge population of 2GHz 70 watt Pentium 4 in these devices. devices, or toys, where you don’t want or small devices running “fit for purpose” J2ME, and With this proliferation of devices, and a need AWT (let alone Swing), J2SE security, more powerful wireless devices with QVGA+ dis- bewildering number of operating system and programming APIs as diverse as Java plays, 200MHz+ CPUs, and 32MB+ memory run- choices, Java is emerging as the common Collections and IEEE floating point libraries. ning J2SE applications – the same application in platform standard that developers can use J2ME is a great platform for small your car, on your desktop, or on your wireless PDA. to ensure portability across different devices, but give me a powerful PDA, an The exciting thing about today’s information devices. Historically, however, Java hasn’t enterprise wireless terminal, or a Web appliances is that, for the first time, we have the been a major player in the information tablet, and I want more – a lot more. In a opportunity to develop and deploy powerful appliance space. What’s changed? wireless PDA I want a phone, pager, PDA, Java applications on a wide range of devices – In theory, solving the “too big, too slow” e-mail device, an Internet-access device from smart card to mobile phone, from PDA to reputation that Java gained in its early days with high-resolution color display, all PC. Both J2ME and J2SE can be used to build is easy: make it smaller and make it faster. rolled into a single package the size and applications for these devices: match the device For small devices this is exactly what J2ME weight of a Palm m505. capabilities and your application API require- has done. J2ME has emerged as the pre- I want to see applications written with the ments to determine which to use. ferred solution to the problem of running rich and flexible UI of Swing and Java 2D. I So I, for one, am looking forward to Java’s Java applications on devices with restricted expect to rely on full security for wireless net- tenth anniversary – and Java 3 Standard Edition functionality. With a limited API, well suited working, end to end. I want seamless Internet Plus on my mobile phone/PDA/Web tablet for devices such as mobile phones, J2ME and voice communications over wide-area voice-activated gizmo. [email protected] AUTHOR BIO George Grey is CEO of SavaJe Technologies Inc., producer of SavaJe XE, an operating system for information appliances with J2SE support and bundled applications. Previously he was CEO of Psion USA; before that he founded and built Tadpole Technology, developer of the notebook-sized SPARC computer. 50 OCTOBER 2001 Java COM JAVA & TRANSLATION Using the Façade Pattern for the Java Internationalization API Produce globally enabled software J2SE One of the outstanding things about Java is that it facili- tates building internationalized programs, programs that work in various languages and regions. Java has used Unicode as its inter- WRITTEN BY nal character set since version 1.0. In Java 1.1 another impor- DAVID GALLARDO tant feature was introduced – an internationalization API. Although the Java Internation- ient way to implement alization API generally provides well- the Java Internation- designed, object-oriented ways to inter- alization API. nationalize an application, it may be a Home J2EEmisnomer to call it an API because it’s J2ME Internationalization and not a single class or package. Rather it’s Localization a set of loosely related classes scattered There are two throughout several different packages. aspects to producing The many features and the relationships globally enabled soft- between them can be overwhelming, ware. The first is interna- especially when you’re trying to do tionalization (sometimes something relatively straightforward abbreviated i18n), which and standard. means producing software This complexity can be tamed by that doesn’t have built-in using the Façade pattern. This pattern assumptions about language and suggests that you create a simple inter- cultural conventions. This should first face for a complex set of functionality by be considered in the design phase of a creating one object that mediates access project. to another set of objects that are related The second is localization (l10n), and a country designation. Java uses the in some complex way. This is a conven- which means adapting software to work in two-letter codes from ISO-639 to desig- a specific language. This is usually done in nate language and the two-letter codes parallel with software development for at from ISO-3166 to designate country. Java least one language and later for additional optionally allows a third part, a variant, ResouurceBurceBuceBuundleu languages. that allows support for dialects within a Properly internationalized software country, for example. Java notably uses a Client can be localized easily, without reengi- variant to provide support for the Euro. PropertyResourceBundleropeertyResouurceBun neering, recoding, and recompiling, by uses someone who specializes in translation, The Façade Pattern Collatoor not programming. Each localized ver- The classes that we’ll be using for l18nnFacaacacade sion must still be tested, of course, but Java internationalization generally have the scope of testing can be significantly three things in common: DateeFormat 3 Formaat more limited than a complete test of the 1. They have an abstract class with one entire application. or more factory methods to obtain MMessageFoFormat concrete classes. The concrete classes Locales are usually cast up to the abstract An internationalized Java application method, and we’re unaware of what NumbberFormaat uses the concept of locale to select the the actual concrete class is. 3 language and set of cultural conventions 2. They usually depend on a locale for to use at runtime. A locale typically con- their behavior, normally specified FIGURE 1 I18nFaçade class overview sists of two parts: a language designation when the factory method is called to 52 OCTOBER 2001 Java COM JAVA & TRANSLATION into different ResourceBundles accord- is the PropertyResourceBundle, which ing to type, so we’ve also made it possi- simply uses text files, .properties files, ble to specify the ResourceBundle that don’t need to be compiled. The when the Façade class is instantiat- other options require us to create class- ed. Here’s an example: es that contain the key and value pairs and compile them. // Use Mexican Spanish and Let’s look at an example. Suppose we AppErrorMessages have a program “Hello.java”. Instead of // ResourceBundle using a string such as “Hello!” directly in I18nFacade intlSpErrors = our print statement, we look up the new I18nFacade( localized string using a key, such as “HI”: "es", "MX", "AppErrorMessages); // Get a localized String using a Tag Now we look at the ways we String hello = intl.format("HI"); J2SE manage and delegate to the interna- System.out.println(hello); tionalization API classes. We briefly note that we often know which class we In ResourceBundle, we have speci- need to call based on the type of the fied a base filename for the parameter or parameters we’re passed. ResourceBundle. This means we must We can create overloaded methods, have a default properties file especially in the case of formatting HelloMessages.properties: obtain the concrete class. classes, which can help reduce complex- 3. They provide one or more methods ity. # AppMessages.properties with various options that provide the The Façade pattern is not intended # functionality we need, such as for- to limit access to the underlying compo- # Default - English matting a date according to the cur- nent classes. We’ve provided get() meth- rent locale’s conventions or compar- ods that return the underlying classes so HI = Hello! ing two strings. that anything that can’t be done through BYE = Goodbye! our simple methods, such as setting cus- HI_NAME = Hello, {0} Home J2EEAs suggested by the Façade pattern, J2ME tom formatting patterns, can be done by we create a single object, the I18nFaçade accessing the classes directly. Listing 2 This is the default version because class (see Listing 1), and use it to organ- provides code that exercises the func- the filename consists of a basename ize and manage the various internation- tionality in the I18nFaçade. “HelloMessages” plus “.properties” and alization classes. (Listings 1 and 2 can be no locale information. found on the JDJ Web site, www.sys- Text Translation A French version might be called con.com/java/sourcec.cfm). We set the Perhaps the most obvious issue for “HelloMessages_fr.properties”, where locale once when the Façade class is applications that are intended to work “fr” specifies the language and might instantiated, then instantiate each of the globally is that we need to be able to contain: various internationalization API classes translate the user-visible text. In the past and delegate to them as needed. people often wrote applications with # AppMessages_fr.properties Various constructors are provided in print statements containing hard-coded # the I18nFaçade class to allow users to text. Translating an application like that # French specify the two options we don’t allow means going through all the source them to change later, locale and code, identifying user interface text, HI = Bon jour! ResourceBundle. changing, recompiling it, and hoping we BYE = Au revoir! Users can supply a locale directly, or didn’t break something else in the HI_NAME = Bon jour, {0}! country and language codes from which process. Separating user text by putting we create a locale, or nothing, in which it in resource files maintained separate- There may also be a file called case we obtain the default locale from ly from the source code is a good way to “HelloMessages_fr_FR”, which would be the system. Here’s an example using lan- solve this problem. (We can do this for specifically French French. Finally, there guage and country codes: graphics and sound files too, by using a may also be a file “HelloMessages- convention involving directory paths _fr_FR_PARIS”, which would be Parisian // Use US English, default and filenames, and putting the path and French. ResourceBundle filename in the resource file.) To add When we search for the value accord- I18nFacade intl = new support for another language we add ing to the key we provided, the I18nFacade("en","US"); another resource file. ResourceBundle will first try to find it The Java API provides an abstract according to the locale we specified when The Façade allows the use of only a class, ResourceBundle, with two impor- loading the ResourceBundle using the single ResourceBundle – a repository of tant subclasses, PropertyResource- basename, language code, country code, localized strings (contained in a set of Bundle and ListResourceBundle, to sup- and variant, each separated by under- related files, as we’ll see later). A default port resource files. These classes allow scores followed by “.properties”. If this ResourceBundle is specified in the us to use a tag as a key to looking up an fails, it ignores the country code and looks Façade, which presumably is the one object in a set of files. Which specific file for basename and language code separat- used for general user interface text. It’s it uses depends on the current locale. ed by underscores and followed by “.prop- good practice though to group messages The most convenient of these to use erties”. If this fails, it will look for just the 54 OCTOBER 2001 Java COM JAVA & TRANSLATION basename followed by “.properties”. This by an array of objects. It parses the pat- By default the currency locale is provides a nice system of defaults. tern string, identifying placeholders the same locale specified when the within the pattern, which it replaces class was instantiated. The Façade Message Formatting with other strings. The simplest non- class has setCurrencyLocale() meth- Another issue to deal with is that trivial pattern is text with numbers in ods to allow specifying a separate cur- programs often construct strings braces, such as: rency locale. dynamically, such as by concatenation The second issue regarding currency or substitution. Generally speaking, this “You have a message from {0} wait- is that we need to carefully consider the should be avoided. Different languages ing.” numeric type we use to represent it. put words and phrases together in ways When we’re talking about most quanti- that are hard to anticipate. For these where the first object in the array of ties, a little rounding here and there is parts to be correctly translated in isola- objects would be a string to be inserted not a problem, and float and double are tion, each part, including its context, in place of {0}. fine. This isn’t usually the case with cur- must be carefully and consistently doc- Additional options are available that rency; a penny here and a penny there umented by the programmer. specify that the object in the array is to be often matter. This suggests that we J2SE Sometimes it’s unavoidable. We formatted as a date or time, for example: might use an integer type, such as long, need to construct sentences with with a decimal offset. In some countries information that can only be known at “A message from {0} arrived at the currency for large transactions can runtime, such as when we inform users {1,date,short}.” require support for large denominations that exceed any of the native Java types. English – U.S. 12,345.678 When deciding whether to use these In that case it may be desirable to use a Spanish – Mexico 12,345.678 features, consider how it will affect the class like BigDecimal to represent num- French – France 12_345,678 task of translation; keeping things sim- bers, perhaps wrapping in a Currency German – Germany 12.345,678 ple reduces cost and errors when trans- class. lating. For the purpose of simplifying our TABLE 1 Number formats example, we assume that the numbers Number Formatting being formatted are known to represent English – US: $12,345.68 The format for numbers, date, time, the correct currency, that their magni- Spanish – Mexico: $12,345.68 and currency vary greatly from place to French – France: 12_345,68 F place. Numbers in U.S. English, for Home J2EEGerman – Germany: 12.345,68 DM J2ME example, use the period as the decimal separator and a comma as the thou- TABLE 2 Currency formats sands separator, whereas some locales use the reverse, as English – U.S.: 8/27/01 August 27, 2001 shown in Table 1. Spanish – Mexico: 27/08/01 27 de agosto de 2001 (Note: The French num- French – France: 27/08/01 27 ao_t 2001 ber used punctuation, German – Germany: 27.08.01 27. August 2001 replaced here with an underscore, that could TABLE 3 Data formats not be displayed correct- ly when I ran the code in English – U.S.: 5:36 p.m. 5:46:39 p.m. EDT a DOS window on Spanish – Mexico: 05:37 p.m. 05:46:40 p.m.EDT Windows 98.) French – France: 17:38 17:46:40 EDT These results were German – Germany: 17:38 17:46:40 EDT obtained by using code similar to the following for TABLE 4 Time formats English: of their last login time or remaining I18nFacade intl = new balance. If other user-interface solu- I18nFacade("en","US"); tions won’t do, the Java Inter- System.out.println(intl.for- nationalization API provides a class for mat(12345.678)); message formatting, the Message- Format class. Currency The MessageFormat class is one of Currency is a special case of format- tude will not exceed the capacity of the five formatting classes, all subclasses of ting numbers, but there are two addi- native types, and that rounding errors the abstract Format class, that we’ll tional issues regarding currency. The will be insignificant. Table 2 shows some include in our Façade class. It shares first is more or less obvious: formatting of the currency formats. many characteristics with the rest of its currency is not the same as converting (Note: The French number used family. The MessageFormat class is an currency. Displaying yen as dollars is a punctuation, replaced here with an abstract class but has a static factory serious error. If the application is underscore, that could not be displayed method, getInstance(), that returns an intended to work only with one curren- correctly when I ran the code in a DOS appropriate concrete class cast to cy, even if it works with multiple lan- window on Windows 98.) MessageFormat. guages, this is not a problem, except that These results were obtained by using The method we’re interested in, for- a separate locale needs to be used for code similar to the following for mat(), takes a pattern string, followed currency. English: 56 OCTOBER 2001 Java COM JAVA & TRANSLATION I18nFacade intl = new Another issue that the standard Java method: I18nFacade("en","US"); Internationalization API doesn’t resolve is that different calendars are used in I18nFacade intl = new System.out.println(intl.currencyFor some countries or for certain purposes. I18nFacade("en","US"); mat(12345.678)); Most of us are familiar with the Greg- Calendar cal = orian calendar and this is the only one Calendar.getInstance(); Date Formatting for which a class, GregorianCalendar, is Date date = cal.getTime(); Date and time formats vary greatly. provided in the Java API. (This is what For dates, the order and punctuation the Calendar.getInstance() factory System.out.println(intl.timeFormat( between day, month, and year differ. In method in the example above returns.) date)); addition, verbose formats include the You shouldn’t use the methods in names of the days and months (or java.util.Date to construct date Strings. Parsing Numbers,Dates,and Time abbreviations) that vary according to the These have been deprecated as of Java The same issues we considered for language. Table 3 shows short and medi- 1.1 because they only allow you to use a formatting apply to parsing user input. um formats for dates for a few countries. Gregorian calendar. In addition, processing user input J2SE (Note: The French name for August IBM has open-source Java classes requires that the format we expect is includes a character, displayed here as in its ICU4J project that support other clear to the user. Finally, we must vali- an underscore, that couldn’t be dis- calendars, such as BuddhistCalendar, date and properly handle bad input. played correctly when I ran the code in a HebrewCalendar, and Japanese- Specifically, the application must be DOS window on Windows 98.) Calendar. See http://oss.software.ibm able to catch and appropriately handle These results were obtained by using .com/icu4j/doc/index.html for more ParseException. code similar to the following for English: information about these classes and It’s also the responsibility of the the calendars they support. application to properly interpret the I18nFacade intl = new returned value. The dateParse() and I18nFacade("en","US"); Time Formatting timeParse() methods both return a Date, Calendar cal = Table 4 shows the short and long but in the first case the time portion is Calendar.getInstance(); time formats for the same countries as zero, and in the second the date is zero. Date date = cal.getTime(); above: Here’s a sample call to parse a date: The code is similar to what we used System.out.println(intl.dateFormat( to obtain dates in the preceding exam- Date userDate; Home J2EEdate)); J2ME ple, except we use the timeFormat() try { userDate = intl.parseDate("12/8/01"); } catch (ParseException e) { // Handle bad input } The parseNumber() method returns a Number object and it’s up to the appli- cation to convert it to the proper primi- tive using the intValue(), longValue(), floatValue(), and doubleValue() meth- ods, for example: Number userNumber = null; // Called parse … long userLong = userNumber.longValue(); Sorting,Searching,and String Comparisons In English, a once common algorithm for comparing strings – the essential operation in performing a sort – is pretty easy: convert the strings to uppercase (assuming we want a case-insensitive sort), then compare them character code by character code. This doesn’t work as a general algorithm, however, because many languages use characters outside of A–Z and a–z, and some languages, such as Chinese, don’t even have the con- cept of upper- and lowercase. Other com- plications include expansion, where a 58 OCTOBER 2001 Java COM JAVA & TRANSLATION language sorts certain letters as though to select between locale-specific options was to make it easier to use the Java they were two, such as the German eszett such as case and accent sensitivity. Internationalization API. Some features (\u00DF), which is treated as two ss for Our Façade has a method compare() are not included because it wouldn’t sorting purposes, and contractions really make those features easier to use where two letters such as “ch” in Czech and would only make the Façade more are treated as a single letter that sorts complicated. Other features are not between h and i. included because they require a differ- Besides optionally taking case ent solution or approach. into account, we also have the option of taking diacritics Text Boundaries into account, depending on The BreakIterator class pro- the situation. For sorting, vides methods for locating we may want the letter “a” character, word, and sentence to sort before “á”, but for boundaries. While it’s relative- searching we may wish to ly easy to detect these bound- J2SE consider them equal. aries in English, many lan- For these reasons guages present difficulties. (among others too Chinese and Thai, for exam- numerous to list here), we ple, have no spaces between shouldn’t use the String.- words. Spanish can have punc- AUTHOR BIO equals() and String.com- tuation at the beginning of a David Gallardo is an pareTo() to compare two sentence. Thai has no punctua- independent software strings. The Java Inter- tion whatsoever. It’s important to consultant specializing nationalization API has a class be aware of these issues, but locating in internationalization, Collator that we should use text boundaries isn’t something that’s Java and database instead. This class, like the format usually useful. development. classes, is an abstract class with a facto- While it’s indispensable for doing Previously he led ry method that returns a concrete class, such things as word wrapping, diction- database and RuleBasedCollator, cast up to Collator. ary lookup, and indexing, using a internationalization Collator has a method compare() that that will obtain a collator for us (if it Façade isn’t going to make the job sig- Homedevelopment at J2EEa will compare two strings using the J2ME doesn’t already have one) and return the nificantly easier – it’s probably best to B2B e-commerce default rules for the locale. Collator also results of comparing two strings: use the BreakIterator class directly in company. has a property, Strength, that allows us those few specific cases where it’s I18nFacade intl = new required. I18nFacade("en","US"); Display, Input, and Output if(intl.compare("Apples", I’ve also omitted support in the "Oranges") Façade for graphical display, and input { and output functionality (including // do something based on character set conversions), because this result these are entirely unlike the other func- } tionality in the Façade. There are other design patterns better suited for this The concrete class is a rule- type of problem. based collator. Using it is expensive since it must parse Conclusion the string according to many Design patterns help software rules and expand or contract developers by allowing them to consid- characters based on diacritics er what the problems have in common. and other language rules. If The insight gained from solving one more than a few strings are can be carried over when solving the going to be compared more next one. The problem with using the than a few times, such as when Java Internationalization API – many sorting a large set of data, it classes, loosely related, with many fea- may be desirable to capture tures – describes the type of problem the result of this parsing in the Façade pattern is intended to solve. advance of sorting by calling Using this pattern does indeed make the getCollationKey() method, the Java Internationalization API easier perhaps as data is entered. to use. The CollationKeys can be saved and later used to per- Reference form the comparisons instead Grand, M. (1998). Patterns in Java: A of the strings themselves. Catalog of Reusable Design Patterns. Wiley. pp. 205–211. Additional Considerations The intention of the Façade [email protected] 60 OCTOBER 2001 Java COM PRODUCT REVIEW n June 2001, Borland released the latest size of a small cinema, it usually takes a bit of version of the JBuilder series. Borland is pruning to get a suitable screen. Ian ever-popular presence in the Java IDE This is not the case with JB5 (see Figure 1) market, but with most IDEs now offering since the information is hidden behind tabs. the same functionality, is there anything to This works extremely well as it enables infor- set JBuilder apart? mation to be displayed when you want it as JBuilder It must be said from the outset, JBuilder opposed to the IDE “guessing” what you 5 boasts some very nice features “on the would like. box.” IDEs have been screaming out for You may have noticed the Cocoon appli- the packages and integration of tech- cation and, no, it isn’t a misprint. One of the nologies that JBuilder 5 promises are more pleasing elements is the ability to “under the hood.” build straight to the familiar Cocoon Web by Borland Software Corporation • Rapid J2EE application develop- ARchive format. As Java finds its way into ment more and more of today’s (and tomorrow’s!) • XML tools Web sites, the ability to deploy solutions J2SE • Deployment to multiple application straight to a .war package ready for distribu- servers tion is both an excellent idea and well • Team development file manage- implemented. ment integration with MS Source- JBuilder 5 includes a Tomcat 3.2 plugin Safe, Rational Clearcase, and CVS (the Enterprise Edition also has Borland and • JSP WebLogic) so add a third-party Web server, • JavaBeans such as Apache, and it’s easy to see how you can compile, run, debug, test, and finally Features deploy from the comfort of one interface. The 5 REVIEWED BY TOM INGLIS Borland seems to have packed distribution also includes Borland’s own everything possible into JBuilder 5. AppServer 4.5. [email protected] Initially, there were some reservations The supplied wizard does it all for you by regarding how all these features, such as providing a complete Tomcat-ready solution team development tools, would be pre- with context mapping. What more could you sented and managed. The chaps at ask for? Home J2EEBorland J2ME would have to get it right for it This doesn’t mean it’s painless. You still to be both practicable and useful. have to ensure dependencies/library files and After using the IDE for a couple of that everything is set up “just so” from within weeks it is my happy duty to report that JBuilder, but you would have to do this any- specs Borland Software Corporation this is indeed the case. way! Both Enterprise and Professional edi- 100 Enterprise Way The main interface is well laid out and tions have this built-in. highly configurable, as you would expect, Another tasty feature is the support for Scotts Valley, CA 95066-3249 with the normal array of debugging and version control packages such as CVS, Phone: 831 431-1000 project control options present by de- SourceSafe, and Clearcase. I haven’t used all Web: www.borland.com fault. Almost every- E-mail: customer-service@ thing is menu-driven borland.com and those friendly wiz- ards we’ve all become accustomed to are Test Environment available for most of Windows 2000 Professional, the more commonly Intel PIII-450MHz, 128MB RAM used features. Windows 98SE, AMD Duron- These wizards can 800MHz, 512MB RAM sometimes be more of a nuisance than they are worth. They seem Supported Platforms to take away some of Solaris: ULTRASPARC2, the learning process Solaris 7,8 regarding what the Windows: 98, 2000, NT 4.0 IDE is doing when it sets all our classpaths Linux: Red Hat 6.2, Mandrake and creates neat pack- 7.2, Caldera Systems 2.3, SuSE ages. But, as wizards 6.3, TurboLinux 6.0 go, the ones I tried Mac: OS X (4th quarter of were easy to use and performed the this year) job well. We’ve all used applications that fill the screen with almost every available option/feature. Inform- ation overload if you like. Given that most of us don’t have screens the 62 OCTOBER 2001 Java COM PRODUCT REVIEW these packages but, of the where near as important as masses of memory. Nearly all three, CVS is familiar and applications will run in direct relation to the amount of bundled with JBuilder 5. memory and JB5 is no exception. It performed admirably Hurrah for open source. on both processors with 512MB installed. It says 128MB on This process would the box, but if the intended use is to run alongside Web normally entail having at servers and other apps, then seriously consider the total least two applications RAM in the target machine. 256MB will provide comfort- open, the IDE and the control package, able levels. so to have it all integrated in one place is The overall footprint isn’t that much and doesn’t appear to an excellent aspect of this impressive overstep similar products. JB5 sits at 2–4MB with the JVM IDE. starting at 40MB and rising to over 80MB with a medium-sized By using the menu options and filling project. It also isn’t a resource hog. There’s nothing worse than in the blanks, I created a repository and an app that eats up 10% of your processor just by being in exis- J2SE by Borland Software Corporation Borland Software by incorporated it into CVS within minutes, tence, something that has been avoided. giving full version control. The Enterprise edition allows you to Help System control and create projects deployable to The help system is a bit haphazard. My personal preference work stations (see Figure 2). is to use the Find option, gain a list of general items, and drill JBuilder 5 Never has it been so easy to it down that way. This wasn’t an easy task, however. Borland maintain version control over even ran a link to almost every word in the help system – useless extremely large projects. words with irrelevant meanings (aardvark, abbot) have links to equally useless information. Deployment It’s not impossible to use, but I found it a bit like a search As the features of JB5 were result on the Internet, having to wade through the dross, keep- explored it quickly became ing an eye open for that key phrase that gives you what you apparent how much thought want. had been given not only to the possible deployment of The Manuals Home J2EEa given J2ME project, but also Not content with simply informing us how to use their how all the necessary steps product, those clever chaps at Borland have included general could be combined to make programming/Java-related principles from bitwise operation this a painless operation. to serialization. In addition, you’ll also find introductions to As my development career Web applications and XML. Superb. has advanced I’ve developed Steve Jobs’ endorsement of Java (at last) at JavaOne 2000 a manner of “getting the job has prompted a release on the Mac OS X platform. It’s a delight done.” This would involve com- to see this. Borland had one or two forays into the Mac soft- piling to the standard class direc- ware market a few years ago, but not since. Hopefully this will tory structure for initial help bring total Mac-derived applications to the marketplace, testing/use with a final switch to .jar which can only be a good thing. packages for deployment. Most IDEs JB5 has made it easier than ever to control and deploy allow this to happen painlessly. JBuilder large-scale solutions by providing many of the tools with takes this to another level. which to do so. It has an intuitive front end with all the You can create both a class directory structure and a main features catered for and available with the minimum .jar package when you build, and that’s not all. If your current configuration. Borland has managed to get the mix between project is also a Web app you can build this too – all at the click simplicity and functionality that others seem to find eva- of a button. This applies across the board so you won’t find sive. 5yourself constantly updating the project properties to reflect what’s required from any given task. Somebody at Borland has thought about this. We, as a com- munity of Java developers, must applaud and commend some of the tools Borland offers with this latest release since more time can be devoted getting on with the juicy bits. Several times I caught myself going ooooh, it does that? And ahhhh, that’s cool. All this has overhead so the constant building and deploying is not recommended for general use; however, it’s easy to see that a lot of the deployment burden has been eliminated. Note the specification of the two machines this IDE was tested under. Never being a shy one, this was adapted and several configurations tried (even to the extent of being FIGURE 2 CVS support slightly naughty and trying to cram it all into a 64MB sys- tem). The results – it appeared processor speed was not any- FIGURE 1 JBuilder 5 64 OCTOBER 2001 Java COM ASK DOCTOR JAVA nlike the doctor that works for your This would be considered a noble and have this method make all the HMO, Doctor Java is here to help you effort but unfortunately it does not do other method calls on your behalf. with all of your Java problems. The the trick. The main problem with this is J2SE U good Doc will not require a copayment for each that you are still trying to acquire a lock I AM BUILDING A JSP/JDBC SITE visit nor ask you to fill out long arduous forms. on this. What we really need is an alter- WITH AN ISP THAT NEVER ALLOWS The Doctor is here to help the readers of Java native object to lock. Let’s restructure our A DSN TYPE CONNECTION. THE Developer’s Journal find a cure for their Java code and see how this can be realized. DATABASE I WANT TO USE IS system ills. ACCESS. HOW DO I DO A DSN-LESS public HRObject { private static Object lock = new CONNECTION? HOW CAN I SYNCHRONIZE METHOD Object(); ACCESS ACROSS TWO DIFFERENT The doctor recommends seriously CLASSES? changing your diet and eliminating Microsoft Access as a database for use The synchronized modifier is used to with Java and migrating to something control access to critical code in multi- that will scale a little better and is sup- threaded programs. When a method is portable. With that being said, let’s dive declared synchronized, you’re instructing into the solution to your problem. Let’s the program to obtain a lock (monitor) on say that you have an ODBC connection Home J2EEthe object that has the method. If you call J2ME with the following configuration: another synchronized [ODBC] method on the same DRIVER=Microsoft Access Driver (*.mdb) object, you don’t UID=admin UserCommitSync=Yes lose the lock and Threads=4 other threads SafeTransactions=0 PageTimeout=5 don’t have MaxScanRows=8 access until the MaxBufferSize=2048 FIL=MS Access lock is freed. DriverId=25 This, howev- public static void DefaultDir=c:\ doIncreasePromotion (int DBQ=c:\doctorjava.mdb er, does not empID, int percent, String work across newTitle) { objects. The best HRIncrease hr1 = new To talk to an ODBC data source you way to solve this prob- HRIncrease(); will need to utilize a JDBC to ODBC HRPromotion hr2 = new lem is not to declare your HRPromotion(); bridge. Sun recommends using the bridge methods as synchronized but to use a in situations where no native JDBC driver synchronized(lock) { synchronized block. First, we’ll look at hr1.increasePaycheck(int exists. Merant is a typical code that does not lock across empId, int percent); company that hr2.givePromotion(int methods: empId, String newTitle); provides } JDBC public synchronized void } increasePaycheck(int empId, int per- } cent) { ... } The preceding code exam- public synchronized void givePromotion(int empId, String ple is the prescription for your newTitle) { woes. We basically used an ... } “impartial” object as the basis for acquiring a lock. This DSN Let’s consider doing something like approach requires that you this: always use the same lock object public void increasePaycheck(int per-DandS methodsN similar in their cent) { approach to synchronization. We synchronized(this); ... could have alternatively created a static } method in a class that is synchronized 66 OCTOBER 2001 Java COM DSN ASK DOCTOR JAVA |
---|