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 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 User Group-User Listing 3: weblogic-cmp-rdbms-jar.xml group-has-users Group-User USER_GROUP many J2EE Group group-has-users

GROUPNAME users

java.util.Collection user-belongs-to-group user-belongs-to-group USERNAME many User USERNAME groups java.util.Collection Listing 4: Ant build script User WebLogic_CMP_RDBMS Listing 5: Client InitialContext ic = new InitialContext(); 6.0 Object objRef = ic.lookup( "UserManager" ); UserManagerHome home = (UserManagerHome) META-INF/weblogic-cmp-rdbms-jar.xml PortableRemoteObject.narrow( objRef, UserManagerHome.class ); UserManager userManager = home.create(); User user = new UserValueObject(); user.setUserName("alex"); WebLogic_CMP_RDBMS user.setUserType("regular"); user.setUserEmail("[email protected]"); 6.0 userManager.createUser(user);

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 .. ..

.. .. <%@ tagliburi="/WEB-INF/struts-html.tld"prefix="html"%> <%@ tagliburi="/WEB-INF/struts-bean.tld"prefix="bean"%> { } public UserFormextendsActionForm{ Listing 2 Listing 1 public ActionErrorsvalidate(ActionMappingmapping, .. .. public setuser(){..} public getUser(){..} private Stringaddress=null; private Stringuser=null; } O Errors.add("user", newActionError("error.user.required")); { CTOBER If (user==null||user.length()<1) ActionErrors errors=newActionErrors(); return errors; .. .. }
HttpServletRequest req) 2001 technologies. focus onJava andopen-source applicationswithaprimary tecting anddeveloping enterprise Hespecializes inarchi- Aaron RustadisaseniorJava developer for OnlineBusinessSystems. Manitobo. Winnipeg, Heisbasedin sulting companyemployingover 300peoplethroughoutCanadaandtheU.S. aleadingcon- Java developerClive Jonesisaseniorenterprise withOnlineBusiness Systems, coding repetitivebusinesslogic. he’s hardtoavoid worked mostofhiscollegea C++program COBOLassignment, towrite Eversincehedeveloped Inc. Steven Sweetingisdirectorofproductmanagementwith Versata, A UTHOR B IOS [email protected],[email protected][email protected] [email protected], } UserDelegate userDelegate=newUserDelegate(); UserForm userForm=(UserForm)form; IOException, } { Listing 5 public finalclassSaveUserActionextendsAction{ scope="request"/> name="userForm" type="com.demo.SaveUserAction" path="/SaveUser" } if (forward==null){ forward =mapping.findForward("failure"); userDelegate( userForm); forward =mapping.findForward("success"); return; } { if (!delta.equals(newBigDecimal("0")) ) delta =addValue.subtract(subValue); } { if ((this.getOldInvoiceStatus()).equals("B")) } { if ((this.getInvoiceStatus()).equals("B")) BigDecimal delta=newBigDecimal("0"); BigDecimal subValue=newBigDecimal("0"); BigDecimal addValue=newBigDecimal("0"); newParent.getDataObject().setAdjust("TotalBilled",delta, true); if (!newParent.isObjNull()) if (!newParent.isInitialized() ) subValue =getOldTotalFinalFee(); addValue =getTotalFinalFee(); HttpServletResponse res)throws HttpServletRequest req, ActionForm form, } newParent.setDataObject(this.getAccount()); J ava ServletException { COM PATTERNS 2

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) || * . All rights reserved. contentType.equalsIgnoreCase("application/x-www-form- **/ urlencoded")) { MultipartRequest multi = new translateParamsToAttributes(servletRequest, servletResponse); MultipartRequest(servletRequest, } filterChain.doFilter(servletRequest, servletResponse); uploadFolder, } 1 * private void translateParamsToAttributes(ServletRequest 1024 * 1024 ); J2SE request, ServletResponse response) Enumeration params = { multi.getParameterNames(); Enumeration paramNames = while (params.hasMoreElements()) { request.getParameterNames(); String name = (String)params.nextElement(); while (paramNames.hasMoreElements()) { String value = multi.getParameter(name); String paramName = (String) servletRequest.setAttribute(name, value); paramNames.nextElement(); } String [] values; values = request.getParameterValues(paramName); Enumeration files = multi.getFileNames(); System.err.println("paramName = " + paramName); while (files.hasMoreElements()) { if (values.length == 1) String name = (String)files.nextElement(); request.setAttribute(paramName, values[0]); String filename = else multi.getFilesystemName(name); request.setAttribute(paramName, values); String type = multi.getContentType(name); } File f = multi.getFile(name); J2EE } // At this point, do something with the // file, as necessary } } } catch (IOException e) Listing 2: Intercepting Filter Implementaion Example: MultipartEncoderFilter { public class MultipartEncodeFilter extends LogManager.logMessage("error reading or saving BaseEncodeFilter { file"+ e); public MultipartEncodeFilter() {} } public void doFilter(javax.servlet.ServletRequest } // end if servletRequest, filterChain.doFilter(servletRequest, javax.servlet.ServletResponse servletResponse); } // end method doFilter() Home servletResponse,javax.servlet.FilterChain }

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 element of the dles or remote references to enterprise with other applications. Web application’s deployment descrip- beans in HttpSession.

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 it to a handle. A compatible application avoid naming collisions with applica- WebTier servlets is required by the specification The context root is the base path of a coolpetse- to correctly manage enterprise bean store references stored in HttpSession. Therefore, remote references (that extend EJBObject) can be stored direct- App2.ear: war_runtime.xml ly in HttpSession with no loss of porta- Servers and deployment bility. WebTier J2EE Platform Specification 1.2, section “ exoticpet- 6.6. they handle context sestore New TagLibrary Format:J2EE 1.2 root collisions If you’re migrating applications from The code snippets in the preceding J2EE 1.2 to J2EE 1.3, you may need to example show how App1 and App2 update any TagLibrary descriptor (TLD) specify unique entries so files in your application to the new for-

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 resource-specific details in their compo- password. A system-level exception (like 1.0 nents’ interfaces since doing so may AccountDAOSysException above) is typ- 1.1 limit where the components might be ically thrown when a nonrecoverable j2ee used. One easily overlooked form of error has occurred, such as a database resource dependence is the set of excep- crash. Learn more about the differences Here is the same snippet for JSP 1.2: tions a method may throw. BMP meth- between system- and application-level ods don’t necessarily use a SQL database exceptions in Chapter 12 of the EJB to manage their persistence, so specification. J2SE 1.0 SQLException doesn’t belong in the 1.2 BMP method signatures. Security:User Authentication j2ee Instead of throwing SQLException, Keep all user login code in classes define system- and application-level separate from your application classes Your application server will hopeful- exceptions for the class and throw those so you can reimplement them if you ly provide good migration tools that will update these files for you; otherwise, you may have to check and edit them manually. J2EE An application developer The samples used in this example are just a few of the JSP DTD tag name changes. See the relevant sections of the shouldn’t make any assumptions JSP 1.1 (section 5.3.5) and JSP 1.2 “ (Appendix C) specifications for details. about the returned value when Always Import Classes Used in JSP Pages designing an application Home With the exception of classes that are guaranteed to be imported, always import any class you use in a JSP page. This may seem like an obvious point, exceptions in response to error condi- but this item addresses a subtlety of tions. Tomcat – and possibly other JSP con- The BluePrints program recom- tainers. Tomcat (version 3.0) found in mends the Data Access Object (DAO) the J2EE 1.2 Reference Implementation design pattern (http://java.sun.com/ ” imported more packages than those j2ee/blueprints/design_catalog/dao) required by the specification (this has to encapsulate a back-end resource, been fixed in the latest release). In par- such as a SQL database. A DAO ticular, it was possible to use provides access to a system java.io.PrintWriter without importing it. resource without reference to Pages that did so would work in Tomcat how that resource is imple- but not in other JSP page environments. mented. For example, a DAO Importing all classes used by a JSP page might offer methods to load, will prevent this problem from occur- update, and delete a persistent ring. object, and methods to set and The only packages that can portably get that object’s properties, be used without importing are while hiding the implementa- java.lang.*, javax.servlet.*, javax.http.*, tion details of how those opera- and javax.servlet.jsp.*. All other pack- tions occur. ages should be imported in the JSP page. The DAO can catch resource- JSP containers other than Tomcat specific exceptions and translate may import classes beyond those those exceptions to the custom sys- required by the specification, but relying tem- or application-level exceptions on the presence of those classes may described above. make your JSP pages nonportable. See See Listing 1 for an example from the section on the import keyword in the the Java Pet Store. In method JSP 1.2 pfd 2 specification, section deleteAccount(), a SQLException is 2.10.1.1. translated to an AccountDAOSys- Exception, which extends java. Never Throw Resource-Specific lang.RuntimeException to indicate a Exceptions from BMP Code system-level exception. Entity beans that manage their own It’s worth noting that the Account persistence should never throw excep- bean indicates application-level

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- element in the EJB opers will do so as long as the container-provid- deployment descriptor (ejb-jar.xml) for all of the ed mechanisms aren’t adequate to suit the EJB client-view methods. needs of an application. If this is done, it would There is a gray area in the J2EE 1.2 specifica- be wise for the developer to isolate the code so tion when it comes to defining the behavior of that it can be easily removed as containers an unspecified method permission if security become more capable. roles are used. The gray area has, legitimately, Isolating the code specific to an authentica- been interpreted inconsistently by container tion mechanism makes porting easier since just vendors. This means that EJB containers may that part of the code will need to be rewritten. not behave consistently for EJB methods with See Scenario #3 on packaging from the JDJ an unspecified method permission when secu- “Build to Spec!” article (Vol 6. issue 7) for more rity roles are used. information. For example, some container vendors may For managing user authentication, consider interpret unspecified method permissions to using Java Authentication and Authorization mean none, essentially an uncallable method Service. JAAS allows services to authenticate and for no user access; others may interpret unspec- enforce access controls on users. To learn more ified method permissions to mean everybody for about JAAS, see the resources section at the end wide-open user access. In any case, if you use of this article. security roles and want the security behavior to See also Table 6.2 of the J2EE 1.2 platform be portable across container vendors, specify specification, where the J2EE security permis- your intentions clearly with well-defined sion set for each type of component (applica- method permissions. tion clients, applet clients, servlets/JSPs, EJBs, The application developer may choose to and so on) are defined. create a role named everybody and then map this role to wide-open user access. This assumes the container has the ability to map the every- body role to a set of users. The everybody role could then be used in the ejb-jar.xml files for those methods where wide- open user access is allowed. For an example, see Listing 2. Refer to the J2EE 1.3 specification for the lat- est changes for using security roles and EJB method permissions. Use of Security APIs: EJBContext.getCallerPrincipal().getName() The J2EE 1.2 specification leaves the result of EJBContext.getCallerPrincipal().getName() as unspecified in terms of the requirements of the returned value. An application developer shouldn’t make any assumptions about the returned value when designing an application or component. Why? The main reason is that there’s no standard format for the return value of EJBCon- text.getCallerPrincipal().getName(). As of pro- posed final draft2, the EJB 2.0 specification mentions that calling methods “might, for example, use the name as a key to information in a database.” In general this will work; howev- er, there’s a caveat that in complex security infrastructures this value might change. Here are some scenarios where this might be a prob- lem: • When running a server from one ven- dor and then switching to a server from another vendor while keeping the same database (e.g., using BMP) • When running two servers from dif- ferent vendors where a bean on each server needs access to that row

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- form. manager Resources AUTHOR BIO 1. Check out the J2EE BluePrints Web Elizabeth Blair is a site at http://java.sun.com/j2ee/ everybody staff engineer with blueprints, where you can down- Sun Microsystems, load the Java Pet Store sample where she leads the application, the BluePrints book Java 2 Platform, Designing Enterprise Applications manager Enterprise Edition with J2EE, and view the complete BluePrints BluePrints design pattern catalog – EmployeeService development all for free. Remote team. Liz 2. Download the J2EE Platform setPerformanceRating contributed to the Specification, as well as other J2EE java.lang.String recent Java Pet Store developer support documentation sample application, and software (including the free J2EE with an emphasis on Reference Implementation), from the tests for EIS and http://java.sun.com/j2ee. EJB architecture. In 3. View the current list of J2EE licensees the past she has who have passed the Compatibility everybody worked on the Test Suite at http://java.sun.com/ Compatibility Test j2ee/compatibility. EmployeeService suite (CTS) for the 4. Learn more about JAAS, the Java Remote J2EE platform, the Authentication and Authorization getPerformanceRatingForm J2SE platform, and Service, at http://java.sun.com/prod- the WABI (Windows ucts/jaas. Applications Binary Interface) projects. [email protected]

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

drivers that can connect to many dis- Singletons can be problematic, like the parate databases. To utilize the bridge, girlfriend in high school They’re typi- your code would look similar to: cally implemented with synchronized try { The doctor assumes the reason you blocks. Many threads will fight to have the need for such code is because obtain a lock on your Singleton causing Class.forName("sun.jdbc.odbc.JdbcOdbcD river"); you are having a problem related to a big performance bottleneck. The types not being set properly on your Singleton pattern can be problematic in Connection conn = DriverManager.getConnection("jdbc:odbc Web server. :DRIVER=Microsoft Access Driver (*.mdb);" + "DBQ=c:\\doctorjava.mdb"); HOW DO I DELETE A ... COOKIE WITHIN A } JSP PAGE?

The ODBC connection strings may Let’s take a look vary in syntax depending upon the at your code and J2SE actual database and language you are see why it doesn’t connecting to. perform as expected.

Cookie killCookie = new I WOULD LIKE TO SEE ALL OF THE Cookie("uid", null); ELEMENTS IN THE REQUEST HEAD- killCookie.setMaxAge(0); ER IN MY JSP FOR DEBUGGING PURPOSES. COULD YOU POINT ME The code removes a cookie from the IN THE RIGHT DIRECTION? browser once the browser is closed. a cluster as you will want more than This approach does not work in all one instance. The other problem with The doctor loves it when readers ask instances. Many browsers keep it in this pattern is that you need to make questions that can be answered quickly. memory and will not actually destroy sure that its access is completely hid- To solve your problem we can take the cookie until the browser instance is den from the outside world, or else it is advantage of the java.util.Enumeration shut down. Let’s take it one step further. essentially a big fat global variable. object. We can loop through the In some scenarios, it may be useful to The other thought I have is that it’s requests and display them to the screen. have the cookie destroyed without always easier to make something a

Home J2EELet’s take a look at some sample code. J2ME shutting down the browser. To realize Singleton than to unmake something a D this goal, you need to change your code Singleton. In my mind, this is a red flag Show slightly as follows: that needs serious architectural think- S ing. Cookie killCookie = new Cookie("uid", null); killCookie.setMaxAge(0); N killCookie.setPath("/"); Letters to Doctor Java: response.addCookie(killCookie); Send your questions, comments, and praise to doctorjava@sys-con.com. Published letters will</p><p>This should do the trick nicely. be edited for length and clarity.</p><p>WHEN SHOULD I USE Doctor Java moonlights as an enterprise archi-</p><p>THE SINGLETON PAT- N tect with Hartford Technology Services Company TERN IN MY JAVA S L.L.C. (www.htsco.com), an information tech- APPLICATION? D nology consulting and services firm dedi- The cated to helping businesses gain Singleton pattern re- competitive advantage through minds me of the use of technology. one of my girl- friends in high school. At first, I found that she was the only thing I wanted but later she proved to be very problematic. Headers The Singleton pattern is useful in situations where you only want to <% java.util.Enumeration e = have a single instance of a particular request.getHeaderNames(); object. The second use for Singletons is for (e; e.hasMoreElements();) { String header = to provide a global viewpoint of com- (String)e.nextElement(); mon functionality. Typically, Singletons out.print(header + " = " + request.getHeader(header) + "
"); will be used for log managers, reference } services, and similar functionality. %>

68 OCTOBER 2001

JJava COM J2ME EDITORIALOR J2ME INDEX J2ME JASON BRIGGS J2ME EDITOR

Wishful Thinking Wishful Thinking In an attempt to help out ’ve come to the conclusion that Japan is of chewing gum) in the top. In fact, why not mobile phone manufacturers the place to live. Not that I really want to throw another slot in the back and we’ll put the in their goal to produce the 70 Imove to a country that by all reports is an operating system on a memory stick as well! “must have” mobile device extremely crowded and busy place, but the The screen should be a high-definition du jour, let me present the Japanese always seem to get the best gad- organic LED – and the CPU should be as specification for the phone I gets. Zev Blut’s article on iAppli development fast as possible without reducing the oper- want in my pocket this last month (“DoJa in NTT DoCoMo Phones,” ating time (personally, I’m hoping for a Christmas. JDJ, Volume 6, issue 9) got me thinking, and I 1GHz processor that will run forever on a by Jason Briggs revisited a couple of Web sites that show the few milliwatts of power...but then again, different mobile phones available there. I’m still waiting for those personal nuclear A good example is Mobile Media Japan reactors that I saw in the movie A Storm in a Coffee Cup where, if you take a look at the list of J-Sky Ghostbusters in the ’80s to appear – so I Embedded real-time Java phones (www.mobilemediajapan.com/hard- don’t hold out much hope for that). components for hardware 72 ware/jsky-handsets/), most have color It will, of course, be PersonalJava-enabled interfacing screens and are exceptionally easy on the – or the Personal Profile, if Sun ever gets by David Hardin and Mike Frerking

Homeeyes (to use J2EE the vernacular). Style J2SE isn’t limited around to releasing it – with (Java) develop- to J-Sky phones; i-mode and EZweb also have ment access to 3D and MP3/audio libraries. some seriously worthy examples. We’ll throw in various interfaces – like Product Review Western phones, by contrast, have pre- infrared and serial access – for good luck. Nokia 9210 dominantly gray-scale screens, and have I want one. Now. Not in a couple of Communicator been (until recently) generally clunky-look- years’ time. I’ve been infected by the bug of If you’re intending to buy a ing when compared with their Asian the Internet generation: I want immediate PDA and are already carrying 84 cousins. Manufacturers in the West have a gratification. I have the attention span of a a mobile, you should look at lot to learn from the Japanese – but then gnat and about as much patience as a tur- the 9210 as a convenient again, perhaps consumers in the West have bocharged snail with nitroboosters and a alternative. a lot to learn as well. penchant for drag racing. by Jason Briggs Things are looking up, however: Nokia Oh, and P.S., Mr. or Ms. Mobile Phone has released the 9210, a Java-enabled mobile Manufacturer, I don’t want to pay the Earth phone/PDA, in Europe (with the 9290 sched- for my new toy. Java for Embedded uled for release in the U.S.). It may have a Is that too much to ask for? Computing – A Reality gray-scale screen on the outside, but it’s full Probably...but I live in hope. It’s more productive as a lan- color within (you can find a review of the Anyway, wishful thinking aside, in this guage, and as a program- 88 9210 in this issue of JDJ). Still, it doesn’t quite month’s issue of JDJ – as well as the afore- ming environment, than have the teenager-attracting good looks of mentioned Nokia review – you’ll discover C/C++. some of those Japanese mobiles – but, of the wonders of robotic programming in Part 2 of 2 course, it isn’t aimed at the same market. Java, where David Hardin and Michael by Vincent Perrier and In an attempt to help out mobile phone Frerking from aJile Systems describe how Steven Schwarz manufacturers in their goal to produce the to develop a line-following robot using “must have” mobile device du jour, let me Lego Mindstorm and aJile components. present the specification for the phone I To round off last month’s article on mak- want in my pocket this Christmas. ing Java for embedded computing a reality, This device will have the “chic factor” of Steven Schwarz and Vincent Perrier from one of those Matrix-style mobiles (Nokia’s Wind River write about determining if Java 7110 or Mitsubishi’s J-D05 are examples of is right for your embedded device. They what I’m thinking of), a slot for an IBM 1GB include a case study in the form of a hands- Microdrive in the bottom, and a slot for one of on porting exercise. Just the ticket if you those Sony memory sticks (shaped like a piece want to get your hands really “dirty.”

[email protected] AUTHOR BIO Jason Briggs works as a Java analyst programmer in London. He’s been officially developing in Java for three years – unofficially for just over four.

70 OCTOBER 2001

Java COM Home J2EE J2SE J2ME 72 O CTOBER 2001 J ava COM OCTOBER 2001 73

Java COM n this article we examine the advantages Properties and disadvantages of using the JavaBean JavaBean properties are get/set methods used to configure Component Architecture for embedded the behavior of the component at design time by a develop- hardware components. We describe a slight ment tool, and at runtime by an application. Some extra over- variation of the JavaBean model that’s used head is associated with calling these get/set methods; howev- in the aJile Java processor runtime libraries er, it’s minimal compared to the benefits gained. This method that make Java components more suited to call overhead is also predictable, making JavaBean properties time-critical and embedded applications. acceptable for embedded and real-time applications without

J2ME We follow with an example application that modification. uses this component model to program a 100% Java-based controller based on the Events aJile aJ-80 Java microprocessor for Lego JavaBean events include an event listener interface that Mindstorms sensors. We conclude with has one or more methods that will be called when an event is suggestions on how to apply this compo- sent. An application implements the interface and registers it nent model to different applications. with the JavaBean, which calls the event methods at the appropriate time. Each of these event methods must also The JavaBean Component Architecture include a parameter of type EventObject. When a component The JavaBean Component Architecture has been used suc- sends an event, it creates a descendent of EventObject, initial- cessfully for graphical applications using AWT and Swing com- izes it, and passes it as a parameter to each registered event ponents and by third-party software vendors to distribute listener. reusable software components using standard packaging. The Normally, a JavaBean will create a new EventObject each JavaBean model specifies properties that can configure the char- time an event is sent since an event handler could keep a ref- acteristics of the JavaBean from inside a development environ- erence to the EventObject for the future. If the JavaBean ment at design time. It also specifies events that are sent from reused the same EventObject, the internal state could be the JavaBean to the application when an event of interest occurs. changed without the event listener expecting it. This event- The JavaBean component specification also includes support transmission technique is less desirable for embedded or for “bean info” files, and many development tools provide property time-critical applications, because creating and discarding editors to configure beans appropriately for the application under EventObjects is expensive. The new() operation for the development. The JavaBean component model is well suit- EventObject is generally time-consuming and unpredictable ed for graphical and nongraphical components for as it could also initiate a garbage-collection cycle at an inap- general-purpose computing systems, but, as propriate time.

Home J2EE J2SE we shall see, the JavaBean event One alternative to creating a new EventObject each time model is less appropriate for an event is sent is to create one EventObject and reuse it. This time-critical or embed- would prevent the overhead associated with the new() opera- ded systems. tion and possible garbage collection at the expense of not strictly adhering to the JavaBean specification. This would also allow development tools to recognize the events and pro- vide full tool support. This alternative still causes some over- head because the fields in the EventObject must be initialized with custom state information and the event handler has to access these fields to get the state information. Cracked Events A second alternative is to pass data directly to event handlers as primitive data types, bypassing the EventObject. This has the maximum speed advantage, at the expense of some development tools not recogniz- ing these events as JavaBean events. This type of event is sometimes called a cracked event or primitive event. Development tool support for cracked events that still con- form to the JavaBeans naming convention varies from no sup- port to almost full support; Borland JBuilder, for instance, rec- ognizes cracked events (see Figure 1). The Real-Time Specification for Java calls for a special real-time event called AsyncEvent that has no parameters. Perhaps, as the RTSJ gains in popularity, more tools support will be provided for this type of event. Cracked events and their respective event listeners can be unique for each component and each type of event that’s sent, or generic and reused for more than one component and for more than one event in the same component. Unique events have the advantage of being more appropriately named: each event is descriptive and specific to one type of event. Generic events, on the other hand, require fewer class definitions and are independent of any one component. This reduces the number of inner classes required to interface the components

74 OCTOBER 2001

Java COM Other JavaBeans implement a multicaster, which is an event listener that relays the event to two additional listeners. If one of the additional listeners is also a multicaster, the event is relayed to two more listeners. In this manner any number of listeners can be registered without the use of a vector. The use of the multicasters is hidden behind the JavaBean event regis- tration methods. The advantages of using multicasters in a real-time envi-

J2ME ronment are clear. When only one listener is registered and an event is sent, the event is sent by a single interface call with no looping and no overhead associated with the vector. However, as more listeners are registered for the same event, events will be routed through multiple multicasters, causing more over- head. At some point, if enough listeners are registered, multi- casters will have more overhead than traversing a vector; how- ever, it’s rare to have more than one or two listeners for the same event. FIGURE 1 JBulder session TriggerEvents, AssertEvents, and DataEvents all have their own multicaster classes that are used internally to implement and also reduces call overhead. Components utilizing generic multicast events. events can be wired together many times in a pipeline fashion, with little or no “glue code” required. Real-Time Components Often a timer is required in a real-time or an embedded The aJile Real-Time Embedded Component Model application. The aRTEC OneShotTimer component imple- The aJile Real-Time Embedded Component Model ments a timer that can be started, stopped, or restarted. When (aRTEC), a variation on the JavaBean Component its time expires, it sends a TriggerEvent and waits to be started Architecture, uses standard JavaBean properties but eschews again. If the timer has been started but has not yet expired, it’s EventObjects in favor of cracked events. These choices enable considered to be running. If the timer is restarted while it’s development tool support, while avoiding many of the nega- running, the timer starts over, effectively extending the time tive runtime consequences of the JavaBean event model. delay. When the OneShotTimer is started, it sends an Three cracked events are used for the majority of the AssertEvent with true as the value to indicate that it’s running.

Home J2EEaRTEC components: J2SE a TriggerEvent with no parameters, an When the time expires, it sends an AssertEvent with false as AssertEvent with one Boolean parameter, and a DataEvent the parameter to indicate the timer is no longer running. At with one int parameter. The trigger event is sent as an indica- that time a TriggerEvent is also sent. tor that some physical condition has occurred. It could be a The OneShotTimer can receive one TriggerEvent to start timeout or a sensor threshold being crossed. It can also be the timer and one to stop it. A trigger event sent directly to this received to control physical conditions, such as resetting a object will start the timer. Because this class can implement timer. the TriggerEventListener interface only once, an inner class is An AssertEvent is sent when a state change occurs. A true used to provide a triggerEventListener() method that will stop value in the parameter indicates some state is active and a the timer. false value indicates the state is inactive. For example, a lamp The aRTEC libraries also include a PeriodicTimer and a component can receive an AssertEvent that will trigger the Counter component with similar interfaces. Generally, these lamp to turn on when a true value is passed, and turn off when components provide a friendly front end to real-time execu- a false value is passed. A DataEvent is used when a value is tion primitives provided by the Real-Time Specification for associated with the event. For example, a rotation sensor can Java. send a DataEvent when the angle of rotation changes; the new angle data is passed as the parameter. There are additional Lego Mindstorms Overview types of cracked events used in the aJile embedded compo- To demonstrate the ability of the aRTEC components to nent libraries, but these three have been found to be ade- monitor and control embedded hardware, components were quate for most of our real-time needs. written for the Lego Mindstorms robot sensors. This platform Many JavaBeans can send the same was chosen because it’s well known and exhibits many of the event to more than one registered listen- same characteristics as other embedded and real-time appli- er, called multicast events. To cations. Lego Mindstorms hardware components include implement multicast events, motors, touch sensors, light sensors, rotation sensors, tem- some JavaBeans keep a perature sensors, and lamps. vector of the registered The Lego Mindstorms controller unit is called the RCX. For listeners. When an event our example program we won’t be using the RCX, but rather occurs, the vector is tra- an advance prototype of the Systronix JCX controller that uses versed and the event is sent the aJile aJ-80 direct execution Java processor. The JCX pro- to each registered listener. vides extremely efficient and time-deterministic execution of

The advantages of using multicasters in a real-time environment are clear

76 OCTOBER 2001 “ Java ”COM J2ME

FIGURE 2 Autonomous Line Follower Mobile Robot

100% Java–control applications. The JCX is a direct replace- component by calling the getReverseListener(), getOff- ment for the RCX unit and in its base configuration supports Listener(), or getBrakeListener() methods.

Home J2EEeight input sensors J2SE and four output ports compatible with the The power level of the motor can be set from zero to full Lego RCX sensor and motor ports. power. Two properties set the motor power level: MaximumPowerLevel, which determines the power range, Lego Components and PowerLevel, which determines the duty cycle for the Each of the Lego Mindstorms sensors and motors has a application of power to the motor when it’s in the forward or corresponding Java component. To use the component the reverse state. Because of the real-time responsiveness of the physical Lego hardware needs to be attached to a JCX sensor aJ-80 direct execution Java processor used in the JCX, the duty or motor port, and a corresponding software component cycle for the motor can be set in the high kHz range. needs to be created and initialized to the correct port number. The port number is a JavaBeans property. Touch Sensor The touch sensor component monitors the state of one Motor Lego touch sensor switch. The state of the switch can be The motor component has a forward, reverse, off, and checked by calling the isPushed() method. An AssertEvent is brake state. This state can be set at any time through the State sent with true for the parameter when the button is pushed property. The motor component can also receive four unique and false when the button is released. A TriggerEvent is also TriggerEvents to set the motor state corresponding to forward, sent when the button is pushed and a second trigger event is reverse, off, and brake. Because a TriggerEventListener is an sent when the button is released. This component also can interface, the motor component can directly receive only one receive an AssertEvent that will disable the touch sensor when TriggerEvent. This is because a Java object can implement false is passed and enable it when true is passed. an interface only once. This default trigger event will set the motor state to forward. Three Light Sensor inner classes that implement the The light sensor component monitors the light intensity TriggerEventListener interface from one Lego Mindstorms light sensor. The light intensity are used to set the state can be checked by calling the getLightIntensity() method, to reverse, off, or brake. which returns a value between 0 and 4095, with 0 being the Applications can obtain a darkest. The light sensor also has a specific light range. The reference to one of these lower and upper limits of the range can be set using the inner classes to register it as UpperLimit and LowerLimit properties. When the light inten- an event listener to another sity transitions from inside the specified range to outside the Java and the JavaBean Component Architecture are an excellent platform for building reusable apps

78 OCTOBER 2001 “ Java ”COM extremely small and easy to maintain. The LineFollower appli- cation creates the components, configures them, and defines any event handlers that require special processing. It’s also possible to use a JavaBean-friendly developer tool such as Borland JBuilder to autogenerate the code that creates and initializes the components (see Figure 1). The LineFollower application uses a light sensor to follow the line. When the robot is over a line, the motors will cause

J2ME the robot to move forward. When the robot leaves a line, the motors will cause the robot to turn back to the line. This is done by remembering which direction the robot had to turn last time to find the line, and turn the other direction this time. This algorithm assumes that the robot crosses the line and exits on the opposite side. There’s a possibility that the robot will leave the line on the same side that it entered it. This can happen if the line curves or if the robot finds the line before it completely turns toward it. In this case, the robot must again change directions to refind the line (see Figure 2). This condi- tion is detected by monitoring the time since the robot left the line. If a time limit expires, the robot again changes directions, this time toward the line (see Figure 3). The LineFollower application is FIGURE 3 arranged into three distinct sections: Java-powered Line Follower creating the components, configur- Robot finding the line. ing their properties, and defining any special event handlers. This same pattern is used for many applications that use JavaBeans. The left and right motor compo- nents control the left- and right-drive wheels of the robot, respectively.

Home J2EE J2SE When both motors are in the forward state, the robot will move forward. When one motor is in the forward state and the other is in the reverse state, the robot will turn. Initially both motors are set to the forward range, a TriggerEvent is sent, as is an AssertEvent with false for state so the robot will move forward until it first finds the line. the parameter. When the light intensity transitions to inside A light sensor component is created and initialized to a the range, a second TriggerEvent is sent as well as an lower threshold of 0 and an upper threshold of 1,000. Test AssertEvent with true for the parameter. If a situation were to cases showed a reading of about 800 when the light sensor was occur where more than one light intensity range were over a black line and about 1,200 when it was not. These lim- required, it’s possible to create more than one light sensor its will configure the sensor to be in range when it is over a component and assign them to the same sensor port, each black line and out of range when it is not. component configured for a unique intensity range. The light When the light sensor detects a line, it sends a TriggerEvent. sensor also receives an AssertEvent that will disable the sensor An inner class is registered to receive this event and in turn when false is passed and enable it when true is passed. calls the enteringLine() method. When a line is entered, the robot should stop turning and move forward so both motors Example:Autonomous Mobile Robot Line Follower are forced into the forward state. When the light sensor detects To show the ease of use of the components, we white space, it will send another trigger event indicating that it implemented an Autonomus mobile robot line fol- is now out of range. A second inner class is registered to receive lower (see Figure 2). The LineFollower appli- this event and in turn calls the leavingLine() method. cation (see Listing 1) uses a light sen- When the robot is no longer tracking a line, it needs to start sor, two motors, and a one-shot turning in the opposite direction. This is done in the timer to drive a wheeled triggerEvent() method that checks the direction variable and robot down a black line sets the motors to turn the other way. The enteringLine() drawn on white paper. method also has to start the timer so that the direction will Because most of the func- again be switched if the line is not found. tionality is in the compo- A OneShotTimer component is used to reverse the direc- nents, the line follower code is tion of the robot if a line is not found. It’s initialized to a peri- A real-time embedded component model makes real-time embedded Java environments all the more compelling for developers

80 OCTOBER 2001 “ Java ”COM od of 500ms and will send a TriggerEvent when a timeout cations. Both a serial port or a debounced button component occurs. Instead of using an inner class to receive the trigger would be appropriate for an embedded controller, a joystick event, our main class implements the triggerEvent() method component for a gaming box, and an error logger component directly and registers itself as the listener for OneShotTimer for an industrial-control application. In all these cases, design timeouts. When a timeout occurs, the triggerEvent() method and implementation time can be drastically reduced and will be called and will reverse the robot’s turn direction. maintainability enhanced by using a standard, embedded The design and implementation of the Mindstorms com- real-time component model. ponents required a few weeks of effort, but after that the Java and the JavaBean Component Architecture are an

J2ME LineFollower application required only about an hour to excellent platform for building reusable applications. However, write, and most of that time was spent writing detailed com- until recently the Java platform was not practical for embedded ments. This is a very small example, but a large example that and real-time computing. The release of J2ME, the Real-Time uses similar components could achieve similar productivity. Specification for Java (RTSJ), and the availability of high-speed The LineFollower implementation on the aJ-80 processor low-power Java hardware have overcome these barriers, allow- is also very memory-efficient. Passing the code through the ing embedded developers to take advantage of the productivity aJile ROMizing tool, JEMBuilder, produced a standalone exe- and portability of the Java platform. The addition of a real-time cutable that required less than 80KB of ROM, and only 35KB of embedded component model makes real-time embedded Java RAM when using the standard J2ME Connected Limited environments all the more compelling for developers. Device Configuration (CLDC) runtime. Finally, because of the Java bytecode execution efficiency of the JCX platform, the AUTHOR BIOS robot line follower was amply powered by 6AA batteries (the David Hardin is chief technical officer and cofounder of aJile Systems, Inc. He is a coauthor same power supply used by the Lego RCX); much of the power of The Real-Time Specification for Java, and a member of several Java expert groups is consumed by the motors. convened under the Java Community Process. Dr. Hardin holds a PhD in electrical and computer engineering from Kansas State University. Conclusion The LineFollower example program described above Mike Frerking is software lead at aJile Systems, Inc., where he develops tools and demonstrates 100% Java-based components that are used to components for embedded and real-time Java development. Mike received his BSEE from control a Lego Mindstorms robot. The components were built Iowa State University. specifically for the Lego hardware, but the concepts are appli- [email protected] & [email protected] cable to many other types of embedded and real-time appli-

lightSensor.addOutOfRangeListener( new TriggerEventListener() Listing 1 { Home/** J2EE J2SE public void triggerEvent() { * Controls a JCX with a light sensor and two motors to follow a leavingLine(); line. } * The line follower has two guiding rules. First if it crosses }); the line, * it will change the direction to find the line again. Second, // use inner class to register the enteringLine method when * if it doesn’t cross the line after a specified amount of time, the * it is probably in error and will again flip to find the line. // light sensor moves in range */ lightSensor.addInRangeListener( new TriggerEventListener() { public void triggerEvent() { package linefollower; enteringLine(); } import com.ajile.jcx.*; }); import com.ajile.components.OneShotTimer; import com.ajile.events.*; } public class LineFollower implements TriggerEventListener { /** // Create left hand side motor * Called by the light sensor when light intensity Motor leftMotor = new Motor(Motor.MOTOR_PORT_0); * increases past the upper threshold indicating that we // Create right hand side motor * are moving from dark to light. We lost a line. Motor rightMotor = new Motor(Motor.MOTOR_PORT_1); */ // Create the light sensor void leavingLine() { LightSensor lightSensor = new // the line has been lost, so reverse turn LightSensor(LightSensor.SENSOR_PORT_2); triggerEvent(); // Create one shot timer // reset the timer in case line is not refound OneShotTimer timer = new OneShotTimer(); timer.start(); } // Indicates last turn direction. public static final int LEFT = 0; /** public static final int RIGHT = 1; * Called by the light sensor when light intensity int direction = RIGHT; * decreases past the upper threshold indicating that we * are moving from light to dark. We found a line /** */ * Main entry point. Creates one instance of this class void enteringLine() { */ // stop the timer public static void main(String[] args) { timer.stop(); LineFollower instance = new LineFollower(); // Line found, move forward } leftMotor.setState(Motor.MOTOR_FORWARD); rightMotor.setState(Motor.MOTOR_FORWARD); /** } * Initializes all JCX components and registers event handlers */ /** public LineFollower() { * Causes the JCX to turn in the opposite direction. * If the JCX is presently going straght, this routine // turn motors on * will still cause it to turn in the opposite direction leftMotor.setState(Motor.MOTOR_FORWARD); * as last time this routine was called. rightMotor.setState(Motor.MOTOR_FORWARD); */ synchronized public void triggerEvent() { // initialize light sensor so on the line is in range (0-2000) if (direction == LEFT) { lightSensor.setLowerLimit(0); direction = RIGHT; lightSensor.setUpperLimit(1000); leftMotor.setState(Motor.MOTOR_REVERSE); rightMotor.setState(Motor.MOTOR_FORWARD); // initialize the timer for a .5 second delay } else { timer.setIntervalMillis(500); direction = LEFT; leftMotor.setState(Motor.MOTOR_FORWARD); // register the flip triggerEvent method when a timeout occurs rightMotor.setState(Motor.MOTOR_REVERSE); timer.addTimerListener(this); } } // use inner class to register the leavingLine method when the // light sensor moves out of range }

82 OCTOBER 2001

Java COM PRODUCT REVIEW

onvergence. A word loved by PR com- Java Support panies and feared by nontechnical The important issue is the 9210’s extremely Cconsumers. If you believe industry strong Java support. The 9210 comes with a pundits, we’ll all be carrying combination PersonalJava VM built in, and there’s also a beta mobile phone-PDA-TV-toasters in the next of a MIDP VM available for download. Java appli- few years. You’ll be able to make a phone cations can be downloaded to the phone as

J2ME call, write a memo, watch the morning straight class files and executed if they’re Nokia news, and cook your breakfast all at the in the default package (which is a hack same time while on your way to work. How and shouldn’t be used as a “produc- close reality comes to the dream (or night- tion” deployment mechanism). The mare, depending upon your point of alternative and recommended method view) is anyone’s guess, but the first is that they be packaged as devices that might fit a definition of “con- install files (.SIS) and installed as with vergence” are emerging on the market. any other application onto the device. by Nokia Nokia’s 9210 Communicator is one such You can run applets, but unfortunately combination – a mobile phone and PDA. not through the browser. I can already think of a couple of real- The Communicator world situations where the The first thing you’ll notice about Communicator, 9210 the 9210 when you get it out of the box is its size. It’s a fairly large phone, not quite retro/’80s size but bigger than Communicator the average. For example, a common (cheap) phone over here in Europe is REVIEWED BY JASON BRIGGS the Nokia 5110, which measures 132x47.5x31mm and weighs about [email protected] 170g. By comparison the 9210 meas- ures 158x56x27mm and weighs in at 244g. Of course, we’re not just talk-

Home J2EE J2SE ing about a phone here since it’s also a PDA. So if you’re currently lugging around a PDA and a phone – a Palm IIIc (for example) weighs around 190g info Nokia – add the weight of the two together and Keilalahdentie 4 you may already be carrying significantly FIN-02150 ESPOO more than Nokia’s Communicator. The 9210 runs Symbian’s EPOC operating Finland system, which will be familiar to loyal Psion Phone: +358 7180 08000 users (alas, poor Psion, I knew him well...), and Web: www.nokia.com comes with a number of useful applications, Specifications such as a WWW and WAP browser, e-mail, word processor, spreadsheet, and presentation view- Processor: 52MHz 32-bit ARM9- er. The screen is not touch sensitive – all control based RISC CPU is done by a very small keyboard – but there are Memory: 14MB application, 2MB “quick” buttons on the right-hand side of the User (+ 16MB application card), 8MB screen, for easy access to essential functions. Execution memory For example, if an icon is highlighted, the word Display: 640x200 pixels, 4096 colors “Open” may appear beside the first button. Size: 158x56x27 mm The mail system is one of the cooler appli- Weight: 244g cations on the 9210 as it integrates SMS as well Power: High power Li-Ion battery as e-mail into the one program, rather than different apps for different mail types. An SMS Talk time: 4–10 hours message that’s longer than 160 characters will Standby time: Up to 230 hours be automatically sent as multiple SMS mes- Input: Keyboard sages. Mental note: How to annoy your friends Ports: Infrared, DLR-2L Cable, – send a 50-page text as an SMS message... MultiMediaCard memory slot Less useful is the video player. Personally Operating system: Symbian platform I’m not sold on the whole “watching videos Java support: PersonalJava prein- on your mobile” thing. Don’t get me wrong. I stalled; download beta of MIDP think it will be brilliant once organic displays Availability: First half 2002 as 9290 become the norm and resolutions are so sharp you could slice through the door of a Price: Estimated $700–$1000 car quicker than you could say “Ginsu.” But on a 640x200 screen with over 4,000 colors, we’re not exactly talking cinematic quality.

84 OCTOBER 2001

Java COM PRODUCT REVIEW

using Java applications, might prove rather handy. For a company Image Test with a large, roving sales force, outfitting their entire staff with mobile This test draws 20 50x50 pixel images per frame for 500 phone, laptop, and mobile Internet connections would prove costly frames, and then works out the frame rate from the time taken.

by Nokia by (to put it politely). A laptop solution seems overkill when you consid- This test runs at 4.4 fps. er exactly how much use the staff of this fictional company is likely to

J2ME get out of a full-blown PC. However, the 9210 is already connected Conclusion and contains most of the applications the salespeople might use, and If you’ve seen Nokia’s TV commercial for the 9210, you’ll company-specific apps (a product catalog, for example) can be writ- probably agree that the company appears to be targeting busi- ten in Java and quite easily installed on the device. nesspeople, the kind of people who are constantly on the go, How well does PJava work on the 9210? It should be noted in perhaps have a need for a PDA, but are less likely to be inter- advance that the processor, while more powerful than most mobile ested in lugging a laptop around. phones, is still only 52MHz. So performance on certain graphics In my opinion, if you’re intending to buy a PDA and are operations won’t be console quality, to put it mildly. However, when already carrying a mobile, you should look at the 9210 as a con- you consider the intended market and the above example, this venient alternative. Corporations that are tooling up their man- doesn’t really seem like that much of a negative point. agement/executive/mobile staff with PDAs and/or mobile Nokia 9210 Communicator Nokia 9210 Communicator phones should definitely consider the Communicator option. Test Results It’s a fairly large phone, as it has to support a keyboard that AWT Component Test could be used by people bigger than a 5-year-old child; so if Here we place a number of AWT components (buttons, text you’re looking for a small device, the 9210 may not be right for fields, etc.) on the screen using a couple of Layout Managers. you. However, it weighs less than an average mobile phone While the 9210 displays all the components as expected, one and PDA together, so I believe it rates highly on convenience slight problem is that with the default (white) background color factor alone. of the panels, it can be quite difficult to see which component With a free SDK available, and built-in and downloadable has the focus. This may be an issue when porting PersonalJava VMs, Nokia’s support for Java on the 9210 is very good. apps without modification to the phone. Of course, it’s not a Graphics performance is not mind-blowing because of the problem if your user-interface color scheme is configurable. CPU speed, but it doesn’t need to be when you take into account the people who are likely to be using the device. Triangle Drawing Test It’s a solid little unit, and the only negative point I

Home J2EEHere we draw J2SE four randomly sized, filled triangles using mul- noticed during testing was Symbian’s typically lack- tiple calls to the drawLine graphics method. The PersonalJava luster PC connectivity (at least on Windows ME). VM on the 9210 takes 200–600ms to draw the four triangles onto Not that it didn’t work; rather, it occasionally the 640x200 screen. Note that these are random triangles, so the decided not to connect without a reboot. Having slower time is indicative of a larger triangle to render. owned a Psion in the past, my opinion is that this is somewhat par for the course, and it happened Pixel Blit Test infrequently enough that it wasn’t a huge bother. Here we blit random pixels to the screen as a single image for 500 After seeing the 9210, I’m looking forward frames. On the 9210 the test runs at about 1.1 frames per second to the new Java-enabled products Nokia has (fps) on a 320x200 window (which is half the 9210’s screen size). up its corporate sleeve.

86 OCTOBER 2001

Java COM J2ME

Part 2 of 2 Home J2EE J2SE

he Java develop- ment and run- T time environ- ment, with its “write once, run anywhere” paradigm, brings enor- mous advantages to the embedded industry. Java code is highly reliable, eas- If you answered yes to ily ported, and includes fea- any of these questions, tures such as Internet readi- Java may be the right ness, security, and the ability to choice for you. Here’s why. download code at runtime to upgrade or extend applications. Java Benefits As such, it’s ideal for Internet appli- The intrinsic advantages of Java ances (such as set-top boxes, Internet screen are portability, reusability, and develop- phones, or handheld devices) as well as traditional ment life-cycle enhancements. They’re invalu- embedded devices (such as printers, medical devices, meas- able for any software engineering project, including urement and control instruments, telecommunication and data- embedded software development. The benefits include: communication equipment now connecting to the Internet). • Dynamic extensibility: A Java program can download code at In Part 1 of this article (JDJ, Vol. 6, issue 9), we discussed runtime by fetching new class files and either replacing the some of the challenges of using Java for developing embedded same classes already loaded into memory or adding them to systems and some of the solutions that are available to develop- the application. Dynamic extensibility enables developers to ers. In Part 2, we describe the benefits Java brings to the world of extend the functionality of an application, upgrade classes embedded software development. We also illustrate, based on a practical case study, how using Java for writing and running 1. Will you want to download code to the device? embedded software can benefit application developers. 2. Will the device run in a network with a similar class of devices from other manu- facturers or any other kind of devices? Is Java Right for Your Embedded Device? 3. Will there be multiple third-party content providers for the device? By asking the questions at the right, you should be able to 4. Will user’s experience (look and feel, stability, security) matter much? determine if Java is the right development environment for 5. Are you working within a short-development time frame? your embedded device.

88 OCTOBER 2001

Java COM J2ME

Over 2,500 lines of commented code with comments in ad hoc format. Under 1,600 lines of javadoc’ed code with comments in standard format.

"Typical" C program structure, with many global variables shared and Clean structure, using an interface to abstract the interaction of the jtalk ses- modified all over the place. sion implementation and the client of the session.

A truly confusing use of alarm signals, and even setjmp/longjmp calls to Natural use of ordinary control structures and Java threads. create complicated artificial flows of control and get around the lack of threads, making the code difficult to understand and completely not portable.

Estimated time to understand (not to write, since we didn’t): two and a Estimated time to write: half day. half days.

TABLE 1 Comparison of C code and Java code

with new versions of code, or simply fix software problems. on an existing version of C for easy comparison, and it’s sim- It’s also the base for implementing an application-manage- ple enough for a quick port, but large enough to be a signifi- ment framework and a service-delivery platform. cant case study. • Security: Strict code verification prior to execution ensures Several aspects of this hands-on porting exercise are

Home J2EEthat code doesn’t J2SE try to disregard the protections imposed described below, basing comments on code snippets. The com- by the language, build direct memory access pointers, or plete application source code is available for download on the use the wrong object. Java applets also obey limitation rules JDJ Web site at www.sys-con.com/java/sourcec.cfm and can be (known as the sandbox concept) that Web browsers enforce freely used, modified, and distributed. The download package to forbid access to system resources, such as files and net- consists of application source code, documentation in javadoc work hosts. It’s impossible in theory to introduce malicious format, Makefile, and precompiled class files and a .jar file. code into a Java application. Java threads can’t corrupt the The application we chose is called jtalk, a port of the Unix execution space of another thread. talk command. Here’s an excerpt from the manual pages on • Portability: Java provides standard programming inter- the talk command on a FreeBSD system (obtained by typing faces to OS-level services such as multithreading, network- man talk on the FreeBSD 4.3 system): ing, and graphics. This enables embedded system develop- ers to write platform-independant code more quickly and Talk is a visual communication program that copies easliy. lines from your terminal to that of another user. • Reliability: Java provides the reliability that embedded sys- When first called, talk sends the message: tems require, such as the obligation of source structuring, strong compile and runtime verifications, and an efficient Message from TalkDaemon@his_machine... exception-handling mechanism. Java’s memory-manage- talk: connection requested by ment mechanism removes sources of many problems asso- your_name@your_machine. ciated with dynamic memory allocation, such as memory talk: respond with: talk your_name@your_machine leaks or corrupted pointers. Java also relieves the embed- to the user you wish to talk to. ded programmer of the hazardous object de-allocation task. At this point, the recipient of the message should • Reusable code: Java provides ease of code development, reply by typing: code reuse, and better code quality due to its true object orientation, simplicity, and development environment. A talk your_name@your_machine wide variety of affordable and efficient Java development tools are available as are many trained engineers. The talk utility is a two-way, screen-oriented communica- tion program. Once communication is established, the two Hands-on Porting Exercise parties can type simultaneously, with their output displayed To illustrate how using Java for writing and running in separate regions of the screen. embedded software can benefit application developers, we The talk application sets up a peer-to-peer communica- selected a single healthy-sized example of a Java application – tion session with a remote user on another host. A talkd dae- suitable and also useful for embedded applications. The mon has to be running on both the caller’s and the callee’s example includes the following characteristics: it uses a sim- machines and act as a repository for active talk invitations ple graphical user interface, it’s network-oriented, it’s based from one party to another. The caller has to be able to leave

90 OCTOBER 2001

Java COM J2ME an announcement on the callee’s machine that an invitation source code, you can use the Makefile for GNU make includ- exists and has to leave the invitation itself on the caller’s own ed in the download package. machine. Once the session is connected, the talk daemon The original C files from which jtalk was created are also isn’t used; it’s just peer-to-peer between the two talk pro- included in the download package for your convenience. grams. These files come from the FreeBSD 4.3 distribution. Since talkd daemons exist for Unix machines only, a port of Choosing to port an existing Unix application, coded as a talkd in Java was also created as part of this case study so talk C program, was deliberate so a head-to-head comparison can be used on Windows machines as well as in a non-Unix could be easily done between the C code and the Java code. embedded Java application environment, such as Wind Table 1 summarizes the major characteristics of the two ver- River’s VxWorks and Personal JWorks. sions. Note: There are two incompatible talk protocols of differ- The experience with jtalk showed that Java can be used ent ages. The older one uses UDP port 517 and is in use on more productively as a language, and as a programming envi- Solaris. The newer one (which we chose to implement) uses ronment, than C/C++ for certain types of applications, espe- UDP port 518 and is in use on BSD systems, such as FreeBSD cially in the embedded area. or Wind River’s BSD/OS. Some of the productivity advantages of Java are at the lan- Technically, the port 517 protocol is called talk and the guage level. For example: port 518 protocol is called ntalk. The port number 518 is cur- • The language’s insistence on strong type checking pro- rently hard-coded into jtalk and jtalkd. But it wouldn’t help to motes the careful arrangement of code into well-designed change them to 517 because the older talk protocol on port classes, saving effort when supporting the code later. 517 is incompatible. • The jtalk program is cleanly organized in a directory struc- To run the jtalk program on your JVM, download the case ture com/windriver/jtalk following the package organiza- study package, put jtalk.jar somewhere on your file system, tion, leading to clean, easily understandable, and maintain-

Home J2EEadd the location J2SE of jtalk.jar to your classpath, and invoke as able code. Each Java source file starts with: follows: package com.windriver.jtalk; java com.windriver.jtalk.jtalk {person} [{terminal}] • The C code for the talk program has a strange organization, If the machine on which you’re running jtalk doesn’t run a with global variables shared by many modules. Most of the talk daemon already, you’ll have to first launch jtalkd with the time it took to port the code was actually figuring out how following command: that code worked. In addition, the use of global variables makes the application non-reentrant, which can be a major java com.windriver.jtalk.jtalkd issue for many embedded systems. As a consequence, it’s impossible to have multiple talk sessions on an embedded The syntax for {person} can be any of the following: system. • The Java language’s class inheritance (where a subclass username extends a superclass, adding new features or overriding username@hostname other features) and interface concepts (making implemen- hostname!username tations pluggable) both lead to more flexible reuse of exist- hostname:username ing Java code. In C, you usually have to modify to reuse code. {terminal} is optional. It’s required when responding to an • The file jtalkSessionClient.java (see Listing 1) defines an invitation from someone with interface for a client session implemented among other more than one login to be sure interfaces in the AWT area, and makes the creation of GUIs you get to the right one. much easier by the main class jtalk in jtalk.java (see Listing If you can’t run multiple JVMs 2). on your system (which is the case • Exception handling is another fantastic built-in language on most embedded RTOSes), the feature that Java programs can efficiently take advantage of download package includes a to manage abnormal situations or a rupture in the usual basic “shell” with a simple self- flow of execution. For example, jtalk defines a new explanatory GUI to help you RuntimeException called jtalkSessionException (see Listing launch the jtalkd and jtalk appli- 3) that is thrown by jtalk when a problem occurs in cations: jtalkSession.java (see Listing 4) when trying to get the host- name information. java • Another example of productivity gains from language-level com.windriver.jtalk.jtalkShell features of Java is automatic garbage collection, freeing developers from tedious management of dynamic memory FIGURE 1 HTML documentation page for jtalkSession class If you want to recompile the allocations, often prone to a generation of nasty bugs.

92 OCTOBER 2001

Java COM J2ME Productivity advantages of Java from the overall pro- there’s no incoming connection before the 30 seconds elapse. gramming environment are, for example: We just have a simple loop in the Java sources (see Listing 6). • The existence of the javadoc tool means that you can gen- erate helpful documentation in HTML format for Java code A Language and Platform right from the program source, leading to better document- In this case study, we’ve demonstrated how Java can bene- ed source code and more available documentation during fit embedded software application developers, especially all engineering phases. those focusing on graphics and multithreaded networking. • Figure 1 shows a snapshot of the HTML documentation Java can benefit these users when used both as as a program- page for the jtalkSession class, ming language and a development platform. • The existence of standard API libraries for almost every Java’s standard, complete, and easy-to-use APIs allow devel- imaginable application programming need leads to quick opers to write portable, more compact, more efficient, simpler, coding of applications. This also leads to smaller applica- and more easily maintainable code than in C, for which net- tion code size, as seen in this case study. work, threading, and graphics APIs are usually proprietary. In • If you’re an application developer, you can write your appli- addition, developers can also benefit from the language’s cation faster using Java and the preexisting standard APIs. If advanced concepts such as object orientation, packages, excep- you’re a system developer, however, you may find Java too tions, and strong typing, as well as from the advantages offered abstract or high level, lacking features like direct access to by Java’s development platform, including documentation gen- memory or interrupt handling. eration, cross-platform portability, and security features (which • The most important preexisting API sets relevant to embed- enable them to write more efficiently for better code). ded applications running in PersonalJava types of plat- Although it wasn’t covered in this article, Java is ideal as an forms, such as Wind River’s Personal JWorks, are networking execution platform. Java’s capability for dynamic and secure and user interface APIs. Thus, if your application performs code updates provides the essential building block for creat-

Home J2EEnetwork communication J2SE and has a user interface, you ing an application and content-management framework that should at least consider using Java to more productively enables a service-delivery platform. Java’s standardized API code those portions of your application. and portable code allows application developers to write plat- form-independent software content or services independent- To understand Java’s suitability to write networking code, ly from embedded-system manufacturers. As long as applica- look at the original C source for the talk program. Note all the tions are written to a Java specification that’s compatible with occurrences of signal() calls to set or clear a handler for the the system’s Java application environment, end users of such SIGALRM used to manage connection timeouts. Instead of systems will be able to download, install, and run those appli- setting a timeout on a socket the way it’s done in the Java pro- cations on their systems. gram, the C version sets a timeout for the process; if the time- out occurs, something is done. In one case, in invite.c, there’s AUTHOR BIOS even a setjmp/longjmp pair, with the longjmp coming from Vincent Perrier is Wind River’s product manager for Java platforms. He has a computer the tail end of the SIGALRM handler used there. The effect is science and engineering degree from the University of Nantes in France. to create a crazy kind of “loop”(see “flowchart” in Listing 5). This loops every 30 seconds, remaking the invitation Steven Schwarz is a senior member of the technical staff at Wind River. Recently he has repeatedly until at some point accept() manages to complete been making processor-independent ports of CLDC and MIDP-reference implementations to before the SIGALRM is delivered. VxWorks. In the Java sources, we simply set a 30-second timeout on [email protected] & [email protected] the ServerSocket. The equivalent accept() call then returns if

/** Listing 1: jtalkSessionClient.java * This method is called by the session to inform the client public interface jtalkSessionClient of a { * character typed by the remote user of the session. */ /** public void jtalkSessionHeTyped(int b); * This method is called by the session to deliver a status message /** * to the client. * This method is called by the session when it is about to */ shut public void jtalkSessionStatus(String s); * down. */ /** public void jtalkSessionEnding(); * This method is called by the session to get a character } typed * by the local user of the session; each such character is * transmitted by the session to the remote user of the ses Listing 2: jtalk.java sion. public class jtalk */ extends Frame public int jtalkSessionITyped(); implements ActionListener, KeyListener,

94 OCTOBER 2001

JJavaava COMCOM J2ME WindowListener, jtalkSessionClient Listing 6: jatlkSession.java void issueInvitation() { Listing 3: jtalkSessionException.java public class jtalkSessionException for (;;) { extends RuntimeException if (current_idnum >= 0) { { client.jtalkSessionStatus(RINGING); /** current_idnum++; * Construct a jtalk session exception without a detail mes } sage. */ client.jtalkSessionStatus(ANNOUNCING); public jtalkSessionException() { super(); } msg.setMessage((byte) talkdMessage.ANNOUNCE, current_idnum, /** myUserName, * Construct a jtalk session exception with a detail message. hisUserName, */ hisTerminal, public jtalkSessionException(String s) { server, super(s); control, } myInetAddr); } controlTransaction(hisInetAddr); remote_idnum = rs.getIdNum();

Listing 4: jtalkSession.java if (rs.getAnswer() != talkdResponse.SUCCESS) { try { throw new jtalkSessionException("invitation rejected: " + myInetAddr = java.net.InetAddress.getLocalHost(); rs.decodeAnswer()); if (args[arg].equals("-host")) { } myInetAddr = java.net.InetAddress.getByName(args[arg + 1]); client.jtalkSessionStatus(INVITING); arg += 2; nargs -= 2; msg.setMessage((byte) talkdMessage.LEAVE_INVITE, } current_idnum, HomemyHostName J2EE = myInetAddr.getHostName(); J2SE myUserName, } hisUserName, catch (Throwable t) { t.printStackTrace(); hisTerminal, throw new jtalkSessionException("can t determine local host server, name"); control, } myInetAddr); client.jtalkSessionStatus("talk@" + myHostName + " starting."); controlTransaction(myInetAddr); local_idnum = rs.getIdNum(); Listing 5: In the process context 1. client.jtalkSessionStatus(WAITING2); 2. 3. try { 4. data = server.accept(); 5. data.setSoTimeout(1 * 1000); 6. dataInput = data.getInputStream(); dataOutput = data.getOutputStream(); Code snippet from invite.c: } void catch (InterruptedIOException x) { invite_remote() current_idnum = remote_idnum; { continue; } setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0); catch (Throwable t) { message("Waiting for your party to respond"); t.printStackTrace(); signal(SIGALRM, re_invite); new jtalkSessionException("can’t get connection"); (void) setjmp(invitebuf); } while ((new_sockt = accept(sockt, 0, 0)) < 0) { if (errno == EINTR) finally { continue; msg.setMessage((byte) talkdMessage.DELETE, p_error("Unable to connect with your party"); local_idnum, } myUserName, hisUserName, In the SIGALRM handler context: hisTerminal, 1. null, 2. control, 3. myInetAddr); controlTransaction(myInetAddr); Code snippet from invite.c: void msg.setMessage((byte) talkdMessage.DELETE, re_invite(signo) remote_idnum, int signo; myUserName, { hisUserName, message("Ringing your party again"); hisTerminal, waddch(my_win.x_win, ’\n’); null, if (current_line < my_win.x_nlines - 1) control, current_line++; myInetAddr); /* force a re-announce */ controlTransaction(hisInetAddr); msg.id_num = htonl(remote_id + 1); } announce_invite(); break; longjmp(invitebuf, 1); } } }

96 OCTOBER 2001

Java COM Java COM J AVA BASICS J2SE J2EE J2ME

Uncommonly good solutions to common application problems PART 2 of 3 Written by James McGovern

Home he performance of J2EE-based applications some- <%@ page session="false"%> times doesn’t live up to users’ expectations. Usually it’s impossible to quantify exactly where the bottle- Servlet and Memory Usage T necks are. Many developers spend time searching for Many application developers are guilty of storing way too articles on the Internet only to find the same old tips about much information in the users session. Sometimes these using the synchronized keyword and string concatenation objects don’t get garbage collected in a timely manner. The without ever finding information that’s useful. This article will typical performance symptom may be periodic slowdowns help you find the holy grail of Java performance. that are reflected in the user experience but aren’t traceable to In my previous article (JDJ, Vol. 6, issue 9) we focused on any particular component. If you’re monitoring the JVM's tips that are common to most applications. The tips present- heap size, this may be reflected as significant peaks and drops ed here focus on common problems found within applica- in memory usage instead of a normal pattern. tions that utilize JSP, EJB, JNDI, and JDBC. Future articles will There are a couple of ways to even out memory usage in this sce- cover some powerful techniques to help your applications nario. The first recommendation is to have all beans that are scoped perform better. as session implement the HttpSessionBindingListener interface. This allows you to explicitly release resources that are used within the Session Invalidation bean by implementing the method valueUnbound(). Many application servers typically have a default timeout The other approach is to simply expire sessions more value of 30 minutes for cleaning up dead sessions. When an quickly. Most application servers have settings that usually application server can’t hold any more sessions in memory, it specify the interval. You can also do it yourself programmati- may cause the operating system to page out portions of mem- cally by calling session.setMaxInactiveInterval(), which speci- ory. The application server may also swap unused sessions to fies the time in seconds between client requests before the disk based on the most recently used algorithm or even throw servlet container will invalidate the session. OutofMemoryExceptions. In a high-volume system, serializ- ing sessions can be expensive. HTTP Keep-Alive Calling HttpSession.invalidate() is the recommended way The majority of Web servers on the market, including to clean up a session when you no longer need to use it. This iPlanet, IIS, and Apache, support HTTP Keep-Alive. This func- method is usually called as part of an application’s logout tion keeps an open connection from client to server so that page. subsequent requests to the server don’t have to be established or reestablished. This is usually a good technique for sites Sessions and JSP serving static content. The problem with sites with heavier The J2EE specification requires all JSP objects that can be loads is that the benefit of keeping a connection open for a referenced in JSP source and tags be usable without explicit single client also has a performance penalty as it ties up declaration. For Web pages that don’t require session tracking, resources when the process is idle. This resource usage is even you can save resources by turning off automatic session cre- more important if your Web and application server are one ation using the following page directive: and the same.

98 OCTOBER 2001

Java COM • Real-World Web Services: Is It Really XML's Killer App? • Demystifying ebXML: A Plain-English Introduction • Authentication, Authorization and Auditing: Securing Web Services • Wireless: Enable Your WAP Projects for Web Services • The Web Services Marketplace: An Overview of Tools, Engines and Servers • Building Wireless Applications with Web Services • How to Develop and Market Your Web Services • Integrating XML in a Web Services Environment • Real-World UDDI • WSDL: Definitions and Network Endpoints • Implementing SOAP-Compliant Apps • Deploying EJBs in a Web Services Environment • Swing-Compliant Web Services • and much, much more!

*Offer expires November 30, 2001 Java COM J AVA BASICS %%OffOff* the annual newsstand rate SAVESAVE 30 30 Choose the Right Include Mechanism A typical JSP architecture may break out headers, footers, and navigation into their own resources, included in each JSP page as appropriate. Currently there are two methods to include a resource: the include directive and the include action. • Include directive <%@ include file="copyleft.html" %> : Includes the content of the resource at compile time. The page with the directive and the resource

*Offer subject to change without notice are merged into one file before final compilation. When resources are ANNUALANNUAL NEWSSTAND COVER PRICE RATE resolved at compile time, they’ll always be faster than resources resolved at runtime. J2SE $71.88 • Include action : Includes the response gen- YOU PAY erated by executing the specified page. Since this is done at runtime, we can $49.99 vary the output produced. Use this action only for content that changes often YOU SAVE and for scenarios in which pages to include can’t be decided until the main page Off the 30% Newsstand Rate has been requested. Receive 12 issues of Java Developer’s Journal for Use Cache Tagging Features only $49.99! That’s a savings of $21.89 off the Several vendors have added cache tagging features to their application servers

J2EEcover price. Sign up online at www J2ME .sys-con.com or call 1-800-513-7111 and subscribe today! for use with JSP. BEA’s WebLogic Server introduced this feature in the 6.0 versions of its product. This feature is also supported by the Open Symphony project. JSP cache tagging allows both fragments and page-level information to be cached. Here’s what you’ll find in When a JSP page executes, if a tagged fragment is found in cache, the code that every issue of JDJ: creates the fragment is skipped. Page-level caching catches requests for specific URLs and caches the resulting • Exclusive coverage output. This feature is extremely useful for shopping cart/catalog and/or portal home pages. In this scenario a page-level cache can store the resulting content to J2EE J2SE J2ME satisfy future requests. Here’s an example URL that would be a good candidate: Home • Exclusive feature articles http://quote.yahoo.com/q?s=hig&d=t. Use of cache tagging features provides performance increases for applications • Interviews with the hottest where there’s significant logic; and has less of an effect for truly architected sites

names in Java that utilize an MVC (Model View Controller)-based framework.

• Latest Java product reviews • Industry watch This feature is extremely “ “useful for shopping cart/catalog and/or portal home pages

Always Access Entity Beans from Session Beans Accessing entity beans directly is bad for performance. When a client applica- tion accesses an entity bean, each get method is a remote call. A session bean accessing the entity bean is local and can collect all data in a structure and return it by value. You can read more about the value pattern in Design Patterns by the Gang of Four. Using a session bean to wrap access of an entity bean allows for better transac- tion management as the session bean will commit only when it reaches a transac- tion boundary. Each direct call to a get method results in a transaction. The con- tainer will execute a store-and-load after each transaction on an entity bean. At times using an entity bean will result in bad performance. If the only pur- pose for an entity bean is to retrieve and update values, you’ll gain better per- formance using JDBC within session beans. Use Read-Only in the Deployment Descriptor The deployment descriptor for an entity bean allows all get methods to be set as Read-Only. This increases performance when the unit of work in a transaction contains no methods other than read-only, as the container won’t invoke the store.

100 OCTOBER 2001

Java COM J AVA BASICS

SUBSCRIBE AND SAVE Cache Access to EJB Homes EJB Home interfaces are obtained through a JNDI naming lookup. This opera- tion requires significant resources. A good place to put lookup code is within a servlet’s init() method. If your application requires EJB access by multiple servlets, it would be wise to create an EJBHomeCache class. This class typically would be implemented as a singleton. Consider Local Interfaces for EJBs Offer subject to change without notice Local interfaces is an addition to the EJB 2.0 specification, allowing a bean to ANNUALANNUAL NEWSSTAND COVER PRICE RATE avoid the overhead of a remote invocation call. Consider the following code: J2SE $83.88 YOU PAY PayrollBeanHome home = (PayrollBeanHome) $77.99 javax.rmi.PortableRemoteObject.narrow (ctx.lookup ("PayrollBeanHome"), PayrollBeanHome.class); YOU SAVE Off the $5.89 Newsstand Rate PayrollBean bean = (PayrollBean) javax.rmi.PortableRemoteObject.narrow DON’T MISS AN ISSUE! (home.create(), PayrollBean.class);

J2EEReceive 12 issues of J2ME The first statement indicates that we want to find the bean’s home interface. XML-Journal for only $77.99! That’s a savings of $5.89 off This lookup is via JNDI, which is an RMI call. We then locate the remote object and the annual newsstand rate. return the proxy reference. This too is an RMI call. The second statement demon- Sign up online at strates creating an instance. This code points to a stub that creates an IIOP request www.sys-con.com or call and transmits it over the network. This too is an RMI call. 1-800-513-7111 To implement this functionality, all you have to do is extend from and subscribe today!

EJBLocalObject instead of EJBObject. My Pentium 700MHz machine, a change Here’s what you’ll find in

Home every issue of XML-J: • Exclusive feature articles There’s only one “ • Interviews with the hottest names in XML appropriate answer: • Latest XML product reviews “ • Industry watch consider using RMI and JNDI together

from remote to local interfaces, sped up method calls overall by 20%. To implement local interfaces, you may have to make the following changes: 1. Methods can no longer throw java.rmi.RemoteException. The rule also applies to exceptions extended from RemoteException, such as TransactionRe- quiredException, TransactionRolledBackException, and NoSuchObjectExcep- tion. EJBs provide equivalent local exceptions (TransactionRequired- LocalException, TransactionRolledBackLocalException, and NoSuchObject- LocalException). 2. All data and return values are passed by reference, not by value. 3. The local interface must be used on the machine where the EJB is deployed. In simpler terms, everything must be within the same JVM. This limits you to deploying on nonclusterable applications. 4. References for beans that implement local interfaces aren’t serializable. Consider Writing Your Own Stubs Stubs are responsible for forwarding method invocations to remote beans, and are typically generated by most deployment tools. If you haven’t already imple- mented the value pattern, you can implement this functionality before anything is transmitted over the wire by modifying the stub. In modifying the stub, you can also implement your own caching routine or even compress data before it’s transmitted. Normally this technique isn’t recommended and would be against previous recommendations about being clever. You’ll have to worry about the deployment tool overwriting your changes as well as having your stub figure out when to reload data if another client changes information.

102 OCTOBER 2001

Java COM Java COM J AVA BASICS %%OffOff* the annual newsstand rate SAVESAVE 30 30 Generating Primary Keys There are many clever ways of generating primary keys within an EJB. I’ll list several common techniques and then explain why they’re all bad. You can use the database’s built-in identity (SQL Server IDENTITY or Oracle’s SEQUENCE). This makes the implementation of your EJB nonportable (bad). You could have an entity bean increment its own value, but this is bad as it requires serializable transactions, which are also slow.

*Offer subject to change without notice You could use a time service such as NTP, but this requires native code and ANNUALANNUAL NEWSSTAND COVER PRICE RATE locks your bean to the particular OS. This approach also allows for the potential of generating two primary keys in the same millisecond on multiple CPU servers. J2SE $71.88 You could architect your bean and steal some ideas from Microsoft by creating YOU PAY a GUID, but you’ll run into the fact that Java can’t determine the MAC address of $49.99 your network card without resorting to JNI, which will make your bean OS- YOU SAVE dependent. Off the 30% Newsstand Rate You’ll also run into an issue if you try to utilize System.currentTimeMillis(), Receive 12 issues of Wireless Business & which will have the same issues previously mentioned. It’ll be hard to identify a Technology for only $49.99! That’s a comparable formula. You could try to implement statics, but you’ll fail as they savings of 30% off the cover price. Sign up online aren’t supported in the EJB specification. J2EEat www.sys-con.com or call 1-800-513-7111 J2ME There are several other approaches but they all have their limitations. There’s and subscribe today! only one appropriate answer: consider using RMI and JNDI together. You’ll start with binding the RMI remote object to the JNDI tree via the RMI registry using the In October WBT: JNDI service provider interface. Your clients will look up the singleton via JNDI. BREW vs J2ME Here’s an example: A look at both sides of the rivalry public class keyGen extends UnicastRemoteObject Will Mobile Travel Do for Wireless What Amazon.com Did for E-Commerce? implements Remote { One area of m-commerce is alive and growing…fast Home The Future of Mobile Entertainment private static long keyVal = System.currentTimeMillis();

The market potential is awesome The GSM Association M-Services Initiative public static synchronized long getKey()

An overview of the guidelines that could make WAP friendlier throws RemoteException { Getting Started in Wireless return keyVal++; } A wireless beginner’s guide Many applications “ “ should consider placing a constraint on cache growth

JDBC and Unicode Hopefully you’ve read the typical industry recommendations about using JDBC such as using connection pools, preferring stored procedures or direct SQL, using type 4 drivers, removing extra columns from the result set, using prepared state- ments when practical, having your DBA tune the query, and choosing the appro- priate transaction levels. Besides the more obvious choices, the best action you can take to increase per- formance is to consider storing all character data in Unicode (Code page 13488). Java processes all data in Unicode and therefore the database driver doesn’t have to perform a conversion. But beware: taking this step will cause your database size to grow, as Unicode requires 2 bytes per character. You’ll have to worry about per- formance when you implement this tip if you have non-Unicode applications accessing the data, as a conversion will also occur. JDBC and I/O When your application requires access to a large result set, consider imple- menting block fetches. By default, JDBC fetches 32 rows at a time. As an example,

104 OCTOBER 2001

Java COM Java COM J AVA BASICS

SUBSCRIBE AND SAVE if you needed to iterate through a result set of 5,000 rows, this would cause JDBC to make 157 calls to the database to fetch data. If you changed the block size to 512, this would require only 10 round-trips. This tip may not work in several scenarios. If you use scrollable result sets or specify FOR UPDATE as part of the query, blocking isn’t used. Another technique to use is the Page-by-Page Iterator pattern.

Offer subject to change without notice Consider Using an In-Memory Database ANNUALANNUAL NEWSSTAND COVER PRICE RATE Many applications have the need to store a significant amount of data on a per- user basis in the session. Typically, you may see this implemented as a shopping J2SE $83.88 cart and catalog. Since this type of data is represented as row/column data, many YOU PAY applications may create either large vectors or hashmaps. Keeping this type of $69.99 data in session severely limits scalability as you must have at least the amount of YOU SAVE memory per session times the maximum number of concurrent users, which can Off the $13.89 Newsstand Rate either be a very expensive server and/or could stretch garbage collection times to unbearably long periods. DON’T MISS AN ISSUE! To achieve slightly better scalability, some people have offloaded the shop- Receive 12 issues of Web Services Journal ping cart/catalog functionality to the database tier. The fundamental problem J2EEfor only $69.99! That’s a J2ME savings of with the database tier is based on the architecture of most relational databas- $13.89 off the annual newstand rate. es. The main principle at work is that they try to make all writes durable; hence Sign up online at www.sys-con.com or call all performance is tied to the ability to physically write the data to disk. 1-800-513-7111 and subscribe today! Relational databases try to reduce I/O, especially for read operations, but accomplish this goal only by execution of complex algorithms that implement In October WSJ: caching and are the main reason that the database tier’s number-one bottle- neck is usually CPU. Web Services Made Easy There is an alternative. Consider using an in-memory database. Several ven- The first step toward collaborating software services dors have addressed this market. I’m a fan of TimesTen, but you’re welcome to Home Web Services: What Does It Take? choose your own. They start by allowing data to be temporarily written but not How to enhance the Web user interface necessarily persisted to disk, and keeping all operations in memory. As a result, they also don’t need complex algorithms to reduce I/O, and are faster because they Web Services Development Issues How to bridge the Web services divide can employ simpler locking mechanisms. Sending Out-of-Band Messages to Develop a Smarter Caching Mechanism SOAP-Based Web Services Many application developers have implemented caching mechanisms for fre- Removing some of the drudgery quently requested data. These caches are typically implemented as hashmaps. The Building Web Services Using Microsoft .NET main problem with this approach is that there’s no constraint on how large the How to harness the connectivity of the Internet hashmap can grow. Many applications should consider placing a constraint on cache growth by using algorithms utilizing a strategy of keeping only the most recently used objects. This is best accomplished by combining a hashmap with a LinkedList. The code should implement the following logic: 1. If the cache is full, remove the last object from the tail of the list and insert the new object at the head of the list. 2. If the cache isn’t full, and you want to insert a new object, put it at the head of the list. 3. If the object is already in cache, move it to the head of the list. Conclusion Optimizing code is one of the last things developers should consider. Slow applications that work are preferred to fast applications that don’t. Keep in mind that performance is sometimes in perception. It’s possible to optimize a user’s per- ception of performance without necessarily optimizing an application. Consider providing immediate feedback, as users will be happier to view a screen that paints immediately and takes 10 seconds to process than to have a screen that paints itself in seven seconds.

AUTHOR BIO James McGovern is an enterprise architect with Hartford Technology Services Company LLC, an information technology services firm dedicated to helping businesses gain competitive advantage through the use of technology. His focus is on developing high-availability Internet applications.

[email protected]

106 OCTOBER 2001

Java COM Plan INTERNATIONAL to Exhibit WIRELESS BUSINESS & TECHNOLOGY Provide the Resources to Implement Wireless Strategy CONFERENCE & EXPO The conference will motivate and educate. The expo is where attendees will want CONFERENCE & EXPO to turn ideas into reality. Be ready to offer solutions. CONFERENCE & EXPO

Shaping Wireless Strategy SHAPE for the Enterprise YOUR WIRELESS Santa Clara, CA May 7-9, 2002 STRATEGY! Wireless Edge will provide the depth SAVE THE and breadth of education and product WHO SHOULD ATTEND resources to allow companies to Mobile & Wireless Application shape and implement their wireless Professionals who are driving their DATES! strategy. Developers, enterprise’s wireless initiatives: i-technologyz professionals and IT/IS ¥ Program Developers management will eagerly attend. ¥ Development Managers ¥ Project Managers ¥ Project Leaders Plan to Attend the ¥ Network Managers 3-Day Conference ¥ Senior IT and Business Executives

Conference Tracks Track One: Track Two: Track Three: Track Four: Track Five: Development Connectivity Wireless Apps Hardware Business Futures WAP Smart Cards Education Cell Phones/ Wireless in WorldPhones Vertical Industries i-Mode EXCLUSIVE Wireless LANs Health Care The WWWW / 802.11 incl. Bluetooth PDAs Unwired SPONSORSHIPS Short Messaging Entertainment Management AVAILABLE Interactive UMTS/3G Headphones/ From 3W to 4W: Gaming Networks Transport Keyboards / Issues and Trends Rise above the noise. Peripherals "Always-On" Establish your company GPS / Location- Satellite Financial Services Management as a market leader. Based Broadband Transmitters Base Supply Chain Exploiting the Deliver your message Wireless Java Stations Management Bandwidth Edge with the marketing FOR INFORMATION CALL Tablets Unplugged support of XML & Wireless Valueware Technologies Wireless Sales & Marketing SYS -CON 201 802-3084 MEDIA SPEAKER PROPOSALS INVITED WWW.SYS-CON.COM

Java COM The World's Leading Java Resource

hohhomeomeme adaadvertisedvertisertise subscssubscribeubscribibe contccontactontact

java forums mailing list

What’sOnline... October 2001

advertise J2SE authors JDJ Online Check in every day for up-to-the-minute news, events, subscribe and developments in the Java industry. Can’t get to the news- stand on time? Visit www.javadevelopersjournal.com and be the first to know what’s happening in the industry.

Search Java Jobs J2EEJava J2ME Developer’s Journal is proud to offer an employment editorial portal for IT professionals. Get direct access to the best com- panies in the nation. Learn about the “hidden job market” and how you can find it. If you’re an IT professional curious about the job market, this is the site to visit. source code Simply type in the keyword, job title, and location and get instant results. You can search by salary, company, or industry. Need more help? Our experts can assist you with retire- jdj edge ment planning, putting together a résumé, immigration Home new york, ny issues, and more. sept 23–26 Radio Interviews Tune in to SYS-CON radio (via the Shoutcast Network) search jdj and hear the industry’s top movers and shakers, interviewed by JDJ editors. Listen to James Gosling, the father of Java, JDJ Advisory Panel members, CEOs, product managers, and other top executives as they share their insight and opinions on today’s hottest issues.

Product Reviews Considering a product upgrade? Want to know the ins- JDJ SPEcials and-outs of a new product before you purchase it? Then make sure you read our in-depth product reviews. Our writers test and evaluate a host of Java products to aid your decision-making process. We get behind the hype and give you the facts. All reviews are written by experts and lead- ers in the information technology industry.

JavaDevelopersJournal.com Developer Forums Join our new Java mailing list community. You and other IT bestsellers professionals, industry gurus, and Java Developer’s Journal writers can engage in Java discussions, ask technical ques- tions, talk to vendors, find Java jobs, and more. Voice your bestsellers opinions and assessments on topical issues – or hear what others have to say. Monitor the pulse of the Java industry!

JavaBuyersGuide.com JavaBuyersGuide.com is your best source anywhere, any- time on the Web for Java-related software and products in more than 20 mission-critical categories, including applica- tion servers, books, code, IDEs, modeling tools, and profilers. Check the Buyer’s Guide for the latest and best Java products available today.

108 OCTOBER 2001

JJavaava COMCOM SYS-CON Media, the world’s leading publisher of i-technology magazines for developers, software architects, and e-commerce professionals, brings you the most comprehensive coverage of The WebSphere. World’s Leading Independent WebSphere Developer WebSphereDevelopersJournal.com Resource

Introductory Charter Subscription SUBSCRIBE NOW AND SAVE $31.00 OFF THE ANNUAL NEWSSTAND RATE ONLY $149 FOR 1 YEAR (12 ISSUES) REGULAR RATE $180 OFFER SUBJECT TO CHANGE WITHOUT NOTICE

INTRODUCTORY OFFER HURRY,SAVE DON’T DELAY! SPECIAL Premiering...this fall subscribe OFFER EXPIRES DECEMBER 31, 2001 FORFASTFAST $ DELIVERY Now! Helping 31 * you enable inter-company collaboration on a global scale Go Online • Product Reviews and Case Studies Subscribe • Today! •Tips, Tricks and more!

WebLogicDevelopersJournal.com SYS-CON Media, the world’s leading publisher of i-technology magazines for developers, software architects, and e-commerce professionals, brings you the most comprehensive coverage of WebLogic. *Only $149 for 1 year (12 issues) regular price $180.

OCTOBER 2001 109

Java COM TEOCO and Kada Team to coming product enhancements of the Java Edition of its Object ny, Crisp Wireless. Crisp Develop Mobile Enterprise Apps in the release of the realMethods Management (OM) product line. Wireless, focused on mobile (Fairfax, VA / Burlington, MA) – Framework 1.5 Beta. The OM product line pro- content, entertainment, and TEOCO has joined the Kada The Complimentary vides network management multimedia application and Mobile Framework pro- functionality for embedded service development, launches Developer gram gives equipment appli- operations backed by a combi- Network (MDN). realMethods’ clients cations, telecom nation of LogicChain’s mLogic Developers at the opportunity to use the management applications, and Engine and Crisp Partners, a TELCO will utilize the Kada Framework for one year at no cost. integration with legacy as well as group with executive-level expe- Mobile Platform (Kada Mobile) to www.realmethods.com next-generation operations sup- rience from premier wireless tune, optimize, and deploy next- port systems (OSS) in both C++ and media companies. generation mobile applications. iPlanet Web Services and Java. www.crispwireless.com J2SE www.kadasystems.com Integration Platform www.vertel.com www.teoco.com (Santa Clara, CA) – iPlanet CyberTeams Upgrades Content launched the EAI and B2B ver- IONA Announces Orbix/E 2.0 Management Products ProSyst Launches mBedded sions of iPlanet Integration (Boston) – IONA announced a (Frederick, MD) – CyberTeams, Server 5.0 Server, its latest release to the C/C++ and Java version of Inc., released version 2.1 of (Cologne, Germany) – ProSyst Sun ONE Web services vision. Orbix/E 2.0 (previously market- WebSite Director Pro, its Web Software AG announced Director of product marketing, ed as Orbacus/E), a lightweight content–management system. mBedded Sanjay Sarathy, spoke to JDJ distributed computing platform In addition to expanding its con- J2EEServer 5.0. J2ME regarding the significance of this optimized for embedded appli- tent-management capabilities, The release release: “This release enables cations. the release includes a new Java- offers complete support for iPlanet to be one of the only plat- Orbix/E 2.0 for Java offers a based user interface, enhanced OSGi standard 2.0, more flexibil- forms that enable the full Web pure Java implementation with workflow management, robust ity in tests and implementa- services integration service.” functional equivalence template-based content deploy- tions, and new capabilities for This release includes a com- to the C/C++ version of ment, both the development of net- plete implementation of SOAP the product. With sup- and ready devices and the design of and XSLT modules, port for Sun Microsystems’ J2ME, database publishing capabilities. applications using Open Service the latter based on J2SE, and PersonalJava specifica- www.cyberteams.com Home Gateways scenarios. the NetBeans open- tions, Orbix/E 2.0 is suitable for a www.prosyst.com source architecture, variety of wireless and handheld Sims Computing Releases to allow developers to easily cre- devices. Flux 3.1 realMethods Announces New ate rules and schemas. www.iona.com (Billings, MT) – Sims Computing 1.5 Beta of Framework Full details, along with a free introduced Flux 3.1, a software (Bridgewater, MA) – realMethods, download, can be found at Espial Delivers First Scalable component that provides job provider of the realMethods www.iplanet.com. Java Browser scheduling functionality to Java Framework, announced lower (Ottawa, Canada) – Espial and J2EE applications. pricing and a complimentary Vertel Announces Java Edition announced the release of Espial Flux 3.1 contains 30 improve- program for their flagship J2EE of OM Product Line Escape 4.8, a 100% Java browser ments Application Framework. (Woodland Hills, CA) – Vertel offering a over realMethods also revealed forth- Corp. announced the availability scalable con- Flux figuration 3.0, including a Web-based man- that matches the memory agement console for administer- i-net Announces New Release requirements of a wide range of ing Flux from a Web browser and devices. Escape 4.8 allows the support for interacting with Flux of Crystal-Clear developer to selectively disable using XML. support for certain Internet stan- www.simscomputing.com dards so the browser can be tai- (Berlin, Germany) – i-net Software has introduced Crystal- lored to run in resource-con- Insignia Names Potts as Clear version 2.0, a Java report engine that enables the cross- strained designs or offer full Senior VP of Sales platform usage of functionality for other, more (Fremont, CA) – Insignia Crystal Reports. This powerful devices. Solutions has appointed Lamar new release comes www.espial.com Potts, former in two flavors: an Be, Inc., execu- EJB version and a LogicChain Acquired to Form tive, as senior standard version, Crisp Wireless vice president of worldwide sales. and both support runtime design components and (New York, NY) – LogicChain, Potts is responsible for the day- crosstabs. A new configuration tool provides an easy inter- Inc., announced that Crisp to-day management of sales face for the deployment of the Partners has including direct and OEM sales, report engine. acquired an equity sales strategy, and business www.inetsoftware.de stake in the development. He will report to company to Mark McMillan, Insignia’s presi- form a new dent and chief operating officer. mobile content–services compa- www.insignia.com

110 OCTOBER 2001

Java COM Your Own Magazine Do you need to differentiate yourself from your competitors? Next Month Do you need to get closer to your customers and top prospects? Could your customer database stand a bit of improvement? Could your company brand and product brands benefit from a higher profile? PRODUCT REVIEW: Would you like to work more closely with your third-party marketing partners? JCLASS SERVERCHART 1.1 Or, would you simply like to be a magazine publisher? by Sitraka SYS-CON Custom Media is a new division of reviewed by Jim Milbery SYS-CON, the world's leading publisher of Internet technology Web sites, print magazines, QUERY THREE WAY and journals. How to store and query data in LDAP, XML, and relational databases SYS-CON was named America's fastest-grow- by Teresa Lau ing, privately held publishing company by Inc. 500 STRUTTING YOUR STUFF in 1999. by Neal Ford SYS-CON Custom Media can produce inserts, supplements, or full-scale turnkey print magazines GOODBYE SNAKE for your company. Nothing beats your own print An introduction to game magazine for sheer impact on your customers' development for MIDP desks... and a print publication can also drive new handsets prospects and business to your Web site. by Mark Quinn and Talk to us! Julien Tranchant We work closely with your marketing depart- ment to produce targeted, top-notch editorial and So contact us today! PRODUCT REVIEW: design.We can handle your distribution and database East of the Rockies, Robyn Forma, WHITEBOARD SDK – BLUETOOTH EDITION requirements, take care of all production demands, by Zucotto [email protected], and work with your marketing partners to develop Tel: 201-802-3022 reviewed by Jason Briggs advertising revenue that can subsidize your magazine. West of the Rockies, Roger Strukhoff, [email protected], Tel: 925-244-9109

SHOP ONLINE AT JDJSTORE.COM FOR BEST PRICES OR CALL YOUR ORDER IN AT 1-888-303-JAVA BUY THOUSANDS 0F GUARANTEED BEST PRICES PRODUCTS AT FOR ALL YOUR GUARANTEED JAVA-RELATED

▲ SOFTWARE

▲ ▲

▲ ▲

World class ▲ ▲ ▲ ▲ AWARD ▲ ▲ ▲ ▲ ▲ ▲ LOWEST PRICES! ▲ ▲ ▲▲▲▲ NEEDS

SYBASE SITRAKA INFRAGISTICS SQL Anywhere Studio v7.0 JProbe Profiler Developer v2.8.1 JSuite v2.5

Sybase® SQL Anywhere Studio is a JProbe Profiler helps you quickly eliminate per- comprehensive package that provides data formance bottlenecks caused by inefficient algo- management and enterprise synchronization rithms in your Java code. JProbe Profiler com- to enable the rapid development and bines a visual call graph interface, a unique JSuite, a low priced bundle of four of the industry's leading deployment of distributed e-business solu- Garbage Monitor, and advanced data collection JavaBeans component products. It includes: CalendarJ: Calendar tions. Optimized for workgroups, laptops, technology to provide you with highly accurate Display Component. DataTableJ: The Fastest Grid Component On handheld devices and intelligent appliances, performance diagnostics, including line-by-line The Net! TreeViewJ: Feature-Rich TreeView Component. WinJ SQL Anywhere extends the reach of a results. Component Library: A Series Of UI Components. corporation’s e-business information anywhere business transactions occur. JProbe Profiler w/ Standard Support $ 99 $ 99 SQL Anywhere Studio (base w/ 1 user) v7.0 . . . . . 348 (includes JProbe Memory Debugger) ...... 458 JSuite 2.5...... $79499

WWW.JDJSTORE.COM

OCTOBER 2001 111

Java COM CAREER OPPORTUNITIES

Who’s HiringNow? Five tips for finding a good fit

Since most of our past articles have dealt with Java jobs from the engineer’s per- WRITTEN BY spective, we decided to write this month’s BILL BALOGLU & column from the hiring manager’s point of BILLY PALMIERI view. J2SE

A year ago you never would have Many seasoned engineers are also Intangible skills should be included been reading this article. At that time the reluctant to negotiate their own rate or (such as working well in a team envi- battle for technical talent was fierce. salary package with a hiring manager. ronment). Companies large and small were fight- When employees must negotiate their ing tooth and nail for engineers. Recent own deals, they often carry that tension 2. Start by asking everyone you know for college grads with no real-world experi- or conflict into the workplace. Managers referrals, both inside and outside of ence were landing fat-salaried jobs. at smaller companies have an even your company. Statistics prove that J2EECompanies couldn’t J2ME get foreign-trained tougher time because they’re now the best placements come through engineers into the United States fast expected to do all of the recruiting personal and professional referrals. enough. Money was no object. themselves. Sifting through hundreds of Diving into this gaping breech of résumés, phone-screening candidates, 3. Look for both technical abilities and opportunity were hundreds of recruiting and checking references can be ex- personal qualities that make the can- firms, providing engineers to the talent- tremely time-consuming. didate a fit for your position. This is starved tech industry. someone you’ll be working with every Then suddenly it stopped. Glut of Professionals day. Make sure that his or her person- Wall Street devoured its dot-com Anyone in a position to hire wants to ality meshes with yours and that the Home young and the Age of the Start-up quick- find the best person for the job. The person will get along well with the ly became the Age of the Layoff. Industry temptation of many hiring managers is others in your group. titans from Intel to HP are now shedding to take someone who’s overqualified workers by the thousands. simply because market conditions have 4. Be specific in your phone screen, cover- Yet companies still need strong tal- caused those people to become avail- ing technical skills as well as personal ent to fill key technical positions. And able. motivations and goals. Before you despite the fact that many technical At first it looks like a great deal to bring anyone in for a face-to-face people are now available, both hiring hire, say, an architect for an individual interview with members of your AUTHOR BIOS managers and skilled engineers report a contributor role. But what that hiring team, be sure that he or she is a strong Bill Baloglu is a principal new set of frustrations. manager may not realize is that candidate. Asking your engineers to at ObjectFocus As companies try to save money by overqualified employees will quickly meet with someone who’s not right (www. ObjectFocus.com), slashing their recruiting budgets and by become bored and will be gone as soon for the job can cast doubt on your a Java staffing firm in using outside or in-house recruiters, the as they find more challenging jobs that credibility. Silicon Valley. Previously he time-consuming task of recruiting has are a true fit for their skills. was a software engineer now fallen on the shoulders of individ- A key part of making a successful 5. Make sure that members of your team for 16 years. Bill has ual hiring managers and HR staff. placement is matching the candidate’s focus on different topics in the face-to- extensive OO experience Many of our client managers tell professional and personal goals with the face interview. Make sure you cover all and has held software us that this method isn’t working. position. your bases. development and senior Managers in mid-sized to large compa- Since many hiring managers today • • • technical management nies tell us they’re getting lots of have no choice but to take on the If as a hiring manager you’re confi- positions at several Silicon résumés, which gives the illusion that responsibility of recruiting for their own dent that doing your own recruiting is Valley firms. top engineers are like cherries to be hires, we’d like to share a few key recruit- working, then great. If not, a better picked off a tree. ing tips that should make the process investment of your time and efforts Billy Palmieri is a But the managers report that most of easier: could be working with an outside seasoned staffing industry those innumerable résumés are from B- 1. Be specific about what you’re looking resource that specializes in the types of executive and a principal and C-level candidates, not the A-list for. The job description should clearly positions you’re offering. of ObjectFocus. His prior engineers. state all of the responsibilities of the Many managers have learned that position was at A-list engineers (who are still in short position, including what tools will be just as it takes a thief to catch a thief, it Renaissance Worldwide, a supply) tell us they don’t like submitting used. Required skills should be listed takes a professional recruiter to catch a multimillion-dollar global their résumés directly to companies for completely (including the minimum true professional. IT consulting firm, where fear of getting lost in the shuffle. Their number of years’ experience in key he held several senior experience is often not recognized by skills). Desired skills should be listed management positions in HR staff (whose expertise is in benefits, separately but completely (including [email protected] the firm’s Silicon Valley policies, and paperwork, not in identify- experience in a certain industry, such [email protected] operations. ing technical talent). as wireless or software development).

112 OCTOBER 2001

Java COM CUBIST THREADS Hacking...

ife happens at a dizzying pace. It seems like yesterday that I was writing my first Cubist Thread, in WRITTEN BY L which my abundance of personal failings was first publicly perused. One that didn’t make the list at the time, BLAIRWYMAN but for which I should be roundly criticized, is vanity.

Oh, I guess my account of frustrated Oh, now... Wait a minute. I don’t amazement that anyone like me would aspirations to rock stardom could be mean the pejorative, computer-related be dumb enough to drive a cab in this J2SE construed as vanity, though it’s verb “to hack,” as in “to gain unautho- city at night. “You’re crazy!” he said, nowhere near as egregious as this most rized access to a computer.” (Of course, “...and you’re probably going to get recent incident. I pretentiously decry that definition – robbed!” The other fellow just sat there, The other day at the mall, while see the book Hackers by Steven Levy.) attracting the planet Jupiter toward hunting for something or other, I was In fact, I’m not talking about any him to a significantly greater degree struck by a desire to go into the book- computer-related form of hacking at all than anyone else for miles around, and store and buy a hard copy of Java – I’m talking about driving a hack, aka silently glaring at me whenever I Developer’s Journal. I knew that I’d find taxicab. I drove a cab in one of the larg- turned around. J2EEmy musings amongst J2ME its pages, and I er cities in the U.S. for a couple of years, Well, I’d already been robbed by never had the experience of walking up and believe me when I tell you there this time, and I told him as much, but to a newsstand and buying something may be no better way to meet a broad he kept ribbing me. I was actually a containing my own words. cross section of humanity. little scared, so I just did the usual – I plunked down my hard-earned Oh, I won’t bore you with any of the tried to “cut wise” and make my pas- cash, tore off the plastic cover right wild stories I have from those years – sengers laugh. On this occasion, there at the register, and turned to the yet – but meeting someone for the first though, it just plain wasn’t working. back page. “There I am.” I said (as mat- time, taking their money in exchange Every “witty” thing I said was fielded ter-of-factly as I could muster) as I for transportation, and then sharing with incredible aplomb, and returned Home showed my picture to the clerk. something as personal as a ride with back to me doubled in every dimen- She smiled and said, “Hey, that’s them is a fast lesson in human nature. sion. cool.” I probably looked like an over- Well, I guess I could “tease” you with When the ride was over, and it was heated basset hound as that big grin highlights from the stories that will apparent that I’d be okay, the passenger spread across my face. undoubtedly influence this column, at identified himself to me through the People in Minnesota are so nice. What least to the extent they influenced me. window. “Do you know who I am?” he I probably deserved was something more I’ve been conned, overtipped, stiffed, asked. “I’m Eddie Murphy!” along the lines of, “So what? Do you want robbed, cheated, belittled, and down- It was 1981 or so, and I don’t think I a cookie?” …or maybe, “You should be right threatened by some of the best. had seen him on Saturday Night Live, properly ashamed of your conspicuous One of my “brushes with fame” yet – Saturday night was a big work vanity, you pompous noodle!” includes some serious haranguing by night for cabbies, after all. One thing But that’s just like Minnesota – peo- the comedian Eddie Murphy. Late one was certain, though – his incredible tal- ple are nice around these parts. Hot evening I remember picking up two ent was unmaskable. To this day I’ve dish, anyone? gentlemen: a smaller, wiry fellow who never felt so utterly “bested” as I did The fact is, I think people are gener- sat in the seat directly behind me, and that night. AUTHOR BIO ally nice most everywhere. I’ve met a lot another man (best described as large Eddie, if you’re out there, I’m a huge Blair Wyman is a software of people in the many and various jobs enough to deserve his own zip code) fan…. Oh, and thanks for not robbing engineer working for IBM I’ve had, but most of my “people skills” who sat diagonally behind me. me. in Rochester, Minnesota, were probably obtained as I was “hack- All the way to the club the smaller home of the IBM iSeries. ing” in a major American city. fellow was joking with me, declaring his [email protected] Java Dudes

114 OCTOBER 2001

Java COM