THE LARGEST EVENT ON THE EAST COAST

TM

The World’s Leading Java Resource Java COM August 2001 Volume:6 Issue:8

Feature: Core J2EE Patterns John Crupi 16 Learning to design comes from experience Applet EJB XML Servlet JSP Guest Editorials Enterprise Java: Fitting the Pieces into the Tony Loton by Sanjay Sarathy pg. 7 by Rob MacAulay pg. 76 Enterprise Java Puzzle Adding functionality with EJBs PART 3 24

Book Review Authorization: J2EE Application Sanjay Mahapatra by Ajit Sagar pg. 30 Security Model A powerful security model that’s robust and reliable 32 J2ME API Rundown pg. 78 Frameworks: A J2EE Application Steven Randolph Framework Checklist Building portable, scalable, and robust apps 38 Product Reviews Jeode pg. 80 Feature: FavoritesComboBox Justin Hill & David Lesle iPAQ pg. 88 STRATRARA Keep each new class simple and flexible STRATRARATEGTEGIEGIE 46 STRRATEGTEGIEEGIE Cubist Threads S TEGG by Blair Wyman pg. 114 Feature: Strategies for Storing Java Objects Scott W. Ambler RETAILERS PLEASE DISPLAY in Relational Databases Apply these fundamentals for years to come 62 UNTIL OCTOBER 31, 2001 Industry Commentary:Wireless Apps Wanted Kimberly Martin A market for third-party J2ME applications is about to explode 84

MIDlets: The Missing Bits Jason Briggs A beginner’s guide to writing applications for the MID profile PART 2 92

Java Basics: A Deeper Look at Java Jacquie Barker Anatomy of a Java program, revisited 98 FROMF THE EDITORDI J2ME INTERNATIONAL ADVISORY BOARD • CALVIN AUSTIN (Lead Software Engineer, J2SE Linux Project, ), • JAMES DUNCAN DAVIDSON (JavaServlet API/XMP API, Sun Microsystems), • JASON HUNTER (Senior Technologist, CollabNet), • JON S. STEVENS (Apache Software ALANWILLIAMSON EDITOR-IN-CHIEF Foundation), • RICK ROSS (President, JavaLobby), • BILLROTH (Group Product Manager, Sun Microsystems), • BILL WILLETT (CEO, Programmer’s Paradise) • BLAIR WYMAN (Chief Software Architect IBM Rochester)

EDITORIAL J2SE EDITOR-IN-CHIEF: ALAN WILLIAMSON We All Needa Week Off in the Sun EDITORIAL DIRECTOR: JEREMY GEELAN ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI t last we can return to sanity. The Looking up the coast from Sun to another J2EE EDITOR: AJIT SAGAR J2ME EDITOR: JASON BRIGGS speeches are over, the bunting is company’s trials and tribulations, this month PRODUCT REVIEW EDITOR: JIM MILBERY Adown, and the mad hysteria is at an we saw that Microsoft was saved from the FOUNDING EDITOR: SEAN RHODY end. After the chaos of JavaOne we can return chopping block and has been allowed to stay PRODUCTION to normal. I am of course paraphrasing that together as a single operating unit. I can’t really VICE PRESIDENT,PRODUCTION AND DESIGN: great literary character Edmund Blackadder. comment on whether this is going to be a good

JIM MORGAN J2EE EXECUTIVE EDITOR: M’LOU PINKHAM It has now been a month since I arrived home thing or a bad thing, but I’m getting a little para- MANAGING EDITOR: CHERYL VAN SISE from our annual pilgrimage to JavaOne and noid regarding Microsoft’s influence on the EDITOR: NANCY VALENTINE I’m still following up on all the business cards desktop market now that Windows XP is just ASSOCIATE EDITORS: JAMIE MATUSOW that were thrust in my general direction. around the corner. For example, have you been GAIL SCHULTZ JavaOne is a great opportunity to do some following the SmartTag debate? This is where BRENDA GREENE ASSISTANT EDITOR: LIN GOETZ serious catching up and general networking, Microsoft will put hyperlinks around special and it was a real treat as Blair Wyman and I keywords it finds in all rendered HTML pages to TECHNICAL EDITOR: BAHADIR KARUV, PH.D. Home took some time out to have a chat with James link you to another site with more information. WRITERS IN THIS ISSUE Gosling about what he’s been up to lately. You For example, say your Web page happened to SCOTT AMBLER, BILL BALOGLU, JACQUIE BARKER, JASON BRIGGS, JOHN CRUPI, can read what we spoke of elsewhere in this mention Sun Microsystems somewhere in the JEREMY GEELAN, JUSTIN HILL, TONY LOTON, ROB MACAULAY, SANJAY MAHAPATRA, KIMBERLY MARTIN, BILLY PALMIERI, STEVEN RANDOLPH, AJIT SAGAR, issue. It was interesting to talk with James con- text. A small link made out of the text would – if SANJAY SARATHY, ANTHONY SIMMONS, ALAN WILLIAMSON, BLAIR WYMAN cerning the overall direction of Java and dis- you were to position your mouse over a pop-up cover how he feels about many of the issues. – display more information and optionally take SUBSCRIPTIONS: We touched on the old debate regarding Java you to another site…all without the approval or FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, being open-sourced and his response was so knowledge of the original Web site producer. In PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT wonderfully practical that I can’t help feeling principle it’s a great idea, but one that is open to SUBSCRIPTION HOTLINE:[email protected] that maybe he resents all the bickering and so much abuse. The upshot is that Microsoft has COVER PRICE: $4.99/ISSUE politics that divert attention from the underly- postponed this feature’s appearance in IE for a DOMESTIC: $69.99/YR. (12 ISSUES) ing beauty that makes Java, well…Java. little while longer, but rest assured it’ll be there in CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. The industry is still struggling to find its feet some version, at some point. (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. after the dot-bomb exploded, and desperately That aside, what annoys me most about EDITORIAL OFFICES: trying to stave off redundancies is the very com- Microsoft’s newest addition to its operating sys- SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 pany behind Java: Sun Microsystems. Although tem suite is that there’s still no embedded Java TELEPHONE: 201 802-3000 FAX:201 782-9600 we probably shouldn’t read too much into this Virtual Machine. With Microsoft’s strong relation- JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly (as Scott McNealy keeps telling us), the core ships with the major PC manufacturers, Windows (12 times a year) for $69.99 by SYS-CON Publications, Inc., 135 Chestnut Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at business at Sun is still manufacturing and sell- XP will find its way into the homes of millions of Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address ing hardware, and the work Sun does with Java users who will simply never think of installing a changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., is still very much full steam ahead. That said, as JVM, let alone replacing the operating system. 135 Chestnut Ridge Road, Montvale, NJ 07645. you’ll read from our chat, James does comment Due to the high-level politics and strategies of two ©COPYRIGHT: on the fact that “all the cool stuff with Java isn’t companies, millions of users are affected, includ- Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. done at Sun,” so even if they are hitting a rocky ing a whole development community that won’t No part of this publication may be reproduced or transmitted in any form or by any patch in the road, Java isn’t going to suffer much. be able to service this new user base. means, electronic or mechanical, including photocopy or any information storage and retrieval system, without written permission. For promotional reprints, contact reprint coor- This was the month that Sun had their We need to start moving Java applications dinator. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its famous one-week nonpaid holiday – a move into the mainstream and have sites chockful of readers to use the articles submitted for publication. to save some pennies, which for an organiza- executable JAR files that users simply 6and run WORLDWIDE DISTRIBUTION BY: tion of Sun’s size and payroll would account without worrying about the requirements they CURTIS CIRCULATION COMPANY for quite a lot of pennies. But you can’t help face in the README.TXT file beforehand. NEW MILFORD NJ wondering how many of the engineers just Maybe if we had this, Microsoft wouldn’t went into work anyway. seem half so bad. Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. SYS-CON Publications, Inc., is independent of Sun Microsystems, Inc. All brand and product names used on these pages are trade names, [email protected] service marks or trademarks of their respective companies. AUTHOR BIO Alan Williamson is editor-in-chief of Java Developer’s Journal. In his spare time he holds the post of chief technical officer at n-ary (consulting) Ltd, one of the first companies in the UK to specialize in Java at the server side. Reach him at [email protected] (www.n-ary.com) and rumor has it he welcomes all suggestions and comments!

AUGUST 2001 5

Java COM GUEST EDITORIAL

WRITTEN BY SANJAY SARATHY The rational The RingIs Bloody alternative

With too many solutions looking for a business problem to solve Version 4.5 Introductory Offer he Thrilla in Manila: both the name and the of the month might be, all businesses want to cre- events of that steamy October day in 1975 ate tighter synergies throughout their entire value $2995 Tremain seared in the memory of all who chain that encompass customers, employees, for Teamwork Server watched it. Muhammad Ali and Joe Frazier, two of suppliers, and partners. the greatest boxers in heavyweight history, battled This is truer today than ever. These synergies have toe-to-toe for 14 rounds, until Frazier’s corner sur- taken on a whole new importance thanks to the rendered and threw in the towel. explosion in online personalization; a development Today the technology industry is in the midst that now touches individual consumers as well as All 9 UML diagrams of its own thrilling fight – one that is centered on larger business-to-business operations. Additional Features: the much-hyped world of Web Services. And just As vendors, we often get so distracted by the • Performs Java, C++ or CORBA IDL as with Ali and Frazier, the various combatants are technology details that we end up losing sight of code round-trip engineering (code treating each other to verbal jabs and taunts. this bigger picture. Worse yet, perhaps, this too generation and reverse engineering); Anyone who attended JavaOne this past June wit- often makes us adversaries, leading to wasted recognizes JavaDoc comments. This nessed this, particularly at some of the morning time and energy as we throw punches at each feature allows you to write code, reverse keynotes. Unfortunately, as companies continue other about which is the best way to proceed. We engineer, make changes to the model to spar over the issue, we are losing the necessary have to remind ourselves that organizations cre- and re-generate the code without losing any implementation specific information. focus on the business impact of Web Services as ate real value when they’re able to implement each vendor beats its own technology drum. • Supports UML 1.3 notation. One thing companies don’t seem to be fighting • Saves diagrams as bitmap PNG/JPG and about is the potential of Web Services to transform scalable WMF/SVG/EPS/DXF formats. how technology is used to inspire and create new • Provides XML interoperability — native revenue-generating opportunities for all sorts of model files are stored in XMI format. businesses. However Orwellian it might sound, • Integrated with Forte for Java (FFJ) IDE the idea of creating, assembling, and deploying versions 1.0 and 2.0. personalized services across a global network and Standard Edition: ...... $249 within a contextual framework – all based on who Professional Edition: . . . . $499 you are, where you are, and what you’re doing – is an enormously appealing prospect to many. The potential to eliminate technolo- Visit us at Java One gy and business silos within and across organizational boundaries provides Floating License . . $100 additional another compelling Upgrade for a $69 annual fee! argument for Web Services, especially when companies real-

ize they won’t have to C abandon the various I investments they’ve ✦ G already made. M ✦ ▲✦ Companies agree No Magic... on something else as Just Technology That Works well: no matter what the technology flavor Download fully functional demo at: www.magicdraw.com [email protected] AUTHOR BIO contact us at Sanjay Sarathy is director of product marketing at iPlanet. He holds a BA in [email protected] quantitative economics from Stanford University and an MBA from the Haas School of Business at the University of California. 100% Pure Java Application

AUGUST 2001 7

Java COM LETTERS TO THE EDITOR The Ring ’m a subscriber to JDJ and am very happy Hi Mohan, Is Bloody with the magazine (I’m from the U.K. liv- I hope the original article was useful to Iing and working in Germany). The digital you. To answer your question, an object may edition is an excellent bonus for me as the be passed from the server to the client only if post takes awhile. The content of the maga- it’s serializable, i.e., implements the zine is simply first class, both in quality and java.io.Serializable interface. Any object not choice of subject matter – I’ll definitely renew implementing Serializable cannot be passed. my subscription when the time comes! Serialized objects are passed “by value” Another publication that interests me is across the network so that the receiver sees a WBT, which I currently read online only. I’d duplicate version of the original rather than be interested in receiving subscription the original. So even if you could pass the J2SE information/pricing for oversea subscrip- HttpSession, it would no longer reflect the cur- tions for this publication (possibly just the rent session state as kept current on the server. digital edition). Presumably you want the client to see some of In the meantime, keep up the excellent the information held within the session. How work, and I look forward to reading the next about defining your own object to hold values issue(s) extracted from the session, make it and profitably meet their busi- Ian Harvey Incidentally, I often see this problem ness objectives. [email protected] J2ME when someone is trying to pass a JDBC con- This is even more important today given nection from server to client. It would be nice the current economic environment. if you could, but I’m afraid not. Technology vendors must be able to articu- late how they enable their customers to gen- Tony Loton erate maximum return on their critical [email protected] assets, which include their people, their business processes, and their information systems. Plaudits for Tony Loton he JDJ that you During and since JavaOne, I’ve had the Home ’ve been a subscriber of Java Developer’s gave me at the opportunity to speak with a number of Journal for the past two years. I read your Tconference companies developing interesting tech- Iapplet-servlet communication article was quite impressive nologies devoted to various aspects of the [“Fitting the Pieces into the Enterprise Java and very informative. Web Service paradigm. I don’t doubt that Jigsaw”, JDJ, Vol. 6, issue 5] and I have a simi- Up until that time I was some of these ideas will be revolutionary. lar kind of job requirement. I’m following your a regular reader of Java World, but after going I’m confident as well that a few of the peo- example in the article of passing a bean from through JDJ I think I might change the maga- ple involved in these developments will the servlet to the applet by trying to pass a zine for my Java requirements.... :) become wealthy, provided, of course, their servlet session object to the applet, but it’s not companies get funded. Still, I could not working. However, when I tried to pass my Ashutosh Bhonsle help but feel overwhelmed by just how bean from the servlet to the applet, it worked. [email protected] many different types of solutions are look- ing for a business problem to solve – even was pleased to see the JNI article in the for someone like myself, who is living and June 2001 Java Developer’s Journal since breathing this stuff! Iit dealt with the IBM iSeries (AS/400) plat- I pity the poor CIO, line-of-business form. As a Java developer using the iSeries it’s executive, or even developer, who, having nice to see it get some press. It seems to be a just figured out how to really take full well-kept secret although it’s a very robust advantage of the Java 2 Platform, Enterprise platform for running Java applications. Edition (J2EE) model, must now wrestle with this dazzling array of new technolo- gies. In the end, a vendor’s credibility is only partly the result of an innovative technolo- I know the servlet runs at the server side gy getting shipped to market. After all, who and also the session, but the applet runs at can’t name a handful of cool companies the client. Can we pass the servlet-session that got knocked out before ever delivering object to the applet ? a product? No, a vendor’s credibility is I’ve been struggling with this problem for more a product of their ability to help busi- the past month and my friends couldn’t help nesses understand how to generate top - me. I would appreciate it if you could throw and bottomline – benefits from the tech- some light on the subject. I hope to see more articles dealing with nology they’ve chosen. What’s more, this Thanks a lot. the IBM iSeries platform. model is true whether the technology trend was yesteryear’s client server model (may it Mohan Palaniswamy T.Allen rest in peace) or today’s promising Web [email protected] [email protected] Services.

8 AUGUST 2001

Java COM J2EE EDITORIALOR J2EE INDEXX

J2ME J2EE Design Patterns: The 10 Next Frontier AJIT SAGAR J2EE EDITOR J2EE provides component APIs that are built on solid design principles. J2EE Design Patterns:The Next Frontier by Ajit Sagar

J2SE e live in a world where of experience of a multitude of developers J2EE FAQ 12 abstraction is the name of the are available for other developers to apply, Wgame. I used to be an avid use, and learn from. The best approach is reader of Asterix comics, and thinking of to consult the appropriate documentation Core J2EE Patterns abstraction reminds me of a couple of and other resources, and not reinvent the Without design patterns, 16 panels in the “Obelix & Co.” comic book. A wheel for each new application. One of the application development can Roman emissary tries to explain to the primary advantages of this approach is be an extremely chaotic task. (simpleton) Obelix the intricacies of that your design paradigm will be support- Turn the page and see how Roman economy in simple words: “Make ed by a larger community than just the design patterns in the realm J2EE much menhir, get much gold," or some- environment that you program in. In some of J2EE can help build thing to that effect. sense, design patterns are simply commu- robust, reusable applications. I don’t mean to say that we developers nication mechanisms for application by John Crupi are simpletons. But, as my colleagues in architects, designers, and developers to marketing say, the presentation needs to share information on best design prac- Fitting the Pieces into the be “dumbed-down” for the appropriate tices. Enterprise Java Puzzle, 24 crowd. As an enterprise architect, I don’t J2EE covers a lot of areas. It’s impossi- Part 3

Home want to deal with the details of system- ble for a single person, or a group of devel- The conclusion of a very level programming and operating system opers, to acquire expertise on all of them. exciting tour on designing implementations. That is one of the rea- This problem is magnified in distributed enterprise applications using sons I chose J2EE as my reference frame- development environments where com- Java. This article uses work for implementing applications. Yes, municating the different aspects of design servlets and Session EJBs to J2EE is an abstraction, a “dumbed-down” and coordinating the modules of the provide the final pieces of the framework for me to develop distributed application becomes an extremely daunt- Enterprise Java puzzle. applications. ing task. Design patterns help alleviate a by Tony Loton One of the really neat things about Java large portion of this pain. is that it’s made standard design patterns Sun’s J2EE Blueprints provide a great Book Reviews: household names for the developer com- starting point to help developers under- Designing Enterprise 30 munity. Java is built on standard design stand the rationale behind the design of Applications with the Java 2 patterns and implementation guidelines. the J2EE platform. The sample Pet Store Platform, Enterprise Edition Five years ago, the majority of the pro- application helps put this in the perspec- & J2EE Technology in Practice grammers I talked to didn’t know what tive of a real-world demo. However, when Reviewed by Ajit Sagar design patterns were. Now, almost all Java you design a real-world application, there developers are aware of Factories, are other aspects of design that you need J2EE Application Listeners, and Adapters. The reason? Core to address. With the acceptance of J2EE as Security Model 32 Java objects use the Factory patterns. the preferred platform for building distrib- A comprehensive and concise Observer-Observable and Producer- uted applications, you’ll see richer sources overview of the J2EE applica- Listener are a part of the language. of information on building these applica- tion security framework. A Adapters and Proxies are applied all over tions emerge. great source for readers who enterprise Java applications. want an introduction to J2EE Starting This Month… security basics. J2EE Design At JDJ, we want to address this higher by Sanjay Mahapatra J2EE provides component APIs that are level of abstraction. This month and in built on solid design principles. However, subsequent issues, you’ll see more cover- J2EE Application in order to apply these APIs to build enter- age on applying J2EE into actual applica- Framework Checklist 38 prise applications, you need a good design tions. In this issue, John Crupi starts a J2EE frameworks enhance base for developing robust and reusable the offerings of application components. The good news is that years –continued on page 74 servers to provide complete application design [email protected] environments. AUTHOR BIO by Steven Randolph Ajit Sagar is the J2EE editor of JDJ, and the founding editor and editor-in-chief of XML-Journal. A lead architect with VerticalNet Solutions, based in San Francisco, he’s well versed in Java,Web, and XML technologies.

10 AUGUST 2001

Java COM J2EE FAQQ J2EE ROADMAPP

The Java2 Platform, Enterprise Edition defines the APIs for building enterprise-level applications. J2SE...... v. 1.2 J2ME WHAT ARE THE COMPONENT TECHNOLOGIES OF THE J2EE ARCHITECTURE? Q The J2EE architecture consists of the following types of Java components: Web components, EJBs, A Enterprise JavaBeans API application clients, and Java applets. Web components consist of servlets and JavaServer Pages (JSPs)...... v. 1.1 The component technologies of J2EE facilitate the development of J2EE components. Java Servlets ...... v. 2.2 These technologies are offered as a set of distributed system APIs that are specified by Sun JavaServer Pages Technology via the (JCP) and are open to vendors, including Sun, for imple- ...... v. 1.1 mentation. These APIs include : • Enterprise JavaBean (EJB): For developing server-side business components JDBC Standard Extension J2SE • Java Database Connectivity (JDBC): For unified RDBMS access ...... v. 2.0 • Java Message Service (JMS): For distributed messaging Java Naming and Directory • JavaMail: For e-mail services Interface API ...... v. 1.2 • Java Native Directory Interface (JNDI): For distributed naming services • JavaServer Pages (JSP): For generating dynamic HTML or XML for Web clients RMI/IIOP ...... v. 1.0 • Java Servlet: For generating dynamic HTML or XML for Web clients Java Transaction API..v. 1.0 • Java Transaction API (JTA): For managing distributed transactions • Remote Method Interface (RMI): For distributed object communications JavaMail API ...... v. 1.1

J2EE Java Messaging Service Enterprise JavaBeans are the central theme for J2EE. EJBs comprise Java’s middle-tier serv- ...... v. 1.0 er-side component model. All the other APIs exist to provide connectivity to and from EJBs. Useful URLs: WHERE DO ALL THE J2EE COMPONENTS EXIST IN A DISTRIBUTED APPLICATION? Q Java 2 Platform Enterprise Edition J2EE is a true n-tier architecture; however, the different components developed on the J2EE A http://www.java.sun.com/j2ee/ framework can be grouped into server-side and client-side components. Applets and application J2EE Blueprints clients are basically pure client-side components and execute in a virtual machine on the client http://www.java.sun.com/j2ee/ blueprints

Home machine. Applets execute in a browser, while applications can execute in other client-side processes. J2EE offers two types of Web components: servlets and JSPs. The purpose of both types J2EE Technology Center of components is the same: to serve up dynamic content to Web clients. In fact, JSPs are http://developer.java.sun.com/developer/prod- compiled into servlets during execution. This means that JSPs and servlets get requests ucts/j2ee/ from Web clients and serve back HTML (or XML). Servlets and JSPs provide the connec- J2EE Tutorial tivity between the client- and server-side components in a J2EE application. To generate http://java.sun.com/j2ee/ the right response, they can communicate with back-end data sources through JDBC, tutorial/ RMI, JMS, or JavaMail, as well as to middle tier Java components, namely, EJBs. In turn, EJBs can communicate with back-end sources.

EJBs are Java’s server-side components. EJB components are developed to model busi- ness logic for an application. EJBs can leverage other APIs to connect to and communicate with back-end systems. There are two types of EJBs – session beans, which are associated with the lifetime of a user session, and entity beans, which are associated with server-side business objects that are persisted in a database and live beyond the life of user sessions.

WHAT ARE J2EE CONTAINERS AND WHAT IS THEIR RELATION TO APPLICATION SERVER VENDORS? Q A J2EE component needs an execution environment to run in. J2EE containers are A runtime hosts for J2EE components. Since there are basically two types of middle-tier J2EE components (Web components and EJBs), there are two types of J2EE containers – Web component containers and EJB containers. Web component containers are basically servlet engines, JSP engines, and Web con- tainers. A servlet container provides network services for servlet execution, such as sup- port for HTTP, and other request-response protocols. JSP containers are basically servlet containers with the additional functionality of compiling JSP pages into servlets. As men- tioned above, JSPs become servlets at runtime. Web containers provide the additional functionality of access to other J2EE APIs, such as RMI and JDBC. EJB containers provide the runtime life-cycle management environment for EJB com- ponents. This includes EJB instantiation, communication, persistence, and transaction management, as well as access to other J2EE APIs, such as RMI and JDBC. Application server vendors such as WebSphere, BEA, iPlanet, and ATG provide implemen- tations of the J2EE service APIs and the containers in which components built on these APIs can execute. Since there are different types of J2EE containers, there are different J2EE contain- er providers. This means that you can buy the Web and EJB containers from different sources and make them communicate by using standard J2EE services. For example, a JRun servlet engine from Macromedia should be able to work with an EJB container from WebLogic.

12 AUGUST 2001

Java COM J2ME J2SE J2EE Home

to the first installment of the “Core been designing mission-critical J2EE solutions since J2EE J2EE Patterns” column by the Sun Java Center technology was introduced. (www.sun.com/service/sunps/jdc). Every other month, we In our work, we often encounter situations where, because (Deepak Alur, Danny Malks, myself, and other architects from technology is moving so quickly, designers and developers are the Sun Java Center) will discuss various topics from our book, still struggling to understand the technology, let alone how to Core J2EE Patterns, Best Practices and Strategies (Alur, Crupi, design with the technology. It’s not good enough to tell design- Malks, Prentice Hall/Sun Press, 2001). These topics include ers and developers to write good code, nor is it sufficient to each of the 15 J2EE patterns in our catalog, design strategies, suggest using servlets and JavaServer Pages (JSP) technology bad practices, refactorings and pattern-driven design in the for developing the presentation tier and EJB components for Java 2 Platform, Enterprise Edition (J2EE). developing the business tier. Since its inception, SJC architects have been working with Applying the Technology clients all over the world to successfully design, architect, Today, as in the past, many of us naively assume that learn- build, and deploy various types of systems based on Java and ing a technology is synonymous with learning to design with J2EE technology and platforms. the technology. Certainly, learning the technology is impor- Recognizing the need to capture and share proven designs tant for success in designing with the technology. Many exist- and architectures, we started to document our work on the ing Java books are excellent at explaining technology details, J2EE platform in the form of patterns in 1999. Although we such as API specifics and so forth, but at the same time they looked in the existing literature, we couldn’t find a complete give no insight on applying the technology. catalog of patterns that dealt specifically with the J2EE plat- Learning to design comes from experience and from shar- form. We found many books dealing with one or more of the ing knowledge on best practices and bad practices. The expe- J2EE technologies, which do an excellent job of explaining the riences we’ll convey in this column are derived from the work technology and unraveling the nuances of the specifications, we have done in the field. We are part of Sun Microsystems, but many of these books fall short on design. Inc.’s, Sun Java Center (SJC) consulting organization and have After two years of work on capturing J2EE patterns and

16 AUGUST 2001

Java COM documenting them in the proper pattern form, at the JavaOne levels of abstraction and in numerous domains. Numerous 2001 Conference we launched our book, which includes the categories have been suggested for classifying software pat- SJC J2EE Pattern Catalog. We also announced that four com- terns, with some of the most common patterns being:

J2ME panies and allies, Rational, TogetherSoft, Forte, and iPlanet, • Design have all agreed to bundle the SJC J2EE Pattern Catalog in their • Architectural respective tools (http://java.sun.com/pr/2001/06/pr010604- • Analysis 25.html). • Creational This is important in our eyes because patterns lend them- • Structural selves to tools so nicely. As a matter of fact, the pattern-driven • Behavioral design concept in J2EE technology is difficult without tool support. More about this later. Even within this brief list of categories, we see numerous J2SE levels of abstraction and orthogonal classification schemes. The Essence of Patterns Thus, while many taxonomies have been suggested, there is First, let’s start with a brief overview of patterns – starting no one right way to document these ideas. with some expert definitions. In our J2EE pattern catalog, each pattern hovers some- In A Pattern Language, Christopher Alexander says each where between a design pattern and an architectural pattern pattern is a three-part rule which expresses a relation between while the strategies document portions of each pattern are at a certain context, a problem, and a solution. a lower level of abstraction. The scheme we have introduced is Richard Gabriel discusses this definition in more detail in to classify each pattern within one of the following three logi- A Timeless Way of Hacking. Gabriel offers his own version of cal architectural tiers: J2EE Alexander’s definition as applied to software: each pattern is a • Presentation three-part rule that expresses a relation between a certain • Business context, a certain system of forces that occurs repeatedly in • Integration that context, and a certain software configuration that allows these forces to resolve themselves. Identifying a Pattern This is a fairly rigorous definition, but there are also much We have successfully completed and deployed many J2EE looser ones. For example, Martin Fowler, in Analysis Patterns, technology projects at the Sun Java Center, and over time have

Home offers the following definition: a pattern is an idea that has noticed that similar problems recur across these projects. We been useful in one practical context and will probably be use- have also seen similar solutions emerge for these problems. ful in others. While the implementation strategies varied, the overall solu- As you can see, there are many definitions for a pattern, tions were quite similar. Let’s discuss, in brief, our pattern but they all have a common theme relating to the recurrence identification process. of a problem/solution pair in a particular context. Some of the When we see a problem and solution recur, we try to iden- common characteristics of patterns: tify and document its characteristics using the pattern tem- • They’re observed through experience • Are typically written in a structure • Prevent reinventing the wheel • Exist at different levels of abstraction • Undergo continuous improvement • Are reusable artifacts • Communicate designs and best practices • Can be used together to solve a larger problem Categorizing Patterns Patterns, then, represent expert solutions to recurring problems in a context and thus have been captured at many

FIGURE 1 J2EE pattern relationships FIGURE 2 Pattern framework

18 AUGUST 2001

Java COM Home J2EE J2SE J2ME 20 A UGUST 2001 ed. to thehigher-level structure pattern inwhichtheyare includ- most clearlycommunicatestherelationship ofthestrategies however,right; we feelthatourcurrent templatestructure umented someofthesestrategies intheirown aspatterns solution atmultiplelevelsofabstraction. We couldhavedoc- details. Through thestrategies, documentsa eachpattern ous strategies thatprovide lower-level implementation of abstraction. At thesametime, includesvari- eachpattern made thedecisiontodocumentthematarelatively highlevel Patterns vsStrategies combination. tion by distillingthesimilarideasintoapattern/strategy the otherhand,itmightbebettertocommunicatesolu- menting twosimilarsolutionsasdifferent patterns. On munication amongdevelopers. If so, thenconsiderdocu- the solution.Sometimes, aseparate nameimproves com- it’stern, toconsiderhow important tobestcommunicate sent asinglepattern. When decidinghow thepat- toform identification. Often,similarsolutionsmayrepre-pattern suchasthis,with rules buttheyhelpprovide acontextfor systems. Certainly, there ismuchroom forinterpretation inatleastthree untilithasbeenverified pattern different catalog. guide fortransitioning intothepattern acandidatepattern Three, asitisknown community. inthepattern isa This rule inimplementedsolutions.terns miningby theprocess ofpattern undertake lookingforpat- their usagemultipletimesondifferent projects. We also cataloguntilwe are anddocument the pattern abletoobserve didate patterns. However, we don’t to addcandidatepatterns plate. At first,we considertheseinitialdocumentstobecan- Service To Worker Combines a Dispatcher componentwiththeFront CombinesaDispatcher Controllerand View HelperPatterns. thehandlingofarequest. Providesacentralizedcontrollerformanaging anaggregate subcomponents Creates View fromatomic View Dispatcher Service To Worker Composite View Facilitates preprocessingandpost-processingofarequest. View Helper Intercepting Filter SYNOPSIS PATTERN NAME Service Activator Activator Facilitates asynchronousprocessingforEJBcomponents Activator sources; providestransparent accesstodata. Abstractsdata Service Activator Data Access Object SYNOPSIS PATTERN NAME factories businessservice locates lookupandcreation; complexity ofbusinessservice Encapsulates andresultsprocessing. results caching, execution, query Manages Locator Service Facilitates exchangebetweentiersbyreducingnetworkchattiness. data handling. Hidesbusiness objectcomplexity;centralizesworkflow Value ListHandler Value Object Assembler handling. Hidesbusiness objectcomplexity;centralizesworkflow Composite Entity Value Object Session Facade andprovides tiers, andservice Decouplespresentation Business Delegate SYNOPSIS PATTERN NAME TABLE 1 TABLE 3 TABLE 2 When we started documentingtheJ2EEpatterns, weWhen we started According tothisrule, asolutionremains acandidate validation process, ofthepattern As part we usetheRule of Presentation-tier patterns Integration-tier patterns Business-tier patterns Combines a Dispatcher component with the Front Controller and View Helper Patterns, deferring many activitiesto deferringmany View processing componentwiththeFrontCombines aDispatcher Controllerand View HelperPatterns, Assembles a composite value object from multiple data sources. Assembles acompositevalueobjectfrommultipledata a facadeandproxyinterfacetotheservices stack oftiers. with theadjacenttier. We represent thewholesystemasa cally separated from oneanother. Eachtierislooselycoupled unique responsibility inthesystem. We vieweachtieraslogi- separation inthesystem.Eachtierisassignedits ofconcerns oftiers.the systeminterms ofthe Atierisalogicalpartition (andapplication)isamultitieredplatform system,we view andsinceaJ2EE on theJ2EEplatform, applications thatrun ApproachThe Tiered tion foreachtier. technology.Connectivity (JDBC) related andJava totheJava Database Message (JMS) Service related totheEJBtechnology. The integration-tier are patterns andJSPtechnology.servlets areThe business-tierpatterns approach. The presentation-tier are patterns related to according tofunctionality, catalogfollows andourpattern this J2EE Patterns Strategies promote bettercommunicationby providing • Developers discover andinventnewwaystoimplement the • Strategies provide anextensibilitypointforeachpattern. • includethemostrecommended Thepatterns ormostcom- • existatahigherlevelofabstraction Thepatterns thanthe • of thestrategies tothepatterns: have notedsomeoftheissueswithrespect totherelationship for now, believingthecurrent documentationtobe clear. We these strategies topatterns, we havedeferred thesedecisions names forlower-level solution. aspectsofaparticular patterns, producing newstrategies forwell-known patterns. mon implementationsasstrategies. strategies. Since this article describes patterns thathelpyouSince build patterns describes thisarticle While we continuetohavelivelydebatesaboutconverting Table descrip- andabrief 1,2,and3eachlistthepatterns We usedthetiered approach todividetheJ2EEpatterns J ava COM Home J2EE J2SE J2ME 22 A UGUST 2001 diagrams toexplaineachstrategy. withmultiplestrategiestion, patterns useclassandsequence diagram thatshows theinteractions In forthepattern. addi- gram thatshows thestructure ofthesolutionandasequence • • • ly asfollows: Using UML Hall/Sun Press, 2001) and is currently concentrating on pattern-driven designinJ2EE. concentrating onpattern-driven 2001)andiscurrently Hall/Sun Press, He iscoauthorof scalable architecturesfor J2EEtechnology. objectcomputingandremainsfocused oncreatingreusable, in distributed experience of Hehasmorethan15years isthechiefJava architectoftheSunJava Center. John Crupi columns, [email protected]. are topicsyou wantustoaddress anyJ2EEpattern infuture intherealences withapplyingJ2EEpatterns world.If there to exchange andshare withyou ourideas, vision,andexperi- columns. We thinkthiswillbeagreat andforum opportunity In Upcoming Issues ascanbeappliedtoabusinessproblem.(across eachtier)patterns ipants ofeachpattern. The diagram identifiestheend-to-end isrepresentedpattern by aUMLpackagethatcontainsthepartic- commonly usedtogether. We frameworks. callthesepattern thataretext ofabusinessproblem andalsodiscussthepatterns each otherasshown inFigure 1. language)tovisuallyseehowpattern relate thepatterns to together tosolveacommonbusinessproblem? Even more so, whatare thatare thepatterns commonlyused the isolatedpatterns, butinhow work together. thepatterns value increating catalogisnotjustunderstanding apattern togethertosolveabusiness problem. Iagree.patterns The that theydidnothaveagoodhandleonhow andwhentouse indevelopment?” problems withusingpatterns answer wasyes. Next, theywere asked, “Do you haveany useful?” wasposedtothegroup. Almostunanimously, the section,thequestion, the pattern “Do are you thinkpatterns focus group togatherdataabouttoolsandpatterns. During A Patterns NeedPatterns UTHOR interaction diagrams. ferent typesofobjectsandroles in theclassand Stereotypes: of thesolution. or astrategy. This provides thedynamicview between different inasolution participants these diagrams toshow theinteractions Sequence (orinteraction) diagrams: This provides thestaticviewofsolution. structure oftheimplementation strategies. the structure solutionandthe ofthepattern Class diagrams: Each pattern in the pattern catalogincludesaclassdia- inthepattern Each pattern We catalog,particular- useUMLextensivelyinthepattern I wantedtogiveyou aflavorofwhat’s tocomeinfuture In Figure 2,we show framework. anexample of apattern Each In inthecon- eachcolumnwe willattepttoputeachpattern We created relationship apattern guide(alsoknown asa The numberoneproblem identified by thedeveloperswas About ayear ago, Sun ran aJava technologydeveloper B IO We usestereotypes toindicatedif- We usetheclassdiagrams toshow [email protected] We use Crupi andDanCrupi Malks (ISBN0-13- Patterns, 064884-1) Copyright 2001.Sun with permission from with permission Core J2EEPatterns Microsystems, Inc. article containexcerptsarticle Portions of this by Deepak Alur, John ak fSnMcoytm,Ic,i h ntdSae n te onre.SnMcoytm,Inc. SunMicrosystems, andothercountries. intheUnitedStates Inc., marks ofSunMicrosystems, JDBCandJMSaretrademarksorregisteredtrade- andJ2EE, EJB, EnterpriseJavaBeans, Java, theSunlogo, SunMicrosystems, Sun, AllRightsReserved. Inc. Copyright 2001SunMicrosystems, fig otiuig oyn,ordistributingtheinformation. copying, contributing, ifying, Reviewed by James McGovern F. Libraries Professional JSP Tag Book Review: by ThomasHammell Drop into JavaDrag ‘n’ by Mark Dykstra Java Recognizing andeliminatingerrors in Multithreaded Errors Eliminating by Jose Barrera Using theJava Reflection classes Reflecting onJava by Alan Williamson JavaOne JDJ J2EE Panel Discussion Next Month Core J2EE (Prentice ete u o h uhr hl elal o n aae ufrda euto sn,mod- sufferedasaresultofusing, damages Neither Sunnortheauthorsshallbeliableforany suitability, truth, accuracy, or completeness of any oftheinformation. orcompletenessofany accuracy, truth, suitability, may have intellectual property rights relating to implementations ofthetechnology toimplementations intellectualpropertyrightsrelating may have chairs majorappvendorsat h uhr aeayrpeettos arnis orguarantiesastothequality, warranties, representations, the authorsmakeany ecie nti ril,adn ies faykn sgvnhr.Pleasevisit kindisgivenhere. andnolicenseofany described inthisarticle, h xetta uhdsliesaehl ob eal nai.NeitherSunnor suchdisclaimersthe extentthat areheldtobelegallyinvalid. www esfrapriua ups,o o-nrneet–aedslie,exceptto ornon-infringement–aredisclaimed, ness foraparticularpurpose, in,adwrate icuigayipidwrat fmrhnaiiy fit- andwarranties–including impliedwarrantyofmerchantability, any tions, o icsinproe ny l xrs ripidcniin,representa- Allexpressorimpliedconditions, for discussionpurposesonly. .sun.com/software/communitysource/ The information inthisarticleThe information (the isprovided “Information”) “as is,” J ava for licensinginformation. COM ENTERPRISE JAVA

J2ME Fitting the Pieces into the Enterprise Java Puzzle

J2SE Adding functionality with EJBs

The story so far: In Part 1 (JDJ Vol. 6, issue 4), I covered Part 3 of 3 servlets and gave a practical demonstration of how a basic access control mechanism for intranet applications could be built using Servlet Session Tracking and HTTP Authentication. In Part 2 (Vol. 6, issue 5), I introduced a couple of applets into the architecture J2EE WRITTEN BY and showed how a communication channel could be established TONY LOTON between the applets and servlets that comprised the application.

The next version of my application delegated the construction of the HTML ceeds and is committed – or it fails and will include the ability for an engineer to form to a separate displayForm() func- is rolled back. Either way, transactional transfer tasks to another engineer when tion to facilitate the representation of integrity is assured. he goes on vacation or when he’s sick. the form in the case of user error. The When presented like this, EJBs look

Home This added functionality requires a first time around, the form is displayed easy, so to spice things up I’ll suggest servlet to present the transfer form and with a null error message via the call another way of achieving exactly the subsequently to process the form sub- displayForm(out.user,null). same functionality. mission. An Enterprise JavaBean (ses- When the user submits the form, the submission is handled by the same The Alternative EJB Solution servlet’s doPost() method given in This time, I’ll use an entity bean to Listing 2. This method first gets hold of represent each individual engineer and the engineer to which the transfer I’ll rework the TaskManager session should be targeted. If no engineer was bean to coordinate the two entity beans specified, it redisplays the form with an that represent the two engineers. The error message – displayForm(out,user, remote interface for an engineer (entity) “You must specify an engineer”) – other- bean has the method definitions shown FIGURE 1 Task Transfer Form wise the transfer goes ahead courtesy of in Listing 4. For any given engineer you an Enterprise JavaBean. can count his tasks, get his tasks, delete sion) will perform the actual transfer them, and assign new ones. function. Simple EJB Solution In case you’re wondering, the AUTHOR BIO I’ve created the simplest possible sometimesFail parameter on the Tony Loton works Task Transfer Servlet Enterprise JavaBean to perform the assignTasks() method was my way of through his Figure 1 shows what the Task transfer of tasks from one engineer to testing this. If set to true, this parameter company, Transfer Form looks like. You can type another. The TaskManager EJB is refer- causes the method to throw an excep- LOTONtech Limited the name of a recipient engineer and enced by name via JNDI, and its home tion once in a while, which triggers the (www.lotontech.com), submit the form to initiate the transfer. interface is obtained. The home inter- entire transfer operation to be rolled as an independent If the transfer succeeds, the user is pre- face is used to create an instance of the back. consultant, course sented with a confirmation page (not bean, and this instance is instructed to The TaskManager session bean now instructor, and shown). transfer the tasks. I said that this is the has a revised version of the transferTasks technical author. He I will be using a single servlet to sup- simplest possible EJB, and it is: the method, given in Listing 5. It looks up has a degree in port two functions: presenting the remote interface has only one method – the two entity beans representing the computer science transfer form, and handling the form transferTasks(…). from- and to- Engineer(s), gets the tasks and management submission. One servlet, two uses, dis- The EJB implementation in Listing 3 of the fromEngineer, deletes them, and and has spent 10 tinguished by invoking the servlet is a minimal session bean with no trans- then adds them one-by-one to the years in IT. His last through its doGet() or doPost() method. actional attributes, and a single method toEngineer. five years have been The initial form presentation is per- with a single JDBC statement to manip- Adopting this approach introduces devoted almost formed by the doGet() method of the ulate the usertasks database table. I’ve many points at which the transactional exclusively to Java, new servlet, which I’ve called kept it simple not only for illustration, integrity might be compromised. The UML, and related TransferServlet. Listing 1 provides the but also because it’s often the best deleteTasks call – or any one of the technologies. code for this method, and for clarity I’ve approach. The sole SQL statement suc- assignTask calls – might fail, leaving the

24 AUGUST 2001

Java COM ENTERPRISE JAVA

considerably easier to implement – and fits of the EJB model come through more reliable – and the other showing using the standard services for transac- the power and complexity of EJBs. In tions, security, and so on. So if you’re general, my suggestion would be: not going to use these services – in the Applet EJB beware the consultant who dives name of keeping it simple – you might XML straight into the second approach with- be better off sticking with simple RMI.

J2ME Servlet out considering the simpler solution, In a nutshell, don’t treat EJBs as a half- JSP although, of course, there are times hearted solution; either find an easier when only a complex solution will do. method or commit to the EJB approach with all your heart. Fitting the Pieces into the Puzzle I’ve not yet mentioned CORBA as a FIGURE 2 Java puzzle Having presented the three major candidate for client/server communica- architectures offered by the J2EE (the tion or even as an alternative to EJBs. In GLOSSARY servlet, applet, and EJB) in a way that the time that it took RMI to mature and J2SE hopefully shows that these three EJB to take off, CORBA – in the form of API Application Programming Interface approaches may be complementary the Visigenic (Visibroker) or Iona (Orbix) AWT Abstract Windows Toolkit rather than competitive, you might now Java ORB implementations – provided a CGI Common Gateway Interface have some good ideas about the direc- solution that was more comprehensive CORBA Common Object Request Broker Architecture tion in which to take your project. But than RMI and ahead of EJB. Now that EJB Enterprise Java Beans you might still be a little unsure about niche has been filled by pure Java tech- HTML HyperText Markup Language the answer to the essential question: nologies and I see CORBA as being lim- HTTP HyperText Transfer Protocol Which horse for which course? ited to the one remaining niche for J2EE Java 2 Enterprise Edition I can only give an opinion, but the which it is uniquely suited – legacy inte- J2EE JDBC Java DataBase Connectivity order in which I have covered these gration. JNDI Java Naming and Directory Interface technologies is no accident. For any JSP Java Server Pages Internet/intranet application, I would, The Three Approaches RMI Remote Method Invocation by default, assume the servlet-only I’ve taken a tour of the three major URL Uniform Resource Locator approach initially as providing the architecture styles for application devel- WAR Web ARchive thinnest possible clients and the lowest opment that are available to Enterprise XML eXtensible Markup Language common denominator for compatibility Java developers – namely servlets,

Home with client Web browsers. applets, and EJB – and I’ve presented my For very limited client-side valida- ideas on how applications may be built database in an inconsistent state. Rest tion and control, I might stick with the comprising all three approaches, with assured that you could make it work by HTML/servlet approach, add some some interesting diversions into areas setting the transactional properties of JavaScript, and stop there. In all other such as access control. I’ve fitted the big the participating session and entity situations that necessitated highly inter- pieces into the puzzle by offering my beans, in which case the EJB container active or graphical clients, I would use advice on which pieces should be insert- will call the ejbLoad and ejbStore meth- applets with the straightforward ed first and which later, if at all. ods (assuming bean-managed persist- applet–servlet communication mecha- I’ll leave you with one final thought. ence) on the entity beans at appropriate nism based on serialized objects. There are a few smaller pieces such as times to assure the transactional In situations that demand true, XML and JSP that could be placed into integrity. stateful, remotely referenced server- the gaps between the big ones to com- This leaves us with (at least) two side objects I would consider plete the final puzzle, as shown in ways to implement the transferring of Enterprise JavaBeans. I would try to Figure 2. tasks between engineers using keep my EJBs as simple as possible, and Enterprise JavaBeans; one way being that’s where the irony is. The real bene- [email protected]

Listing 1: TransferServlet "doGet" Method if (user==null) public void doGet(HttpServletRequest req { /* -- write error message -- */ } , HttpServletResponse res) throws IOException else { { // -- get the current http session -- // -- handle the transfer form submission -- HttpSession session=req.getSession(true); res.setContentType("text/html"); String user=(String) PrintWriter out = res.getWriter(); session.getAttribute("user"); String toEngineer= if (user==null) req.getParameter("toEngineer"); { /* -- write error message -- */ } else if (toEngineer==null) { { // -- display the transfer form displayForm(out,user res.setContentType("text/html"); ,"You must specify an engineer"); PrintWriter out = res.getWriter(); } else displayForm(out,user,null); { } out.println(""); } out.println("TransferServlet "); Listing 2: TransferServlet "doPost" Method public void doPost(HttpServletRequest req try , HttpServletResponse res) throws IOException { { Context initial = new InitialContext(); // -- get the current http session -- HttpSession session=req.getSession(true); TaskManagerHome taskManagerHome = String user=(String) session.getAttribute("user"); (TaskManagerHome) PortableRemoteObject

26 AUGUST 2001

Java COM .narrow(initial.lookup("TaskManager") } ,TaskManagerHome.class); public TaskManagerEJB() {} TaskManager taskManager= public void ejbRemove() {} taskManagerHome.create(); public void ejbActivate() {} public void ejbPassivate() {} taskManager.transferTasks(user,toEngineer); public void setSessionContext(SessionContext sc) {} } out.println("Transfer to "+toEngineer +" succeeded. "); Listing 4: Engineer Entity Bean } public interface Engineer extends javax.ejb.EJBObject catch (TransferException ex1) {

J2ME { public int getTaskCount() throws java.rmi.RemoteException; out.println("Transfer to "+toEngineer public String[] getTasks() throws java.rmi.RemoteException; +" failed with an application error. "); public void deleteTasks() throws java.rmi.RemoteException; } public void assignTask(String task, boolean sometimesFail) catch (Exception ex2) throws java.rmi.RemoteException; { public String getKey() throws java.rmi.RemoteException; out.println("Transfer to "+toEngineer } +" failed with a system error. "); } Listing 5: transferTasks Method with Entity Beans public void transferTasks out.println(""); (String fromEngineerID, String toEngineerID) out.println(""); throws java.rmi.RemoteException } {

J2SE } try } { EngineerHome engineerHome= (IEngineerHome) ctx.lookup( "EngineerHome" ); Listing 3: TaskManager Implementation public class TaskManagerEJB Engineer fromEngineer=engineerHome implements SessionBean .findByPrimaryKey(fromEngineerID); { public void ejbCreate() throws CreateException Engineer toEngineer=engineerHome {} .findByPrimaryKey(toEngineerID); public void transferTasks(String fromEngineer String[] tasks=fromEngineer , String toEngineer) throws TransferException .getTasks(); { try fromEngineer.deleteTasks(); J2EE { InitialContext ic = new InitialContext(); for (int i=0; i

Home } catch (Exception e) { /* handle the error */ }

28 AUGUST 2001

Java COM BOOK REVIEW

f you’re familiar with the J2EE Blueprints there is no attempt to sell a one-shoe-fits-all from Sun, Designing Enterprise concept. The authors make it clear that all IApplications with the Java2 Platform, aspects of J2EE do not apply to all applica- Enterprise Edition is the official “Java Series” tions. These chapters help the reader decide book from Addison-Wesley on them. It’s a what to apply and when. part of the Java Series Enterprise books The next section Chapters 7–9 deals

J2ME from Sun. J2EE Blueprints are still avail- with specific issues that designers and able for a free download from Sun’s Java architects encounter when building enter- site, but if you like to have the profession- prise applications. The issues related to ally bound book, this is it. deploying EJBs, transactions, and security J2EE Blue prints were discussed in pre- are covered in brief. The last section dis- vious issues of JDJ. They tie the compo- cusses the Pet Store application – an exam- nents of a complex platform with sever- ple application that illustrates the design of al aspects of software application devel- a commerce application using the compo- J2SE opment into one brief overview. This nents of J2EE. J2EE book is that excellent overview of the I highly recommend this book. It should J2EE platform. I didn’t think it feasible be useful to a variety of readers, ranging from to cover all major aspects of Enterprise programmers and architects to product man- Java in 341 pages, but the authors have agers. However, it is not a book you can pick Design and Practice done a great job in doing just that. up and use as a programming reference. This is a good book for architects Rather it’s a book you can use for design and designers. It introduces all the guidelines. major components of J2EE in a nut- ¥ ¥ ¥ J2EE REVIEWED BY AJIT SAGAR shell. Readers may be familiar with J2EE Technology in Practice is another some of the information, but I haven’t book from the Java Series Enterprise Edition [email protected] seen another source where it has been set from Addison-Wesley. I picked the book up covered in such a concise fashion. It at JavaOne this year. I was happy to see a book introduces the building blocks of J2EE, that verifies for the skeptical that J2EE has applicability of individual compo- taken off in the real world. nents in different scenarios, and tiered You may have mixed emotions. I liked the

Home application development. The book is book because it met my expectations – written by a team of authors from Sun, examples of J2EE applications. However, to who have contributed to the develop- others it may seem like a series of white ment or documentation of the J2EE papers from different J2EE vendors. If you’re info Designing Enterprise framework. looking for development techniques, pro- Applications with the Java 2 The book can be segmented into gramming tips, or API details, you won’t find four basic sections, which may apply to dif- them here. This is a book of case studies that Platform, Enterprise Edition ferent audiences, or validates the J2EE platform. by Nicholas Kassem, make for different The book contains examples of Enterprise Team reading sessions. My business applications built using Addison-Wesley recommendation is for J2EE technologies. Eight leading the reader to go through J2EE application server vendors ISBN: 0-201-70277-0 the whole book. It is not describe specific customer appli- voluminous and does cations in which they were J2EE Technology in Practice not delve into API able to successfully use J2EE Rick Cattell, Jim Inscore, details. As mentioned to deploy applications. The before, it provides an applications are in various Enterprise Partners overview and guidelines, business domains, includ- Addison-Wesley not practical application ing catalog sales, a telecom- ISBN: 0-201-74622-0 development examples. munications application, Chapters 1 and 2 con- and a manufacturing appli- sist of an introduction to J2EE cation. Design criteria, issues technologies. The compo- faced, topology design, nents of J2EE are described, a transaction management, brief overview of the APIs is and many other aspects of given, and the types of services applying J2EE technologies offered by J2EE are described. are discussed by the vendors. This month I review two books, both of The discussion on the types of J2EE contain- Design patterns, guidelines, and valuable ers was lucid. advice are offered by folks who have been in which are valuable sources for developers The second part of the book – Chapters 3 the trenches with the customer. and architects building enterprise applica- to 6 – discusses the basic tiers of applications I recommend this book for readers who tions using J2EE technologies. that can be built on a J2EE base. I found this are looking at examples of real-world J2EE section particularly interesting. The authors applications. It is not a comprehensive present the business scenarios in which J2EE source, but a good book to help you make a can be applied. What I liked most was that dif- crucial decision before you start a new project ferent types of applications are addressed, but using J2EE.

30 AUGUST 2001

Java COM AUTHORIZATION

J2ME J2EE ApplicationSecurity Model

A powerful security model that’s simple,robust,and reliable J2SE The J2EE platform architecture provides for the secure deployment of application components. It emphasizes the declar- ative approach wherein the application components’ security structure, roles, access control, authentication and authorization requirements – as well as the other characteristics pertaining to WRITTEN BY transactions, persistence, and more – are expressed and managed SANJAY MAHAPATRA outside the application code. J2EE J2EE server products provide deploy- role is a logical grouping of users that’s is generated and maintained by the J2EE ment tools that support the declarative used to define a logical security view for platform. This security context is the customization of application components the application. Protected application encapsulation of the identity of the for the operational runtime environment. resources have associated authorization authenticated user principal. An application component provider isn’t rules – roles that are allowed to access a expected to implement security services, given component are specified in the Web Container’s Support for Authentication as it’s the responsibility of the J2EE con- application component’s deployment The element in the

Home tainer and server. The security functions descriptor. The deployer maps the roles Web deployment descriptor is used to provided by the J2EE platform include to actual users using the J2EE server’s configure the type of authentication authentication, access authorization, and deployment tools. The J2EE server mechanism such as “BASIC”, and “FORM”. secure communication with clients. enforces the prescribed security policies at runtime and ensures that only those FORM Authentication users who belong to the appropriate role Authentication is the process by are able to access the protected compo- The deployment tools provided with which an entity (such as a user, organi- nents’ functionality – while those who the J2EE server product insulate us from zation, or program) proves and estab- don’t belong are denied access. having to manually write the deploy- lishes its identity with the system by ment descriptors; the elements are pro- supplying authentication data. For users J2EE Containers vided here for reference. The following this typically means a user name and A container is part of the J2EE server. are some of the authentication mecha- password. (In general, authentication It provides deployment and runtime nisms made available by the Web con- data could be comprised of a digital cer- support for application components tainer and server. tificate, or even biometric data such as a and is responsible for infrastructural fingerprint, iris, or retina scan.) A princi- services including security. There are Basic Authentication pal is an entity that can be validated by three types of J2EE containers that are HTTP basic authentication is the an authentication mechanism; it’s iden- meant to house different J2EE applica- simplest. When a user attempts to tified using a principal name and veri- tion components: access any protected Web resource, the fied using authentication data. 1. EJB container: Houses EJB compo- Web container checks if the user has nents already been authenticated. If the user Authorization and Access Control 2. Web container: Houses servlets, JSPs, hasn’t, the browser’s built-in login Authorization and access control static HTML, JPEG files, and more screen is used to solicit the user name mechanisms ensure that only authenti- 3. J2EE application client container: and password from the user so that the cated principals who have the required Houses J2EE application clients Web server can perform authentication. permissions to access application com- If the login fails, the browser’s built-in ponents are able to do so. In general, Each of these containers has its asso- screens and messages will be used. The there are two fundamental approaches ciated deployment descriptor. user name and password are sent using to controlling access – capabilities and simple base 64 encoding. permissions. The capabilities-based Obtaining the Initiating Security Context approach focuses on what resources a In the J2EE model, secure applica- Form-Based Authentication given user can access. The permissions- tions require that the client programs be Form-based authentication is used if based approach on the other hand authenticated. An end user can be an application-specific login screen is focuses on which users can access a authenticated using either a Web or an required, and the browser’s built-in given resource. The J2EE authorization application client. Once the user is authentication screen isn’t adequate. The model uses role-based permissions. A authenticated, an initial security context Web deployment descriptor needs to

32 AUGUST 2001

Java COM AUTHORIZATION

specify the login form page and the error to deal with the login issue. As with resources and indicate the user roles that page to be used with this mechanism. other J2EE components, a J2EE applica- should be permitted access to the Web When the user attempts to access any tion client is created with the J2EE serv- component. The roles used here should protected Web resources, the Web con- er’s deployment tools. J2EE application appear in the element. tainer checks if the user has already been clients provide a standard and portable This security context can also be authenticated. If the user hasn’t, the con- way for authentication, therefore the propagated from the Web to the EJB

J2ME tainer presents the login form as specified J2EE architecture encourages the use of container, which will use it to authorize in the deployment descriptor. If authenti- J2EE application clients rather than access to the EJB components’ methods. cation fails, the error page, as specified in “plain” Java application clients. the deployment descriptor, is displayed. EJB Component Authorization The and elements are respectively A “plain” Java application client is a to EJB components based on the caller’s used to specify the location of the login nonbrowser based, stand-alone Java appli- security context, in conjunction with the and error pages that need to be dis- cation. There’s no standard procedure permissions stipulated in the EJB J2SE played. Further, the login page must defined by the EJB 1.1 specification regard- deployment descriptor(ejb-jar.xml), via contain fields named precisely j_user- ing their authentication. However, several the and elements. user name and password, respectively, as shown in Listing 1.

HTTPS Authentication HTTPS (HTTP over SSL) authentica- In general, there are two fun- tion is a strong authentication mechanism. J2EE It requires the user to possess a public key damental approaches to con- certificate and is ideal for e-commerce “ applications as well as single sign-ons from trolling access – within the browser in an enterprise. capabilities and permissions Hybrid Authentication In both the HTTP basic and the

Home form-based authentication, passwords aren’t adequately protected for confi- that involves appropriately setting the The deployment descriptor setting in dentiality. This deficiency can be over- environmental property constants, Listing 3 grants permissions to all the come by running HTTP basic and HTTP java.naming.Context.SECURITY_PRINCI- methods (indicated by the “*”) exposed form-based authentication mechanisms PAL and java.naming.Context.SECURI- via the home and remote interfaces to over SSL. Generally, the use of the CON- TY_CREDENTIALS, and creating the initial an authenticated user in the” role of “cus- FIDENTIAL flag in the element of the Web deployment The deployment descriptor setting descriptor ensures the use of SSL for Security Context and Access Control shown in Listing 4 grants specific per- data transmission. Once the J2EE platform performs missions to the placeOrder() method authentication and obtains the security exposed via the home and remote inter- CONFIDEN- context of an authenticated principal, faces to an authenticated user in the role TIAL it’s maintained in the background. of “customer”. Whenever an attempt is made to access All J2EE specification–compliant a protected application component, the Propagating the Security Context Web servers support the concept of a container uses the roles known to be When one component calls another, single sign-on so that one login session associated with the authenticated user the J2EE platform architecture provides can span multiple applications, thus in conjunction with the roles authorized for the propagation of the caller security allowing a user to log in once and access to access the component, as prescribed context across components along a call multiple applications. in the deployment descriptor, to either chain. The security context can propa- permit or deny access. For example, the gate across the various J2EE containers J2EE Client Container’s Support for Authentication container will allow the authenticated within the J2EE server. For example, it A J2EE application client is a Java user “John Doe,” who belongs to the can propagate from the JSP component application, but differs from a “plain” “sales representative” role, to access a housed in the Web container to an EJB Java application client in that it’s a J2EE protected component with a deploy- component housed in the EJB container. component that’s deployed in the J2EE ment descriptor setting that specifies The J2EE platform’s support for the “client” container. When a J2EE applica- “sales representative” as one of the roles propagation of the sensitive security tion client is run, a login window provid- authorized to access it. context information provides reliability ed by the J2EE application server will and convenience. It eliminates the need pop up and require user name and pass- Web Component Authorization for the security context information to word fields to be input. Once the user is JSPs, servlets, and HTML pages can be be passed around as an additional authenticated, the application will be set up as protected resources using J2EE parameter in the business methods. started. The authenticated user security server deployment tools. The and its subelement are used respectively to asso- ponent calls so that a specified principal the client application code doesn’t have ciate security constraints on Web identity other than the original caller

34 AUGUST 2001

Java COM AUTHORIZATION

identity will be propagated down the call allow programmatic access to security- role>, , and chain. The proposed EJB 2.0 specification related information, namely get- elements of the deployment descriptor. provides a standard technique for CallerPrincipal() and isCallerInRole(). addressing the issue of identity selection The getCallerPrincipal() allows the EJB Future Directions along a call chain via the and

J2ME ty> elements of the deployment descrip- may be used for info only in conjunction context from the J2EE server to the tor. If is specified with declarative management. In a com- enterprise information systems (EIS), for a component, it results in the propa- mon scenario, getCallerPrincipal() may such as database, ERP, or mainframe gation of the caller principal along the be called from within an entity EJB com- transaction processing systems. The call chain. If the element is used to specify a particu- the user who caused the insertion of the expected to be included in the next ver- lar identity, then that specific principal row to the database. This can be accom- sion of the J2EE platform specifications, identity is propagated down the call plished by using code in the ejbCreate() addresses the propagation of the securi- J2SE chain and all access control is governed method as below: ty context from the application server to by permissions for the specified identity. the EIS. The objective is to extend the this.loginID = end-to-end security model of J2EE Programmatically Querying the Security theEntityContext.getCallerPrincipal applications to include the EIS tier. Context Information ().getName() ; The next release of the J2EE specifica- The getRemoteUser(), getUser- tions is expected to include the Java Principal(), and isUserInRole() methods String loginID is a container-man- Authentication and Authorization available in the HttpServletRequest inter- aged persistent field that represents the Service (JAAS), which implements the face provide servlets and JSPs with access to login/user name that caused the inser- Pluggable Authentication Module (PAM) J2EE security context information. The tion of a particular row, and framework and endeavors to make the getRemoteUser() method obtains the name EntityContext theEntityContext was login services independent of the actual of the authenticated user, while the obtained using the callback underlying authentication mechanism, getUserPrincipal() returns the principal setEntityContext(). This approach so that different security and authentica- object associated with the authenticated allows sensitive data for recording pur- tion implementations may be “plugged” user. These methods may be useful for poses to be obtained via the EJBContext. in or out seamlessly. recording the user’s access to Web compo- The method isCallerInRole(String More than one J2EE server product may

Home nents or dynamically generating HTML roleName) allows the bean implementa- be used in the production environment of a content that includes the name of the user. tion to query whether the caller belongs large enterprise; therefore the passing of the AUTHOR BIO Similarly, the isUserInRole( String to a particular named role. Typically this is security context between different J2EE Sanjay Mahapatra works roleName) queries the underlying security used to provide fine-grained control server products assumes significance. for Cook Systems mechanism of the container to determine if access and/or programming logic corre- Currently, the mechanism of passing the International. He’s been the authenticated caller belongs to a given sponding to that role. When programmat- security context tends to be specific to the writing distributed and security role. This may be useful for dynam- ic calls are made to the isCallerInRole() particular J2EE server product. In the cur- object-oriented ically generating Web content and options method, the component provider rent J2EE specification, the EJB to CORBA applications for more based on the role of the user. declares the logical role names referenced mapping, which addresses the propagation than five years and is a Similarly, the EJBContext provides in the code in the deployment descriptor, of the security context over IIOP, is not a Sun-certified Java EJB components access into the security and the deployer is responsible for map- required feature. The next release of the developer and Java 2 context (as well as transaction context). ping the logical role to an actual security J2EE platform specification is expected to platform architect. EJBContext provides two methods that role. This is achieved via the ent vendors deployed on J2EE servers. Conclusion Listing 2 The J2EE architecture provides a Properties props = new Properties () ; powerful security model that’s simple props.put ( Context.SECURITY_PRINCIPAL, theUserLogin ) ; yet robust and reliable. It emphasizes props.put ( Context.SECURITY_CREDENTIALS, thePassword ) ; IntialContext ic = new InitialContext ( props ) ; the flexible and cost-effective declara- // proceed with lookup using above InitialContext ic ... tive approach of managing security via Listing 3 XML-based deployment descriptors. It provides for the propagation of the customer security context across components CustomerServicesEJB along a call chain. This eliminates the * need for the user information to be passed around as an additional parame- Listing 4 ter in the business method calls, thereby providing reliability and convenience. It customer also supports the concept to applica- CustomerServicesEJB tions of single Web sign-on access. placeOrder [email protected]

36 AUGUST 2001

Java COM FRAMEWORKS

J2ME A J2EE ApplicationFramework Checklist

What to look for to build portable,scalable,

J2SE and robust applications

In recent months, there have been significant writings and dis- cussions surrounding J2EE frameworks and the key benefits one provides. I will not spend time reiterating those here.The bottom line is most professionals in this space agree on one thing: applica- J2EE tion-level reuse is a good thing and the right J2EE framework can WRITTEN BY deliver just that.This article concerns itself with identifying what STEVEN RANDOLPH specific features to look for in a J2EE application framework.

First, let’s decide on an appropriate for the other J2EE aspects (EJB, JMS, etc.), nents, each not necessarily having any definition of an application framework. and because it supports the presentation relationship with the set. This isn’t to tier only, Struts is not qualified to be con- undermine their importance, but such

Home • An application framework: It’s an sidered a J2EE application framework. components are often not required for implementation of a set of application- the J2EE application being consid- neutral components and services based realMethods Framework ered. A framework should provide on the best design patterns, standards, This framework attempts to provide reusability for all applications across and practices available. These compo- support for all the major J2EE technolo- the enterprise using the targeted tech- nents and services should cover all gies, on all tiers. realMethods contends nology. A calendar component, while identifiable tiers of the technology they that its framework is completely design reusable, isn’t required of every J2EE are addressing. It should encapsulate pattern–based and has been developed application. many application complexities and from the ground up for the past 18 2. An application: Even the best commonalties, as well as encourage months. There is more on this frame- designed and written J2EE applica- appropriate design and implementa- work later in the article. tion is not a framework. Sifting tion principles of the consumer. through such an application will J2EE Blueprints and the Pet Store Demo hopefully provide some best practices As it relates to J2EE, there already Sun’s J2EE Blueprints seeks to pro- toward proper idioms and techniques exists a set of well-defined design pat- vide a set of best practice guidelines for of implementation. However, the level terns geared toward the technology. J2EE application development. The Pet of reusability required of a framework They can be found in the recently pub- Store demo represents an application would be nearly impossible to extract lished book, Core J2EE Patterns. Sun’s built using these guidelines. It also from the application. J2EE Blueprints provide best practice includes potentially reusable vertical 3. Any other framework: This simply guidelines and architectural recommen- components, such as a shopping cart. means that you should expect the dations for real-world application sce- Our definition also rules out the framework to be constructed “with narios. These enable developers to build Blueprints Pet Store demo since it’s an intention” from the ground up. As portable, scalable, and robust applica- application with an implementation software vendors attempt to capitalize tions. But remember, a framework must based on design patterns, instead of a on the need for J2EE frameworks, provide an implementation of the core set of reusable classes and services. understand the origin of the resulting guidelines and design patterns across all framework. Be cautious of vendors tiers. Before listing what to look for in What To Look For porting existing frameworks from one the implementation, it’s important to There are roughly a half-dozen key technology to J2EE. Ultimately, the look at existing framework references. features and characteristics to look for best J2EE frameworks will be based on in a J2EE application framework. But the best design patterns and guide- Struts first, let’s define three things a frame- lines related and specific to J2EE. This framework implements the work is not: Model-View-Controller (MVC) pattern to 1. A library of independent Java compo- The Shopping List aid JSP and servlet development efforts. nents: Too often, an enterprise consid- Design Patterns Implemented Regardless how appropriate its implemen- ers itself to have a framework when A framework must have at its core a tation, without components and services what it has is a set of reusable compo- set of design patterns. Patterns provide

38 AUGUST 2001

Java COM FRAMEWORKS

solutions for problems typically Application Server Neutral you will play in consuming the frame- encountered in the design and develop- A framework should not make a com- work will be consistent and predictable. ment of J2EE applications. It’s important mitment to any one J2EE application to remember that these patterns should server. None of its core capabilities Code Generation be implemented in such a way as to pro- should have a dependency on a single Since a framework should be based vide full coverage on all J2EE tiers. app server. A feature with a dependency on design patterns and provide multi-

J2ME By building your application on top of should be peripheral to the essential tier support, generating much of the such a framework, it should immediate- offerings of the framework, or encapsu- code as it relates to the application and ly inherit the important characteristics lated and implemented in such a way its integration with the framework intended by the design patterns. that the dependency is transparent to should be expected. In fact, if this code the application. is not generated, the application runs Multiple Tier Support the risk of incorrectly interpreting the Any substantial J2EE implementation Configurable intent of the design patterns already will require support on the presentation, A considerable number of features implemented by the framework. This J2SE business, and data/service tiers. and services of a framework should be would defeat the purpose of using a 1. Presentation tier: Encompasses modifiable without making changes to framework in the first place. JavaServer Pages, servlets, presenta- its code. This should happen by means tion logic, minimal security, and an of property and/or XML files. One way Dependent (Yet Independent) Services object cache in which a framework can maintain Just because a framework should be a 2. Business tier: Encompasses applica- application-server neutrality is by allow- cohesive implementation of design pat- tion business objects, session/entity ing property-based configuration. This terns doesn’t mean the application beans, and JMS technologies should simplify migration from one app needs to be dependent on all available 3. Data/service tier: Encompasses data server to another, or allow a heteroge- services. A framework is of the greatest J2EE access considerations as well as asyn- neous mix of app servers in a single use when an application is able to pick chronous service definitions and pro- application deployment. and choose those features that are most visions important. Loose component coupling Useful But Not Intrusive by the framework assists in accomplish- Extendable There is a fine line between each. A ing this. Since a framework is an implementa- framework takes a stand with its imple- tion, it represents a decision toward mentation, but is it forcing your design Application Server Vendor Positioning

Home process definition. To be flexible and and development to take place in an Vendors are busy keeping in step with useful in as many implementations as unnatural or unacceptable fashion? A an ever-changing J2EE specification and possible, it should provide the applica- framework is of no use if it causes you to JDK. Many have provided vertical com- tion designer and developer with retrain in ways that are not transferable ponents and applications that are main- design-time and run-time access to to other J2EE efforts (that do not use the ly tied to their server offering. Most both involvement and notification of its same framework). Again, this is where either include, or offer at an additional execution. This is done by traditional design patterns play a part. By having cost, tools to assist in bean deployment, means, such as interface implementa- patterns as the foundation of the frame- O/R mapping, and more. Some include tion and class extension. work, you can be assured that the role Struts or the Blueprints Pet Store demo as part of their download. But what good are any of these if, fun- damentally, the first hurdle is under- standing J2EE itself? And the second hurdle, an even higher priority, is to effectively design and implement in J2EE. Fast-moving technology with an increasing level of complexity needs to provide relief in many areas. Frameworks address this need. To date, no application server vendor provides a complete J2EE application framework. There exists a natural relationship between app server and framework ven- dors. Considering the neutrality re- quirement of a J2EE application frame- work, it should seamlessly complement and enhance any app server vendor offering. A simple comarketing relation- ship shows that each vendor endorses and supports the other’s product. A more “collaborative” relationship is an indica- tor of a committed, embedded correla- tion between the two. This type of rela- tionship should serve notice of both ven- dors’ commitment to simplifying and FIGURE 1 The realMethods Framework implementation of a dozen design patterns enhancing your J2EE experience.

40 AUGUST 2001

Java COM FRAMEWORKS

fact that many J2EE-based applications remain on the peripherals of the tech- nology, using EJB and JMS technologies A framework is of the greatest sparingly, preferring to focus on the JSP/servlet and JDBC aspects. A frame- use when an application is able work encourages more thorough con- J2ME “ sumption of an application server’s to pick and choose those offerings, and ultimately a deeper com- mitment by the enterprise to J2EE. As features that are most important competing technologies attempt to get the attention of software architects and developers, J2EE application frame- works will be an important part of gain- realMethods Framework nents, the realMethods Framework ful- ing deeper loyalty and dedication to J2SE All of the necessary design patterns fills the need for application-level J2EE. AUTHOR BIO required of any well-structured J2EE reusability across the enterprise (see Steven Randolph is application are already implemented by Figure 1). By furnishing design time, founder and chief the realMethods Framework. As such, development time, and runtime” sup- Resources technology officer for the framework provides support on all port, it appropriately allows design and 1. Struts: http://jakarta.apache.org/ realMethods, a J2EE tiers (Web, business, and data access). development efforts to be focused on struts/ software product Its main purpose is to provide a cohe- business-related issues, and not neces- 2. J2EE Blueprints: http://java.sun.com company based in sive implementation of the best J2EE sarily on application infrastructure. /j2ee/blueprints/ Bridgewater, design patterns. This framework also Much like the Microsoft Foundation 3. Core J2EE Design Patterns: www.sun. J2EE Massachusetts. provides a set of solutions to reoccur- Classes is to the Windows API, the com/service/sunps/jdc/J2EE Prior to founding ring complexities and issues found in realMethods Framework is to the J2EE 4. realMethods Framework: www.real- realMethods, he spent most, if not all, J2EE application devel- Application Server: it applies structure, methods.com; www.j2eeframework. more than 12 years opment. order, predictability, and simplification com designing, managing, Observe the realMethods Framework toward building J2EE applications. 5. Alur, D., Crupi, J., and Malks, D. and implementing implementation of a dozen design pat- (2001). Core J2EE Patterns, Best enterprise software terns as defined by the book, Core J2EE Utilization Is an Issue Practices and Design Strategies.

Home solutions for Fortune Patterns, Best Practices and Design Acceptance of J2EE is becoming Prentice Hall . 500 clients as well as Strategies. more widespread, but its utilization [email protected] Internet start-ups. Unlike single-purpose Java compo- remains an issue. Today it is a known

42 AUGUST 2001

Java COM J2SEJ EDITORIALOR J2SE INDEXX

JEREMY GEELAN J2SE EDITOR

Java Comes of Age Sun gets a good midterm 44 Java Comesof Age report from developers worldwide here’s an old joke: “It’s not progress Pekka Ala-Pietila, traveled all the way from by Jeremy Geelan J2SE I’m against, it’s just change that I Tokyo to San Francisco to announce at Tloathe!” This isn’t one you hear JavaOne that Nokia confidently expects told very often in Internet technology cir- this total to increase to a staggering 50 mil- cles! lion Java-enabled phones by the end of But Sanjay Sarathy is right. As he says 2002 and 100 million by the end of 2003. in his “Guest Editorial” at the front of the It’s interesting to note that another issue, it would be easy to feel sympathy for mobile story has been unfolding...involv- FavoritesComboBox: A 46 the poor CIOs, line-of-business execu- ing not J2ME but J2SE. A new operating Custom Component for tives, or even developers, who, every time system for information appliances, such Displaying Recent they feel they’ve figured out how to take as advanced PDAs, Web tablets, and so- Selections full advantage of one edition of Java, find called "smart phones" has recently been How it works, and the impor- themselves promptly confronted with launched. It’s based not on J2ME at all, but tance of design patterns. another. on plain vanilla Java 2, Standard Edition. by Justin Hill and David Lesle But for once, or so it seems to me from In public beta release for the first time the sidelines anyway, this isn’t a case of just last month, this new OS supports the

Hometechnology J2EE being dominated by two types full J2SE J2ME platform. savaJe XE 0.1.1 (to give of people – those who understand what it its official name) is the first and only OS they do not manage, and those who man- to date that allows information appliances age what they do not understand…with to run full J2SE applications, but it proba- Sun Microsystems falling into the second bly won’t be the last. Anyone who has used A Chat with category. On the contrary, the general con- a Compaq iPAQ handheld device – 54 sensus among industry executives and reviewed in this issue of JDJ in the J2ME On a sunny Tuesday afternoon commentators alike seems to be that Sun – Section - will tell you: even without going at JavaOne, James Gosling, the for all its recent headline-making to Japan, it’s possible to sense that the next creator and father of Java, economies – is truly on to a winner with wave of wireless devices is going to embed takes time out to chat with J2SE, J2EE, and J2ME. Java firmly not just into people’s minds but JDJ’s Alan Williamson and Nearly everyone I spoke to or inter- also into their handheld devices. Blair Wyman. viewed in the last few weeks and months On the other hand, no matter how of conferences and travel – from Mumbai bright the future may seem for PDAs and to Seoul to San Francisco to New York to for wireless Java, recent events with Psion Paris to Copenhagen – has emphasized the remind us of the enormous difficulties of self-evident and increasing maturity of the being involved with hardware. As the old Java platform. Sun, they clearly feel, has adage goes, “We are all manufacturers. been an astute and able custodian of its Making good, making trouble, making Strategies for Storing own technology. excuses.” Java can help solve all sorts of Java Objects in 62 technical problems, but those who would Relational Databases Small Is Big use it to achieve ROI still need to have a Storing your objects in relation- Everyone has been asking JDJ’s editori- sound business model. al databases is a reality for the al board members, ever since JavaOne, vast majority of Java develop- what was truly the biggest news? Well, to Conference Draws Near ers. This article presents some me there’s little doubt that it was also the The JDJEdge 2001 Conference & Expo, basic techniques for doing so. smallest news: J2ME – the small-footprint the largest Java conference ever held on by Scott W. Ambler Java 2 MicroEdition. the East Coast, is fast approaching. According to Sun’s own estimates, there Opening keynote speakers include the are already 3 million mobile phones enabled with J2ME. Nokia’s President, –continued on page 74

[email protected] AUTHOR BIO Jeremy Geelan, editorial director of SYS-CON Media, speaks, writes, and broadcasts about the future of Internet technology and about the business strategies appropriate to the convergence of business, i-tech, and the future.

44 AUGUST 2001

Java COM J2SE

wing is a library of graphical components used by Java front- ing listeners. FavoritesComboBox (see Listing 1), a subclass of JComboBox, is no exception, and along with performing the

Home J2EEend developers to create robust J2ME and functional graphi- default setup specified in the super class, it accomplishes the following: cal-user interfaces. Although there are many exciting • Adds a focus listener • Creates and sets a custom combo box model topics in Swing, one of its most salient features is its abili- • Creates and sets a custom renderer

ty to be customized. Before providing a detailed description of the above-men- tioned items, we need to clarify some fundamental assump- One of the more powerful and customizable widgets in the tions regarding user interaction with FavoritesComboBox. Swing library is JComboBox. JComboBox, a combination of a One of the more interesting problems we came across text field and a list, allows the user to select an item from a when designing and developing FavoritesComboBox was try- drop-down list that appears at the user’s request. ing to determine what constituted a selection in the widget. FavoritesComboBox, our extension to JComboBox, is a practi- For example, suppose a user chooses an item from the combo cal and functional component similar to the Fonts drop-down box, but the focus remains in the widget. Does this constitute list in Microsoft Word (see Figure 1). a selection? Furthermore, when a user is keying the up/down The concept of FavoritesComboBox is that it provides a arrows to navigate the combo box’s list, does this mean the listing of the most recently selected items at the top of the list, user is making valid selections? We think not. To solve this italicizing and separating them with a horizontal line. A problem, FavoritesComboBox assumes a selection has not combo box containing a listing of all the countries of the been made until the component’s focus is lost. While this world is an example of a domain in which Fav- basic assumption may seem vague at this point, the following oritesComboBox would be applicable. More often than not, if sections will make things clearer. you live in the United States, “United States” is the selected choice, so why make the user traverse the entire list to find it? NestedComboBoxModel FavoritesComboBox solves this problem by placing “United A close look at the pop-up list of possible selections in States” at the top of the list. FavoritesComboBox shows two separate user-selectable lists. This article closely examines FavoritesComboBox and its We’ve separated them into distinct ComboBoxModels – one associated classes. In addition to discussing how with recent selections and one with all the valid choices. A FavoritesComboBox works internally, the article introduces FavoritesComboBoxModel combines these two models into design patterns, their importance, and how we used them in one for presentation in FavoritesComboBox. The underlying the design and development of FavoritesComboBox. behavior that supports this combination of models into one is provided by the base class – NestedComboBoxModel. FavoritesComboBox We developed NestedComboBoxModel as a generic com- Classes in the Swing package that start with the letter “J” ponent that takes the contents of any number of individual serve an important purpose – they act as the glue between the ComboBoxModel instances and presents them as a single model and the UI-delegate. In addition, JWhatevers perform concatenated list of items. Support for the basic features of a “special” operations such as setting up renderers and initializ- ComboBoxModel is inherited from its base class,

46 AUGUST 2001

Java COM AbstractComboBoxModel. This provides the initial required While Wrapper solves our selection index and equality interfaces and support for registering event listeners and problem, we use another approach to obtain the combo box’s firing events to them. We had to implement the remaining selected item. We now have a Favorites- methods of the ComboBoxModel interface in order to present ComboBoxModel that can have selected items that are either the combination of several submodels as a single list of ele- Wrappers or the “actual” objects. However, we want ments. FavoritesComboBox getSelectedItem() to report the “actual” To report the current selection the model must keep track object. In the case where the selected item is in the recent list, of the currently selected submodel. If one is defined, we want to return its corresponding “actual” object. To getSelectedItem() delegates the request to the selected sub- achieve this behavior, getSelectedItem() delegates the respon- model. For applying new selections the model must search sibility to the FavoritesRecentComboBoxModel’s through all elements to find the submodel that contains the getCurrentSelection(). The getCurrentSelection() method new selection. Again, the operation is delegated to the sub- determines the selected item [via the model’s model, and the new submodel is recorded as the currently getSelectedItem()] and, in the case of a Wrapper, returns the selected one – after the previously selected submodel’s select- encapsulated “actual” object; otherwise, it returns the select- ed item is cleared. This ensures that if a submodel is present- ed item – the “actual” object. J2SE ed in multiple visual components, the selections are consis- tent. FavoritesListCellRenderer NestedComboBoxModel, as we’ve shown, is a robust To display the most recently selected items at the top of ComboBoxModel capable of grouping distinct the list, italicized and separated by a horizontal line, we need- ComboBoxModels into one entity and is an important part of ed to create a custom ListCellRenderer. Our class, the success of FavoritesComboBox. FavoritesListCellRenderer, extends DefaultListCellRenderer and is capable of determining which items exist in the recent FavoritesComboBoxModel and FavoritesRecentComboBoxModel list as well as where the horizontal divider should be placed. FavoritesComboBoxModel extends NestedCombo- With most ListCellRenderers the rendering logic is defined in BoxModel, thus it combines recent selections with possible the getListCellRendererComponent() method; our renderer is selections from two separate ComboBoxModels. One impor- no exception. The following code fragment contains the logic tant customer requirement of our component was the ability for altering the item’s font and displaying the underline: to share recent lists across similar combo boxes. As a result we introduced a facility for models containing related items to if(anIndex < recentModel.getSize()) share the list of recent selections. This is possible by assigning label.setFont(this.recentListFont);

Home J2EEa type (of class String) to each instance. J2ME Combo boxes that share the same type will adjust their set of recent selections if (anIndex >= 0 && anIndex == recentModel.getSize()- when any other combo box of that type changes selection. 1) Due to the interesting communication interaction between label.setBorder(this.underlineBorder); recent lists, we’ve chosen to delegate this functionality into a separate model – FavoritesRecentComboBoxModel. As you can see by the code fragment, the font change and To construct a FavoritesComboBoxModel, a programmer underline placement are contingent on the size of the recent must pass an existing ComboBoxModel into the constructor. model. Internally, the passed-in model will be used to define the “whole” list. In addition, FavoritesComboBoxModel will cre- FavoritesComboBoxFocusAdapter ate another model, FavoritesRecentComboBoxModel, to be FavoritesComboBoxFocusAdapter, a subclass of Focus- used as the recent list. Finally, both models will be added as Adapter, is added as a focus listener to receive focus events submodels to FavoritesComboBoxModel. from the combo box component. Focus events are fired inter- The “shared” recent list behavior is possible because all the nally when a component either gains or loses focus. FavoritesRecentComboBoxModels are notified when a Selections in FavoritesComboBox are not made until the change occurs in a similar combo box. This event notification component’s focus is lost. is implemented in the FavoritesComboBox component As we alluded to earlier, JComboBox and its associated through the use of the Observer design pattern (described in default model implementation internally set the current detail in the Design Pattern section). selection whenever items in the combo box change. One Along with handling shared recent lists, example of this behavior is that as a user navigates the drop- FavoritesRecentComboBoxModel has several other obliga- down list via the up/down keys, the model changes the cur- tions. One of the peculiarities of JComboBox is that it has a rent selections. Although this selection behavior is acceptable getSelectedIndex() method. However, the ComboBoxModel for JComboBox, it’s not adequate for FavoritesComboBox to can’t report the current selection by index, so JComboBox use the same selection paradigm. scans the model to determine the selected position when To handle the selection properly, we determined that an showing the pop-up. JComboBox’s implementation means item in the combo box is selectable only when the component each value must be unique as determined by equals(). loses focus. If we had chosen to follow JComboBox’s selection However, this paradigm won’t work for our component paradigm, then in the case of user navigation via the key- since the same item can exist in both submodels. To over- board, we would be populating the recent list whenever the come this restriction, all items in Favorites- user pressed the up/down keys – which makes no sense when RecentComboBoxModel are encapsulated in a wrapper. The you think about it. In our selection paradigm the recent list is two important methods in our Wrapper class (see Listing 2) updated only when the combo box component loses focus. are toString(), which delegates the call to the item wrapped, The following sections describe in detail how and extendedEquals(), which provides a less restrictive FavoritesComboBox handles the two types of focus events – comparison that’s needed during focus-gained and recent- focus gained as well as focus lost. FIGURE 1 A FavoriteComboBox model update.

48 AUGUST 2001

Java COM public void focusLost(FocusEvent e) The ensureRecentSelectedOnFocusGained() method uses The focusLost() method is defined in FocusListener and is our extended equality check to search the recent list for the invoked when a component loses the keyboard focus; in our match and, if found, selects it, ensuring recent list visibility. case, when the combo box component loses focus. Although the code contained in focusLost() is minute, it serves a pow- Design Patterns

erful purpose – updating the recent list. The following is Design patterns are reusable solutions to common prob- J2ME focusLost()’s implementation: lems that arise during software design. With the publication of Design Patterns in 1995, several of if (!(aFocusEvent.isTemporary())) { these solutions were cataloged and named. One of the many ben- JComboBox source = efits of design patterns is that they enable software developers to (JComboBox)aFocusEvent.getSource(); abstractly discuss designing and developing software in a com- Object selectedItem = source.getSelectedItem(); mon vernacular. During the design of the FavoritesComboBox if (selectedItem != null) component, we relied on several design patterns to guide the

structure of code and ensure flexibility. One of the more promi- J2SE favoritesModel.getRecentModel().updateRecentModel nent patterns we used, the Observer, played a critical role in (selectedItem); maintaining the recent list in FavoritesRecentComboBoxModel. } In Patterns in Java, Grand says the Observer design pattern “allows objects to dynamically register dependencies between The first line of code simply ensures that the focus has not objects, so that an object will notify those objects that are been lost temporarily. The isTemporary() method allows an dependent on it when its state changes.” application programmer to differentiate between a focus shift The roles of the Observer are: between components (returns false) and focus events, which • ObserverIF: This interface defines a method, which is J2EE are triggered via window deactivated, window activated, and invoked upon notification. In our component, more (returns true). Once we’ve determined the focus lost is FavoritesModelChangeListener plays this role. not temporary, we can invoke FavoritesComboBoxModel’s • Observer: This class is a concrete implementation of updateRecentModel() method, passing in the selected item ObserverIF. Our concrete implementation of from the combo box as a parameter. The update- FavoritesModelChangeListener is FavoritesRecent- RecentModel() method simply updates its recent list along ComboBoxModel. with firing an event that notifies all registered listeners. The • Observable: This class is responsible for maintaining a list

event-firing mechanism (see Design Pattern section) enables of registered Observers and delivering notifications. Home the recent list to be shared for all combo boxes of the same FavoritesRecentComboBoxModel performs this role. type. Our Observer implementation doesn’t include as many public void focusGained(FocusEvent e) classes as the “classic” Observer pattern. The reason we have The focusGained() method is defined in FocusListener and fewer classes is because, for simplicity, we’ve chosen to ignore is invoked when a component gains focus; once again, in our the ObservableIF role and have Favorites- case, when the combo box component gains focus. Initially RecentComboBoxModel play the role of both Observer and we decided to use focus events for handling combo box selec- Observable. To see how these classes interact along with the tion and focusLost() exclusively; as a result, focusGained() running of our test application, the FavoritesComboBox com- had an empty implementation. However, during initial devel- ponent is available on the JDJ Web site. opment we discovered a substantial problem and conse- When a selection is made in a FavoritesComboBox, it quently found a useful purpose for focusGained(). updates its recent model. In addition, it notifies all registered The problem we encountered can best be explained FavoritesModelChangeListeners of the event. When each lis- through example. Suppose a combo box exists that contains tener – in this case other FavoritesRecentComboBoxModels – a listing of all the universities in North America in alphabeti- receives notification, the selected item is inserted into its cal order. This combo box would be large and, for argument’s recent list, providing us with the desired functionality of sake, let’s assume that St. Peter’s College is the current selec- “shared” recent lists. In addition to employing the Observer tion. When the combo box gains focus and the drop-down list design pattern, our component uses the Factory Method (cre- is displayed, the list displays the current selected item (St. ating the renderer) and the Adapter (Favorites- Peter’s College). Unfortunately, in this example our recent ComboBoxFocusAdapter) design patterns. list, residing at the top of the drop-down list, won’t be dis- played since the visible portion of the list is centered on St. Future Enhancements Peter’s near the bottom. To solve this problem, we took FavoritesComboBox has been a useful widget in our advantage of focusGained() by simply obtaining the combo library of GUI components. However, as with many compo- box’s selected item, finding its match in the recent list, and nents in their infancy, there are always features left unimple- setting the selected item to the recent list’s corresponding mented. The following two features would prove useful to item, guaranteeing that the recent list will always be visible FavoritesComboBox: when the drop-down list is displayed. As with focusLost(), the focusGained() implementation is fairly straightforward and 1. Recent List Persistence is as follows: Currently, when an application containing FavoritesComboBoxes is launched, the recent list is empty; JComboBox source = (JComboBox)aFocusEvent.getSource(); however, it would be nice if the combo box was populated if (source != null) with its last known recent items. This could be accomplished return; in several ways. One way to persist the recent list, albeit a sim- this.favoritesModel.ensureRecentSelectedOnFocusGained( plistic approach, would be through the use of Java source.getSelectedItem()); Serialization.

AUGUST 2001 51

Java COM Home J2EEJ2SE J2ME 52 A UGUST 2001 renderers intoone. additional logicinorder tocompoundthetwoseparate RendererComponent() methodwouldneedtocontain Furthermore, FavoritesListCellRenderer’s getListCell- ListCellRenderer parameters. asoneofitsconstructor FavoritesListCellRenderer couldbealtered totakea render boththeiconsandseparator/italics. Asaresult, box aFavoritesComboBox, heorshewouldbeunableto and/or colors. If thedeveloperwantedtomakethiscombo box by providing iconsdisplayingtheschool’s mascot ence. The developermightwantto “spice up” thecombo containing alistoftheuniversitiesinBig Ten confer- For example, supposeadevelopercreated acombobox unable tosinceJComboBox onlyonerenderer. supports another renderer withFavoritesComboBox, butwillbe implemented. In manycases, adeveloperwillwanttouse list, aspecialrenderer, FavoritesListCellRenderer, was cue (theseparator) between therecent listandthe “whole” 2. Chicago-based trading firm. multitierJava applicationsata He’s designinganddeveloping currently “front office” for works Advanced SystemsConsulting. Java programmer, a Sun-certified David Lesle, control managementfront-endtobereleasedtheopen-sourcecommunity. onaJava-based source He’s working currently inChicago. consultingfirm Java-centric a for works Advanced SystemsConsulting, Java programmer, aSun-certified Justin Hill, A Eckstein, R.,Loy, M.,and Wood, D.3. (1998). Grand, M. (1998). 2. Gamma, E.,Helm, R.,Johnson, R.,and Vlissides, J. 1. Resources ful review andthoughtfulsuggestions. Acknowledgment terns. nent’s designanduseofpat- goodobject-oriented enhancements, canbeaccomplishedduetothecompo- we’re confidentthatthese, alongwithotherfuture the designofGUIcomponentscanbequitecomplex, FavoritesComboBox useinreal applications. Although tom renderers, were discovered during tion, newrequirements, includingpersistenceandcus- and maintainabilityofourcustomcomponent.In addi- known inorder designpatterns toincrease thereliability each newclasssimpleandflexible. ality wasassignedtoaseparate customclass–keeping aspect ofourenhancementtothebasicSwing function- the flexibilityofJComboBox. In ourcomponenteach through extendingSwing classesandtakingadvantage of es demonstrate how ausefulcomponentcanbecreated Conclusion UTHOR O’Reilly &Associates. Oriented Software (1995). To changethefontofrecent listandcreate avisual Compound Renderer Support We wouldliketothanktheASCltdteamfortheircare- During designanddevelopmentwe leveraged well- FavoritesComboBox class- anditsassociatedsupport B IOS einPten:Elements ofReusable Object- Patterns: Design [email protected] [email protected] , Addison-Wesley. Patterns inJava . Vol.1. Wiley. Java Swing . } { protected staticclassWrapper //FavoritesRecentComboBoxModel } provide theirownrenderer.@returnthedefaultlistcellrenderer the combobox.Subclassesshouldoverridethismethodinorderto A factorymethodthatcreatesthedefaultrenderertobeusedfor the datamodel method.@returnthecurrentlyselectedlistobjectfrom invoke theFavoritesComboBoxModel’sgetCurrentSelection() Returns thecurrentlyselecteditem.Thismethodisoverriddento recent list can hold.@returnthemaximumnumberofselectionsallowedin Returns themaximumnumberofitemsmostrecentfavoriteslist list can hold.@paramaMaximumNumberthemaximumnumberofitemsin Sets themaximumnumberofitemsmostrecentfavoriteslist ated model.@paramaModelthecombobox’smodel Constructs theFavoritesComboBoxandsetsitsassoci- { public classFavoritesComboBoxextendsJComboBox *************************************************/ Microsoft Word. combobox widgetmimicsthebehaviorof“FontList”in 2) alistoffavorite(ormorerecentlyselected)choices.This displays twoseparatelists:1)theentirelistofselectionsand FavoritesComboBox isacomboboxwidgetthatvisually /************************************************* import javax.swing.event.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; package com.chicagojava.awp.client.components.combobox; Listing 1 Listing 2 //a staticinnerclassfoundin } { public StringtoString() } { public booleanextendedEquals(Objecto) } { public Wrapper(ObjectaWrappee) private Objectwrappee; } { protected ListCellRenderer ***********************************************/ /*********************************************** } { public ObjectgetSelectedItem() ***********************************************/ /*********************************************** } { public intgetMaximumNumberOfFavorites() ***********************************************/ /*********************************************** } { public voidsetMaximumNumberOfFavorites(int ***********************************************/ /*********************************************** } { public FavoritesComboBox(FavoritesComboBoxModel ***********************************************/ /*********************************************** implements Serializable return wrappee.toString(); return equals(o) this.wrappee =aWrappee; return newFavoritesListCellRenderer(); createFavoritesComboBoxRenderer() return ((FavoritesComboBoxModel) return ((FavoritesComboBoxModel) ((FavoritesComboBoxModel) aMaximumNumber) setModel(aModel); addFocusListener( setRenderer(createFavoritesComboBoxRenderer()); super(); aModel) wrappee.equals( ((Wrapper)o).wrappee)); || (oinstanceofWrapper&& || wrappee.equals(o) getModel()).getCurrentSelection(); getModel()).getMaximumNumberOfFavorites(); aMaximumNumber); getModel()).setMaximumNumberOfFavorites( new FavoritesComboBoxFocusAdapter(aModel)); J ava COM James Gosling on...

J2SE Real-world Home J2EE J2ME

: How are you finding JavaOne so far? On a late : There’s an awful lot of energy here Javaand just seeing what people are up to is a lot of sunny Tuesday fun. As we go from year to year, things are mov- afternoon, James ing at such a quick pace. Seeing how much Gosling, the creator and stuff is incredibly real these days is quite a rush. father of Java, takes time : Are you still involved with Java? out to chat with : It’s my job, every day.

Williamson and Blair : We can’t imagine you sitting there in front of a compiler; do you? Wyman. : Actually for the last couple of JDJ’ months I’ve been tormenting the guy who s Alan owns the compiler source and I’ve been hacking on it relatively heavily. But I think someday he will forgive me.

: What’s the big surprise this year when you walk around all the booths and exhibitors? : The thing that I get the biggest kick out of is all the stuff that is now in shrink-wrap

54 AUGUST 2001 O Java COM There’s now such a high “ threshold for a major announcement ”

AUGUST 2001 55

Java COM boxes. When we did that goofy shopping videotape, none of those devices were fakes; none of them were balsa blocks. My first paying job was working for a They were all prototypes. They were all group of physicists writing satellite data shipping in volume shrink-wrap gizmos; acquisition software for the Isis 2 satellite you have subclassing and inheritance of it’s just terribly real. A year or two ago Ð that was a real rush. Seeing people implementation have issues. You can get when we were talking about these doing this kind of stuff is pretty amazing. around some of that with different styles. devices, it was of academic interest to Actually Josh Watt came out with this most people there. To the people who : Java is a wonderful lan- book called Effective Programming. It were actually building it, it was very inter- guage; it’s your child, I think people contains information on how to think esting. would agree. I’m just wondering, are about object-oriented programming and Today it’s a completely different game there still any warts on your child that how to avoid some of the pitfalls we’ve because anybody here at the forum can you’d like to see removed? Are there discussed over the years. For example, really enjoy the feedback. It’s nice to have any problems in Java that you think one of the solutions that often comes up J2SE the U.S. headed out of being a third-world need fixing or changing? is: throw away object-oriented comput- country in terms of its phone system Ð you : The answer is yes and no. In ing completely and go for something can go to a phone store in San Francisco some sense people are being very suc- along the lines of delegation models that some people have used – it’s similar to class inheritance but somewhat differ- ent. It solves some problems, but cre- If you talk to real-time people, they hardly care ates its own. There are things to be uneasy about but no clear answers. You about speed; what they care about is determinism, could do all kinds of interesting experi- “ mentation. namely, when it’s time to adjust the flutter on the : You spoke of being a science geek. Do you see Java playing in that space? Do you see it compete against F16 wingtab, I want to do it now please FORTRAN, or what was your satellite

Home J2EE J2ME acquisition software written in? : PDP8 assembly code.

: PDP assembler, wow! : That dates me, right? A PDP8 has less compute power than your aver- ” age smartcard. : Is there much PDP8 code in Java? : There’s some learning from and buy a Nextel phone. You can go to the cessful with it. In another sense, if I had a writing PDP8 code. I had been program- Motorola Web site and get the developer clean slate and was doing things different- ming for a number of years before I found kit. There’s a little handshake you have to ly, there are many things that would come a machine beefy enough to run FOR- do, but it’s relatively minor and you too out differently. I actually have a small Web TRAN. By then I was writing CDC6000, can hack your phone set, you too can site that’s this long laundry list of things 7000 assembly code. The cyber series build an app that does anything from that would be entertaining. It goes from, and its predecessors were pretty hot. It video games to enterprise data stuff that yeah that might be worth doing to that’s was almost like half an MIP. goes end-to-end. truly goofy. A lot of these things are pretty hard design trade-offs. A lot of engineering : MIP is meaningless informa- : With respect to the whole is not a black-and-white choice Ð this is tion for product salespeople? spectrum of Java, it’s now covering a the right thing to do and that’s the wrong : Yeah, exactly. ;-) tremendous amount of space there. thing. It’s similar to Whackamole, a game Which particular area is now ringing you play on the Santa Cruz boardwalk : In the science arena, do you your bell? and various other places. There’s a big see the megahertz catching up to make : I tend to be a science geek, board with a little mechanical mole that Java effective in a real-time program- and for the longest time I was Mr. sticks his head out of the ground and you ming environment? Everything Except Enterprise. All kinds of have a big baseball bat that you whack it : It’s been effective in real time things ring my bell in that area. A while down with, but he pops out somewhere for quite a while. Lots of people have been ago I visited the Keck Observatory at the else. real-time programming in Java for years. top of Mauna Kea and saw how Java has A lot of program design (and any other The issue has never been megahertz and really taken over. The giant telescope kind of engineering) is like that. For speed. If you talk to real-time people, they crowd and the tools they’re building are instance, many things about the basic hardly care about speed; what they care just incredible. notion of a class-based system in which about is determinism, namely, when it’s

56 AUGUST 2001

Java COM

N time to adjust the flutter on the F16 wingtab, I want to do it now please. newsgroups about open sourcing : So no GC cycle then? ;-) Java? : No, no waiting for the garbage : If I actually knew what people heard rumors that Tiger 1.5 is now collector to be done with its business. No meant by open sourcing, I might be able starting to have some serious develop- waiting for the paging system. No waiting to answer the question. In a strong sense ment. for the kernel to context-switch out of the it’s been open sourcing from the begin- : I’ve been working on the Tiger sendmail daemon. When you’ve got to ning. We’ve always shipped the source; complement for several months now. pull the cadmium rods out of the reactor anybody who wants it can easily get hold core, you have to do it now. of it. The thing that blocks the zealots call- : Anything you can tell us ing it open sourcing is that there’s actual- about that? : One thing that we’ve been ly something that we care about: if some- : Nothing useful. On the piece speaking to all the vendors about, and body has a Java program, and somebody I’ve been working on are applications, J2SE one thing they’ve said is that it’s nice else has something that they call a Java other than the compiler, that would like to to see that there are no major new platform, the program ought to run. So we use the guts of the compiler. I got into this announcements with respect to Java. get uptight about that particular point. On because I was building a tool that could It’s as if Java is maturing to a state average, developers actually care about play with the animated graph. I had built where we’re now actually using it, and that, they seem to think that that’s a good myself yet another Java compiler clone we don’t need to help it any longer. In thing. Yet the open-source community pil- because I wanted to get at the syntax tree, that respect it’s cool to see Java now lories us. Our license is identical to any of but that seemed kind of goofy because reaching in. Where do you think Java is the other open-source licenses, but we the compiler we had is nicely structured. going in the next 12 months? have these catches that are mostly about All it needed was for its innards to be : That comment about no major interoperability. exposed as an API. What I’ve been work- announcement feels kind of weird ing on for the last couple of months is because when I listen to some of the : Another hot question we cleaning up the guts of the compiler, so it things that are going on, maybe one of get asked is, back in December 1990, it could be an accessible API. them, four or five years ago, would have was released as Java2, but it was actu- counted as a major announcement. ally 1.2. Now it’s going to 1.3. Where : You speak of the JavaC com-

Home J2EEThere’s now such a high threshold for a J2ME does this Java2 come into it? piler and expose it at an API level, or is major announcement.

: Seriously impressive type of situation going on now. In a strong sense, it’s been open sourcing : Yeah, it’s like, “Oh gee, Mr. Nokia, only 100-million cell phones, that’s from the beginning. We’ve always shipped boring.” We’ve gotten jaded these days. “ the source; anybody who wants it can : Isn’t that a sign of the lan- guage maturing though? easily get hold of it : Well, it’s sort of maturing and engaging and it’s a community thing. We’ve been trying to get to the point where Sun is not the driver of Java, and I think we’ve been pretty successful at it. The really cool stuff in Java is not hap- pening at Sun. We haven’t been slowing ” down in what we’re doing; the rest of the world has been ramping up. Would class, as a really huge announcement, be like the uptake in MID-P? What people are doing with develop- : Marketing guys, what can I say! it too soon to talk about it? Would you ment tools, the Java faces thing, there’s a 1.2, 1.3, 1.31, that’s the numbering be able to give me the parse tree and way to do a UI toolkit that’s supported by scheme in the source-code system; that’s show me the nodes and all the good- IDE tools, yet projects its UI across the the numbering scheme that the engineers ies? Web. That sounds to me like a pretty major actually believe. : Yeah, that’s what it does now. announcement, but it’s not us doing it. It’s There’s this question of what to do with it. not guys with Sun badges doing most of : Will we ever see it bump We got started on it because that compil- the design and the work. It’s people from into 2.0? er is officially a Sun product and we need- Borland, WebGain, etc., who are doing it. : Beats the crap out of me. ed it. The question is whether to just sail on doing that or start a JCP group to fig- : How do you feel about the : I heard 1.4 is around the ure out what to do. We’ve got a first cut at overall issue that’s often debated in corner at the end of the year. Then I an API, but we’ll have to talk to people to

58 AUGUST 2001

Java COM

N find out what kind of interest there is. For me, I’m doing it because I needed it, whether it turns into part of the product is equal, and the things can mutate, then another question. you can do copies arbitrarily, which is the number one thing you can do to allocate and I get exactly the same kind of rock- : Do you see any changes to objects into registers where they aren’t et optimization. the specification really objects, just things that live there underneath the Java language? To momentarily. The things that you can do : Is the automatic optimization extend any of the architectural limits are pretty terrific. in JavaC and other compilers? Do you that exist in the byte codes? see the dynamic versus static issue : There are actually remarkably : Like a new pseudo-primitive. anymore? There used to be a real issue few limits. We have this long laundry list of : Yeah, although there have doing static analysis of a program things that would be cool to do, most at been about a dozen sketches like that because you always had to worry the language-level. It’s interesting to see done, it’s actually possible to properly do it about something slipping into the J2SE how few of them have any impact on the so it actually doesn’t affect the Java VM classpath at runtime. But static analy- virtual machine. The number one and two specification at all. I mean that in the sis is precluded by that dynamic language requests have been generics sense of correctness, namely a correct nature, wouldn’t you say? and assertions and neither of those VM would just ignore it, but then these : You can do static compilers require BM changes. immutable objects would be allocated like and get the dynamics right, the problem There’s a number of them, one of regular. However, if you really wanted to is that it’s difficult and the people who which I’m particularly hot on called take advantage of this, there’s a huge built static compilers were on the lazy immutable objects: a way to declare an amount of work in the optimizer. Then you side. The average static compiler was object immutable. It means to declare could start doing things like 3D graphics at built by retreading someone’s C compil- that a class is final with all final fields, but unbelievable performance because with er’s back end and all kinds of funny with a twist Ð the quality operator is things like point beta structures, you could things creep in. Dynamic compilers have somewhat different. The motivation is do some very amusing optimizations with gotten a lot better and they’re pretty con- that a sufficiently good optimizing JIT can them. sistently beating the static compilers; optimize away the existence of these since they know what your program is objects. So if you did something, such as : As a big Mandelbrot set fan, I doing and what chip it’s running on, they

Home J2EEcomplex numbers in terms of immutable J2ME would love to see a complex as a pseu- can do a lot more interesting things. They objects, you could end up with code that do-primitive. know what’s loaded in, and it’s been did complex numbers as efficiently as : You can certainly do complex interesting watching the evolution of the FORTRAN. numbers now, the issue being that you programming style as it constructs large systems because more and more of what people do to construct systems is they don’t build a big monolith; they build a There’s a way to do a UI toolkit that’s supported spine that’s a central place where things can plug in. by IDE tools, yet projects its UI across the Web. A Web server is a prime example, the way the Tomcat works with plug-in JSP “ pages and servlet pages. EE this and That sounds to me like a pretty major who knows what else. People roll in their announcement, but it’s not us doing it own APIs all over the place. As a gener- al technique for building flexible systems that can dynamically upgrade and all that kind of stuff, it’s used all over the place. It’s hard to find a Java program that doesn’t use dynamic loading. Many people aren’t even aware when it hap- pens because with many of the underly- ” ing systems doing it, things like localiza- tion, they’ll dynamically link in stuff, depending on where you happen to be. You don’t have something where all the Right now the big blockage in getting can’t get to FORTRAN optimization kanji you type in modules are now C++ or Java performance up to FOR- level with it. One answer to it is to make loaded for almost everybody; for the TRAN in a number of these numerical complex be a primitive the way FOR- folks in Japan, it’s right there, so you get issues is that there’s a limit as to how far TRAN does, but to do something that what you need. you can optimize the primitive objects. In has the same optimization opportuni- particular, the major block is that they still ties, that’s general enough, so you can : Well, James, thank you have an identity as an object. If you can define complex for use in your for taking the time out to talk with us, get to where the notion of identity disap- Mandelbrot sets. I can define 3D points and we look forward to seeing you pears so EQ goes away, you have only for doing constructive solid geometry again in September at JDJEdge.

60 AUGUST 2001

Java COM

N STRATEGIESTRARATEG STRATEGIESTRARATEGGIE STRATEGIESEGIE J2SE STRATEGIESS RATEGRA EGI F RA OR STOATE IN RELATIOR ORRINTEG APPPLY AT G JAVJ THESE TIO A OB ES WRIT FUUNDAMENDAMENTALNALNA DATAB ITTETEN BY ENTA JECTE BY S ATABAS S SCOTTSCOSC F ORWRYEAR YE Home J2EE J2ME AS T W. S TO CO E AMBLERAM ME L ike it or not, the majority of Java devel- opers use a relational database (RDB), such as Oracle, Sybase, or MySQL, to persist their objects. That’s reality for most people, so let’s deal with it. What’s the big deal about storing Java objects in relational databases? Something called the object-relational impedance mismatch. The object paradigm is based on proven software STRATEGY engineering principles for building applications out of objects Use Persistent Object IDs 1 that have both data and behavior, whereas the relational par- adigm is based on proven mathematical principles for effi- ciently storing data. The first thing you need to do is get a handle on the key The impedance mismatch comes into play when you look at strategy for your database, a likely source of contention the preferred approach to access: with the object paradigm you between Java developers and database administrators traverse Java objects via their relationships whereas with the because objects force you to rethink some of the precepts of relational paradigm you duplicate data to join the rows in tables. data modeling’s approach to assigning keys. This fundamental difference results in a nonideal combination To store data in an RDB, you need to assign unique identi- of Java and RDBs, although when have you ever used two differ- fiers to the data rows representing your object to be able to ent technologies together without a few hitches? One of the identify them. In relational terminology, a unique identifier is secrets of success for mapping Java objects to relational data- called a key; in object terminology, it is called a persistent object bases is to understand both paradigms – and their differences – identifier (POID) or simply an object identifier (OID). POIDs are and then make intelligent tradeoffs based on that knowledge. often implemented as full-fledged objects in your Java applica- In this article, I present strategies for storing Java objects in tions, for example, the EJB specification enforces this concept RDBs. These strategies cover the following topics: in its primary key class for entity beans, and as large integers or • Use persistent object IDs strings in your database tables. • Map an attribute to zero or more columns A critical issue that needs to be pointed out is that POIDs • Map a class to zero or more tables should have absolutely no business meaning whatsoever, This article is modified • Map inheritance structures which goes against common data modeling practices. Any from Chapters 7 and 8 • Use one data entity for an entire class hierarchy table column with a business meaning can potentially change. of Ambler’s latest book, • Use one data entity per concrete class And what’s the one thing we learned as an industry over the The Object Primer 2/e, • Use one data entity per class years in the relational world? www.ambysoft.com/th • Implement associations in relational databases It’s a fatal mistake to give your keys meaning. No doubt eObjectPrimer.html. • Encapsulate persistence code about it.

62 AUGUST 2001

Java COM If your users decide to change the business meaning (per- TextBook as an attribute, which maps to several columns in haps they want to add some digits or make a number the database. alphanumeric), you need to make changes to your database in The important thing is that this is a recursive definition. At every single spot where you use that information. Anything some point, the attribute will be mapped to zero or more that is used as a primary key in one table is likely used in other columns. It is also possible that several attributes could map tables as foreign keys. What should be a simple change to one single column in a table. For example, a class repre- (adding a digit to your customer number), can be a huge senting an American ZIP code may have three numeric attrib- maintenance nightmare. Yuck. In the relational database utes, one representing each of the sections in a full ZIP code, world, keys without business meaning are called surrogate whereas the ZIP code may be stored as a single column in an keys. address table. POIDs allow you to simplify your key strategy within a rela- tional database. Although POIDs do not completely solve the navigation/traversal issue between objects, they do make it easier. You still need to perform table joins (assuming you don’t intend to traverse, to read in an aggregate of objects such STRATEGY as an invoice and all of its line items), but at least it’s doable. Map a Class to Zero or More Tables

J2SE 3 Another advantage is that the use of POIDs enables you to easily automate the maintenance of relationships between objects. When all of your tables are keyed on the same type of Classes map to tables, although often not directly. Except column(s), in this case POIDs, it becomes straightforward to for simple databases, you will never have a one-to-one map- write generic code to take advantage of this fact. ping of classes to tables. In the following sections, I discuss A POID should be unique within a class hierarchy, and ide- three strategies for implementing inheritance structures to a ally unique among all objects generated by your organization relational database and an example where dissimilar classes (something often called global uniqueness). For example, will map to one table. the POID for a customer object be unique only for instances of customer, to people in general, or to all objects? Given the POID value 74656, will it be assigned to a student object, a professor object, and a seminar object? Will it be assigned to a student but not a professor (because the Student class and the STRATEGY Professor class are in the same class hierarchy)? Or will it only Map Inheritance Structures 4 be assigned to a student object and that’s it?

Home J2EEThe real issue is one of polymorphism: J2ME it is probable that a student object may one day become a professor object, but The concept of inheritance throws in several interesting likely not a seminar object. To avoid this issue of reassigning twists when saving Java objects into an RDB. There are three POIDs when an object changes type, you at least want unique- fundamental solutions for mapping inheritance into a rela- ness at the class hierarchy level, although uniqueness across tional database, and to understand them I discuss the trade- all classes completely avoids this issue. This can be another point of contention between Java developers and data profes- sionals – polymorphism is an important concept in the object world but not the data world. There are several ways that you can generate values for POIDS: 1. Use the MAX() function (and add 1) on the POID column. 2. Maintain a separate table for storing the next value of a key. 3. Use Universally Unique Identifiers (UUIDs) from the Open Software Foundation. 4. Use Globally Unique Identifiers (GUIDs) from Microsoft. FIGURE 1 Simple class hierarchy FIGURE 2 Persistence model 5. Use proprietary database essential generation functions. 6. Use the HIGH/LOW approach. See the article “Enterprise offs of mapping the class diagram presented in Figure 1. To Ready Object IDs” (www.sdmagazine.com/articles/1999/ keep the issues simple I have not modeled all of the attributes 9912/9912p/9912p.htm) of the classes, nor have I modeled their full signatures, nor any of the methods of the classes. Use One Data Entity for 4a STRATEGY an Entire Class Hierarchy Map an Attribute to Zero or More Columns 2 With this approach you map an entire class hierarchy into one data entity, where all the attributes of all the classes in the hierarchy are stored. Figure 2 depicts the persistence model An attribute of a class will map to zero or more columns in for the class hierarchy of Figure 1 when this approach is taken. a relational database. It’s important to remember that not all Notice how a personPOID column was introduced for the pri- attributes are persistent. For example, an Invoice Java object mary key of the table – I will use POIDs in all of the solutions may have a grandTotal attribute that is used by its instances to be consistent and to take the best approach that I know of for calculation purposes but is not saved to the database. To for assigning keys to data entities. complicate matters, some attributes of an object are objects in The advantages of this approach are that it is simple, that their own right, which in turn need to be mapped to your polymorphism is supported when a person changes roles, and database. For example, a course object has an instance of that ad-hoc reporting is made easy because all of the data you

64 AUGUST 2001

Java COM Home J2EEJ2SE J2ME 66 FIGURE 3 A UGUST Mapping eachconcreteclasstoasingledataentity 2001 role that an objectmighthave. It’s alsoeasytomodify super- because you have records tablesforeach intheappropriate concepts.well toobject-oriented It polymorphism supports andforeign keysfor those tables.the primary assigned twotaggedvalues, both oneindicatingthatitforms personPOID columninboth Professor andStudent is three dataentities. Aninteresting feature ofFigure 4isthatthe Notice how keyforall personPOID isusedastheprimary for thedatamodelFigure 1whenthisapproach istaken. specific tothatclass. Figure 4depicts thepersistencemodel ofwhichareattributes thatare thePOIDandattributes name ofsomeonewhoisbothastudentandprofessor? tain dataintegrity. For example, where wouldyou store the lot ofwork. tableandassignitanewPOID–onceagain the appropriate eral disadvantages, however. about asingleclassisstored inonlyonetable. There are sev- easy todoad-hocreporting becauseallofthedatayou need key,primary studentPOIDandprofessorPOID, respectively. depicted initalics).Eachofthedataentitieswasassigneda because it’s abstract (indicatedby thefactthatitsnameis Professor classesbecausetheyare concrete, butnotPerson data entitiescorresponding toeachoftheStudent andthe hierarchy ofFigure 1whenthisapproach istaken. There are resents. Figure 3depictsthepersistencemodelforclass oftheclassthatitrep- attributes andtheinherited attributes person isbothastudentandanprofessor). quickly breaks down ifheorshehasmultipleroles (i.e., the person. This works well whensomeonehasasinglerole but the row represents astudent,professor, oranothertypeof your code(by recompiling it)tothenewdataschema. base and,inthecaseofsomedatabases, forces you torebind attribute. It alsopotentiallywastesalotofspaceinthedata- and notjustthesubclassesofwhateverclassgotnew attribute, itcouldaffectalltheclasses withinthehierarchy the classhierarchy. If amistakeismadewhenaddingsingle to beaddedthetable. This increases thecouplingwithin added anywhere intheclasshierarchy needs anewattribute need aboutapersonisfoundinonetable. per Class Use OneDataEntity per ConcreteClass Use OneDataEntity The mainadvantage ofthisapproach isthatitconforms With thisapproach, you create onetableperclass, the Third, it’s multipleroles andstillmain- difficulttosupport First, whenyou modifyaclass, you needtomodifyitstable The mainadvantage ofthisapproach isthatitstillfairly With thisapproach, eachdataentityincludesboththe I alsoneededtoaddtheobjectType columntoindicateif is The disadvantages are timeanewattribute thatevery need tocopy thedatainto become aprofessor, you graduating studentsto haps you hire oneofour object changesitsrole, per- both tables–alotofwork. you wouldneed to addit weight tothePerson class, you were toaddheightand subclasses. For example, if and thetableofanyits Second, wheneveran 4b 4c Employee dataentity. Iwasforced todoitthiswaybecause positionPOID, thekeyofPosition dataentity, inthe multiplicities are one. one associationisinwhichthemaximumsofeachits between thePosition andEmployee dataentities. Aone-to- ships between them.First, there isaone-to-oneassociation course), andtheforeign keysusedtoimplementtherelation- have toincludethekeyofonetableinothertable. ment one-to-oneandone-to-manyrelationships you merely to relate arow inonetablewitharow inanother. To imple- cidental –withthekeyofanothertable. Foreign keysallow you of–oriscoin- ute(s) thatappearsinonetablemaybepart through theuseofforeign keys. Aforeign keyisadataattrib- you addviewsto simulatethedesired tables. Third, ad-hocreporting onyour databaseisdifficult,unless within aclasshierarchy ondifferent volumes. physicaldrive organize your databaseintelligentlyby puttingeachtable access multipletables. This problem canbealleviatedifyou read datausingthistechniquebecauseyou needto andwrite tables tomaintainrelationships). Second, ittakeslongerto there are manytablesinthedatabase, class(plus oneforevery fy/add onetable. classes andaddnewsubclassesasyou merely needtomodi- Implement AssociationsinRelationalDatabases FIGURE 5 FIGURE 4 STRATEGY To implementthisrelationship Iusedtheattribute In Figure 5you seefourtables, theirkeys(POIDsof Relationships inrelational databasesare maintained There are several disadvantages tothisapproach. First, A persistencemodelfora simple humanresourcesdatabase Mapping eachclasstoitsown dataentity J ava 5 COM Home J2EEJ2SE J2ME 68 A UGUST oln,WebGain Inc. Toplink, Osage ObjectSpark LPC JdbStore, ThoughtInc. CocoBase, Castor TABLE 1 2001 EmployeeData class) or asacollectionofstored procedures business class (e.g., Employee hasacorresponding Java classeswithembeddedSQL, onedataclassforeach the databaseare made. a recompilation (ofyour dataclasses)whensimplechangesto tems oflessthan40to50business classes, butitstill results in again, thisapproach issuitableforprototypes andsmallsys- still havethedataclassestodevelop andmaintain.Once cantly lesscodeinthebusinessobjects, althoughyou would similar tothatinListing1).Asyou cansee, there issignifi- the Order class(thecodefortheOrderData classwouldbe classes. Listing2shows how thiscodewouldbeinvokedfrom your businessclassesare encapsulatedinoneormore data finding multipleinstancesbasedondefinedcriteria. operations letalone theadditionalcoderequired tosupport ments forsimpleCRUD (create, retrieve, update, anddelete) significantamountsofSQLcode,to write atleastfourstate- results inarework ofyour source code. Second, itforces you (such asrenaming toanotherdatabase) acolumnorporting of your relational database, implyingthatasimplechange First, itdirectly couplesyour businessclasseswiththeschema tions and/orprototypes. There are twomaindisadvantages. codequicklyandisaviableapproach forsmallapplica- write an exercise foryou, pleasedon’t e-mailme.) OrderItem, codethatfrankly isn’t bulletproof. (I’ll leavethatas class; similarcodewouldbeneededtopersistaninstanceof classes. Listing1shows anexampleofhow topersisttheOrder palatable inmyopinion,istoembedSQLstatementsyour code withinyour software. The mostcommon,andleast one-to-many associations. associative tablethatimplementsthemany-to-many astwo many associations. Instead theyneedtoberesolved withan relational databasescannotnativelyimplementmany-to- ciation between thePosition andBenefit tables. Unlike Java, associative table, onethatimplementsamany-to-many asso- on themanysideofrelationship. being thatIhadtoputtheforeign keyin Task becauseitwas and Task ofapproach, theonlydifference usingthesamesort referred toasaone-to-manyassociation)between Employee a foreign keycalledemployeePOID inPosition aswell. been abidirectional association,Iwouldhaveneededtoadd their positionrows butnottheotherwayaround. Had this the associationisunidirectional –employee rows know about Java persistence frameworks STRATEGY Encapsulate PersistenceCode Your dataclassesare typicallyimplemented asnormal A slightlybetterapproach iswhentheSQLstatementsfor The advantage ofthisapproach isthatitallows you to There are several waysyou implement thepersistence The PositionBenefit tableisinteresting becauseitisan Second, Iimplementedthemany-to-one association(also www http://osa www www www http://castor .webgain.com/products/toplink/ .objectspark.com .ila .thoughtinc.com p.com/lpc/html/jdbstore.html ge.sourceforge.net .exolab.org 6 to buildbusinessapplicationsfrom endtoend. This isdone ing mynewbook ects. If you are interested inthistopic,Ihighlysuggestread- guage you are working with. you’ll beabletoapplyforyears tocomeregardless ofthelan- proven inpractice, in facttheyare fundamentalstrategies that this complextopic. The strategies Ipresented havebeen some basictechniquesfordoingso, scratching of thesurface ofJavathe vast majority developers. In I presented thisarticle andRelational DatabasesJava Are Here to Stay provide. as well asatthesignificanttimeandcostsavingsthatthey you’ll athow bepleasantlysurprised well theyactuallywork – themout. open mindandtotry When you doso, Isuspect suggestion istoapproach persistenceframeworks withan database access–theyknow thatyou don’t. alotoftricks My build persistenceframeworks specialize inhigh-performance code.written However, thereality isthatthepeoplewho head toyour Java codewhencompared toexceptionally well- the case. databaseaccesscode,high-performance butthisisseldom it. atwriting iftheyhappentobeexperts This maybetrue intheircodebyperformance hardcoding SQLstatementsinto persistence frameworks, assumingtheycanachievethebest thatmanyJavaperformance developershavewithrespect to stored inanRDB. they don’t evenneedtoknow thattheirobjectsare being schemas; your application programmers don’t and,infact, maintaining themetadataneedstounderstandtwo code. merely needtoupdateyour metadata insteadofyour source Java objects. When your objectordataschemachangesyou metadata togenerate thesource codeneededtopersistyour inmetadata,andthenusingthat your mappinginformation code.not affectyour object-oriented They dothisby storing manner thatsimplechangestotherelational schemaoftendo 1 listsseveral forJava) thatpersistobjectsinRDBssucha place –thedataclasses. source codethathandlesthehard-coded interactions inone this approach isthatyou haveatleastencapsulatedthe deleting, andsoon). The bestthingthatcanbesaidabout in your database(oneor more forretrieving, oneormore for SQL: database. theschemaofarelational ormanipulate delete data SQL statement: world. equivalent ofkeysintherelational POIDsaretheobject-oriented typicallyalargeinteger number. objects, Persistent objectidentifier(POID): Surrogate key: Composite key: form auniqueidentifierforeachrecordinthetable. Key Alsocalledarecordortuple. table. stored inarelational Row: table. ty storedinarelational Column: RELATIONAL TERMINOLOGY I’ve personallyusedthemonC++,Smalltalk, andJava proj- Storing your objectsinrelational databasesisareality for Yes, intheory, persistenceframeworks addabitofover- The maindisadvantage is themisconceptionsregarding The advantage ofthisapproach isthatonlytheperson A third approach istouseapersistence framework (Table : One or more columns in a relational data table that whencombined tablethat data Oneormorecolumnsina relational : Structured Query Language. Structured Query The relational database equivalent of an instance of a data entity equivalentofaninstanceadata database The relational The relational database equivalent of an attribute of a data enti- ofadata equivalentofanattribute database The relational A keywithoutabusinessmeaning. A keyconsistingoftwoormorecolumns. ic fSLcd sdt eree pae net or insert, update, A pieceofSQLcodeusedtoretrieve, The Object Primer 2/e, J ava A uniqueidentifierassignedto in whichIshow how COM Home J2EEJ2SE J2ME 70 OrderID =?"); connection.prepareStatement(OrderItem.getInsertSQL()); "INSERT INTOOrderVALUES(?,?,?,?,?,?,?)"); connection.prepareStatement(OrderItem.getUpdateSQL()); "Update INTOOrderVALUES(?,?,?,?,?,?,?)"); A Listing 1:EmbeddedSQLCodeintheOrderClass UGUST // Addtheorderinformationfromthisobject { public voidretrieve(Connectionconnection) /** } private voidsave(Connectionconnection)throwsSQLException{ /** */ * theorderwithgivenid. * Refreshesthisobjectwiththedatafor */ * SaveanorderanditsaggregateItems 2001 setOrderDate(rs.getDate(3)); setCustomerNumber(rs.getInt(2)); rs.next(); ResultSet rs=statement.executeUpdate(); statement.setInt(getOrderID()); connection.prepareStatement("SELECT *FROMOrderWHERE PreparedStatement statement= // RetrievetherecordfromOrdertable int shipToID,billToID; OrderContact ship,bill; throws SQLException orderItemStatement.close(); } for (inti=1;<=items.size();i++){ items =getOrderItems(); // Savetheorderitems orderStatement.close(); orderStatement.executeUpdate(); // Savetheorderandcontactinformation orderStatement.setDouble(7, getSubtotal().getNumber()); orderStatement.setDouble(6, getLocalTax().getNumber()); orderStatement.setDouble(5, getStateTax().getNumber()); orderStatement.setDouble(4, getFederalTax().getNumber()); orderStatement.setDate(3, getOrderDate()); orderStatement.setInt(2, getCustomerNumber()); orderStatement.setInt(1, getOrderID()); } } else{ if (isPersistent()){ // Buildstatementstoeitherinsertorupdate Vector items; PreparedStatement orderItemStatement=null; PreparedStatement orderStatement=null; .Abe,SW (2001). 3. Ambler, S.W. Ambler, S.W. “Enterprise Ready2. Object IDs.” (1999). 1. Ambler, S.W. Recommended Reading the backend. into implementationusingJava andrelational databaseson ments andthenmoving through analysistodesignandfinally from thepointofviewadeveloper, withrequire- starting item.save(orderItemStatement, getOrderID(),i); OrderItem item=(OrderItem)items.elementAt(i); orderItemStatement = orderStatement =connection.prepareStatement( orderItemStatement = orderStatement =connection.prepareStatement( Application Developer’s Guide toObject Orientation. www University Press. Systems withObject Technology. Step-by-Step com/theObjectP York: Cambridge University Press. .htm A pplications .sdmagazine .html uligOjc plctosTa ok YourBuilding Object Applications That Work: (1998). r imer .com/ar www .html h betPie n dto:The The Object Primer 2ndEdition: Handbook Robust forDeveloping .amb ticles/1999/9912/9912p/9912p . ysoft.com/buildingObject- SIGS Books/Cambridge www .amb ysoft. New Listing 2:DelegatingPersistenceofOrdertoOrderData .UUIDClassJavadoc. 5. 4. SzyperskiC. oukrt,Kbd aae and Tai Kobudokarate, Chi. Goju karate, Scottstudies hissparetime, In bothfromJohn &Sons. Wiley EJB2/e, Mastering forthcoming Heisalsoauthoroftheforthcoming Agile Modelingandco-authorofthe Press. University of bothfromCambridge 2/eandco-authorof The ObjectPrimer The ElementsofJava Style, Heistheauthor leader ofthe Agile Modeling(AM)methodology(www.agilemodeling.com). Scott (www.ronin-intl.com) Ambler isthepresidentofRoninInternational andthought W. A 6. Vermeulen, A.,Ambler, S.W., Bumgardner, G.,Metz, E., BOUTTHE Oriented Programming. www Java Style. Misfeldt, T., Shur, J.,& Thompson, P. (2000). gr ?"); ammer/api/or A ps =connection.prepareStatement("DELETEOrderWHEREOrderID .amb UTHOR /** } /** } } throws SQLException{ private voiddelete(Connection connection) /** } { public voidretrieve(Connectionconnection) /** } private voidsave(Connectionconnection)throwsSQLException { throws SQLException{ private voiddelete(Connectionconnection) */ * DeletetheorderItsItems */ * theorderwithgivenid. * Refreshesthisobjectwiththedatafor */ * SaveanorderanditsaggregateItems */ * DeletetheorderandItsItems ysoft.com/elementsJ } for (inti=1;<=items.size();i++){ items =getOrderItems(); // Adddeletionoftheorderitemstotransaction ps.close(); ps.executeUpdate(); ps.setInt(1, getOrderID()); } } catch(Exceptionex){ try { // ReadtherecordsfromOrderItemtable setIsPersistent(true); setSubtotal(rs.getDouble(7)); setLocalTax(rs.getDouble(6)); setStateTax(rs.getDouble(5)); setFederalTax(rs.getDouble(4)); OrderData.delete(this, connection); OrderData.retrieve(this, connection); throws SQLException OrderData.save(this, connection); Vector items; PreparedStatement ps=null; C New York: Cambridge University Press. (1998). ps.executeUpdate(); ps =item.delete(connection); OrderItem item=(OrderItem)items.elementAt(i); // Handletheexceptionappropriately... setOrderItems(items); Vector items=OrderItem.retrieveOrderItems(orderID); g/w3c/util/UUID [email protected] J Component Software: Beyond Object- Beyond Component Software: ava New York: ACM Press. http://jigsaw av aS .html tyle .html .w3.or The Elements of g/Doc/P COM r o- J2ME EDITORIALOR J2ME INDEXX

Out of Nowhere 72

J2ME There are real-world applica- JASON BRIGGS J2ME EDITOR tions in which J2ME just fits. by Jason Briggs Out of Nowhere J2ME FAQ 74 f you’ve ever spent time in the Middle interface, the map rendering could be done Fiat Lux East, you’ll know that bargaining is a on the client side, reducing the probable Now that we have J2ME and, 76 Iway of life. You haggle over everything, network traffic required. in particular, Java processors, especially if you’re a tourist – they automat- What this example hopefully illustrates Java in embedded systems will ically triple and quadruple the price if is that there are real-world applications in really take off. you’re a foreigner. So it doesn’t seem that which J2ME just fits. Part 2 of the beginner’s by Rob MacAulay unusual to be arguing over the price of a guide to MIDP, found in this issue, will bus fare to the center of Turkey – a reduc- demonstrate one such application, simpli- tion, when converted to sterling, works out fied greatly by the use of Java. You’ll also The Great J2ME 78 to around 50 pence. So, in the flush of pride find a review of one of the ever-growing API Rundown at finally having outwitted the locals and number of devices that could run this sort arguing the price down to an “acceptable” of app: the Compaq iPAQ. For good luck, amount (which is still probably 2 quid we also review one of an also-increasing Jeode by Insignia more than the locals pay), you should not, number of J2ME virtual machines: Solutions 80 on the face of it, be that surprised when the Insignia’s Jeode. What can you expect from

Homecoach pulls J2EE up on the outskirts J2SE of some As expected, there were a number of Insignia's PersonalJava-com- unknown city, depositing you, your back- important announcements at JavaOne cov- patible virtual machine? pack, and some equally bewildered Turks ering a bewildering range of products and Find out here. unceremoniously on the side of the road at APIs. In some ways I’m glad I wasn’t there, by Anthony Simmons 4 in the morning. so Alan (our E-I-C) has to summarize it all Looking back, I’ve come up with the for me. That’s what I keep telling myself in perfect J2ME application for situations those moments when my skin turns that Wireless Apps Wanted: such as those – an instant travel guide: part delicate shade of green. Must be something Developers Only 84 phrase book, part translation guide, and to do with my diet. Need Apply part GPS-based map system. Ignore for a A couple of the more surprising pieces Kimberly Martin, from ATG, moment the small difficulties such as the of news: Sony announced the integration gives her take on the world of fact that very few phones and even fewer of Java into the PlayStation 2 console, and J2ME and application PDAs (if any) have GPS facilities built in, Sun proclaimed a new J2ME Games Profile. provisioning. and it does seem like an incredibly useful Java is definitely underrepresented in the by Kimberly Martin tool. At the time I’m sure I would’ve been console market with only Sega’s ill-fated quite happy to pay an extortionate U.S.$20 Dreamcast supporting a version of membership fee and three months’ sub- PersonalJava so far. At this point it seems iPAQ by Compaq scription in advance, just for the peace of likely that one will have an impact on the Computer Corporation 88 mind of knowing exactly where on earth I other, since Sony is involved in the Games The first in a series of reviews was and a few useful phrases to converse Profile specification, but what it will mean of J2ME-capable devices. in with my fellow travelers, also stranded for you and me, as developers, is not yet Caffeine in your hand! on the roadside. Again, even before starting clear. Stay tuned. by Anthony Simmons to travel, I might have been interested in a By the way, while standing on the side of more reasonably priced subscription for a Turkish road in the middle of the night, three or four months, or perhaps a year. without a clue what to do, a cab will gener- The Missing Bits 92 I’m sure someone out there is going to ally come hurtling out of nowhere, the driv- Why Record Management has argue that WAP is a likely enough candidate er pretending he hasn’t seen you, and still nothing to do with organizing for this application; however, I’m equally somehow manage to stop right next to you your music collection, and why sure that a Java version is a better idea. by applying the brakes at the last possible networking is more than mak- Designed well, it would present a slicker instant. He will, of course, also speak ing friends and interface – relatively consistent, no matter English. It’s one of those unfathomable, influencing people... what the platform. With a slightly heavier natural laws. by Jason Briggs

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

72 AUGUST 2001

Java COM J2ME FAQQ

IS PERSONALJAVA PART OF J2ME? Q

J2ME The short answer is yes. For the long answer, we'll refer to Sun’s FAQ for J2ME, which A AJIT SAGAR J2EE EDITOR states that PersonalJava was the “first Micro Edition technology.” Because PersonalJava has been around for a while now, you’ll find more products with a version of it installed. But sometime this year (2001), Sun is expected to replace the existing PersonalJava tech- J2EE Design Patterns: nology – based on Java 1.1 – with a new release based upon Java 2, and incorporated into the J2ME concepts of Configuration and Profile components. The Next Frontier IS ALL THE JAVA API WITHIN J2ME? Q No. Even PersonalJava – which has the most complete coverage of the Standard A –continued from page 10 Edition API – is still just a subset. bimonthly column based on his popular book Core J2EE Patterns. There is a J2EE WHAT IS A “MIDLET”? Q Patterns community out there. Feel free to Actually, the correct word is MIDlet. A MIDlet is an application written for MIDP (the A write to us to find out how you can learn Mobile Information Device Profile). You might find these on mobile phones, PDAs – in more about J2EE Patterns. Among other general, small devices. excellent articles, we also have a piece on J2EE frameworks by Steven Randolf that CAN I USE THREADS? IS THERE A PENALTY? Q should help you design better applica- Yes, you can use threads, unless you’re writing a JavaCard applet. As for the penalties, it very A tions by reusing J2EE framework compo- much depends upon how you want to use them, and the environment you are working within. nents. We also bring you reviews on a cou- When developing for constrained devices, you always have to keep the resources you have avail- ple of books that address J2EE design and able in the back of your mind. If you’re writing a MIDlet, and create 100 threads to try to load 100 real-world application of J2EE frame- images simultaneously, then there definitely will be a penalty – it undoubtedly won’t work. works. Q So, return to the J2EE section, and as

Home J2EE J2SE DO I USE AWT OR SWING FOR MY GUI? the Roman emissary in my Asterix comics If you’re developing a PersonalJava application, then you have access to a modified A would say: “make less factories, build version of AWT – “modified” meaning that a few java.awt classes/methods are optional, much objects.” that some have been changed, and that there are some additions to the basic package. You may be able to get Swing to work within a PersonalJava environment as well. A brief skim of the PersonalJava forums show some success stories – and more than a few painful attempts. None of the other J2ME “products” support AWT or Swing (for example, MIDP has the javax.microedition.lcdui package, for user interfaces).

WHERE CAN I FIND MORE INFORMATION ABOUT WIRELESS TECHNOLOGIES? Q The back issues of JDJ are one place you can look. For online information, you can look A JEREMY GEELAN J2SE EDITOR at the following URLs: 1. http://developer.java.sun.com/developer/products/wireless/ 2. Bill Day's J2ME archive: www.billday.com/j2me/ 3. Sun's Wireless forums: http://forum.java.sun.com/ Java Comesof Age –continued from page 44

WHERE CAN I DOWNLOAD J2ME EMULATORS? Q father of Java himself, James Gosling, and The J2ME Wireless Toolkit: http://java.sun.com/products/j2mewtoolkit/ A Dr. Alan Baratz, formerly president of download.html JavaSoft and of the Software Products & To download the MIDP reference implementation on this page: Platforms division at Sun Microsystems, http://java.sun.com/products/midp/ now CEO of Zaplet, Inc. CLDC : www.sun.com/software/communitysource/j2me/cldc/download.html As well as a full program of richly var- CDC (and the Foundation profile): www.sun.com/software/communitysource/ ied technical sessions on J2SE, J2EE, and j2me/cdc/download.html J2ME, there will also be a high-powered SuperSession in which key industry fig- ures will dissect for delegates and atten- WHERE CAN I FIND DEVICES THAT RUN J2ME? Q dees the fast-emerging new Web Services Move to another country. At the moment, there are a limited number of countries A Paradigm of distributed Internet appli- where J2ME capable devices have been released – especially for mobile phones. While cations. you can probably find PDAs that support PersonalJava almost anywhere in the world, the It’s all at the Hilton, New York, on same is not true for mobiles. September 23–26. I’ll see you there! In Japan, NTT DoCoMo has a number of phones from Panasonic, Fujitsu, Sony, and others (only available in Japan, of course). In the U.S., Motorola has a couple of J2ME capable mobiles. For a more comprehensive list, check out www.javamobiles.com/

74 AUGUST 2001

JJavaava COMCOM GUEST EDITORIAL

WRITTEN BY ROB MACAULAY PUBLISHER,PRESIDENT,AND CEO FUAT A. KIRCAALI [email protected] ADVERTISING SENIOR VICE PRESIDENT,SALES AND MARKETING CARMEN GONZALEZ [email protected]

J2ME Fiat Lux VICE PRESIDENT,SALES AND MARKETING MILES SILVERMAN [email protected] ADVERTISING SALES DIRECTOR ersonally, I think J2ME is what Java of us start eulogizing about J2ME and Java ROBYN FORMA [email protected] is really about. Let’s leave aside the processors, it’s all about cheap color PDAs ADVERTISING ACCOUNT MANAGER Pfact that Java was originally devel- using Java. Me, I get excited about light MEGAN RING [email protected] oped (as project Oak) for just this purpose, switches. My company makes native ASSOCIATE SALES MANAGER CARRIE GEBERT [email protected] and see what it means today. processors for Java-based applications, ASSOCIATE SALES MANAGER The demand for embedded micro- and these are already small enough so we CHRISTINE RUSSELL [email protected] processor systems has exploded, as con- can see that the cost of a Java-based con- SALES ASSISTANT sumers and equipment manufacturers troller will, in five years time, be cheap ALISA CATALANO [email protected] require systems that incorporate more enough to put in your light switch. EDITORIAL “intelligence.” The “intelligence” is used in Why would you want to run Java on EXECUTIVE EDITOR M’LOU PINKHAM [email protected] a number of different ways. Systems can, your light switch? If you need to control EDITOR of course, be used to automate complex your lights, you need some way of com- NANCY VALENTINE [email protected] tasks without user intervention – the tra- municating with them, and this brings in MANAGING EDITOR ditional requirement. However, there’s the other part of the equation: wireless. CHERYL VAN SISE [email protected] also a trend toward systems that are adap- Cheap wireless technologies change the ASSOCIATE EDITOR JAMIE MATUSOW [email protected] tive to changing needs and can communi- picture completely because they do two ASSOCIATE EDITOR cate with other equipment or with other things: slash installation costs and allow GAIL SCHULTZ [email protected] applications running on the same device. you to work with any controller that sup- ASSOCIATE EDITOR These extra requirements are putting ports wireless technology. However, tech- BRENDA BREENE [email protected] traditional methods of designing embed- nologies such as Bluetooth need Java; the ASSISTANT EDITOR LIN GOETZ [email protected] ded systems under increasing strain. communication protocols need a reason- PRODUCTION

HomeConventional J2EE embedded systems J2SE can suf- able amount of processing power to man- VICE PRESIDENT,PRODUCTION AND DESIGN fer from the following problems: increased age them. In the past, providing this JIM MORGAN [email protected] complexity and device count, lack of resource for a light switch was unthink- ART DIRECTOR portability of solutions, lack of support for able, but now it’s just around the corner. ALEX BOTERO [email protected] ASSOCIATE ART DIRECTOR networking, poor performance, and so Java immediately brings other benefits LOUIS F. CUFFARI [email protected] forth. Designing a working embedded sys- too. The light switch is now capable of ASSISTANT ART DIRECTOR tem has been something of a black art, announcing itself to any passing con- CATHRYN BURAK [email protected] and the number of engineers with the troller, which can discover what capabili- GRAPHIC DESIGNER ABRAHAM ADDO [email protected] required skills are in short supply. ties it has and could even download a con- GRAPHIC DESIGNER Java, and J2ME in particular, offers a troller applet from the switch. RICHARD SILVERBERG [email protected] number of solutions to these problems, And what is that passing controller? Very GRAPHIC DESIGNER AARATHI VENKATARAMAN [email protected] and also offers the promise of completely probably a mobile phone running – guess WEB SERVICES new ways of building embedded systems. what? – Java! These devices are starting to WEBMASTER The most obviously helpful feature of appear in the shops right now, so this is not ROBERT DIAMOND [email protected] Java is the notion of “write once, run any- science fiction. Using mobile phones as con- WEB DESIGNER where.” This is achieved through the dis- trollers also means you get wide-area network- STEPHEN KILMURRAY [email protected] tribution of code via class files, and also ing for free. Mind you, it might be disconcert- WEB DESIGNER PURVA DAVE [email protected] through the definition of the APIs. In the ing to find that your huge phone bill is due to WEB DESIGNER INTERN past, it was extremely difficult to port an the light switch talking to its friend in Japan. CAROL AUSLANDER [email protected] application from one embedded platform Do I have to change all my light switch- A CCOUNTING to another. With Java it’ll be easier to sell es? No, of course not. The light switch sim- ASSISTANT CONTROLLER your application into multiple markets. ply downloads a new interface, or possibly JUDITH CALNAN [email protected] ACCOUNTS PAYABLE Of course, the big bugbear of using Java the controller downloads an adapter class. JOAN LAROSE [email protected] in embedded environments was always the Easy! And automatic too – the user would- SYS-CON EVENTS large amount of resources required to run n’t need to know it has happened. VICE PRESIDENT,SYS-CON EVENTS interpreted or Just-In-Time (JIT) JVMs – usu- The light switch is perhaps a facetious CATHY WALTERS [email protected] ally a desktop PC. Now that we have J2ME example; it certainly won’t be the first appli- CONFERENCE DIRECTOR DANIELLE NAPPI [email protected] and, in particular, Java processors, Java in cation of the technology, and it sounds a bit CONFERENCE MANAGER embedded systems will really take off. like overkill. However, I think it’s the ulti- MICHAEL LYNCH [email protected] However, my vision is a little different mate point of this sort of technology: cheap, SALES EXECUTIVE,EXHIBITS from what you might expect. When most controllable, and above all, adaptable. MICHAEL PESICK [email protected] SALES EXECUTIVE,EXHIBITS RICHARD ANDERSON [email protected] [email protected] SHOW ASSISTANT AUTHOR BIO NIKI PANAGOPOULOS [email protected] Rob is a founder and technical director of Vulcan Machines, designers of native processors for Java-based applications. Rob has been JDJSTORE.COM ANTHONY D. SPITZER [email protected] involved in the manufacture of semiconductors for nearly 20 years and has been designing microprocessors for 10. In the last three years, he has concentrated exclusively on Java technology.

76 AUGUST 2001

Java COM java.security.cert see CDC com.sun.util for handling timer events ome of the more commonly asked ques- java.security.acl access control lists tions on the various forums for J2ME java.security.interfaces interfaces for generating keys PersonalJava will eventually be superseded by the Sseem to be "What is J2ME?" and "Is a part of J2ME?" Here is rithm parameter specifications PersonalJava Application Environment: where you will find all the APIs that fall java.text see CDC http://java.sun.com/products/personaljava/ beneath J2ME’s umbrella, and the packages you java.text.resources see CDC will find within those APIs. java.util see CDC JAVA TV – VERSION 1.0 java.util.jar see CDC javax.tv.carousel access to broadcast file and CONNECTED, LIMITED DEVICE CONFIGURATION java.util.zip see CDC directory data

J2ME (CLDC) – VERSION 1.0 javax.microedition.io see CDC javax.tv.graphics root container access and java.io input and output through data streams alpha blending java.lang fundamental classes The profile products page is here: javax.tv.locator referencing data and resources java.util collections, data and time facilities, other http://java.sun.com/products/foundation/ javax.tv.media controls and events for man agement of real-time media utilities J2ME GAME PROFILE javax.tv.media.protocol access to generic streaming javax. generic connections classes This is a proposed Micro Edition specification, so data in a broadcast micro- nothing is yet defined. According to the JCP home page javax.tv.net IP datagram access edition.io for JSR #134 (the Game Profile), the following areas will javax.tv.service service information access be covered: You can find more information on CLDC at the fol- javax.tv.service.guide supporting electronic program guides lowing URL: http://java.sun.com/products/cldc/ 1. 3D Modeling and Rendering for Games javax.tv.service.navigation services and hierarchical serv- 2. 3D Physics Modeling for Games ice information navigation 3. 3D Character Animation for Games javax.tv.service.selection select a service for presentation CONNECTED DEVICE CONFIGURATION 4. 2D Rendering and Video Buffer Flipping for Games javax.tv.service.transport information about transport (CDC) – VERSION 0.2 5. Game Marshalling and Networked Communication mechanisms java.io input and output 6. Streaming Media for Games javax.tv.util creating and managing timer java.lang fundamental classes 7. Sound for Games events java.lang.ref reference object classes 8. Game Controllers javax.tv.xlet communications interfaces java.lang.reflect reflective information about 9. Hardware Access for Games classes used by apps and the app manager java.math BigInteger support Stayed tuned to JDJ – we'll attempt to bring more java.net networking support information as it comes to hand. java.security security framework Get off that couch and check out the Java TV page java.security.cert parsing and management of at the following URL: certificates PERSONALJAVA SPECIFICATION – VERSION 1.2A http://java.sun.com/products/javatv/ java.applet full support from JDK1.1.8 Homejava.text J2EE used for handling J2SE text, dates, numbers and messages java.awt modified from JDK1.1.8 JAVA EMBEDDED SERVER – VERSION 2.0 java.text.resources contains a base class for locale • note: there is an extra method for PJ for double- com.sun.jes.service.http servlet/resource elements buffering in java.awt.Component registrations java.util collections, date/time, miscel- java.awt.datatransfer full support com.sun.jes.service.http.auth.basic http basic authen- laneous functions java.awt.event full support tication java.util.jar reading Jar files java.awt.image full support com.sun.jes.service.http.auth.users management of java.util.zip reading Zip files java.awt.peer modified users and their javax.microedition.io connections classes java.beans full support access java.io modified com.sun.jes.service.timer for handling timer Look for more CDC information here: java.lang modified events http://java.sun.com/products/cdc/ java.lang.reflect modified org.osgi.framework consistent model java.math optional – may or may not be for app. dev., sup- supported ports dev. and use MOBILE INFORMATION DEVICE PROFILE – java.net modified of services VERSION 1.0 java.rmi optional org.osgi.service.device detection of java.io java.rmi.dgc optional devices java.lang CLDC, plus an additional java.rmi.registry optional org.osgi.service.http http access of exception java.rmi.server optional resources java.util CLDC, plus timer facilities java.security modified org.osgi.service.log logging facility javax.microedition.io networking support based java.security.acl unsupported on the CLDC framework java.security.cert some classes required, some You can find more information on Embedded Server javax.microedition.lcdui for user interfaces for MIDP optional on the following site: applications java.security.interfaces required if code signing is www.sun.com/software/embeddedserver/ javax.microedition.rms persistent data storage included javax.microedition. defines applications and interac- java.security.spec required if code signing is API Rundown tions between app and envronment included – VERSION 2.1.1 java.sql optional java.lang fundamental classes The products page for MIDP is here: java.text full support javacard.framework core functionality of a JC http://java.sun.com/products/midp/ java.text.resources modified applet java.util modified javacard.security security framework java.util.jar required if code signing is javacardx.crypto extension package with secu- FOUNDATION PROFILE – VERSION 0.2 included rity classes and interfaces java.io see CDC java.util.zip modified java.lang see CDC java.lang.ref see CDC Additional PersonalJava specific packages are: Next time you use that American Express Blue card, java.lang.reflect see CDC com.sun.awt for mouseless environments you may want to know how it works, so take a look java.math see CDC com.sun.lang a couple of error & exception here: java.net see CDC classes http://java.sun.com/products/javacard/

The Great J2ME The Great java.security see CDC

78 AUGUST 2001

Java COM PRODUCT REVIEW

3.0, Windows NT4, VxWorks, Linux, ITRON, Nucleus, BSDi UNIX, and pSOS – and also supports a number of microprocessors: ARM, MIPS, x86, Hitachi SuperH-3, Hitachi SuperH-4, and PowerPC. Putting the OS and microprocessor support together, you’re likely to have a myriad array of

J2ME devices to choose from. If you’re reading JDJ from back to front, or have flipped to this page in the bookstore (then stop loitering and buy it, this isn’t a library, you know?), you should read the iPAQ review first. JDJ’s Jeode review used Jeode as the virtual machine upon which to run test appli- cations; so, to find out how Jeode per- forms on an actual device, look there grande.org), which gives stats on base Java by Insignia Solutions first. However, in this review we look at functionality (additions, divisions, array Jeode running on a desktop Windows assignments, casts, etc.). NT machine and compare its perform- The five VMs I’ll be comparing are Sun JDK ance against a number of other VMs. 1.1.8, Sun JDK 1.3, Sun PersonalJava Emulation Environment, Insignia’s Jeode 1.7 How Does It Work? (of course), and Microsoft VM 5.00.2752. REVIEWED BY ANTHONY SIMMONS Jeode uses a tool called the (Note: If you’re looking for proper benchmark- JeodeConfigurator to configure the vir- ing software or benchmarks for various virtu- [email protected] tual machine before running an appli- al machines, see References at the end of the cation. This is useful if you want to review.) develop in the Windows NT environ- ment (for example), but your applica- RESULTS OF TEST 1 tion will be running on a more limited

Home J2EE J2SE platform (such as WinCE). The The only perceivable difference between Configurator allows you to tune proper- the virtual machines for test 1 is that the ties such as memory size, maximum version of PersonalJava that I’m using dynamic memory size, system memory, (PJEE3.1) uses the truffle peer set, hence the specs Insignia Solutions Inc. Java memory, and stack size. You can components look different to standard 41300 Christy St. switch dynamic compilation on or off, set AWT. Apart from that, each VM behaves the the space used for dynamic compiling, same as the others. Fremont, California 94538 turn debugging on or off, and so on. If your Web: www.insignia.com target device has a minimum of 8MB of RAM RESULTS OF TEST 2 Phone: 800 848-7677 available, you can quite easily set your mem- E-mail: [email protected] ory size to 8MB and tweak other options The results of this test, which was run in a accordingly. 640x480 window, are shown in Table 1. The Tests Test Environment RESULTS OF TEST 3 P800 with Windows NT 4.0 SP4 As with the iPAQ review there are three main tests I’ll be running Jeode through to The results for this test, again run in a give a very basic idea of how it performs. Test 640x480 window, are shown in Table 2. ounded in the U.K. in 1986, Insignia 1 just displays some of the AWT components started out developing technology that on the screen ensuring that the VM isn’t doing Table 3 shows the basic arithmetic opera- Fenabled non-Intel computers to run anything odd. Test 2 draws four triangles tions provided in Section 1 of the Java Grande DOS and Windows applications. Twelve years using the drawLine() graphics method and benchmark. later, after a shift in focus, the first beta ver- gives the time taken for the draw. Test 3 turns sions of the Jeode platform and Jeode a byte array of pixels into an image before Conclusion Embedded Virtual Machine emerged. drawing that image to the screen. In addition, On WinNT, Jeode appears to hold its own According to Insignia’s statistics, more than 35 I’ve also decided to run the Sequential against the competition, pulling in better million runtime units of Jeode technology Benchmarks from Java Grande (www.java- results than the PersonalJava Emulation have been contracted by OEMs, OS, and middleware suppliers. SUN JDK 1.1.8 SUN JDK 1.3 SUN PJEE3.1 INSIGNIA’S JEODE 1.7 MS VM Jeode includes class libraries for 6ms 8ms 14ms 7ms 5ms either PersonalJava or EmbeddedJava (depending on which implementation TABLE 1 Test 2 results the device manufacturer chooses), and a tool suite that includes a configura- SUN JDK 1.1.8 SUN JDK 1.3 SUN PJEE3.1 INSIGNIA’S JEODE 1.7 MS VM tor, monitor, and deployment tools. 41.39fps 38.17fps 1.41fps 25.97 46.44fps Jeode is available on a variety of oper- ating systems – Windows CE 2.12 and TABLE 2 Test 3 results

80 AUGUST 2001

Java COM PRODUCT REVIEW

Environment (which, in its defense, is not supposed to be a References) for customers interested in using your Java soft- production VM), and fairly similar results to a 1.1 VM. Running ware is a no-brainer. on the iPAQ (see iPAQ review) Jeode manages to beat the Sun VM on the pixel blit test, but not on the drawLine creation of References

J2ME triangles. These are not comprehensive tests, of course, so I 1. The Compaq/Insignia Jeode deal: www.compaq.com/prod- invite you to draw your own conclusions, depending upon the ucts/handhelds/java.html nature of the applications you’re developing. 2. Java Grande: www.javagrande.org by Insignia Solutions by The ability to tweak your environment to mimic a device, 3. Java Performance Report: www.javalobby.org/fr/ before you even have the hardware, must count as a selling html/frm/javalobby/features/jpr/ point. And with Compaq and Insignia releasing a $19.95 ver- 4. CaffeineMark: www.pendragon-software.com/pendrag- Jeode sion of the software – at the very least, providing a link (see on/cm3/

SUN JDK 1.1.8 SUN JDK 1.3 SUN PJEE3.1 JEODE 1.7 MS VM Add:Int (adds/s) 342,023,616.0 423,154,144.0 5,484,367.5 330,135,392.0 294,593,472.0 Add:Long (adds/s) 130,653,904.0 125,009,064.0 5,105,004.0 136,632,960.0 144,011,424.0 Add:Float (adds/s) 6,175,184.5 6,496,946.5 2,935,569.5 5,888,018.5 6,636,422.5 Add:Double (adds/s) 6,168,210.0 6,480,500.0 2,616,249.2 5,743,532.0 5,674,309.0 Mult:Int (mult/s) 156,794,064.0 162,097,456.0 5,333,680.5 146,958,176.0 106,320,568.0 Mult:Long (mult/s) 81,603,784.0 31,864,452.0 4,595,019.0 67,299,240.0 43,600,560.0 Mult:Float (mult/s) 6,916,582.0 6,730,753.5 2,955,267.0 6,600,064.5 6,713,103.5 Mult:Double (mult/s) 6,586,268.0 6,417,045.0 2,582,760.5 5,900,742.0 5,090,095.5 Div:Int (div/s) 1,145,233,660.0 18,094,870.0 4,026,740.0 17,885,486.0 17,535,184.0 Div:Long (div/s) 186,619,200.0 5,711,497.0 2,843,259.8 6,549,932.0 7,426,344.0 Div:Float (div/s) 6,316,601.0 5,985,241.5 2,906,407.5 6,054,246.0 6,197,140.5 Div:Double (div/s) 6,378,075.0 6,096,599.0 2,532,772.8 5,686,125.0 5,274,612.0

Home J2EE J2SE TABLE 3 Basic arithmetic operations

82 AUGUST 2001

Java COM INDUSTRY COMMENTARY Wireless Apps Wanted: J2ME Developers Only Need Apply A market for third-party J2ME applications is about to explode With the growth of the wireless industry, and telecom- munications providers realizing the potential of provisioning per- sonalized mobile applications for customers, Java developers are positioned to capitalize on a tremendous market opportunity.The number of wireless communications devices installed worldwide WRITTEN BY has already exceeded the number of desktop PCs, and more explo- KIMBERLY MARTIN sive growth is anticipated.

While new technologies create that addresses the need for a universal hardware so that consumers can easily unprecedented opportunities for standard for wireless devices. Java 2 change or customize their devices as telecommunications companies, their Micro Edition (J2ME) is Sun’s version of needed. core competencies lie in the network Java aimed at machines with limited itself, not the content delivered on it, hardware resources, such as PDAs, cell J2ME Gaining Widespread Acceptance

Home J2EEand beg for the J2SE development of com- phones, and other consumer electronic Network operators, such as pelling consumer products and services. and embedded devices. J2ME addresses Cingular, NTT DoCoMo, Vodafone, As in other industries, content will the needs of devices with as little as Telefonica, and others, have publicly become king and Java developers will 128KB of RAM and with processors a lot proclaimed their support for J2ME. play a key role in providing fresh content less powerful than those used on typical Device manufacturers, such as Nokia, in the form of applications. desktop and server machines. Motorola, Siemens, and Research in The rapid evolution of the wireless Like the other Java technologies Motion (RIM), are building J2ME into marketplace means carriers need skilled (J2SE and J2EE), the J2ME platform their next-generation wireless handsets. support to deliver value-added services, maintains these advantages: Soon, the majority of mobile phones, particularly with the imminent arrival • Built-in consistency across products including less expensive models, will be and adoption of GPRS and 3G. The vari- to run anywhere, anytime, over any able to run applications written in Java. ety of applications that consumers will device In fact, Nokia has predicted that in 2002 want is seemingly endless. While no one • Portability of the code it will sell more than 50-million hand- particular killer app for mobile use is in • Leveraging of same Java program- sets with Java, and even more by the sight, it’s pretty clear that the killer app ming language end of 2003 – populating the world with for a teenaged girl in Texas is significant- • Safe network delivery at least 100-million Java-equipped ly different from that for a middle-aged mobile phones. Furthermore, J2ME man in Helsinki, despite the fact that In addition, applications written technologies also played a major role at both demographics are wired. Mobile with J2ME technology are upwardly JavaOne 2001, Sun’s worldwide Java operators simply won’t keep up with scalable to work with the J2SE and J2EE developer conference, signaling the demand for the variety of applications platforms, creating a platform that mainstream acceptance of Java on that the consumer will want unless they enables thin-client applications to work mobile devices, smart cards, and in look to third-party developers to gener- in a larger client/server environment. embedded solutions. ate the applications and content for Beyond these cross-technology Based on this widespread support, the their network. advantages, J2ME extends the promise message to developers is loud and clear – of Java by eliminating the problem of real J2ME-based devices are on sale Sun’s J2ME Creates Universal device proliferation while also providing today; network operators are beginning Standard for Wireless Devices additional benefits. Through caching on to deploy the technologies to support Until recently, mobile devices repre- the device, it solves the problem of spot- downloadable Java code to devices, and sented a developer’s worst nightmare ty network coverage. It also provides ASPs and traditional ISVs are currently because they typically have no standard graphic capabilities for wireless devices, developing software based on J2ME. operating system, microbrowser, or representing even more development Tremendous opportunity abounds. Now form factor, meaning all applications opportunities. Applications written in that the technologies are ready and rapid had to be written for specific devices. Java are future-proofed to evolve with adoption is underway, developers should To combat these limitations, Sun has the hardware. Devices that support Java be hustling to build and deploy real solu- taken a step toward creating a product permit easy upgrades of applications on tions for Java-powered devices.

84 AUGUST 2001

Java COM INDUSTRY COMMENTARY

Consumers will also benefit. Since it helps the developer as well as the con- trip to Manhattan, would probably view Java is platform-independent, programs sumer. First, it provides developers with it as a benefit to be offered a map of will become vendor-independent; for access to wireless carriers’ customers London’s Tube system the next time he example, apps written for Motorola and billing services so that the develop- or she lands at Heathrow. This hyperper- phones will be able to run on mobile er community can leverage the carriers sonalization ensures that the consumer phones from NEC without changes. By as a distribution channel for their appli- is not presented with irrelevant offer- selecting a Java-enabled phone, con- cations. Second, it uses scenario-driven ings, while also specifically targeting the

J2ME sumers won’t be limited to games and personalization so that carriers can application to qualified buyers. For the applications bundled with the firmware design highly targeted offers to their developer, this means there’s a higher on their phone, but will be able to customers. likelihood of purchase and increased replace them with new ones – down- To keep the consumer happy, net- revenue potential. loadable anytime. work operators must ensure that con- Through advanced personalization sumers are offered the right application, capabilities, carriers that provide feed- Keys to Success at the right time, on the right device. back to the developer on the applica- To encourage the development com- Consumers must view these new appli- tion’s success will ensure that their munity to build such applications, carri- cations and services as a benefit, not a content is always fresh and always rel- ers must manage their channel effec- blatant mechanism for generating rev- evant. For example, a developer of a tively. They must make it easy for the enue on the carrier’s part. Furthermore, wildly successful 1.0 version of a game developer to roll out applications to the consumers want one bill, and develop- should be encouraged monetarily to AUTHOR BIO consumer and provide the billing and ers want a simplified way to track and develop a version 2.0. Likewise, target- Kimberly Martin is a metering services for the developer, collect royalties. Successful carriers will ing those users of version 1.0 should product manager for ensuring royalties are tracked. A market extend their already robust billing and provide a great base of customers for ATG, a provider of for third-party J2ME applications will metering capabilities to seamlessly bill the 2.0 version. relationship flourish when carriers can effectively consumers for new applications and The convergence of wireless hard- management and target applications to specific con- services whether created by the carrier ware and software is inevitable. J2ME is e-commerce sumers and direct payments to develop- or by a third-party developer. the current leader and standard by products and ers based on usage. By considering contextual informa- which this convergence is starting. By services. She’s To effectively meet these two condi- tion such as time of day, location, and effectively managing relationships with responsible for tions, ATG has developed a service- past behavior, carriers can target the suppliers and consumers in the devel- product direction and delivery solution that will provide server offering of new applications to individ- opment community, carriers will be able

Homestrategy for the J2EEinfrastructure support J2SE for Java technol- ual consumers. For instance, a con- to reap the rewards of J2ME. mobile and wireless ogy–enabled wireless devices. Named sumer who has purchased a map of the market. the ATG Mobile Application Provisioner, New York City subway system while on a [email protected]

86 AUGUST 2001

Java COM PRODUCT REVIEW

his is the first in a series of reviews of However, Compaq has recently an- devices that are capable of running nounced a $19.99 deal for users to purchase TJava 2 Micro Edition – be it the JeodeRuntime for the iPAQ (see the Jeode PersonalJava, MIDP, or any other new pro- review in this issue of JDJ), so for the purpos- file that comes along. In this and future es of this review we’ll be using the issues of JDJ, we’ll try to provide a run- JeodeRuntime. And with ActiveSync, the down of the various kinds of handheld, installation just means downloading the run-

J2ME embedded, and mobile devices, and how time to the device. well they run your favorite language. First When evaluating a Java-ready device, if it up is Compaq’s iPAQ. has a screen, only one thing really matters – The iPAQ, a pocket PC from graphics performance. Everything else is sec- Compaq, (see Figure 1), comes in two ondary. After all, you’re not likely to be writing flavors. There’s the gray-scale H3135, servlets for your handheld (although consid- which is 5.1"x3.2"x0.6" and weighs in ering the perversity of some people in the iPAQ at 6.3 ounces, and the color H3635, development community, maybe you are, so which is the same size but 0.3 ounces scratch that as an argument). As the iPAQ lighter (according to the specs, at doesn’t come with a modem built in, network by Compaq least). Both use the same processor, a connectivity performance is of secondary 206MHz Intel StrongARM 32-bit importance. As the test model I was supplied chip;however, the H3635 has an extra with didn’t come with the modem option, it’s Computer Corporation 16Mb of memory. a nonstarter. The other important specs are a The tests we use are fairly simple; howev- color LCD touch screen that supports er, they do give us an idea of what we can REVIEWED BY ANTHONY SIMMONS 4,086 colors with a resolution of expect from the iPAQ with more serious Java 240x320 pixels for the H3635; and a 15 applications. In all cases, the tests are run [email protected] gray-scale, semitransmissive STN LCD (where graphical) using the full screen size touch screen for the H3135. A available. CompactFlash Expansion slot is includ- ed in both, and extra RAM/modem options are available separately.

Home J2EE J2SE The iPAQ is one of the better look- ing PDAs. Considerable thought has gone into the design of the silvery case and it just looks good in the hand – and specs Compaq Computer Corp. feels comfortable as well. A litmus test of 20555 SH 249 its appearance is undoubtedly: Would Houston, Texas 77070 you feel safe using the product in public? Web: www.compaq.com (That is, is someone likely to mug you and Phone: 281 370-0670 run off with it?) The iPAQ definitely rates Specifications as a device that little old ladies are likely to Processor: 206 MHz Intel StrongARM knock you senseless with their handbags 32-bit processor just to get their hands on. Memory: 16MB RAM (H3135) or But enough about the boring hardware 32MB RAM (H3635)16MB ROM stuff. What we really want to know is the Display:15 Grayscale STN (H3135) caffeine factor! or 4086 Color TFT To use Java on any device when it 240x320 resolution hasn’t been preinstalled will always be a Size: 5.11" x 3.28" x 0.62" Weight: 6.3oz (H3135) or 6.0oz (H3635) hassle – usually it means a hefty down- Power: Lithium Polymer Rechargeable load and then a problematic installa- battery or AC Adapter tion. Sun has a runtime environment Input: Touch-sensitive display, software for Java, available for the StrongARM keyboard, handwriting recognition, voice processor (WinCE); however, it’s cur- recorder, five application buttons, five-way rently in beta, so performance is less joystick, on-off and backlight buttons and than stellar (based on my prior note taker Ports: USB, CompactFlash expansion, experience). Your average user infrared, microphone, speaker probably isn’t going to bother, Operating System: Windows CE which is disappointing, espe- (a version of Linux is available for the cially if you’re developing iPAQ – see www.pocketlinux.com) applications and want to tar- Java Preinstalled: No. PersonalJava get the largest audience possi- Runtimes are available from Sun, Insignia ble. It’s more disappointing (Jeode), and others when you want to target the Price: U.S.$399 (H3135) or U.S.$599 (H3635) Notes: A 64MB RAM option is available; fastest processor currently see the Compaq Web site for more details. available and aren’t likely to get the performance your application requires. FIGURE 1 The iPAQ

88 AUGUST 2001

Java COM PRODUCT REVIEW

iPAQ TEST 1

The first test is an AWT application (or applet; it can run as either) with a few of the basic AWT components on a single screen (see Figure 2). What

J2ME we want to know is how responsive are the compo- nents. When you click a button, is it slower to rebound than a snail on depressants? When you type (or write) a message into a text field, are you likely to sprout cobwebs under your arms before you see the text appear? As expected, the news for the iPAQ is good – there’s no noticeable sluggishness on any of the components with Jeode (the same is true for Sun’s FIGURE 2 AWT application FIGURE 3 drawLine() by Compaq Computer Corporation Compaq Computer by PersonalJava runtime). When entering text with the handwriting tool, it appears in the text boxes Conclusion iPAQ iPAQ instantaneously; there are no perceptible prob- Performance lems with button, checkbox, or list drawing. With the JeodeRuntime, the iPAQ performs fairly well. It’s good enough for minor animations, puzzle games, and the like, though perhaps not powerful enough for more advanced iPAQ TEST 2 particle effects, 3D graphics, and more. Of course it would take more than a week’s evaluation to really establish how the PDA The second test is basic graphics performance (see fits in the gaming world, but certainly, for business applica- Figure 3). In this case, the test application uses one tions, the power is more than adequate. of the most fundamental graphics operations – drawLine() – to create random triangles on the Secret Agent Factor screen. Note: The reason for using The iPAQ is a PDA, so secrecy isn’t really drawLine() to create the triangles, and an option while you’re using it, and in terms of

Home J2EEnot fillPolygon(), J2SE is that MIDP doesn’t the competition, it comes in a little larger support the fillPolygon() method, than a Palm Vx. However, it’s an extremely and it’s useful to use code in our sleek-looking piece of hardware – so a wor- PersonalJava test that’s similar to thy addition to any budding spy’s kit. what we might use in a MIDP test, for example. The application does- For the Gadget Geek n’t provide the frame rate, but This device wins outright in the raw power rather the length of time to draw stakes. But it’s Windows CE, so it’s got all four random triangles on the screen. those…Windows…bits and pieces. For real- In this case, the iPAQ (unlike the ly happy hacking, install an embedded ver- screenshot shown in Figure 3) starts to sion of Linux on it (for example, www.pocketlin- struggle a bit more: the average time need- ux.com), and compile a version of Java for Linux. ed to draw the four triangles is 450–800ms. You’ll probably destroy any chance you had of being Interestingly, in this test only, Sun’s PersonalJava truly productive with the device, but who cares! It’s a PDA, it’s beats Jeode hands down, taking only a few mil- Linux, it’s Java… oh, just forget it! liseconds to complete the operation. Overall From a Java developer’s point of view, the iPAQ’s proces- iPAQ TEST 3 sor is definitely a selling point. It looks good, has specifica- tions that generally could put some laptops to shame, and The third test, if you’re developing a game, is coupled with Jeode, could be used to produce some fairly probably the most important: raw pixel through- good multimedia applications (perhaps not cutting-edge, put. In other words, if you provide an array of pixel though). But bear in mind, if you’re developing to take colors, how fast can they be blitted to the screen as advantage of this extra power, your market may be fairly lim- an image? This is useful if you want to write a ited for a while; however, more and more devices are appear- game with more interesting particle effects, for ing with 200+ CPU speeds, so the market may not stay small example. This test application creates a random for long. array of black and white colors, links the array to image creation, and paints the pattern to the References screen as an image. Here we’re interested in the 1. Compaq handhelds: www.compaq.com/showroom/hand- maximum frame rate possible. Here the iPAQ pro- helds.html duces an average frame rate of 10.6–10.8 frames 2. The Compaq/Jeode deal: www.compaq.com/products/| per second – not quite as high as I hoped, but still handhelds/java.html an improvement on the Sun beta (around 1.3 fps). 3. Jeode: www.insignia.com/products/default.asp

90 AUGUST 2001

Java COM M I D L E T S The MissingBits J2ME A beginner’s guide to writing applications for the MID profile

In Part 1 of this article, which can be found in JDJ (Vol. 6, issue 7), we covered the basics of creating a Mobile Information Device Part 2 of 3 Profile application (also called a MIDlet).We covered some of the WRITTEN BY functionality available in the user interface packages and a slightly JASON BRIGGS more advanced graphics example.

Missing from that discussion was • getSize(): Get the size of the record one of the more unusual APIs included store (in bytes) in MIDP – the Record Management • getSizeAvailable(): Get the available System – which can be found in the space for the store to grow (also in package javax.microedition.rms. This is bytes) a persistent storage system based on a • setRecord(…): Set the data in a speci- “simple record-oriented database.” If fied record you want to store data on a device (and not on the server, for example), you’ll Enumeration Is Not the Same as Remuneration FIGURE 1 Main menu need to become very familiar with RMS. Use a RecordEnumeration to move

Home J2EEThe most fundamental J2SE object in RMS back and forth through the store and is the javax.microedition.rms.Record- view the data: Store, which is owned by a particular suite of applications currently installed RecordEnumeration recordEnum = on the device. What this means is that all store.enumerateRecords(null, the applications in the suite can share pbcomp, false); the same data, if necessary – games, for example, can store their saved state in Where the first argument (null) is the FIGURE 2 Screen one RecordStore. A phone book applica- filter that specifies the subset of records tion might share its data with a simple that will be enumerated, the second scheduling application – as long as it’s in argument (pbcomp) is a Record- the same suite, of course. Comparator (more on that soon) that To open (or create) a new RecordStore, specifies the order, and the final argu- use a static method found in the ment (false) specifies that the enumera- RecordStore class. Assuming we wanted tion will, in this case, not be kept up-to- to write a Phone Book MIDlet, we would date with the contents of the store (in probably call our store “PhoneBook”. other words, the enumeration is a copy FIGURE 3 Entry Screen of the store at that point). RecordStore store = A RecordComparator, as mentioned RecordStore.openRecordStore("PhoneB before, is used to order an enumeration. ook",true); Create a comparator by implementing the RecordComparator interface. The The Boolean value “true” is used to interface describes a single method specify that the store will be created, if (compare) that returns an integer value necessary. depending upon whether the contents A RecordStore has a number of of one byte array FOLLOWS, PRECEDES, FIGURE 4 List of tests methods that can be applied to it. The or is EQUIVALENT to a second byte most useful of these are: array (see Listing 1). Listings 1–7 can be • addRecord(…): Add a new record to found on the JDJ Web site, www.javade- the store velopersjournal.com. • deleteRecord(…): Delete a record Now that we have an enumeration of from the store records, what can we do with it? The • getNumRecords(…): Get the number important methods in the of records in the store RecordEnumeration are: • getRecord(…): Get a copy of data in a • hasNextElement(): Does the enumer- FIGURE 5 Output from tests record ation have more elements?

92 AUGUST 2001

JJavaava COMCOM M I D L E T S

• hasPreviousElements(): Are there source; Listing 3 provides the source of elements prior to the current posi- the canvas class. tion? • nextRecord(): Get a copy of the data Large Mouthfuls,or Multiple Bytes in the next record The records in a store are byte • nextRecordId(): Get the recordId of arrays, meaning you store and retrieve the next record your records as simple byte arrays. So

J2ME • numRecords(): Get the number of you can either work with the raw bytes records in the enumeration (as I’ve done in my PhoneBook applica- • PreviousRecord(): Get a copy of the tion, for simplicity’s sake), or use a data in the previous record combination of ByteArray and data • PreviousRecordId(): Get the recordId streams. Obviously, unless you have a of the previous record requirement for fixed data sizes (which is inefficient, but again that’s what I’m In the case of our aforementioned using in the PhoneBook), the stream PhoneBook application, we might dis- combination will probably be the more play the contents of the phone book on efficient way to go, in terms of the most a canvas and use the up and down but- effective use of storage space. tons to scroll back and forth through It has the added advantage that the enumeration dataset. On the can- using the various read methods in a vas we could trap the key press and DataInputStream (for example, then pass the game action (game readInt, readLond, readShort, actions are special events, such as readUTF), keep you one step away pressing an arrow button, which are from the messy details of how that data mapped to particular keys) back to the is actually stored in the byte array. parent application (containing the data To use the stream combination, store) to handle: you’ll probably do something like the following: public void keyPressed(int k) { ByteArrayOutputStream baos = new

Home J2EE J2SE parent.processAction(getGameAction ByteArrayOutputStream(); (k)); DataOutputStream dos = new } DataOutputStream (baos); dos.writeUTF("Hello"); In the parent class (in this case the dos.writeUTF("Test"); MIDlet), the processAction() method dos.writeInt(100); will move forward and backward in the enumeration depending upon whether byte rec[] = baos.toByteArray(); the up or down arrow has been pressed. For example: In comparison, the save() method in PhoneBook.java uses a fixed length if (action == Canvas.UP && name and variable length phone num- recordEnum.hasPreviousElement()) { ber, creating byte-arrays of the data currentRecordID = using a specially defined function recordEnum.previousRecordId(); called rpad (which adds spaces on the end of the name if it’s not long enough) set(store.getRecord(currentRecordI (see Listing 4). D)); I leave it up to the individual to } decide which way works better for else if (action == Canvas.DOWN && them. One of the joys of Java is that recordEnum.hasNextElement()) { while it provides functionality to insu- currentRecordID = late developers from any “nastiness,” it recordEnum.nextRecordId(); also allows you to get in there and “do things your own way.” set(store.getRecord(currentRecordI Figures 1–3 show the main screens D)); in the PhoneBook MIDlet. } Networking:It’s More than Making In this case, currentRecordID is an Friends and Influencing People int that holds the recordId the enumer- MIDP has to include networking ation is currently pointing to, and support. A large number of Java devel- set(…) is a user-defined method that opers in lynch-mode, with nooses calls the canvas and changes the dis- made from coaxial cable and baseball play accordingly. bats molded out of melted-down net- Listing 2 provides the full method work cards, would turn up on Sun’s

94 AUGUST 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!

Java COM M I D L E T S

doorstep in Palo Alto baying for blood if tests that’s used as the first screen the a Java product was released without user sees. When the user selects a test, OffOff adequate network support, and Sun and then selects the OK command, the the annual subscription rate knows that. Accordingly, you can find code in Listing 6 is executed. SAVESAVE $10 $10 the various network IO classes in the In Listing 6 lines 2–5 destroy the javax.microedition.io package. application if the Exit command was However, network connectivity is han- selected. Line 7 checks the current

J2ME dled differently from what you might state, which is used to switch between be used to in the Standard Edition of the two screens, and line 8 changes the ANNUALANNUAL SUBSCRIPTION COVER PRICE RATE Java (in java.net.*). One major differ- display to a TextBox (tb), which will be ence is that instead of creating/open- used to show the output. Line 11 gets $89.99 ing a socket or a URLConnection and the currently selected index in a list of then getting an input stream from that tests that can be executed. Line 13 YOU PAY object, you use the Connector class to checks that the test selected is valid. create and open a Connection, an Line 14 calls the test method with the $79.99 Input/OutputStream, or a URL of a TestServlet and passes a YOU SAVE DataInput/DataOutputStream. For parameter action, which will be in the Off the example: form, http://localhost:8080/servlet/ $10 Subscription Rate TestServlet?action=n (n being the num- HttpConnection c = bers 1-5, depending upon the user’s (HttpConnection)Connector.open("ht selection). Lines 16–18 check that the Receive 12 issues of tp://…………….."); test method returned a valid result, and XML-Journal for only $79.99! assigns that result to the output That’s a savings of $10 off There are a number of Connection TextBox, using the setString(...) method. the annual subscription rate. interfaces defined in javax.microedi- Finally, lines 26–28 change the display Sign up online at tion.io: Connection, ContentCo back to the list of available tests. nection, DatagramConnection, Http- www.sys-con.com or call Connection, InputConnection, Output- It Takes Two 1-800-513-7111 Connection, StreamConnection and One other thing is missing from this and subscribe today! StreamConnectionNotifier. network conversation – Test-

Home J2EE J2SE In Listing 5 we’ll look at the Servlet.java, shown in Listing 7. This is HttpConnection interface using a not the right place for a deep and MIDlet called HttpTest.java. In this meaningful discussion on servlet XML Training and Certifications Adding value to your knowledge of XML application we’ll define a test method development, but to summarize what that takes a URL string as a parameter the servlet is doing: XML Essentials carriglearning – an online and then opens an HTTP POST con- 1. A doPost event arrives to be handled learning course nection to that URL (for more informa- by the servlet. XML Tutorial: Get into DTD tion on HTTP see RFC 2616 – 2. The servlet gets the writer for the Development Mode www.ietf.org/rfc/rfc2616.txt?num- ServletResponse object. XML Servers – An Overview ber=2616). 3. The content type of the response is Looking at Listing 5 line by line: set. An Introduction to JDOM Creating a JDOM document Lines 1 and 2 declare the 4. The parameter “action” value is

Coming in August: HttpConnection object and the retrieved from the ServletRequest. Designing Processable XML Tagging Languages InputStream. Line 5 opens an 5. The parameter is converted to an int, The Canonical vs Transactional HttpConnection to the supplied URL. and the word “test” is appended to a approaches Line 6 sets the request method on the string a number of times based upon connection. In this case we want to that number. perform HTTP POST operations. Line 8 6. Finally, the number is concatenated opens an input stream to the connec- on the end of the string, and the tion. Line 10 tries to get the content result is written out using the writer. length. If a content length is provided, lines 12 and 13 create a byte array and Figures 4 and 5 show the MIDlet then read from the stream into the (and servlet, behind the scenes) in array. If no length was provided, lines action: 18–22 read from the stream, character by character, until a terminator is Summary reached. Lines 15 and 23 return the We’ve now covered the major parts result from either set of operations. of creating MIDP applications. In Part Finally, lines 27–30 and 32–35 close the 3, we’ll put all the pieces together InputStream and Connection. extending the PhoneBook application I think you’ll agree that this is fairly already created. We’ll retrieve data painless networking (as with most using an EJB, and funnel it through a communications in Java). servlet and into our J2ME front end. What else is included in this MIDlet? HttpTest creates a simple list of five [email protected]

96 AUGUST 2001

Java COM J AVA BASICS A DEEPER

J2SE AT J2EE J2ME

Anatomy of a Java program Home Written by JacquieJacqu ie Barker

This excerpt discusses the specifics of coding the Student their debugging and code/project management features, Registration System (SRS). Java is an extremely rich language, among others. and our goal is not to duplicate the hard work that has gone into existing Java language books, but rather to complement Anatomy of a Java Program,Revisited them by showing you how to bridge the gap between produc- The anatomy of a trivially simple Java program, which con- ing an object model and turning it into live Java code. sisted of a main() method, contains the logic of our program inside of a class “wrapper” (see Figure 1). Setting Up a Java Programming Environment Such a class would reside in a file by the name of class- Everything you’ll need to get started programming in Java name.java; Simple.java, in this example. on various platforms – Solaris, Windows, Linux – is available Note: The external name of the file containing the source for free with Sun Microsystems’ Java 2 Software Developer’s code of a Java class must match the name given to the class Kit (SDK), which can be downloaded from Sun’s Web site, inside the file, including the same use of upper/lowercase, http://java.sun.com. We strongly advise that you take the time with .java tacked on at the end. Java is a case-sensitive lan- now to establish your Java development environment, so guage, even on operating systems like DOS that are tradition- you’ll be prepared to experiment with the language as you ally case insensitive in most respects. learn. A common error for beginners is to assume that case does- Note that the Java 2 SDK is a command line–driven toolkit, n’t matter, and to name the file for our example program sim- which means that on a Windows platform you’ll be opening ple.java, SIMPLE.java, or some other variation. This leads to up an MS-DOS Prompt window, from which you’ll be doing all compilation problems, as we’ll see in a moment. of your work (UNIX and Linux are naturally command-line A nontrivial Java application consists of many such .java This is an excerpt from oriented). Of course, there are also numerous Java Integrated files, because the source code for each class comprising your Chapter 13 of Beginning Java Development Environments (IDEs) to choose from, some of application typically (but not always) resides in its own *.java Objects written by Jacquie which are available on a free trial basis as Web downloads. file. Barker, published by Wrox Press. However, my personal bias is that if you first learn Java from You’ll have one .java file for each of the domain classes that No part of this excerpt the ground up, writing all your code from scratch using only you defined in your object model. For the SRS application, for may be reproduced, in any form Sun’s SDK and your favorite text editor, you’ll gain a much bet- example, we’ll have eight. Course.java, Person.java, or by any means without the ter understanding of Java language fundamentals than if you Professor.java, ScheduleOfClasses.java, Section.java, prior written permission of the rely too heavily on an IDE, particularly those that provide Student.java, Transcript.java, and TranscriptEntry.java. publisher, except in the case of drag-and-drop, GUI-building capabilities and automated You’ll also typically have a separate .java file for each of the brief quotations embodied in code generation. You can always consider graduating to an primary “windows” comprising the graphical user interface of critical articles or reviews. IDE after you’ve mastered the language to take advantage of your application, if any. For the SRS application, we’ll have

98 AUGUST 2001

Java COM two: MainFrame.java and PasswordPopup.java. Typically you’ll have a separate .java file that contains the “official” main() method that serves as the application driver. One of the primary responsibilities of this driver class’s main() method is to instantiate the core objects needed to fulfill a sys- tem’s mission; of course, actions taken by the objects as well as by the user will cause additional objects to come to life over time, as the application executes. The main() method is also responsible for displaying the start-up window of the graphi- cal user interface of an application, if any (see Figure 2). We’ll name the driver class for our Student Registration System application SRS, so of course it will need to be stored FIGURE 1 A simple Java program in a file named SRS.java. Finally, you’ll quite possibly have other “helper” classes To run a Java program from the command line, type the fol- necessary for behind-the-scenes application support; with lowing to invoke the JVM: J2SE the SRS, we’ll have a need for three such classes: CollectionWrapper.java, CourseCatalog.java, and Faculty.java. java MainClassName Assuming that you’ve properly installed Sun’s Java 2 SDK, a Java source code file (.java file) can be compiled at the com- for example: mand line via the command: java Simple javac classname.java or J2EEfor example: J2ME java SRS javac Simple.java where MainClassName is the name of the class file (minus the Again, pay close attention to match upper/lowercase .class suffix) containing the compiled byte code version of the usage; if you were to name your class Simple (uppercase “S”), “official” main() driver method for your application. but store it in a file named simple.java (lower case “s”), the The JVM loads the byte code for whatever class you’ve Java compiler would generate the following compilation error: named, and if it discovers a main() method within that byte code with the proper signature (recall that the name of the Home Public class Simple must be defined in a file called argument being passed into the main() method – args, in this 'Simple.java'. case – is the only thing that’s flexible in the signature):

Note that you can compile multiple files in a single step: public static void main(String[] args)

javac file1.java file2.java ... filen.java then the JVM executes that main() method to jump-start your application. From that point on the JVM will load additional or classes – either classes that you’ve written and compiled or classes built into the Java language – as needed, when refer- javac *.java enced by your application. That is, the first time the SRS appli- cation has occasion to refer to the Person class, the byte code Assuming that no compilation errors for the Person class will be loaded into the JVM, and so forth. occur, compilation produces at least one It’s important that you don’t type the .class suffix when classname.class file for every .java file; for attempting to run a program, as you’ll get an error: example, Simple.class for our sample pro- gram (see Figure 3). (We’ll see later in this java Simple.class article why more than one .class file might be produced from a single Exception in thread "main" .java file.) The *.class files contain java.lang.NoClassDefFoundError: Simple/class platform-independent Java byte code that can be run on any which is, to say the least, not very intuitive! This particular platform for which there is a error message arises because the Java compiler interprets the Java Virtual Machine available. name Simple.class as being the name of a class called “class”, to be found within a package called “Simple”; we’ll be talking about packages shortly. Why must the main() method of an application be ava is a declared static? At the moment that the JVM first loads what- J ever class you’ve told it to load to jump-start your application, no objects exist yet, because the main() method hasn’t yet exe- case-sensitive cuted; and it’s the main() method that will start the process of instantiating your application’s objects. So, at the moment of application start-up, all the JVM has at its disposal is a class; language” and a static method is a type of method that can be invoked on a class as a whole, even if we don’t have an instance of that class handy.

100 AUGUST 2001

Java COM One final note about program structure: we said that the source code for each class comprising your application typi- cally resides in its own .java file. It’s actually permissible to place the source code for two or more Java classes back to back in the same physical .java file. We don’t generally do so, however, as it’s much easier to manage Java source code when there is a one-to-one correspondence between the external file name and the internal Java class name. If we were to com- bine multiple class definitions back-to-back in a single .java file, however, they would each produce their own .class file when compiled. Importing Packages To appreciate import statements (see Figure 4), we first must understand the notion of Java packages. J2SE Because the Java language is so extensive, its various built- FIGURE 2 The main() method in one class of a Java program in classes are organized into logical groupings called packages. For example, we have: • java.sql: Contains classes related to communicating with Object Database Connectivity–compliant relational data- bases • java.io: Contains classes related to file input/output • java.util: Contains a number of utility classes, such as the J2EEJava collection classes J2ME that we’ll be learning about • java.awt: Contains classes related to GUI development

Most built-in Java package names start with java, but there are some that start with other prefixes, such as javax. If we acquire Java classes from a third party, they typically come in a package that starts with com.companyname, for example, com.xyzcorp.stuff. FIGURE 3 Creation of multiple class files from multiple Java files The package named java.lang contains the absolute core of Home the Java language, and the classes contained within that pack- The asterisk (*) at the end of the import statement above is age are always available to us whenever we write Java pro- a wild card character; it informs the Java compiler that we grams, so we needn’t worry about importing java.lang. wish to import all of the classes contained within the java.util However, if we wish to instantiate a Vector (one of Java’s built- package. As an alternative, we can import individual classes in collection classes) as an attribute inside one of our classes, from a package: for example, then we must import the java.util package, as the following example illustrates: // ImportExample.java

// Simple.java // We can import individual classes, to better docu- ment where each class // Our class needs to instantiate a // that we are using originates. Vector, and so we must import the package // that defines what a Vector is. import java.util.Enumeration; import java.util.Vector; import java.util.*; import java.util.Date; import java.io.PrintWriter; public class Simple { public static void // etc. main(String[] args) { Vector v = new Of course this requires more typing, but it serves as better Vector(); documentation of where each class that we’re using in our } program originates. } If we were to attempt to reference the Vector class in one of our classes without this import statement, we’d get the follow- ing compilation error when compiling that particular class: e needn’t Class Vector not found. This is because Vector is not in the name space of our class; worry about that is, it’s not one of the names the Java compiler recognizes in the context of that class. Generally speaking, the name importing space for a given class contains the following categories of names, among others: java.lang” • The class • All the attributes of the class

102 AUGUST 2001

Java COM Java COM • All the methods of the class • Any local variables declared within a method of a class • All classes belonging to the package that the class in ques- tion belongs to • All public classes in any other package that have been imported • All public features (attributes, methods) of any of the class- es whose names are in the name space • All public classes in java.lang

We could work around the failure to import a package by fully qualifying the names of any classes, methods, or other, that we use from such a package; that is, we can prefix the name of the class, method, or other, with the name of the package from which it originates, as shown in the next exam- FIGURE 4 Modified Java file J2SE ple: import com.objectstart.srs; // Simple2.java in their code, and even though our compiled class files are // no import statement kept physically separated from their application’s compiled class files, our classes would become logically combined with public class Simple { theirs, assuming a few other environmental details had been public static void main(String[] args) { taken care of. J2EEjava.util.Vector J2ME v = new java.util.Vector(); Going into a detailed discussion of how to create our own } packages is beyond the scope of this article. But, as it turns } out, if you do nothing in particular to take advantage of pro- grammer-defined packages, then as long as all of the com- This, of course, requires a lot more typing, and impairs the piled .class files for your code reside in the same directory on readability of the code. your computer system, they’re automatically considered to Although most built-in Java packages have names that con- be in the same package, known as the default package. All sist of two terms separated by periods (for example, java.awt) the code that we write for the SRS application will be housed some built-in Java packages have three, for example, in the same directory, and hence will fall within the same Home java.awt.event. As far as packages developed by third-party default package. This is what enables us to write code such organizations are concerned, there’s really no limit to the number as: of terms that can be concatenated to form a package name. The important point to note about all of this is that the statement: public class SRS { public static void main(String[] args) { import nameA.nameB.*; Student s = new Student(); Professor p = new Professor(); will only import classes in the nameA.nameB package; it won’t // etc. import classes in the nameA.nameB.someothername pack- } age. That is, the wild card pertains to class names only. } It’s also important to note that importing a package is only effective for the particular .java file in which the import state- without using import statements, because Student, and ment resides. If you have three different Professor, and SRS, and all of the other classes compris- classes of your own that all need to ing our SRS applications are within the same default manipulate Vectors, then all package. three of their .java files must The bottom line is that import statements as a building include an import statement block of a .java source code file are optional; they’re needed for java.util. only if we’re using classes that are neither found in package Java also provides java.lang nor in our own (default) package. programmers with the ability

to logically group their own class- ABOUTTHE AUTHOR

es into packages. If we wanted to, we Jacquie Barker is a professional software engineer and adjunct faculty member at George could invent a package, such as Washington University and Johns Hopkins University and a principal member of the “ com.objectstart.srs to house our SRS technical staff at SRA International, Inc. in Fairfax, Virginia. She holds a BS in computer application. Then, anyone else wishing engineering from Case Western Reserve University and an MS in computer science, from to incorporate our SRS classes within an UCLA. application that they were going to write could include the statement: [email protected] The wild card pertains to class names only”

104 AUGUST 2001

Java COM The World's Leading Java Resource

hohhomeomeme adaadvertisedvertisertise subscssubscribeubscribibe contccontactontact

java forums mailing list

What’sOnline... August 2001

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

Subscribe to Our FREE Weekly Newsletters J2EE J2ME editorial Now you can have the latest industry news delivered to you every week. SYS-CON newsletters are the easiest way to keep ahead of the pack. Register for your FREE newsletter today! There’s one for Java, XML, Web Services, Wireless, and source code ColdFusion. Choose one or choose them all!

JavaOne 2001 Radio Interviews Tune in to SYS-CON Radio (via the Shoutcast Network) jdj edge and hear the industry’s top movers and shakers, interviewed Home new york, ny by JDJ editors. Listen to James Gosling, the father of Java, JDJ sept 23–26 Advisory Panel members, CEOs, product managers, and other top executives as they share their insight and opinions on today’s hottest issues. search jdj JDJEdge Conference Program Now Available; Opening Day Keynotes to be Delivered by James Gosling and Alan Baratz Join us at the Hilton New York, September 23 – 26, in New York City for the largest Java and Web Services event on the East Coast. James Gosling and Alan Baratz will deliver the opening day keynotes; top executives from Sun, IBM, BEA, JDJ SPEcials Macromedia, PointBase, Sitraka, and Zaplet are also sched- uled to speak. The conference offers cutting-edge tracks, night school, and an accelerated weekend program. More information about the conference program and registration is available at www.sys-con.com/javaedge/.

Product Review Considering a product upgrade? Want to know the ins 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 bestsellers 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 professionals, industry gurus, and Java Developer’s Journal writers can engage in Java discussions, ask technical questions, talk to vendors, find Java jobs, and more. Voice your opinions and assessments on topical issues – or hear what others have to say. Monitor the pulse of the Java indus- try!

108 AUGUST 2001

Java COM RadView Launches WebLOAD 5.0 for interactive digital TVs, real-time operating system features include enhanced dynamic (Burlington, MA) – RadView Internet appliances, and auto- (RTOS). 2D and 3D visualization, personal- Software Ltd. recently motive infotainment systems. www.windriver.com ization and root-cause analysis: announced WebLOAD 5.0. The Six winners of the first phase will www.fastobjects.com technologies. http://ca.com latest version offers up to a 60% receive $2500. These six ideas performance enhancement over will be used for phase 2 of the CA Delivers Unicenter 3.0 Aligo Offers Free previous versions and enables competition, which will be to (Islandia, N.Y.) – Web Seminars software developers and QA pro- build one of the applications. For Computer Associates (San Francisco, CA) - fessionals to more easily and effi- more information on the International, Inc. has Aligo, a leading wireless software ciently verify the scalability of e- Devicetop announced the general infrastructure company is offer- business apps competi- availability of Unicenter 3.0 ing live Web seminars on the throughout the tion, see Network and Systems Management business benefits of mobile apps J2SE development www.devicetop.com. (NSM), the cornerstone of its new and Java. Classes are under one life cycle. www.radview.com Unicenter family of solutions. New hour. www.aligo.com Applied Reasoning Introduces realMethods Releases Mobile Classic Blend Framework 1.0 (Overland Park, KS) – Applied SYS-CON Media Named Winner of the 2001 (Bridgewater, MA) - realMethods, Reasoning has announced New Jersey Technology Fast 50 Awards Inc. has announced the release of Mobile Classic Blend, a Java mid- the Framework 1.0, a robust sys- dleware product that delivers fast J2EE J2ME tem designed for speeding devel- Internet wireless applications on (Montvale, NJ) – SYS-CON Media (www.sys-con.com), the world’s opment of the most difficult J2EE Java-enabled mobile devices. The leading i-technology publisher and the producer of i-technology apps. The realMethods current release supports the Palm developer conferences, headquartered in Montvale, NJ, has been Framework is based on the most OS platform on the Kyocera named by Deloitte & Touche to its annual list of the 50 fastest-grow- widely recog- Smartphone and uses IBM’s J9 ing technology companies in New Jersey. As a winner of the nized J2EE virtual machine on the Technology Fast 50 Award, SYS-CON was also nominated for the Design Smartphone. national competition for the 500 fastest-growing technology compa- Patterns and Sun Microsystems’ www.appliedreason- nies in the United States, the Technology Fast 500 Awards, with J2EE Blueprints. A downloadable ing.com results to be announced later this year. Home version is available at www.real- In 1999, SYS-CON Media was ranked 194 by Inc. 500 on the list of methods.com. Eoscene Announces World’s America’s fastest-growing privately owned companies. SYS-CON First J2EE Based OLAP App was nominated again for Inc. 500 in 2001 and is awaiting the results. Performance Benchmarks (Seattle, WA) – Eoscene The 2001 ranking of Technology Fast 50 is based on percentage of Demonstrate New Release of Corporation corporate revenue growth over the five-year period between 1996 FioranoMQ has announced and 2000. Winners include both public and private corporations. (Los Gatos, CA) – Fiorano the rollout of “We are delighted to be a 2001 New Jersey Technology Fast 50 Software, Inc. announced bench- the world’s first J2EE compliant winner,” said Fuat Kircaali, founder and CEO of SYS-CON Media. mark results that demonstrate On-Line Analytical Processing “Although we have experienced consistent growth since 1994, the that the latest version of (OLAP) application, as part of its year the company was founded, only after SYS-CON turned five FioranoMQ is more than 100% Intelligence Portal product. years old were we eligible for these nominations. This year, based on faster than the previous version Eoscene’s new technology our 2000 operating results, we are confident that our company will released in February 2001. gathers and interprets data from be named as one of America’s fastest-growing companies once The performance benchmarks any structured data source based again by Inc. 500, as well as by Deloitte & Touche Technology Fast consist of 72 individual tests in on its Meta models, combines 500.” In 2000, Fuat Kircaali was nominated by Ernst & Young for varying real-world scenarios. A sig- several data sources, and saves their Entrepreneur of the Year award. nificant optimization of the mes- the data in its OLAP store that Technology Fast 50 winners will be honored at an annual sage headers as well as improve- runs on most RDBMSs including awards breakfast on August 16, 2001. Winners of last year’s New ments to the unique file-based data Oracle, Informix, SQL Server, Jersey Technology Fast 50 included IDT Corp., Programmer’s store were the main reasons behind DB2, Sybase, and PostgreSQL. Paradise, Novasoft, Neil Laboratories, Computer Horizons, and the performance improvement. www.eoscene.com Hexaware Technologies. The performance tests used for SYS-CON received the Technology Fast 50 award based on a the benchmarks are FastObjects Partners With 1,075% five-year revenue growth between 1996 and 2000. SYS- publicly available Wind River CON’s prior national recognition, the 1999 Inc. 500 award was given from the Fiorano (San Mateo, CA) – FastObjects by based on a 1,307% five-year revenue growth between 1994 and 1998. Web site at www.fiorano.com. Poet has joined the WindLink The company’s first national recognition, published in Inc. mag- Partner Program of Wind River azine’s October 1999 special Inc. 500 issue and reaching over 2.5 mil- Devicetop.com Announces Systems, Inc. lion readers, was an exclusive report on the companies and CEOs Developer Contest Through the who are changing the face of American business. Noteworthy alum- (Ontario, Canada) – WindLink ni include household corporate names such as: Microsoft, Oracle, Devicetop.com has recently Partner Program, FastObjects is WordPerfect, CompUSA, Gateway announced its third developer making its embedded object 2000, Intuit, e*Trade, Timberland, contest for smart device applica- database technology available to Jenny Craig, and Domino’s Pizza. tions. In phase 1, contestants customers building systems submit proposals for applications based on Wind River’s VxWorks

110 AUGUST 2001

Java COM *Offer expires Dec. 31, 2001

*

AUGUST 2001 111

Java COM Career Opportunities

Who Needsan Agency? Do they provide valuable services?

ou’re a skilled technical professional with experience that’s in demand. Your WRITTEN BY Y résumé reads like a Who’s Who of top companies and a What’s What of top skills. So BILL BALOGLU & how come you’re the one working 40 hours a week, but a chunk of the money the client BILLY PALMIERI is paying for your services is going or has gone to the agency that placed you? J2SE

If you’ve been placed in a permanent erences.” This leads us to a very impor- that client at all. Because they lack cred- position, why should the client pay your tant distinction between reputable and ibility, many quick-sale agencies are agency a percentage of your annual “fly-by-night” agencies. merely trying to fill positions they pulled salary for just sending out your résumé When you get a phone call from a off a company’s Web site. and setting up an interview? Or if you’re fast-talking recruiter who can’t wait to a contractor, sure, the agency sends you zap your résumé off to a client for “a • Show me the money! a timesheet and mails you your pay- great opportunity,” how carefully does So you’ve found yourself a good, J2EEcheck, but how much J2ME does that cost? that recruiter explain the position? solid agency to work with that cares And how much is the client company Unfortunately, the majority of agency about building a long-term relationship you’re working for paying them? recruiters know little, if anything, about with you. You’ve found your Jerry At some point these questions are the kind of work you do. Maguire. What does that agency do to bound to run through the mind of any Their primary goal is to spam out as earn its percentage? intelligent engineer. No one wants to many résumés as possible (often unso- Building and maintaining strong feel like they’re being taken advantage licited) to clients who may be looking for relationships with new and existing of, or share their income with a compa- someone with skills that are totally dif- clients requires constant effort, from ny that’s a necessary evil. ferent from your own. cold-calling to seven-day-a-week net- Home There are good agencies out there. And your résumé arrives on the desk working. The end result is the job you’re They provide valuable services to engi- of an annoyed, frustrated hiring manag- working on today and in the future. neers, not the least of which is finding er with that agency’s letterhead embla- Each client has its own contract to be you that opportunity in the first place. zoned across the top. What many engi- negotiated, which means detailed, time- But with the past few years’ boom in neers don’t realize is the following: consuming legal work before you begin AUTHOR BIOS demand for technologists, innumerable your new position. If you’re on a con- Bill Baloglu is a principal agencies have sprung up, eager to cash • You’re guilty by assocation. tract, there’s constant monitoring of at ObjectFocus in on the high-tech bandwagon without These agencies that are mostly inter- your project, progress, and on-site rela- (www. ObjectFocus.com), much regard for little details, such as ested in closing a quick deal won’t both- tionships enabling the agency to solve a Java staffing firm in industry experience, technical expertise, er to fully qualify you before submitting problems before they occur. Silicon Valley. He was a or solid business ethics. you for a position. You can bet that By constantly searching for and qual- software engineer for 16 What should you look for in an they’re also submitting totally unquali- ifying new engineers, agencies burn up years prior to his position agency? What should you expect from fied candidates to their clients. the phone lines and ever-changing at ObjectFocus. Bill has them? And what should they expect The agency has no credibility with Internet resources. extensive 00 experience, from you? Our combined experience on the client and therefore you have no A good agency should provide full and has held software both sides of the technologist/agency credibility with the client. You have only disclosure of their fees and margins, development and senior relationship has given us more than a partnered with that quick-sale agency to regardless of whether it’s a contract or technical management few insights that we’d like to share. waste the hiring manager’s valuable permanent placement. Not all agencies positions at several Silicon time. And burn a potential bridge. do this, but at the very least, they should Valley firms. The Technologist/Agency Relationship be willing to tell you the placement fees “Traditionally speaking, many agen- • A good agency has strong working or the percentage markup they’re Billy Palmieri is a cies represent a broad spectrum of tech- relationships with its clients. charging. seasoned staffing industry nical professionals. The trend is chang- When approached by an agency, ask As in any business, there’s no greater executive and a principal ing, however,” says Kiran Khanna, a sen- the recruiter about the relationship with source of credibility than a referral. of ObjectFocus. Before ior recruiter at ObjectFocus. “There is a the client. How long have they been pro- Once an agency has said they’d like to that he was at strong demand for the services of spe- viding candidates to that client? How work with you, ask to speak to one of the Renaissance Worldwide, a cialized, niche agencies that can provide many of their consultants are currently engineers who currently works with multimillion-dollar global the needed talent in specific technology working with that client? What is the hir- them. You’re likely to get valuable IT consulting firm where segments quickly and efficiently.” ing manager like? What is the style and insight. he held several senior Many potential candidates balk at culture of the company? management positions in providing references to an agency, If the recruiter can’t answer at least [email protected] the firm’s Silicon Valley claiming, “I work with lots of agencies, I some of these questions, there’s a good operations. can’t have all of them bothering my ref- chance they have no relationship with [email protected]

112 AUGUST 2001

Java COM CUBIST THREADS RadicallyIconoclastic

he powers that be let me out of my cube long enough to attend the JavaOne Conference a couple of WRITTEN BY T months ago in San Francisco.While I was there, I got the chance to meet some of the movers and shakers behind BLAIRWYMAN Java Developer’s Journal. Of course, I had already met a couple of the “big cheeses,” but by no means all of them.

At one point I was introduced as come up with some cherished belief “Wow! I’m actually standing out of JDJ’s “resident iconoclast.” Naturally, I system to attack for this month’s col- doors listening to this streaming J2SE smiled a big smile, puffed out my chest, umn. I couldn’t just go after the low- Internet radio! Who could’ve imag- and tried my best to look genuinely hanging fruit though, like tarot readers ined?” Of course, the whole kit and proud of myself. Then, at the first or the Psychic Eyebrow Network or portable kaboodle – hardware and soft- opportunity, I made some excuse to somesuch. And whatever I did come up ware – would set you back almost steal away and look up the word “icon- with should be at least tangentially $1,000. (Hopefully, it might also do oclast.” computer-related to fit into the context other useful things, like provide driving Well, as it turns out, my feigned of this fine publication. directions to that poorhouse in your pride was a good guess. It seems that Well, a couple of weeks ago I just future; he didn’t say.) J2EEthe term iconoclast J2ME historically origi- happened to be viewing the big screen Oh, I know this Net radio device is nated with wild-eyed 8th-century – I had my remote control deftly really just a “proof of concept” for the Byzantine Christians destroying reli- clutched in the Random Button Access whole “wireless connectivity” belief gious images and idols – and later came with Embedded Tobacco Harness posi- system. One of the most prominent to mean anyone who attacks cherished tion, and was flipping joyously amidst features at JavaOne was the ubiquity of beliefs and traditions. Today, it has the tripe – when I suddenly experi- connectivity, both on the show floor finally come to mean something like, enced a catalytic inspiration for the and among the attendees. Everywhere “incredibly nice fellow with closely- choice of this month’s “target” belief. you looked, people had tiny phones trimmed eyebrows.” The image is of a young fellow, that could start their cars, feed their Home Actually, I guess the middle defini- standing in a courtyard, positively rav- pets, and ignore their e-mail. tion of “iconoclast” – the one that talks ing about how he’s listening to the radio I can’t deny that this connectivity about attacking cherished belief sys- outside...without any wires attached. has its upside. But do I really want to tems – is the one I would most hope to Naturally, I was a little confused. I need a cell phone? I’m not so sure. embody for JDJ. (After all, I made up mean, radios are wireless by definition, Currently you’re effectively ante- the one about the eyebrows.) Basically, right? Didn’t Guglielmo Marconi send diluvian if you don’t have one of these if I were to set out to try to describe wireless radio signals across the devices, the tinier the better, hanging myself, I know the phrase “cynically Atlantic Ocean almost a century ago? from your belt or your ear or your skeptical” would figure prominently (as Didn’t I snap my fingers to a wireless spaghetti strap. I’m going to theorize would the phrases “dashingly hand- transmission of “The Immigrant Song” that it won’t be long before the lucky some” and “conditionally conscious”). in my $100 1962 Studebaker Lark? I ones are those who don’t have to be Personally, I’m simply unwilling to mean, what’s the big deal? connected. Frankly, most of the time I take much of anything on faith, or Then the commentator went on to don’t want to be 10 dialed DTMF digits because so-and-so says so. A couple of explain that this is Internet radio he’s away from anyone in the world. In fact, my heroes are James Randi and the late listening to on his little handheld there are times when I’d simply like to AUTHOR BIO Richard Feynman, so you could say I’m device. It’s streaming audio arriving say, “Gone fishin.” Blair Wyman is a software not exactly in the mainstream of mod- over a 24Kbit/sec wireless Net connec- How’s that for radically iconoclas- engineer working for IBM ern belief systems. So be it. With any tion (barely phone quality). I guess what tic? in Rochester, Minnesota, luck, I’ll do my eyebrows proud. struck me as funny was the amazement home of the IBM iSeries. So, along those lines, I needed to in the commentator’s voice. [email protected] Java Dudes

114 AUGUST 2001

Java COM