THE LARGEST & WEB SERVICES EXPO IN THE WORLD! P.99

TM

The World’s Leading Java Resource Java COM May 2002 Volume:7 Issue:5

FULL CONFERENCE PROGRAM INSIDE PAGE 99 Systems: Optimizing Database Didier Cabannes 12 From the Editor Performance in J2EE Apps The best of both worlds Alan Williamson pg. 7 Feature: The Critical Role of Walter Hurst J2EE Editorial Application Architecture A fundamental issue 22 Ajit Sagar pg. 9

J2SE Editorial Show Review: First Impressions Ajit Sagar Keith Brown pg. 36 JavaOne 2002: How did it measure up to past shows? 30

J2ME Editorial AI: Programming Neural Networks in Java Jeff Heaton Jason R. Briggs pg. 62 An efficient way to perform certain operations 38 Industry Commentary Kuldip Singh Pabla pg. 64 JDBC 3.0: Something for Everyone John Goodson The new features and why they’re important 56 JDJ Labs Enterprise JavaBeans pg.90 Java-Miner pg. 92 Jini & J2ME: Jini Surrogate As a Platform William Swaney Using HTTP as a protocol 66 RETAILERS PLEASE DISPLAY for J2ME Games UNTIL JULY 31, 2002 Feature: OSGi: The Last Mile of Peter Kriens Software Deployment Solve last-minute problems 74 Pro Mobile: Keep Mobile Data and Applications Jeff Capone in Sync with Java An integral part of your mobile strategy Java Clients 84

Intermittent Connectivity WAP/Brows Based Clien ateways I SYS -CON App Management: Manifest Destiny Norman Richards MEDIA Simplify the packaging and releasing of Java applications 94 Sonic Software www.sonicsoftware.com

2 MAY 2002

Java COM Zero G www.zerog.com

MAY 2002 3

Java COM Apple Computer, Inc. www.apple.com/macosx

4 MAY 2002

Java COM Apple Computer, Inc. www.apple.com/macosx

MAY 2002 5

Java COM BEA www.bea.com/download

6 MAY 2002

Java COM 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 My Kingdomfor a Phone J2SE EDITOR-IN-CHIEF: ALAN WILLIAMSON EDITORIAL DIRECTOR: JEREMY GEELAN EXECUTIVE EDITOR: NANCY VALENTINE he whole wireless space has been an of you who don’t know the name, Bruce was J2EE EDITOR: AJIT SAGAR interesting one to keep an eye on for the main engineering man behind the data- J2ME EDITOR: JASON R. BRIGGS the past couple of years, in particular base at Oracle, so when he talks about data- J2SE EDITOR: T KEITH BROWN how it relates to the Java space. Sure, we’ve bases, you kinda wanna listen. PRODUCT REVIEW EDITOR: JIM MILBERY heard wonderful tales about the vast mil- PointBase was doing some cool stuff with FOUNDING EDITOR: SEAN RHODY lions of phones in Japan and how quickly syncing technology, as they had given up PRODUCTION Java is being adopted there, but for the rest of hope regarding the always-on network, and J2EE VICE PRESIDENT,PRODUCTION AND DESIGN: JIM MORGAN us here in the West, it’s not quite as exciting. their clients were looking for real-world ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI Regular readers know only too well my woes solutions they could use today. It was a great EDITOR: M’LOU PINKHAM with my Nokia and the lack of Java support. JDBC database/driver that operated at the MANAGING EDITOR: CHERYL VAN SISE The question is this: Is it a pipe dream or is it J2ME level. You would simply tag the ASSOCIATE EDITORS: JAMIE MATUSOW really coming? columns you wanted synced with the data- GAIL SCHULTZ That was the question I posed to Nokia at base at the back end, and when the network JEAN CASSIDY Home ONLINE EDITOR: LIN GOETZ JavaOne. Whereby I was given the usual mar- was available, the two would automatically TECHNICAL EDITOR: BAHADIR KARUV, PH.D. keting pitch about the great array of develop- sync with one another, recovering should the er’s tools and shown the nice color chart of all network drop. It doesn’t seem that impres- WRITERS IN THIS ISSUE the models that have been Java-enabled. sive on the face of it, until you realize they do BILL BALOGLU, JASON BELL, JASON R. BRIGGS, KEITH BROWN, Naturally, I ooh’d and ah’d in the right places. all this in under 50KB! However, the reason I DIDIER CABANNES, JEFF CAPONE, JOHN GOODSON, JEFF HEATON, I then asked to what extent would the KVM mention PointBase is that they were atypical WALTER HURST, PETER KRIENS, KULDIP SINGH PABLA, BILLY PALMIERI, be integrated. For example, would I be able to of the shift in the wireless space I witnessed NORMAN RICHARDS, AJIT SAGAR, HENDRIK SCHREIBER, BILL SWANEY, ALAN WILLIAMSON, BLAIR WYMAN access the hundreds of telephone numbers at JavaOne. SUBSCRIPTIONS: already stored in my Nokia address book? Developers were going to great lengths to FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, The answer was no! Excuse me? Okay, try not tell me about their solutions regarding the PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT to panic, I thought, not a major problem. I state of the network, and the conditions their SUBSCRIPTION HOTLINE:[email protected] just need to import them to my Java applica- software would excel in, such as a tempera- tion and they can reside there. I asked for mental network going up and down. This I COVER PRICE: $5.99/ISSUE DOMESTIC: $49.99/YR. (12 ISSUES) confirmation that my Java application would found reassuring because I live in a rural CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. be able to make phone calls from my now area where reception for my mobile is not (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. imported contact list. No was the answer always 100%; I was beginning to worry that I again, “That would be a security risk and vio- may be left behind in this new always-on, EDITORIAL OFFICES: late the openness of the specification.” always-connected, Web-serviced world! SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 At this point, I couldn’t believe what I was On the whole, JavaOne was a good show TELEPHONE: 201 802-3000 FAX:201 782-9600 hearing. Is this true? We have a with plenty of walking space between the JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly (12 times a year) for $49.99 by SYS-CON Publications, Inc., 135 Chestnut phone…whose main purpose in life is to booths (you definitely knew the bottom had Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at make calls. That’s its calling, to use a very fallen out of the dot-com world). I caught up Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address bad pun. We can load applications on it that with a lot of old faces, listened attentively to changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., can’t actually take advantage of the core what they were up to, had a brush with J2EE 135 Chestnut Ridge Road, Montvale, NJ 07645. functionality of the phone? Major oversight, Blueprints, and met a vast array of new faces. ©COPYRIGHT: wouldn’t you say? Tell me again why I want It was a great event, as usual. Copyright © 2002 by SYS-CON Publications, Inc. All rights reserved. my next phone to be Java-enabled? Someone We were there with SYS-CON Radio No part of this publication may be reproduced or transmitted in any form or by any please e-mail me and tell me I’m wrong. interviewing the latest and greatest. Keith means, electronic or mechanical, including photocopy or any information storage and At JavaOne, I had a great meeting with Brown, our esteemed J2SE editor, conducted retrieval system, without written permission. For promotional reprints, contact reprint coor- dinator Carrie Gebert, [email protected]. SYS-CON Publications, Inc., reserves the right Bruce Scott from PointBase; he kindly spent the majority of the interviews, which you can to revise, republish and authorize its readers to use the articles submitted for publication. time discussing what they were doing and listen to online at www.sys-con.com/java/. where they see the future of J2ME. For those Until next month … 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. During the day 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. Rumor has it he welcomes all suggestions and comments.

MAY 2002 7

Java COM TogetherSoft Corporation www.togethersoft.com/1/jd.jsp

8 MAY 2002

Java COM J2EE EDITORIALOR J2EE INDEXX

Are You Being Served? J2ME Customer service and - 9 ship management is the corner- stone of a successful business. AJIT SAGAR J2EE EDITOR Before selecting a vendor who supplies J2EE wares, make sure that adequate support will be available when you’re struggling with critical and complex issues. J2SE Are YouBeing Served? by Ajit Sagar J2EE FAQ ’ll never buy a Casio watch again. Not have been playing catch-up with Sun’s The answers to your J2EE 10 just because they break down – that’s J2EE platform APIs. The platform is now questions te Ijust the luck of the draw – but because stable and there are ample examples of of their extremely poor service. I’ve spent real-world deployments. At this stage in a Optimizing Database months trying to get my $200 watch back platform’s development cycle, support and Performance in J2EE J2EE from their service center, but to no avail. It service for J2EE-based products becomes Applications isn’t the money that matters; it’s the princi- of paramount importance. With the recent With hybrid , ple of the thing. For a couple of months it economic debacle, there’s less room in J2EE developers can demand was nearly impossible to get anyone on organizations for “buy and try” and more a database that meets the the phone, and there was no advertised of a requirement for well-supported prod- intrinsic requirements of 12 Web address for contacting the service ucts. scalability, high transaction center. Before selecting a vendor who supplies volumes, high-volume data

Customer service and relationship J2EE wares, organizations need to make transfer, and the need for fast Home management is the cornerstone of a suc- sure that adequate support will be avail- throughput as well as an cessful business. Today’s software industry able when they’re struggling with critical object data model that more is a lot like other industries – it’s service- and complex issues. Almost all the J2EE accurately represents busi- driven and highly competitive. With the application server vendors have their part- ness processes, now and in three-month Internet-year release cycle, ner programs. However, based on recent the future. vendors work hard to keep their service experience, I’d like to caution you before by Didier Cabannes offerings at an acceptable level and to marrying your development to a specific keep up with the rapid changes to the product. It’s very important to make sure The Critical Role of baseline products. They struggle with the support will be provided by skillful per- Application Architecture same issues that all other industries do – sonnel in a timely manner. Vendors are delivering tools selling products to customers and then One of the risks with the programs and frameworks to ease the retaining those customers. Vendor prod- offered by vendors is that often the support next level of application ucts that offer functionality for J2EE have person at the other end is not very quali- development for many proj- to work on a framework that’s evolving at a fied, and may be even less familiar with the ect teams, allowing them to breakneck speed. product than you are. There’s no option but focus on the business 22 Since they deal with new functionality to run the gauntlet before the support call requirements at hand and and APIs that are still stabilizing with every is escalated to where you get the right level obviate the need to deal with release of the platform, vendors have to of technical support. Sometimes you end what will soon become mun- make sure their marketing message is well up educating the person at the other end dane development tasks. coordinated with their ability to deliver before getting any valuable feedback. This Nowhere will this be more the goods in light of rapidly evolving stan- could take several weeks and potentially apparent than in the area of dards. Vendors face a paradoxical situa- jeopardize your deadlines. application architecture. tion. To gain a larger market share, they To select the right vendors, it’s impor- By Walter Hurst need to make sure they’re standards-com- tant to look at their legacy. After all, J2EE is pliant. To distinguish themselves from the a fairly new platform – less than 10 years competition, they need to offer propri- old. Therefore, most of the J2EE applica- JavaOne Show Review etary value-adds to the basic functionality tion server and other tool vendors are rein- If you didn’t make it to offered by Sun’s specs for the J2EE plat- carnations of vendors who came from JavaOne this year, find out form. other product lines. The legacy defines what you missed – what the Retaining customers is largely depend- their areas of expertise. Eventually, it big announcements were, 30 ent on how well the products are support- determines the level of support they can who the best keynote speak- ed. For the past few years, J2EE vendors offer to your application development. ers were, and more. by Ajit Sagar [email protected] AUTHOR BIO Ajit Sagar is the J2EE editor of JDJ and the founding editor and editor-in-chief of XML-Journal. A lead architect with Metavonni, LC, based in Dallas, he’s well versed in Java,Web, and XML technologies.

MAY 2002 9

Java COM J2EE FAQQ J2EE ROADMAPA

The Java 2 Platform, Enterprise Edition defines the APIs for building enterprise-level applications. J2SE...... v. 1.2 J2ME Enterprise JavaBeans API WHAT IS EJB 2.0? Q ...... v. 1.1 JB 2.0 is the latest release of the Enterprise JavaBean specification. The major releases of the EJB specifi- A Java Servlets ...... v. 2.2 Ecation have been 1.0, 1.1, and 2.0. EJB 2.0 adds several crucial features to version 1.1, including message- driven beans, local interfaces, an enhanced container-managed persistence, and EJB-QL (). JavaServer Pages Technology ...... v. 1.1 JDBC Standard Extension J2SE WHAT ARE THE MAIN INTERFACES IN EJB 2.0? Q ...... v. 2.0 he figure below illustrates the class hierarchy (EJBLocalObject and EJBLocalHome) don’t extend A Java Naming and Directory T for EJB 2.0 and the interfaces that are includ- the java.rmi.Remote interface. You can’t use them to Interface API ...... v. 1.2 ed. The main interfaces for EJBs are packaged under access distributed objects. The local interfaces were javax.ejb; they’re standard extensions to the core added to the EJB specification in 2.0 so that compo- RMI/IIOP ...... v. 1.0 Java classes. nent accesses to EJB components within the same Java Transaction API..v. 1.0 The javax.ejb package defines the interfaces you JVM don’t have to be done through RMI, which is need to extend your application’s components. By def- very expensive since each call requires a distributed JavaMail API ...... v. 1.1 inition, Enterprise JavaBean is a specification for dis- call.

J2EE Java Messaging Service tributed architecture. In Java terms, this means that a The enterprise bean interfaces are illustrated on ...... v. 1.0 Java class running in one JVM should be able to com- the left side of the figure. These interfaces were municate with an EJB component in another via an added to the EJB specification in 2.0. Local inter- Useful URLs: RMI call. First, let’s look at the EJBObject and faces support the concept of colocated EJBs (local Java 2 Platform, Enterprise Edition EJBHome interfaces, which are shown in the middle interfaces). The local interfaces (EJBLocalObject and www.java.sun.com/j2ee/ pane of the figure. These interfaces extend the EJBLocalHome) don’t extend the java.rmi.Remote J2EE Blueprints java.rmi.Remote interface. The Remote interface interface so you can’t use them to access distributed www.java.sun.com/j2ee/ blueprints

Home serves to identify interfaces whose methods may be objects. Other than that, the EJBLocalObject is the invoked from a nonlocal virtual machine. Any object equivalent of the EJBObject, and the EJBLocalHome J2EE Technology Center that’s a remote object must implement this interface. is the equivalent of EJBHome. Note that the same http://developer.java.sun.com/developer/ As you probably know, EJBs can only run inside EJB component can implement both interfaces products/j2ee/ a J2EE EJB container. The container abstracts many simultaneously, thus allowing remote access J2EE Tutorial of the low-level services from the application devel- through RMI and local access through a local http://java.sun.com/j2ee/ oper (you). One set of services that it abstracts is the method call. tutorial/ life-cycle management of the EJBs. The EJBHome The right pane of the figure shows the interfaces interface is used to create this abstraction and can used to create the actual implementation class. The

<> java.io.Serializable

javax.ejb package <> java.rmi.Remote <> EnterpriseBean <> <> EJBLocalObject EJBLocalHome <> <> EJBObject EJBHome <> <> <> EntityBean SessionBean MessageDrivenBean

be accessed remotely to create or find the actual EnterpriseBean interface is a serializable interface EJB component. The methods are invoked by the for creating the EJB component. The three types of remote client, but are executed by the container. EJBs supported in 2.0 are EntityBean, SessionBean, The EJBObject interface is used to define the and MessageDrivenBean. Each of these extends the business methods for your EJB component. The EntityBean interface. interface defines methods to access the actual EJB As an application developer, for each enterprise class and to remove it when it’s no longer needed. JavaBean in your application, you need to extend the The EJBObject is a delegator interface that dele- appropriate home and remote interfaces gates the actual execution of the business objects to (local/remote) and provide an implementation for the the enterprise bean. appropriate enterprise bean (entity/session/mes- The latest release of the EJB specification adds sagedrivenbean). classes and interfaces to support the concept of Details on developing the interfaces and classes colocated EJBs (local interfaces). As you can see in for your application’s EJBs will be covered in subse- the left pane of the figure, the local interfaces quent FAQs.

10 MAY 2002

Java COM Metrowerks Corp. www.wireless-studio.com

MAY 2002 11

Java COM DATABASE MANAGEMENT SYSTEMS

J2ME Optimizing Database Performance in J2EE Applications The best of both worlds J2SE J2EE The Java 2 Platform, Enterprise Edition (J2EE), is the platform of choice for implementing scalable and reliable enterprise applications WRITTEN BY from reusable components. But Java developers building enterprise- DIDIER CABANNES class J2EE applications face a quandary.

The object paradigm has proven objects whose classes have been highly interconnected, and it’s very

Home ideal for modeling a wide variety of real- declared “persistent-capable” and can important to know precisely which world scenarios. However, finding a be manipulated seamlessly by the Java objects have been stored with the data- Java-compatible data repository opti- language. base and which have not. Consider an e- mized for such applications has become That has been the promise of commerce application in which prod- a stumbling block. While object data- ODBMSs, which made their appearance ucts, customers, and orders are all base management systems (ODBMSs) in the mid-1990s as a solution designed linked together (see Figure 1). The object provide the convenience of transparent specifically for objects and thus better model naturally captures the interrela- persistence of Java objects, their client- suited for object development. With tionships of real-world applications. centric architecture has not scaled well ODBMSs, Java developers can define With transparent persistence, you wind in enterprise environments. Relational persistent Java classes in the same way up loading an entire closure of objects database management systems transient Java classes are defined in the even though you want to access only a (RDBMSs) do scale well, but map each application. single object (see Figure 2). While the object to a two-dimensional relational An apparent advantage of pure programmer wants to load only one cus- table. The increased overhead can object databases is the implementation tomer, the closure of instances reach- reduce application performance to a of transparent persistence that auto- able from this object recursively loads a crawl. mates the process of mapping persistent large portion of the database. Loading This article discusses the limits of data objects into the data repository. unneeded data in the Java VM limits using these two types of databases with With transparent persistence, you don’t concurrency and scalability. Java and suggests a better alternative for even have to alter your existing Java A simple customer query, for exam- J2EE – a hybrid database that combines classes to describe the persistent data ple, could also lock pending orders and the best features of both. Hybrid data- that’s permanently stored in the data- products purchased, even though this bases share with ODBMSs the ability to base (see Listing 1). That means you data was not requested and will remain map data stored in back-end databases don’t have to decide ahead of time, usu- unchanged. Such “overloading” is not a directly into an implementation-neutral ally during the design phase, which noticeable problem within a standalone Java representation. As with relational objects to include and exclude from the environment that manipulates a small systems, hybrid databases can scale to database. amount of data. However, in an enter- meet the performance requirements of Adding a new customer order into prise-class, multiuser, transaction- an enterprise-class J2EE application. the database is as simple as creating a intensive application, large portions of new object in Java. Persistent-capable data get locked and instantiated, limit- ODBMSs:The Hidden Headache of objects are transient until attached to a ing concurrency and scalability. Transparent Persistence persistent manager or to other persist- During the pilot phase of develop- Over the years, finding a database ent objects. ment, performance is usually accept- that’s both Java-compatible and scalable This convenience quickly becomes a able since the system is not running enough for enterprise-class J2EE appli- nightmare, however, when developing under heavy computational loads. But cations has not been easy. Ideally, a Java- scalable enterprise-class applications. with wider deployment and more users, compatible database should store Java In a typical application, objects are transaction rates can slow unacceptably

12 MAY 2002

Java COM Sun Microsystems www.sun.com/forte

MAY 2002 13

Java COM Infragistics, Inc. www.infragistics.com

14 MAY 2002

Java COM Infragistics, Inc. www.infragistics.com

MAY 2002 15

Java COM DATABASE MANAGEMENT SYSTEMS

as a massive amount of data – much of it The hard lesson, often learned at have two major advantages: a long, suc- unneeded – fills the pipeline. In the end, company expense, is that the ODBMS cessful track record of deployment in transparent persistence leads to a per- used to validate a pilot application must scalable, transaction-processing sys- formance black hole, requiring substan- be replaced by a relational database tems and a standard language, SQL. tial work to improve scalability, increase when the system goes into production. While the works well concurrency, and reduce network traffic. That’s the programming equivalent of a enough in banking applications where

J2ME To gain sufficient control over which heart transplant, setting development the -and- model reflects the objects stay persistent and which do schedules back by months. As we will two-dimensional world of ledgers and not, the ODBMS’s transparent persist- see, relational databases bring their own spreadsheets, it has proven more limited ence mechanism must be bypassed and set of problems in terms of overhead, in tracking highly interconnected infor- the ODBMS’s proprietary API used and can require 25–50% more Java code. mation. Relationship navigation com- instead. Developers must master the monly used in J2EE applications ODBMS’s proprietary API and then RDBMSs:The Frustration of requires extensive use of multitable invest the many hours required for the Object-Relational Mapping joins. But joins are computationally J2SE complex, trial-and-error process, which Java developers are hindered by rela- intensive, and each join is computed at has no guarantee of success. tional databases; however, RDBMSs do runtime to link information on-the-fly (see Listing 2). Reconstructing an order object with its line items from row-and- column tables requires two SQL queries and much coding. The same operation in an would require only one call. Moreover, relational sys- tems require the rebuilding of relation- J2EE ships between objects each time they’re accessed, substantially impacting per- formance. In today’s economy where business intelligence is key, the Java object model provides a more powerful mechanism for capturing real-world relationships

Home and concept commonalities. In the rela- tional model the relationships disap- pear and are replaced by primary keys; foreign keys, columns, and indexes; and often by intermediate tables (see Figure 3). In response to the demands from object developers, relational vendors have extended the relational model to FIGURE 1 UML diagram of a typical J2EE e-commerce application support objects, much the way C++ was an object extension of C. But just as C programmers did not fully embrace C++, Java programmers have remained skeptical of object extensions to what is clearly not an object-oriented environ- ment. The underlying model of object-rela- tional databases remains the same: rows and columns. As a result, the simplicity of the object model vanishes because classes, inheritance, and relationships must be mapped into tables – a struc- ture ill-suited to the task. Even a simple many-to-many relationship between two classes must be expressed using intermediate tables, with two associated indexes. Therefore, a cleanly designed Java application translated through the normalization process results in a thick- et of tables that must be recombined whenever an object is called by the application. The process adds signifi- cant load, especially when executing extensive table joins. To solve the problem of mapping FIGURE 2 The downfall of a transparent instantiation mechanism objects into relational databases, a

16 MAY 2002

Java COM Sitraka www.sitraka.com/jclass/jdj

MAY 2002 17

Java COM DATABASE MANAGEMENT SYSTEMS

ing contention as well as network traf- fic and taking advantage of the faster processing speeds of many server architectures. Like RDBMSs, hybrid databases support the SQL-99 syntax. While SQL

J2ME queries are relational in their syntax, they take advantage of the object para- digm by supporting inheritance, poly- morphism, and true navigation. Furthermore, the query processing takes place on the server to enforce security and achieve performance. Consider a broad query of two classes J2SE of customers: business and consumer. The query is issued from the client, exe- cuted on the server, with selected objects from each class retrieved to the client. This approach gives developers full access to Java objects through JDBC without having to learn a proprietary API (see Listing 4). In this listing, two J2EE FIGURE 3 Relational diagram customer subclasses, Consumer and Business, share properties from the par- number of OR mapping tools have been kind is needed. Unlike an ODBMS, a ent Customer class while maintaining created. While these tools do make it hybrid database enforces a layered properties of their own. A query to easier to develop Java applications that design of the persistent classes. The locate “good customers” can combine use relational databases, they don’t operations to manipulate objects are criteria – bonus miles for home con- eliminate the underlying RDBMS prob- explicit, enabling you to keep tight con- sumers, a high credit line for businesses

Home lems of code complexity and poor per- trol over the data that’s locked and – pulling the information simultaneous- formance. instantiated in the JVM, seamlessly ly from both subclasses. Unlike an Both database technologies have improving the application’s scalability. RDBMS, a hybrid database returns Java limitations for Java programming. A Hybrid databases eliminate the mis- objects through JDBC and natively sup- pure object database makes sense in a match between the Java and database ports inheritance. standalone environment in which con- environments, while still maintaining While developers still benefit from currency and network traffic are not the scalability of server-side processing, the power of expression and perform- issues. Relational databases, while such as relational systems. Within the ance of SQL queries, these queries elim- accommodating transaction-processing J2EE environment, you manipulate Java inate the object-relational mapping loads, merely simulate a true object objects representing a proxy to the layer to reduce source code by 25–50% environment. object in the database by means of and improve application performance. object-to-object mapping. The proxy Unlike first-generation ODBMSs, Hybrid Databases:The Best of Both Worlds objects are pure Java classes that map to hybrid databases can be accessed Hybrid databases represent the best those of the database schema (see through JDBC and ODBC drivers, both of both worlds: the ability to map Listing 3). With a hybrid database, the of which support the SQL-99 language, objects from Java directly to the data- code stays compact and object-based thereby taking advantage of in-house base with the support of a standard (as in Listing 1), providing the same ben- SQL expertise. Support for ODBC and query language (SQL-99) and the scala- efit as a first-generation ODBMS. Hybrid JDBC drivers also allows IT staff to use ble, enterprise capabilities implement- databases don’t require any of the spe- off-the-shelf database tools without ed in relational database products. cial compilation tricks or postprocess- having to master SQL. Designed from the ground up as a data- ing byte code manipulations of base server for objects, hybrid databases ODBMSs – both of which make it hard to First Major Optimization:Keep It Simple directly map the object model of Java as identify the root cause of performance Building enterprise-class J2EE appli- well as other object programming lan- degradation. cations with a hybrid database is guages. Because the database object In a typical application, classes are straightforward. Here are some consid- model matches perfectly with Java, you highly interconnected, and the graph of erations to make the process even can freely and easily define the database instances can include large portions of smoother: classes that describe real-world scenar- the database. Therefore, controlling • Carefully define the object model of ios. object-locking effectively, always a your persistent classes, reflecting the Unlike an RDBMS, a hybrid database challenge in enterprise-class J2EE business model as closely as possi- preserves the original Java data model. applications, is crucial to controlling ble. That’s common sense in an For example, a single class and two sub- the instantiation of Java objects in the object environment, but is even classes represent customers, con- JVM. To build scalable applications, more crucial in database applica- sumers, and business customers, data-intensive processing needs to take tions because the way you define the respectively. No tables are mapped back place where the data sits on the server, model greatly impacts system per- into Java objects; no translation of any not on the client, further reducing lock- formance.

18 MAY 2002

Java COM www.oracle.com/javacode

MAY 2002 19

Java COM DATABASE MANAGEMENT SYSTEMS

Defining the right level of granular- ity for your objects has a big payoff in Listing 1: Transparent persistence with an ODBMS terms of transaction rate because pmf.setConnectionURL(dbName); only the specific queried data gets pm = pmf.getPersistenceManager(); locked. tx = pm.currentTransaction(); • Avoid cross-referencing persistent tx.begin(); J2ME and transient objects as transient Order odr = new Order("Parrot", 2, 99.95); information can access persistent pm.makerPersistent(odr); // make the Order persist information, but not the other way Customer cstr = new Customer("Jay", "D", "Ho"); around. Doing so makes the applica- odr.orderedBy = cstr ; // the new Customer now persists by the mean of tion much more complex to manage attachment since the persistent objects loaded tx.commit(); pm.close(); from the database may need to be linked to transient information that’s J2SE not yet available. While a callback can Listing 2: The OR mapping layer adds 25–50% of ugly code also be used, it unnecessarily compli- String select = "select * from Order o where o.odr_id = ?"; cates program flow and can usually be pstmt = conn.prepareStatement(select); avoided with more ordered layering of pstmt.setLong(1, 10608974); the application. resultSet = pstmt.executeQuery(); • Keep transactions as short as possi- // Construct an instance of Order from its rows if (resultSet.next()) { ble. Long transactions will unneces- Order odr = new Order(resultSet.getLong("odr_id"), sarily lock data for long periods of resultSet.getString("ship_address"), time, making it unavailable to other

J2EE resultSet.getString("ship_carrier")); business transactions. } • In some cases, data is cached by the resultSet.close(); middleware, reducing contention, but it pstmt.close(); requires “dirty reads” (reading data without locking) from the database. A String select = "select * from lineItem l where l.odr_id = ? order by way around this is to use a versioning lt_id"; pstmt = conn.prepareStatement(select); facility, which allows a consistent pstmt.setLong(1, 10608974);

Home of the database any time, even while resultSet = pstmt.executeQuery(); users are modifying the current version. // Construct objects from rows while (resultSet.next()) { Conclusion LineItem litem = new LineItem(resultSet.getString("lt_id"), Hybrid databases give developers a resultSet.getString("quantity"), new and important option when select- resultSet.getBigDecimal("unit_price"), ing a database for their J2EE application. resultSet.getString("delivery_mode"), resultSet.getString("address")); Until now, Java developers have really odr.lineItems.add(litem); had just one viable option: an RDBMS. } Despite the drawbacks of the relational resultSet.close(); AUTHOR BIO model, only RDBMSs solved the per- pstmt.close(); Didier Cabannes, formance requirements intrinsic to chief technology enterprise applications. As for ODBMSs, officer at Fresher they haven’t even begun to meet these Listing 3: A hybrid database provides compactness and efficiency Information, is the requirements. Without that, an adapt- Database db("dbName"); chief architect of the able object model is irrelevant to large- db.open(); db.startTransaction(); Matisse database, a scale J2EE development. Customer cstr = new Customer(db, "Dee", "O", "Haye"); hybrid database for With hybrid databases, J2EE devel- Order odr = new Order(db, "Parrot", 1, 99.95); object developers. For opers can demand both: a database that odr.setOrderedBy(cstr) ; // the order and the customer are linked together the last 15 years, meets the intrinsic requirements of scal- by a bi-directional relationship he’s focused on ability, high transaction volumes, high- db.commit(); object and database volume data transfer, and the need for db.close(); technology, and fast throughput, together with an object Listing 4: With a hybrid database, SQL queries return objects, not tables developing and data model that more accurately repre- deploying sents business processes, now and in String query = "select REF(c) from Customer c where count(orders) > 20" + "AND ((class Consumer).bonusMiles > 50000 OR" + mission-critical the future. "(class Business).creditLine > 10000) ORDER BY lastName"; object-based As the number of J2EE applications stmt = conn.createStatement(); applications in a grows, the limitations of RDBMSs and resultSet = stmt.executeQuery(select); variety of ODBMSs will become more and more while (resultSet.next()) { environments. He apparent. Hybrid databases represent Customer cstr = (Customer)resultSet.getObject(1); // instances of holds a master’s the missing ingredient for broader J2EE Consumer or Business are actually returned degree in engineering implementation, providing scalability } and has conducted without compromising Java’s object resultSet.close(); stmt.close(); post-graduate environment. research in computer science. [email protected]

20 MAY 2002

Java COM Compuware Corp. www.compuware.com/products/optimalj

MAY 2002 21

Java COM J2ME J2SE J2EE Home

Anyone with any application experience knows that the Microsoft DCOM, they’re still left a blank slate when develop- application development process is fraught with unknowns. In ment begins. This opens up questions like “Where do I start?” the networked applications space, the unknowns can be even “How does all of this technology – EJBs or JMS or DCOM or more extreme when it comes to the gap between the technical .NET – help me with what I’m building?” “How do I glue it all infrastructure – application servers – and the actual business together to get to my end application?” Infrastructure tech- requirements. More specifically, the architectural issues alone nology often leaves the developer with more options than in the “developing the application” stage are often left to the answers. developer or distributed to architectural teams. Several pitfalls can arise in the critical architectural stage: • Many developers are solving the same technical problems. Take, for example, an e-commerce site. How are decisions • Developers don’t know where to start when building an such as how to maintain a catalog applied across a project? If application. the tasks are split up, a developer focused on just one aspect of Often a developer allows the user interface (UI) to drive the the application has his or her own deadlines and likely won’t business requirements and begins to code. A typical mistake is have the time or inclination to share this information with that the UI developer goes too far when extending the presen- others. From a technical perspective, this evolves into more tation logic with actual business functionality. It then becomes critical decisions, such as how to manage data persistence or difficult to decouple the functionality and share it across the validation. For example, “How do I manage input from an application, or the developer gets backed into a corner when HTML form or data type validation?” “What does my valida- faced with more difficult issues like data persistence. tion routine look like?” “What is a valid address?” “How do I call an EJB and what are the steps to do this?” It’s easy to see • Developers have difficulty with the steps needed to success- how the development team quickly focuses on nitty-gritty fully build an application. details, not on the application itself. Not only are developers Even if a development team has been sufficiently trained trying to solve the same problems, they’re also not sharing in the infrastructure technology, such as WebLogic or these decisions.

22 MAY 2002

Java COM Precise Software www.precise.com/jdj

MAY 2002 23

Java COM • Project managers don’t know what to expect from develop- oped and its rules. ers. Sometimes the infrastructure provided by J2EE application Take, for example, a developer who tells his or her manag- servers or the technical plumbing provided by a collection of er that it will take two months to develop the “user flow expe- third-party class libraries is confused with application archi- rience.” How does the project manager judge this answer tecture. Infrastructure components are required for an appli- when he or she doesn’t have insight into the technical deci- cation, but their role in a distributed application is to provide sions to a working application? some “technology feature” such as transaction management,

J2ME thread management, or distribution. The infrastructure, how- • Project managers can’t easily assign work based on devel- ever, stops short of determining how the application needs to opers’ skills, as the delineation of work is often nebulous. behave. How do you separate tasks such as business logic from the Application architecture gives development teams the user interface or from integration? How do you make sure the structure for the application and eliminates a significant user interface doesn’t extend too far into the business code? amount of the coding effort. This structure shields the devel- This often forces a developer to tackle more issues than he or oper from common development mistakes by providing a bet- she needs to, such as addressing security and distribution. ter format that eliminates redundancy and inconsistent code J2SE Developers start dealing with not just one class but 10 classes and by bringing the actual development closer to the business equaling thousands of lines of code and often don’t have the requirements. Application architecture is reusable across proj- domain expertise sets to do the work. ects allowing: • Developer resources to be transferable between projects • The application is hard to maintain and extend. • Lower costs due to not reinventing the wheel Applications built without architecture are extremely diffi- • Lower maintenance costs due to a uniform approach cult to update, extend, and modify for basic bug fixes and • Lower training costs modifications, as well as for more robust overhauls, to meet changing business requirements. Developers tasked with In the not so distant past, a developer’s productivity was J2EE updating applications spend a majority of their time locating measured by how much code he or she wrote. Today, in a the specific areas they have to change and carefully modifying world of increasing development complexity and time those areas so as not to break another part of the application. demands, less is more. Less code means less to create, less to maintain, and less to execute. • The delineation between the technical details and business logic or functionality of the application is not clear. Application Architecture Approaches:Ignore It,Build It,or ??? This is most often found when handling persistence In the long history of enterprise applications, there are two

Home in the application, such as how to interact with answers when approaching application architecture issues: The nature of the beast in application delivery is that deadlines are looming. “ The end result is the application, not the document, so teams will cut corners where they need to”

the data store. Do you use EJBs to interact “don’t have one” or “build one.” By definition, architecture is with the data store or data access objects? Are the structure of an application. If you have an application, you you directly calling your EJBs or using Session have an application architecture. Facade for this interaction? If your development team’s If you chose the “don’t have one” approach, what actually not careful, they’ve coupled those decisions to the application. occurs is architecture that “just happens.” Developers make Often, trouble is not uncovered until the testing phase. At this critical application decisions in isolation or don’t apply deci- point, the cost of overhauling the application is very high. sions consistently across the application. If you chose “build one”, whether it’s your first, second, or The bottom line is that the architectural issues behind third application, the architectural issues you need to address developing enterprise applications are significant. Without a are significant. structure in place, developers are left with undocumented pro- • How are development teams reusing the architecture? How cedures or a verbal design philosophy to guide their develop- is it being implemented? ment. On top of this, anything ambiguous is left to the team to • How is it documented? How do I train development teams work out. The nature of the beast in application delivery is that to use it? deadlines are looming. The end result is the application, not • Is it current? How will you port the architecture as the the document, so teams will cut corners where they need to. underlying infrastructure technology changes? • How do you plan to maintain the current architecture? The Importance of Application Architecture How do you plan for continually changing resources? The Role of Application Architecture How do you take advantage of emerging technologies, Where are the above issues most appropriately addressed? such as Web services, if your original resources on the This is the role of application architecture – a very critical step project left? in the application-development process. Unfortunately, this • What if consultants don’t want to work with the current step is often lumped with “develop the application.” The appli- framework because of “spaghetti code” syndrome and are cation architecture determines how the application is devel- proposing a new approach?

24 MAY 2002

Java COM Canoo Engineering AG www.canoo.com/ulc/

MAY 2002 25

Java COM This is just the beginning. Given that development teams Results of Building – The 3 Ps are measured on the delivery of the application, not on the The building process results in three types of architec- “purity” of the architecture, this results in either paper-based ture: a paper one, one that a single programmer uses, or one or poorly documented implementations that only get used by that a single project uses – paper, programmer, project – the a single programmer or single project. If problems do arise as 3Ps. a result of the architecture, there’s little chance to correct it. As The paper architecture is actually not an architecture; that development teams generally need to move on to the next is, it isn’t physical code, therefore it leaves the developer at

J2ME project, there’s little time allocated to perfecting it. If the appli- square one when it comes time to build it. Paper architectures cation is functioning, the “if it ain’t broke, don’t fix it” mantra usually result when there’s a central think-tank group that rings true when it comes to architecture. determines the overall technical direction. While important architectural decisions are made, the actual code still needs to Problems with Building Architecture be written for the architecture. Revisiting where architecture typically fits in the applica- The programmer architecture involves an individual pro- tion development life cycle, it’s easy to see why time is a prob- grammer who builds the application architecture. More lem. The architecture is usually squeezed between design and than likely other programmers on the same team are solving J2SE development. The customer of the application probably does- the same problems in their parts of the application. So you n’t care about the architecture and very likely wouldn’t under- have a single project with little or no consistency across stand it. Because architecture is an intermediate result, quite developers. often it’s not given the proper attention it deserves. The archi- The project architect is the best possible outcome in a tecture is usually the first thing to give way when there’s a build situation. The need for an architecture has been recog- schedule crunch. Typically, the design stage runs over and the nized, but the architecture is likely limited to the project for final deadline isn’t flexible. Architecture usually suffers first. which it was built. Because the architecture was made to The skills required to build a quality architecture are in solve the problems of one project, it probably won’t be short supply, making the cost to build it prohibitive. Recent reusable across other projects. Since the architecture wasn’t a J2EE studies show that firms need to budget as much as $3,500 a day tangible goal of the project, it likely won’t be documented nor for one architect in the J2EE arena (Forrester Research, “Putting will it continue to evolve. In short, it starts and ends with the J2EE to Work,” July 2001). One firm claimed that it would take project. them 12 months just to build the development framework needed to support the application. Architecture marries the Buying Application Architecture business application to the technology infrastructure, and Why do companies historically build architectures? requires the architecture builder to be intimately familiar with Usually, there’s no alternative. If the infrastructure technol-

Home application building and the technical infrastructure. ogy used by a company is unique, then it’s not likely that The last problem encountered when building an architec- they would find a commercially available architecture to ture is the need for iterative development. Consider the evo- support the infrastructure. However, with infrastructure lution of the application develop- standardizing around platforms like J2EE and .NET, buying ment life cycle. Not too long an application architecture is a viable alternative. It not only ago, the waterfall approach eliminates the build challenges discussed earlier, it also pro- was very popular. This vides many benefits such as best practices, future-proofing As companies build more sophisticated “ enterprise applications, proceeding without a proven architecture will be folly”

approach broke the work into large chunks (requirements, of the application, significant costs savings, and quicker design, development, etc.) that were done sequentially over time-to-market. a long period of time. The current trend in application devel- opment is to use an iterative approach. The steps taken are Best Practices similar to the old process (e.g., requirements, design, devel- Best practices for application architecture include those for opment, etc.) but they’re executed in an iterative fashion developing code as well as for solving the architectural prob- over short periods of time. Using small iterations means lems. Becoming familiar with these best practices is done results are seen sooner and feedback is incorporated more through experience and shared industry expertise. In the world often, resulting in a better product. This same approach is of enterprise applications, an increasingly important source of required for a high-quality architecture. Iterations are this industry expertise is design patterns, such as the J2EE required to refine the architecture and prove its validity. Blueprints or object-oriented patterns. Design patterns capture However, architecture iterations are close to impossible to a problem definition and a possible solution in a textual format, incorporate into an application development life cycle allowing people to share their experiences with others to avoid because of the logistics involved. The developer training, similar problems. Implementing these patterns while staying application rewrites, and delivery schedule hinder incorpo- on top of best practices requires constant attention that only a rating architecture iterations. vendor who is providing the solution can realistically afford.

26 MAY 2002

Java COM SpiritSoft www.spiritsoft.com/climber

MAY 2002 27

Java COM Future-Proofing Applications A good application architecture will provide a longer life for your application. Incorporated as a product, the architec- ture allows the application to easily adopt new functionality and isolates the application from technology changes PUBLISHER,PRESIDENT,AND CEO whether it’s upgrading to a new version of a J2EE application FUAT A. KIRCAALI [email protected] VICE PRESIDENT,BUSINESS DEVELOPMENT server or taking advantage of emerging Web services func- GRISHA DAVIDA [email protected] J2ME tionality. CHIEF OPERATING OFFICER MARK HARABEDIAN [email protected] Less Time and Lower Cost A very immediate benefit of purchasing an application ADVERTISING architecture is lowering the cost of building the application SENIOR VICE PRESIDENT,SALES AND MARKETING and accelerating the application creation. Many companies CARMEN GONZALEZ [email protected] VICE PRESIDENT,SALES AND MARKETING are realizing that it’s taking 12 months just to get their devel- MILES SILVERMAN [email protected] opment framework or application architecture implemented. ADVERTISING SALES DIRECTOR J2SE That’s not even taking into account the actual construction of ROBYN FORMA [email protected] the business application itself. ADVERTISING ACCOUNT MANAGER A good application architecture product needs: MEGAN RING [email protected] ASSOCIATE SALES MANAGERS • To be tested, proven, and built on industry best practices CARRIE GEBERT [email protected] • To have extensive documentation KRISTIN KUHNLE [email protected] • To be supported by a company that’s focused on providing ALISA CATALANO [email protected] architecture and that will continue to maintain and extend LEAH HITTMAN [email protected] EDITORIAL the offering EXECUTIVE EDITOR • To provide formal training to get the application team up to J2EE NANCY VALENTINE [email protected] speed quickly EDITOR M’LOU PINKHAM [email protected] Just as in the early days of object-oriented, Java, and Web MANAGING EDITOR application development, many companies attempted to CHERYL VAN SISE [email protected] ASSOCIATE EDITORS build their own distributed services (load balancing, security, JAMIE MATUSOW [email protected] dynamic page generation, and scripting) to support their GAIL SCHULTZ [email protected] applications. Tackling this in-house was cost-prohibitive, in JEAN CASSIDY [email protected] ONLINE EDITOR Home terms of time-to-market and maintenance, and opened a door for an application server market in which lead vendors LIN GOETZ [email protected] PRODUCTION assumed the role of providing this infrastructure (BEA, IBM, VICE PRESIDENT,PRODUCTION AND DESIGN and others). Can you imagine having a conversation with JIM MORGAN [email protected] your CIO about wanting to build your own application serv- LEAD DESIGNER er? LOUIS F. CUFFARI [email protected] As companies build more sophisticated enterprise appli- ART DIRECTOR cations, proceeding without a proven architecture will be ALEX BOTERO [email protected] ASSOCIATE ART DIRECTORS folly. How you approach application architecture and address CATHRYN BURAK [email protected] its considerations across the application, as well as across RICHARD SILVERBERG [email protected] future applications, is increasingly critical to your overall AARATHI VENKATARAMAN [email protected] ASSISTANT ART DIRECTOR success. TAMI BEATTY [email protected] WEB SERVICES Conclusion WEBMASTER Application architecture is critical to the initial suc- ROBERT DIAMOND [email protected] cess of an application and the ongoing success of main- WEB DESIGNERS STEPHEN KILMURRAY [email protected] taining and extending it. Companies have historically CHRISTOPHER CROCE [email protected] built their own development frameworks with varying A CCOUNTING degrees of success. With no other options available, devel- CHIEF FINANCIAL OFFICER opment teams were left to poorly documented, unrepeat- BRUCE KANNER [email protected] able application architectures. ASSISTANT CONTROLLER JUDITH CALNAN [email protected] As standard technical infrastructures such as J2EE and ACCOUNTS RECEIVABLE .NET continue to mature over time, development teams JAN BRAIDECH [email protected] AUTHOR BIO will gather more enterprise experience grappling with ACCOUNTS PAYABLE Walter Hurst is the how best to divide up work tasks, utilize the infrastructure JOAN LAROSE [email protected] ACCOUNTING CLERK CTO and cofounder technology, and deliver applications on time. With grow- BETTY WHITE [email protected] of Wakesoft, a ing industry acceptance of these infrastructures, vendors SYS-CON EVENTS provider of prebuilt are delivering tools and frameworks to ease the next level VICE PRESIDENT,SYS-CON EVENTS application of application development for many project teams, CATHY WALTERS [email protected] architecture and allowing them to focus on the business requirements at CONFERENCE MANAGER MICHAEL LYNCH [email protected] frameworks for J2EE. hand and obviating the need to deal with what will soon SALES EXECUTIVES,EXHIBITS He received a BS become mundane development tasks. Nowhere will this MICHAEL PESICK [email protected] in computer be more apparent than in the area of application architec- RICHARD ANDERSON [email protected] engineering from the ture. C USTO MER RELATIONS/JDJ STORE University of MANAGER,CUSTOMER RELATIONS/JDJ STORE ANTHONY D. SPITZER [email protected] Michigan. [email protected]

28 MAY 2002

Java COM SilverStream Software www.silverstream.com/coals

MAY 2002 29

Java COM J2ME Jim Balsillie John Gage Scott Relf Scott McNealy Amit Pau

FirstImpressions WRITTEN BY AJIT SAGAR J2SE 2002 Show Review

un’s seventh annual JavaOne con- J2EE ference was held March 25–28 at Sthe Moscone Center in downtown San Francisco. This was the sixth Java conference I attended and it was inter- esting to compare it with the previous shows.

Home It’s All About Networking JavaOne, as always, is a great confer- the past. However, the ence for networking. And I don’t mean majority felt that the the networking that requires wires for exhibition hall and the connectivity. I’m referring to people vendor demos were very hooking up with others who are using interesting. Many felt the Java platform to solve business that by attending the conference, they • 10 media cosponsors problems. This JavaOne was no differ- had generated leads they normally • 300 in-depth technical sessions ent. I chatted with several attendees wouldn’t have. On the other hand, the • 200 birds-of-a-feather sessions about what they expected from the con- information in the sessions could have ference, and what they got out of it. easily been picked up on the Internet. Attendance The majority felt the conference was Most attendees felt that their trip to My first impression was that atten- a great way to generate leads and to get JavaOne gave them a better understand- dance was down, and the atmosphere an idea of who else was leveraging Java ing of what’s available in the market to was more sober than in previous years. and how; shared experiences, war sto- build real-world applications. The obvious reason for this was that ries, and potential alliances were some Based on estimates at Sun’s site, companies have cut back on spending of the outcomes. Many of the attendees there were: and it’s hard to justify using already- who had been at previous JavaOnes felt • Over 50 countries represented stretched resources. Another thing of the sessions were not as exciting as in • Over 350 members of the press note was that international representa- • 35 cosponsors tion was not as high as in previous years. • 200 exhibitors Again, with concerns over safety and travel expenses, this wasn’t unexpected. In addition, the conference took place during the week of Passover, ruling out atten- dance from the Jewish community. This year’s attendance seemed domi- nated by the Bay area folks and seemed to consist of seasoned developers who were involved in the devel- opment of real-world ap- plications. I didn’t come across many newbies in the crowd.

30 MAY 2002

JJavaava COMCOM Altova www.altova.com

MAY 2002 31

Java COM J2ME Ernie Cormier Rob Gingell Alfred Chuang Hasso Plattner Rich Green Bill Boggess

The Message ty, and enterprise applications based on – I felt they were more balanced this The message was clear. Sun’s new J2EE were the cornerstones of the con- year. Monday’s presentation indicated logo “We make the Net work” seems a lot ference. that Sun was supporting Web services more palatable than “The network is the initiatives, and the Java platform has computer.” The Java platform is coming Keynotes ample specifications and tools coming of age and it’s all about enabling the Besides Sun’s keynote presentations down the pipe to support building dis- J2SE development of distributed applica- on the vision of Java technology and tributed applications based on Web tions. The maturity of the products dis- Web services, additional themes cen- services. played in the exhibition hall was quite tered around the role of Java in wireless apparent. The main additions to the and small devices, enterprise integra- Technology Showcase platform consisted mostly of the tion, and telecommunications. Unlike The Sharp Zaurus PDA, bundled enabling APIs for developing Web ser- last year, when the keynotes focused on with the Linksys 802.11b wireless net- vices. Web services, wireless connectivi- Web services – then the brand-new fad work card, was the official device pro- moted this year. It was available to attendees at a special show price of J2EE $299, way below market price. The Technology Showcase featured Per- sonalJava technology, SOAP, Web serv- ices, JXTA, JXTA for J2ME, and an 802.11b wireless network. Developers used this device to work through the competitions hosted at the conference

Home – “What Time Is It?” and the “Hack- athon.”

INT, Inc www.int.com

32 MAY 2002

Java COM DataDirect Technologies www.datadirect-technologies.com

MAY 2002 33

Java COM J2ME Paul Saffo Blake Stone Patricia Sueltz Jason Hunter Jeff Jackson Ivo Toter

Session Themes As mentioned earlier, Web services was one of the themes of the conference, but the content of the sessions was much more balanced. I attended some of the sessions under the “Java J2SE Technologies, Products, Solutions, and You” track and was quite happy to find that others in the industry have faced similar victories and defeats with Java technologies. Overall, the real-world examples of applications were reassur- ing, as they indicated the commitment Java has from leading companies around the world. design patterns, archi- mental and more geared J2EE There were few sessions on new APIs tecture, and language toward supporting serious for the simple reason that the Java plat- usage. developers working on seri- form hasn’t added major modules to the ous applications. The Java framework. This is a good thing, as it Pavilion tools market has matured a indicates a maturing of the platform. The pavilion was, for lot in the past couple of Sessions that introduced new modules me, the most interesting part of the years. This was evident by the fact that centered around Java 1.4, EJB2.1, the show. I met with most of the vendors on most of the IDE vendors were exhibiting

Home Java XML Service Pack, and the Sun ONE the exhibit floor and was very tools that addressed integrated applica- Web Services initiative. There were also impressed by the products coming out tion development (instead of stand- several interesting sessions on Java in the Java market. They are less experi- alone), enterprise application testing,

This year’s JavaOne was a testimony to how far Java has come toward becoming a mature “ and robust platform

debugging, and logging. The design tools offer environ- ments that allow developers and business process mod- elers to work at more abstract levels. The application server vendors who showed up at the conference are the ones who have emerged with solid products in” the Java Capella market. The vendor booths were more spread out in the exhibit hall, primarily because there were fewer vendors than in previous years. However, there was traffic throughout the day, which indicated that most of the University attendees were seriously interested in what the vendors had to offer. It also seems like marketing budgets have been replenished, as there were more toys, T-shirts, etc., handed out.

www.capellauniversity.edu SYS-CON Radio At SYS-CON’s popular radio booth, leading vendors and industry luminaries were interviewed throughout the day. I interviewed several of the vendor representa- tives and, overall, the mood was enthusiastic and upbeat. All in all, this year’s JavaOne was a testimony to how far Java has come toward becoming a mature and robust platform that’s widely adopted by the comput- ing industry.

34 MAY 2002

Java COM AltoWeb www.altoweb.com

MAY 2002 35

Java COM J2SEJ EDITORIALOR J2SE INDEXX

KEITH BROWN J2SE EDITOR We’ve Built the House If you read my editorial last month (JDJ, Vol. 7, issue 4), you’ll recall that I was try- ing to work out just who the Java community was and 36 whether or not you or I feel a J2SE part of it. Well, I think I met the community at We’ve Builtthe House JavaOne 2002. by Keith Brown

f you read my editorial last month (JDJ, Wendell Hicken, and Cynthia Dunlop and Vol. 7, issue 4), you’ll recall that I was published by Hungry Minds, Inc.), and Itrying to work out just who the Java how we, as developers, can ensure our Programming Neural community was and whether or not you or Web applications are reliable and consis- Networks in Java I feel a part of it. Well, I think I met the tent. The book contains an interesting sec- How to construct a simple, community at JavaOne 2002. tion on JSP, and the interview is well worth yet particle, neural network in During JavaOne we spoke to over 100 a listen (www.sys-con.com/java/javaone Java that can recognize 38 people at SYS-CON Radio, and recorded 2002b.cfm). handwritten letters, and and uploaded these conversations to JDJ’s Iain Shiegoka also gave a good implement a neural network Web site. Some are more interesting than overview of Java instant messaging and in a small sample program. by Jeff Heaton Homeothers, and J2EE some have more to offer the explains J2ME what it’s like to write these types Java developer. of books. His book, Instant Messaging in There’s a lot of jargon to wade through Java (Manning Publications), concen- in these interviews and it’s often tricky to trates on the open source Jabber XML- identify what it all means. based IM protocols (www.sys-con.com/ Better Scaling with Two years ago, the big thing that so java/javaone2002c.cfm). New I/O many companies were talking about was It was also nice to see a few familiar With J2SE version 1.4, application servers and how they were faces at the SYS-CON Radio booth, Java finally has a scalable I/O 46 going to save the world. That area of the including Ralf Dossmann from Borland, API. This article shows how to Java world has now consolidated and the the first person I ever interviewed; that write a simple Web server emphasis at JavaOne had progressed to first interview was two years ago at the with both the new and the the next stage – software to analyze our IBM Java Conference in Austria. Further old API. software! evidence that the Java community not by Hendrik Schreiber There was a major focus on testing and only exists, but is also persistent! performance tools. Java technology has In addition to talking with exhibitors matured to a point where applications and and attendees at the conference, there’s systems are now so widespread that the also a lot of socializing, a little gossip, and JDBC 3.0 – market is demanding tools to fine-tune a bit of eavesdropping – it can’t be helped. Something for Everyone the software’s efficiency and performance. One interesting discussion I overheard There was no We’ve built the house. Now we need to was about Swing’s JTree component. The ticker tape parade to accom- find out where those drafts are coming basic gist of the debate – that I might, pany the release of the JDBC from and fit some double-glazing. slightly tongue in cheek, agree with – was 3.0 specification, but many Besides the software-tuning vendors, that JTree should have a certification pro- will be pleasantly surprised it’s always interesting to speak to authors gram all its own. Perhaps a Sun Certified at its list of enhancements 56 and discuss their specific topics. As JTree Developer badge will be my next that include everything from authors, they tend to be effective commu- goal. Anyone who has wrestled with the performance-tuning options nicators and speak in a language develop- JTree and come out alive will know that it’s to support for extended-level ers are used to. not a particularly easy task to produce the database features. Adam Kolawa spoke to us animatedly tree you want. I was glad to hear others by John Goodson about his new book, Bulletproofing Web had the same experience. You’re not Applications (coauthored by Kolawa, alone!

[email protected] AUTHOR BIO Keith Brown has been involved with Java for many years.When he’s not coding up client solutions for a European Java company, he can be found lurking in the corridors of conferences all around the world.

36 MAY 2002

Java COM Addison-Wesley

MAY 2002 37

Java COM ARTIFICIAL INTELLIGENCE Programming NeuralNetworks in Java An efficient way to perform certain operations

omputers can perform many operations a lot faster J2SE C than humans. However, there are many tasks in which the com- puter falls considerably short. One such task is the interpretation of graphic information.A preschool child can easily tell the differ- WRITTEN BY ence between a cat and a dog, but this simple problem confounds JEFF HEATON today’s computers.

In the field of computer science, artifi- java -classpath OCR.jar MainEntry will be completed in a matter of sec- cial intelligence attempts to give comput- onds. A small popup will be displayed ers human abilities. One of the primary When the letter-recognition program when training is complete. When you means by which computers are endowed begins, there’s no data loaded initially. A save, only the character patterns are with humanlike abilities is through the training file must be used that contains saved. If you load these same patterns use of a neural network, which the human the shapes of the letters. An example later, you must retrain the network. brain is the ultimate example of. The training file (sample.dat) is preloaded You’ll now be shown how this exam- human brain consists of a network of over with the 26 capital letters. To see the ple program is constructed, and how you a billion interconnected neurons. These program work, click the “Load” button, can create similar programs. The file

Home J2EEare individual cells that can process small J2ME which loads the sample.dat file. Now 26 MainEntry.java contains the Swing amounts of information and then activate letter patterns are in memory and the application that makes up this applica- other neurons to continue the process. network must be trained. Click the tion, which is little more than placing the However, the term neural network, as it’s “Begin Training” button; now the net- components at their correct locations. normally used, is actually a misnomer. work is ready to recognize characters. The three areas this article focuses Computers attempt to simulate a neural Draw any capital letter you like and click on are downsampling, training, and network. However, most publications use “Recognize”; the program should now recognition. Downsampling, an algo- the term neural network rather than arti- recognize the letter. rithm used to reduce the resolution of ficial neural network. the letters being drawn, is used for char- This article shows how to construct a Training the Sample Program acter recognition and training, so we’ll neural network in Java; however, they Maybe my handwriting is consider- address this topic first. can be constructed in almost any pro- ably different than most people’s. (My first gramming language. Most publications grade teacher would certainly say so.) Downsampling the Image about neural networks use such com- What if you want to train the program All images are downsampled before puter languages as C, C++, Lisp, or specifically for your handwriting? To being used, which prevents the neural Prolog. Java is actually quite effective as replace a letter that’s already defined, you network from being confused by size and a neural network programming lan- must select and delete that letter first. position. The drawing area is large enough guage. This article shows you a simple, Pressing the “Delete” button does this. so you could draw a letter in several differ- yet particle, neural network that can rec- Now draw the character you wish to train ent sizes. By downsampling the image to a ognize handwritten letters, and the program for. If you’d like to see this consistent size, it won’t matter how large describes the implementation of a neu- letter downsampled before you add it, you draw the letter, as the downsampled ral network in a small sample program. click the “Downsample” button. If you’re image will always remain a consistent size. (All sample programs and source code happy with your letter, click the “Add” This section shows how this is done. for this article can be downloaded from button to add it to the training set. To save When you draw an image, the pro- www.sys-con.com/java/sourcec.cfm.) a copy of your newly created letters, click gram first draws a box around the the “Save” button and they’ll be written to boundary of your letter. This allows the Recognizing Letters the Sample.dat file. program to eliminate all the white space Using the sample program (shown in Once you’ve entered all the letters around your letter. This process is done Figure 1) you can see a neural network you want, you must now “train” the neu- inside the “downsample” method of the in action. For ease of distribution, the ral network. Up to this point you’ve sim- Entry.java class. As you draw a character, class files are packaged into a single JAR ply provided a training set of letters this character is also drawn onto the file named OCR.jar. To run the program, known as input patterns. With these “entryImage” instance variable of the use the following command (assuming input patterns, you’re now ready to train Entry object. To crop this image and you’re in the same directory as the JAR the network, which could take a lot of eventually downsample it, we must grab file). Some systems may allow you to time. However, since only one drawing the bit pattern of the image. This is done simply double-click the JAR file. sample per letter is allowed, this process using a PixelGrabber class:

38 MAY 2002

Java COM ESRI www.esri.com/mapobjectsjava

MAY 2002 39

Java COM ARTIFICIAL INTELLIGENCE

for ( int i=0;i

Home J2EE J2ME for ( int y=h-1;y>=0;y-- ) { dinate for the specified section, first the FIGURE 2 A small Kohonen network if ( !hLineClear(y) ) { “downSampleLeft” is used; this is the left downSampleBottom=y; side of the cropping rectangle. Then x is int w = entryImage.getWidth(this); break; multiplied by “ratioX”, the ratio of how int h = entryImage.getHeight(this); } many pixels make up each section. This } allows us to determine where to place PixelGrabber grabber = new “startX”. The starting y position, “startY”, PixelGrabber(entryImage, You can see how the program calcu- is calculated by similar means. Next the lates the top and bottom lines of the crop- program loops through every x and y 0,0,w,h,true); ping rectangle. To calculate the top line, covered by the specified section. If even grabber.grabPixels(); the program starts at 0 and continues to one pixel is determined to be filled, the pixelMap = (int[])grabber.getPixels(); the bottom of the image. As soon as the method returns true, which indicates first nonclear line is found, the program that this section should be considered After this code completes, the establishes this as the top of the clipping filled. pixelMap variable, which is an array of rectangle. The same process, only in The “downSampleQuadrant” met- int datatypes, now contains the bit pat- reverse, is carried out to determine the hod is called in succession for each sec- tern of the image. The next step is to bottom of the image. The processes to tion in the image. This results of the crop the image and remove any white determine the left and right boundaries sample image are stored in the space. Cropping is implemented by are carried out in the same way. “SampleData” class, a wrapper class that dragging four imaginary lines from the Now that the image has been cropped, contains a 5x7 array of Boolean values. top, left, bottom, and right sides of the it must be downsampled. This involves It’s this structure that forms the input to image. These lines will stop as soon as taking the image from a larger resolution both training and character recognition. they cross an actual pixel. By doing this, to a 5x7 resolution. To reduce an image to these lines snap to the outer edges of the 5x7, think of an imaginary grid being Neural Network Recognition image. The hLineClear and vLineClear drawn over the high-resolution image. There are many types of neural net- methods both accept a parameter that This divides the image into rectangular works, and most are named after their indicates the line to scan, and returns sections, five across and seven down. If creators. I’ll be using a Kohonen neural true if that line is clear. The program any pixel in a section is filled, the corre- network, a two-level network (see Figure works by calling hLineClear and sponding pixel in the 5x7 downsampled 2). The downsampled character pattern vLineClear until they cross the outer image is also filled. Most of the work done drawn by the user is fed to the input neu- edges of the image. The horizontal line by this process is accomplished inside the rons. There’s one input neuron for every method (hLineClear) is shown here. “downSampleQuadrant” method shown pixel in the downsampled image. Because here. the downsampled image is a 5x7 grid, protected boolean hLineClear(int y) there are 35 input neurons. { protected boolean down- Through the output neurons, the int w = entryImage.getWidth(this); SampleQuadrant(int x,int y) neural network communicates which

40 MAY 2002

Java COM Dice www.dice.com

MAY 2002 41

Java COM ARTIFICIAL INTELLIGENCE

letter it thinks the user drew. The num- input neurons by passing the input output[i] = 0.5 * (output[i] + ber of output neurons always matches array to the Kohonen’s “winner” 1.0) ; the number of unique letter samples method. This returns which of the 35 if ( output[i] > biggest ) { that were provided. Since 26 letters were neurons won and is stored in the “best” biggest = output[i] ; provided in the sample, there will be 26 integer. win = i ; output neurons. If this program were } modified to support multiple samples int best = net.winner ( input , norm- per letter, there would still be 26 output fac , synth ) ; Each output neuron’s weight is cal- neurons, even if there were multiple char map[] = mapNeurons(); culated by taking the dot product of samples per letter. each output neuron’s weights to the In addition to input and output neu- JOptionPane.showMessageDialog(this, input neurons. The dot product is calcu- rons, there are also connections " " + map[best] + " (Neuron #" lated by multiplying each of the input between the individual neurons. These + best + " fired)","That Letter Is", neuron’s input values against the connections are not all equal. Each is JOptionPane.PLAIN_MESSAGE); weights between that input neuron and assigned a weight, which is ultimately the output neuron. These weights were J2SE the only factor that determines what the Knowing the winning neuron is not determined during training, which is network will output for a given input too helpful because it doesn’t show you discussed in the next section. The out- pattern. To determine the total number which letter was recognized. To line up put is kept, and if it’s the largest output of connections, multiply the number of the neurons with their recognized let- so far, it’s set as the “winning” neuron. input neurons by the number of output ters, each letter image the network was As you can see, getting the results neurons. A neural network with 26 out- trained from must be fed into the net- from a neural network is a quick process. put neurons and 35 input neurons work and the winning neuron deter- Actually determining the weights of the would have a total of 910 connection mined. For example, if you were to feed neurons is the complex portion of this weights. The training process is dedicat- the training image for “J” into the neural process. Training the neural network is ed to finding the correct values for these network, and the winning neuron were discussed in the following section. weights. neuron #4, you would know that it’s the The recognition process begins one that had learned to recognize J’s How the Neural Network Learns when the user draws a character and pattern. This is done by calling the Learning is the process of selecting a then clicks the “Recognize” button. First “mapNeurons” method, which returns neuron weight matrix that will correctly the letter is downsampled to a 5x7 an array of characters. The index of each recognize input patterns. A Kohonen

Home J2EEimage. This image must be copied from J2ME array element corresponds to the neu- neural network learns by constantly its two-dimensional array to an array of ron number that recognizes that charac- evaluating and optimizing a weight doubles that will be fed to the input neu- ter. matrix. To do this, a starting weight rons. Most of the actual work performed matrix must be determined. This matrix by the neural network is done in the is chosen by selecting random numbers. entry.downSample(); winner method. The first thing the win- Of course, this is a terrible choice for a ner method does is normalize the inputs weight matrix, but it gives a starting double input[] = new double[5*7]; and calculate the output values of each point to optimize from. int idx=0; output neuron. The output neuron with Once the initial random weight SampleData ds = sample.getData(); the largest output value is considered matrix is created, the training can begin. for ( int y=0;y

42 MAY 2002 ” Java COM Rational Software www.rational.com/offer/javacd2

MAY 2002 43

Java COM ARTIFICIAL INTELLIGENCE

if ( bigerr[0] < quitError ) break ;

Neural networks should be If there is not an acceptable number considered anytime complex of winners, one neuron is forced to win. “ if ( (winners < patterns must be recognized outputNeuronCount) && (winners < train.getTrainingSetCount()) ) { number of characters the program has The learn method will loop up to forceWin ( won ) ; been given. an unspecified number of iterations. continue ; This is the part of the program that Because this program only has one } could be modified if you want it to sample per output neuron, it’s J2SE accept and train from more than one unlikely that it will take more” than Now that the first weight matrix has sample per letter. For example, if you one iteration. When the number of been evaluated, it’s adjusted based on its wanted to accept four samples per let- training samples matches the output error. The adjustment is slight, based on ter, you’d have to make sure that the neuron count, training occurs very the correction that was calculated when output neuron count remained 26, even quickly. the error was determined. This two-step though 104 input samples were provid- process of adjusting the error calculation ed to train with (4 for each of the 26 let- n_retry = 0 ; and adjusting the weight matrix is con- ters). for ( iter=0 ; ; iter++ ) { tinued until the error falls below 10%. Now that the size of the neural net- work has been determined, the training A method, “evaluateErrors”, is adjustWeights ( rate , set and neural network must be con- called to evaluate how well the current learnMethod , won , bigcorr, correc ) structed. The training set is constructed weights are working. This is deter- ; to hold the correct number of “sam- mined by looking at how well the ples.” This will be the 26 letters provid- training data spreads across the out- This is the process by which a neural ed. put neurons. If many output neurons network is trained. The method for

Home J2EE J2ME are activated for the same training adjusting the weights and calculating TrainingSet set = new Train- pattern, then the weight set is not a the error is shown in the KohonenNet- ingSet(inputNeuron,outputNeuron); good one. An error rate is calculated, work.java file. set.setTrainingSetCount(letterList- based on how well the training sets Model.size()); are spreading across the output neu- Conclusion rons. The example presented here is very Next, the downsampled input modular. The neural network Java files images are copied to the training set; evaluateErrors ( rate , learnMethod contained in this example are this is repeated for all 26 input patterns. , won , KohonenNetwork.java, Network.java, and bigerr , correc , work ) ; TrainingSet.java. These files do not per- for ( intt=0;t

44 MAY 2002

Java COM Prentice Hall PTR www.newatlanta.com

MAY 2002 45

Java COM Better Scaling with New

J2SE I/O

The end o f the thread/socket marriage written by Hendrik Schreiber Home J2EE J2ME

ith J2SE version 1.4, Java finally has a scalable I/O API. Not that the old API was an absolute failure (Java’s tremendous success in the application server market refutes this), but some of the old API’s properties led to drastic restrictions. The worst one was the blocking I/O.

46 MAY 2002

JJavaava COMCOM To write data over a socket, you have to call the write() method of an associated OutputStream. This call returns only after you’ve written all the necessary bytes. Given that the send buffers are full and the connection is slow, this might take a while. If your program operates only with a single thread, other connections have to wait, even if they’re ready to process write() calls. To work around this problem, you have to associ- ate a thread with each socket. This way one thread can work while another one is blocked due to I/O-related tasks. Threads aren’t as heavyweight as real processes. But, depending on the underlying platform, they’re not resource savers either. Each thread uses a certain amount of memory and, apart from that, many threads imply many thread-con- text switches, which aren’t cheap. Java needed a new API to separate the all-too-happy mar- riage of socket and thread. This finally happened with the new I/O API (java.nio.*). In this article I show how you can write a simple Web serv- er with both the new and the old API. Since HTTP, the Web’s protocol, is not as trivial as it used to be, I’ll realize only some simple central features. Therefore, the programs shown here are neither secure nor protocol-conforming. Old School Httpd Let’s look at the old-school HTTP server first (see Listing 1). (Listings 1–5 can be downloaded from www.sys-con.com/ java/sourcec.cfm.) Since I need only a single class for this real- ization, it’s quickly explained. In the main() method, a ServerSocket is instantiated and bound to port 8080. Of course, you’d usually bind a Web server to port 80, but on systems you can only do this with superuser rights. Fortunately, not everyone has them, which is why I chose to use port 8080.

public static void main() throws IOException { ServerSocket serverSocket = new ServerSocket(8080); for (int i=0; i < Integer.parseInt(args[0]); i++) { new Httpd(serverSocket); } }

Then a number of Httpd objects are created and initialized with the shared ServerSocket. In the Httpd’s constructor, I make sure all instances have a meaningful name, set a default protocol, and start the server by executing the start() method of its superclass Thread. This leads to an asynchronous call to the run() method, in which an infinite loop is located. In this infinite loop, the ServerSocket’s blocking accept() method is called. When a client connects to port 8080 of the server, the accept() method will return a socket object. Associated with each socket are an Input- and an OutputStream. Both are used in the following call to the handleRequest() method. In this method the client’s request is read, checked, and an appropriate response is sent back. If it’s a legitimate request, the requested file is sent back using sendFile(). If it’s not, the client will receive a corresponding error message (sendError()). To keep things simple, I won’t discuss the specifics of the protocol.

while (true) { ... socket = serverSocket.accept(); ... handleRequest(); ... socket.close(); }

MAY 2002 47

JJavaava COMCOM ow let’s think about this requires the cooperation of different threads. It con- realization for a second. Does sists of four classes (see Figure 1): it perform well? On the whole, 1. NIOHttpd (see Listing 2) yes. Certainly I could opti- 2. Acceptor (see Listing 3) mize the request parsing – the 3. Connection (see Listing 4) StringTokenizer doesn’t have 4. ConnectionSelector (see Listing 5) a reputation for being ex- tremely fast. But at least I NIOHttpd basically launches the server. Just as turned off the TCP delay in Httpd, a server socket is bound to port 8080. The (slow-start algorithm), which important difference is that this time I use a is unsuitable for short con- java.nio.channels.ServerSocketChannel instead of a nections, and the sending of ServerSocket. I need to open the channel with a fac- the file is buffered. But even tory method before binding it explicitly to the port Nmore important, all threads using the bind() method. Then I instantiate a operate independently of ConnectionSelector and an Acceptor. Doing so, J2SE each other. The native, and each ConnectionSelector is registered with an therefore fast, accept() method decides which thread Acceptor. In addition, the Acceptor is provided with accepts a new connection. Apart from the the ServerSocketChannel. ServerSocket object, the threads don’t share any resources that might need to be synchronized. This public static void main() throws IOException { solution is fast but, unfortunately, not very scalable, ServerSocketChannel ssc = as threads are definitely a limited resource. ServerSocketChannel.open(); ssc.socket().bind(new Nonblocking Httpd InetSocketAddress(8080)); Let’s look at another solution that uses the new ConnectionSelector cs = new I/O package. It’s a bit more complicated and ConnectionSelector(); new Acceptor(ssc, cs); }

Figure 2 depicts the concurrent execution of the

Home J2EE J2ME Acceptor and ConnectionSelector threads. To understand the interaction between the two threads, let’s first take a closer look at the Acceptor. Its task is to accept incoming connections and reg- ister them with the ConnectionSelector. Already in the constructor, the superclass’s start() method is called as the required infinite loop is in the run() method. In this loop a blocking accept() method is called that will eventually return a socket object – almost exactly as in Httpd. But this time it’s a ServerSocketChannel’s accept() method, not a ServerSocket’s. Finally, with the obtained socket- Channel as an argument, a connection object is cre- ated and registered with the Connection- Selector using its queue() method.

while (true) { ... socketChannel = serverSocketChannel.accept(); connectionSelector.queue(new Connection(socketChannel)); ... }

To summarize: the Acceptor can only accept and register connections with a ConnectionSelector in an endless loop. Like Acceptor, the ConnectionSelector is also a thread. In its constructor a queue is instantiated and a java.nio.channels.Selector is opened using the fac- tory method Selector.open(). The Selector is proba- bly the most important part of the server. It allows me to register connections and to obtain a list of those connections that are ready for reading or writ- FIGURE 1: Class diagram for NIOHttpd ing.

48 MAY 2002

Java COM Mongoose Technology www.portalstudio.com

MAY 2002 49

Java COM After the start() method is called in the construc- if (!queue.isEmpty()) { tor, the endless loop in run() is executed. In this loop synchronized (queue) { I call the Selector’s select() method. This method while (!queue.isEmpty()) { blocks until either one of the registered connections Connection connection = is ready for I/O operations or the Selector’s wake- up() method is called. (Connection)queue.remove(queue.size()-1); connection.register(selector); while (true) { } ... } int i = selector.select(); } registerQueuedConnections(); ... Selector Registration Using Keys // handle connections… At this point I have to focus on the Connection’s } register() method. Until now I’ve talked about a con- nection that’s registered with a Selector. This is a bit J2SE It’s crucial to understand that while the simplified. Instead, a java.nio.channels.Socket- ConnectionSelector thread executes select(), no Channel object is registered with a Selector, but only Acceptor thread can register connections with the for specific I/O operations. After registration, a Selector, because the corresponding methods are java.nio.channels.SelectionKey is returned. This key synchronized. Therefore I use a queue, to which the can be associated with arbitrary objects using its Acceptor thread adds connections as needed. attach() method. To get a connection with a key, I attach the Connection object to the key. By doing so public void queue(Connection connection) { I can indirectly obtain a Connection from the synchronized (queue) { Selector. queue.add(connection); } public void register(Selector selector) selector.wakeup(); throws IOException { } key = socketChannel.register(selector, SelectionKey.OP_READ); Right after queuing a connection, the Acceptor key.attach(this);

Home J2EEcalls the Selector’s J2ME wakeup() method. This causes } the ConnectionSelector thread to resume execution and return from the blocking select() call. Since the Getting back to the ConnectionSelector, the Selector is not blocked anymore, the Connection- select() method’s return value indicates how many Selector can now register the connection from the connections are ready for I/O operations. If the return queue. It happens the following way in register- value is zero, I skip the rest and return to the select() QueuedConnections(): call. Otherwise, I iterate over the selection keys, which I obtained as Set by calling selectedKeys(). From the keys I get the previously attached Connection objects and call their readRequest() or writeResponse() meth- ods. Which method is actually called depends on whether the connections were registered for read or write operations. This eventually brings me back to the Connection class. It represents the connection and handles all the protocol’s specifics. In its constructor the provided SocketChannel is set to nonblocking mode. This is essential for the serv- er. Then a couple of default values are set and the buffer requestLineBuffer is allocated. As the allocation of direct buffers is somewhat expen- sive and I’m using a new buffer for each connec- tion, I use java.nio.ByteBuffer.allocate() instead of ByteBuffer.allocateDirect(). If I reuse the buffer, a direct buffer could prove to be more efficient.

public Connection(SocketChannel socketChannel) throws IOException { this.socketChannel = socketChannel; ... socketChannel.configureBlocking(false); requestLineBuffer = ByteBuffer.allocate(512); ... FIGURE 2: Sequence diagram for NIOHttpd }

50 MAY 2002

Java COM Parasoft Corporation www.parasoft.com/jdj5

MAY 2002 51

Java COM After all initializations are done and the If all data is transferred, close() does the clean- SocketChannel is ready for reading, the readRe- up work. Here, the deregistering of the Connection quest() method is called by the ConnectionSelector. is important. This is achieved by calling the selec- Using socketChannel.read(requestLineBuffer), all tion key’s cancel() method. available bytes are read into the buffer. If the full line can’t be read, I return to the calling Con- public void close() { nectionSelector and thus allow another connection ... to take over. However, if the whole line is read, it’s if (key != ) key.cancel(); time to interpret the request just as I did in Httpd. If ... it’s a legitimate request, I create a java } .nio.Channels.FileChannel for the requested file and call the method prepareForResponse(). Again I wonder: How does this realization per- form? And again I can answer: it performs well. private void prepareForResponse() throws In principle, one Acceptor and one Connection- IOException { Selector are sufficient to keep an arbitrary number J2SE StringBuffer responseLine = new of connections open. Thus this realization shines in StringBuffer(128); the category of scalability. But as the two threads ... have to communicate through the synchronized responseLineBuffer = ByteBuffer.wrap( queue() method, they might block each other. There responseLine.toString().getBytes("ASCII") are two ways out of this dilemma: ); 1. A better realization of the queue key.interestOps(SelectionKey.OP_WRITE); 2. Multiple Acceptor/ConnectionSelector pairs key.selector().wakeup(); } One solution could be realized by using a LinkedQueue (see Concurrent Programming in Java prepareForResponse() builds the response line by Doug Lea). This data structure is synchronized and (if necessary) headers as well as error messages, with two independent locks – one for the head and and writes this data to responseLineBuffer. This one for the tail. This ensures that adding and remov- ByteBuffer is a thin wrapper around a byte array that ing threads don’t block each other. Only if the queue was created using the factory method Byte- is empty is there a possibility of mutual blocking,

Home J2EEBuffer.wrap(byte[]). J2ME After generating the data that I but this can be avoided with an extra check. want to write, I need to notify the Con- In comparison to this elegant approach, my sec- nectionSelector that from now on I want to write ond solution qualifies for the “brute force” category. data rather than read it. This is achieved by calling The load is balanced with multiple Acceptor/ the selection key’s method interestedOps(Sel- ConnectionSelector pairs and the synchronization ectionKey.OP_WRITE). To guarantee that the selec- problem isn’t solved, but is somewhat reduced. tor quickly realizes the connection’s change of inter- Unfortunately, this causes additional costs for con- est, I call its wakeup() method. text switches. Compared to Httpd, fewer threads are Now the ConnectionSelector calls the connec- needed. tion’s writeResponse() method. First, the response- One disadvantage to NIOHttpd, in comparison LineBuffer is written to the socket channel. If the to Httpd, is that for each request, a new Connection entire content of the buffer can be written, and if I object with buffers is created. This leads to an addi- still have to send the requested file, I call the tional CPU cycle burning caused by the garbage col- transferTo() method of the FileChannel that I lector. How large these extra costs are depends on opened before. transferTo() potentially transfers the VM. However, Sun doesn’t tire of emphasizing data very efficiently from a file to a channel. How that with Hotspot, short-lived objects are not a efficiently depends on the underlying operating sys- problem anymore. tem. In any case, only as many bytes are transferred as can be written to the target channel without Comparative Number Games blocking. To be on the safe side and to ensure fair- How much better does NIOHttpd scale than ness between connections, I set an upper limit of Httpd? Let’s play with a couple of numbers, but 64KB. before I go into media res, be warned: the formulas and the numbers I’m going to find are highly specu- lative. Only the concepts’ performance is estimated. b in bytes/s s in bytesd for–> ∞ 1/d Important context variables like thread synchro- 8000 1000 0.89 1.13 nization, context switches, paging, hard disk speed, 8000 10000 0.44 2.25 and caches are not considered. 8000 100000 0.07 13.5 First I estimate how long it takes to process r 8000 1000000 0.01 126 simultaneous requests for files with size s bytes, if 10000000 1000 1.00 1.00 the client bandwidth is b bytes/second. In the case 10000000 10000 1.00 1.0 of Httpd, this obviously depends directly on the 10000000 100000 0.99 1.01 number of threads t, as only t requests can be 10000000 1000000 0.91 1.1 processed at a time. I assume that a corresponding formula looks like Formula 1. c is the constant cost TABLE 1: d for r –> ∞ with c=10ms and t=100 for parsing, etc., that has to be paid for every

52 MAY 2002

Java COM Interland www.interland.com

MAY 2002 53

Java COM FORMULA 4

Thus, besides the number of threads and con- stant costs, the connection’s length s/b has tremen- dous influence on d. The longer the connection exists, the smaller d is, and the advantage of NIOHttpd compared to Httpd is greater. Table 1 and Figure 3 show that NIOHttpd can be 126 times faster than Httpd, given that c=10ms, t=100, s=1MB, and b=8KB/s. NIOHttpd has a big advantage if the J2SE connection stays open for a long time. If the con- nection is short, e.g., in a local 100Mb network, the advantage is only 10% provided the files are large. If the files are small, the difference won’t be detectable. In these calculations it’s assumed that the con- stant costs of NIOHttpd and Httpd are about the FIGURE 3: d for r –> ∞ with c=10ms and t=100 same and no new costs are introduced by the differ- ent ways the servers have been implemented. As mentioned before, this comparison only holds under ideal conditions. This is sufficient, however, to give you the request. In addition, I assume I can read data faster idea that either concept might be beneficial. It from the disk than I can write it to the socket, my should be noted that most Web files are small, bandwidth is greater than the sum of the clients’ but HTTP-1.1-clients try to keep the connection

Home J2EEbandwidth, and J2ME the CPU is not fully utilized. open as long as possible (with a keep-alive or Therefore the server-side bandwidth, caches, and persistent connection). Often, connections that hard disk speed are not part of the equation. will never again transfer any data are kept open. In a server with one thread per connection this leads to an incredible waste of resources. So, especially for HTTP servers, the scalability can FORMULA 1 be increased dramatically by using the new I/O API. Conclusion However, NIOHttpd is not dependent on t. The With the new I/O API you can build highly scala- transfer time l depends mostly on the client band- ble servers. In comparison to the old API, it’s a bit width b, the size of the file s, and the previously more complex and requires a better understanding mentioned constant costs c. This leads to Formula 2, of multithreading and synchronization. Also, the which estimates the minimum transfer time for documentation needs improvement. But if you’ve NIOHttpd. gotten over these hurdles, the new API proves to be a useful and necessary improvement of the Java 2 platform. FORMULA 2 References • HTTP 1.1: www.w3.org/Protocols/rfc2616/rfc The quotient d (see Formula 3) is of interest 2616.html since it measures the relationship of the perfor- • Lea, D. (1999). Concurrent Programming in Java: mances of NIOHttpd and Httpd. Design Principles and Patterns. Second Edition. Addison-Wesley. http://gee.cs.oswego.edu/dl/ cpj

FORMULA 3 AUTHOR BIO Hendrik Schreiber works as senior consultant for innoQ Deutschland GmbH (www.innoq.com) in Ratingen, Germany. His main area of interest is the After closer examination (…and some rows of architecture of modern Java-based solutions using J2EE. He is a coauthor of data), it becomes apparent that if s, b, t, and c are Java Server and Servlets: Building Portable Web Applications, published by constant, d grows toward a limit. This limit can be Addison-Wesley. easily calculated using Formula 4, which measures [email protected] the limit of d for r –> ∞.

54 MAY 2002

JJavaava COMCOM Actuate Corporation www.actuate.com/info/jbjad.asp

MAY 2002 55

Java COM J D B C 3 . 0 JDBC 3.0– Something for Everyone Important new features

J2SE There was no ticker tape parade to accompany the release of the JDBC 3.0 specification, but many will be pleasantly surprised at its list of enhancements that include everything from perfor- WRITTEN BY mance-tuning options to support for extended-level database fea- JOHN GOODSON tures.

This article describes, in detail, the mit the group of inserts as if the updates idle before they’re discarded from the new features that are available in JDBC had never been attempted (see the pool 3.0 and explains why they are important. Listing 1). • How often the connection pool The JDBC 3.0 specification was should be evaluated to see if it meets shipped as part of the J2SE 1.4 release Pooling Enhancements the configuration criteria early in 2002. The key goals of the JDBC Connection pooling existed in the Expert Panel were to align with the most JDBC 2.0 specification, but JDBC 3.0 In addition to connection pooling important features of SQL99, combine provides a much finer granularity of tuning options, JDBC 3.0 also specifies all the previous JDBC specifications into control over the connection objects in semantics for providing a statement

Home J2EEa single document, provide a standard J2ME the pool. The single most expensive pool. Similar to connection pooling, a way to take advantage of native DBMS operation in a database application is statement pool caches Prepared- functionality, and improve scalability. establishing a connection. With some Statement objects so they can be reused The JDBC 3.0 specification contains a databases, establishing a database con- from the cache without application collection of useful new features, none nection can take up to nine network intervention. For example, an applica- of which, if taken individually, would be round-trips between the JDBC driver tion might create a PreparedStatement considered “major.” and the database. object similar to the following SQL state- Connection pooling essentially ment: Transactional Savepoints involves keeping a cache of database One of the more useful new features connection objects open and making select name, address, dept, salary of JDBC 3.0 is transactional savepoints. them available for immediate use by any from personnel where empid = ? or Traditionally, database transactions application that requests a connection. name like ? or address = ? have been “all or nothing” types of Instead of performing expensive net- events. An application would start a work round-trips to the database server, When the PreparedStatement object transaction, insert some rows, do some a connection attempt results in the reas- is created, the SQL query is validated for updates, and either make the changes signment of a connection from the local syntax and a plan is permanent (commit) or discard them all cache to the application. When the produced. The process of creating a (roll back) – all the changes would be application disconnects, the physical tie PreparedStatement is extremely expen- made permanent or none of them to the database server isn’t severed; sive in terms of performance, especially would be. instead the connection is placed back with some database systems such as With JDBC 3.0, the transactional into the cache for immediate reuse. DB2. Once the PreparedStatement is model is more flexible. An application With JDBC 2.0 connection pooling, closed, a JDBC 3.0–compliant driver might start a transaction, insert several there were no tuning options. You either places the PreparedStatement in a local rows, and then create a savepoint, which used connection pooling or you didn’t. cache instead of discarding it. If the serves as a bookmark. Then, the applica- With JDBC 3.0, there’s a finer level of application subsequently attempts to tion might continue by performing granularity available to control the char- create a PreparedStatement with the some if/then/else type of logic, such as acteristics of the connection pool. For same SQL query, the driver can retrieve updating a group of rows. With JDBC 2.0, example, you can fine-tune the follow- the associated statement from the local the application at this point would have ing options to allow for maximum per- cache instead of performing a network been forced to either commit or roll formance and scalability: round-trip to the server and expensive back all the changes. In contrast, a JDBC • The minimum number of connec- database validation. 3.0 application might contain logic that tions to keep in the pool One advantage of connection pool- determines that the updates were a bad • The maximum number of connec- ing tuning properties and statement idea, but the initial inserts were okay. In tions to have in the pool pooling is that their benefits can be real- this case, the application can roll back to • The initial pool size ized in existing applications without any the savepoint (the bookmark) and com- • How long connections can remain code changes. Upgrading an environ-

56 MAY 2002

Java COM InstallShield Software Corp. www.installshield.com

MAY 2002 57

Java COM J D B C 3 . 0 Updating BLOB and CLOB Data Types The SQL99 specification introduced two new advanced built-in data types, BLOB and CLOB, that provide flexible One of the more useful and fast access to long binary and char- acter data items, respectively. While “ JDBC 2.0 provided mechanisms to read new features of JDBC 3.0 BLOB and CLOB data, it lacked a stan- dard update method for those types, is transactional savepoints resulting in several problems for JDBC application developers. The first problem is that some JDBC driver vendors introduced proprietary update mechanisms for BLOB and ment to include a JDBC 3.0–compliant An optional feature of the JDBC 3.0 CLOB data types. Using proprietary J2SE application server or driver can improve specification is the ability to retrieve methods inside an API standard makes the performance and scalability of autogenerated key information for a row those applications nonstandard by defi- deployed systems, because the JDBC when the row is inserted into” a table. nition. The second problem is that many pooling enhancements are not directly This new functionality removes the JDBC application developers assumed invoked by the application’s compo- drawbacks in existing implementations that they could use existing JDBC meth- nents. Instead, the pooling features are that we discussed, because a separate ods, such as setString, to update the val- transparently used by the JDBC infra- query is not required to retrieve the key ues. Again, this resulted in different structure. and the application is not responsible behavior on a driver-by-driver case, ulti- for the logic to retrieve the key. For mately making those applications non- Retrieval of Autogenerated Keys example: standard. Many databases have hidden JDBC 3.0 introduces a standard columns (called pseudo-columns) that Int rowcount = stmt.executeUpdate ( mechanism for updating BLOB and represent a over every row in "insert into LocalGeniusList (name) CLOB data. Note that the BLOB and a table. For example, Oracle and values (‘Karen’), CLOB interfaces apply only to database Informix have ROWID pseudo-columns Statement.RETURN_GENERATED_KEYS); systems, such as Oracle, DB2, and

Home J2EEand Microsoft SQL Server provides iden- J2ME // insert row AND return key Informix, that support the new SQL99 tity columns. Using these types of BLOB and CLOB data types. Microsoft columns in a query typically provides ResultSet rs = stmt.getGeneratedKeys SQL Server and Sybase support long the fastest way to access a row, because (); // key is automatically varbinary and long varchar data types the pseudo-columns usually represent available (image and text) that are similar to the the physical disk address of the data. new SQL99 types, but they don’t support Before JDBC 3.0, an application could The application contains a value that BLOB and CLOB types. Many JDBC only retrieve the value of the pseudo- can be used in a search condition to pro- application developers mistakenly think columns by executing a Select statement vide the fastest access to the row and a that the BLOB and CLOB interfaces immediately after inserting the data. For value that uniquely identifies the row, should be used for all types of long data; example: even when no primary key exists on the however, they should be used only with table. BLOB and CLOB data. The JDBC specifi- Int rowcount = stmt.executeUpdate ( Some databases, like DB2, do not cation provides methods such as "insert into LocalGeniusList (name) provide an autogenerated key such as a setString to deal with long varchar and values (‘Karen’)"); // insert row pseudo-column. Fortunately, the JDBC long varbinary data. Listing 2 shows how 3.0 specification also allows the appli- to update the contents of a CLOB col- // now get the disk address Ð rowid Ð cation to ask for the columns it knows umn. for the newly inserted row represent a key on the table. For exam- ResultSet rs = stmt.executeQuery ( ple: Multiple Open Result Set Objects "select rowid from LocalGeniusList Data architects routinely build their where name = ‘Karen’"); // insert the row and specify that business integrity rules into database the employee ID be returned as the system stored procedures. For example, This method of retrieving pseudo- key instead of trying to remember all the columns has two major flaws. The first is Int rowcount = stmt.executeUpdate ( tables that must be updated when a that retrieving the pseudo-column "insert into LocalGeniusList (name) new employee is hired, developers requires a separate query to be sent over values (‘Karen’), commonly use a central stored proce- the network and executed on the server. "employeeID"); dure, perhaps one named AddNew- The second is, because there might not Employee, that can be called when a be a primary key over the table, the ResultSet rs = stmt.getGeneratedKeys new employee is hired. Calling stored search condition of the query may not (); // Karen’s employeeID value procedures can result in table updates be able to uniquely identify the row. In is now available and, also, queries being executed that this case, multiple pseudo-column val- return result sets. ues could be returned and the applica- The ability to retrieve autogenerated Invoking a single tion may not be able to figure out which keys provides flexibility to the JDBC can result in multiple result sets being one was actually the value for the most developer and a way to realize perform- returned to the calling application. For recently inserted row. ance boosts when accessing data. example, a stored procedure named

58 MAY 2002

Java COM LOOX Software Inc www.loox.com

MAY 2002 59

Java COM J D B C 3 . 0

employeeInfo might return the follow- Listing 1 ing result sets with: Statement stmt = conn.createStatement (); • The employee’s address and personal Int rowcount = stmt.executeUpdate ("insert into etable (event) values information (‘TMM’)"); • A list of the employee’s staff if he or she is a supervisor Int rowcount = stmt.executeUpdate ("insert into costs (cost) values • A list of the projects on which the (45.0)"); employee is working Savepoint sv1 = conn.setSavePoint ("svpoint1"); With JDBC 2.0, an application call- // create savepoint for inserts ing the employeeInfo stored procedure would have to serially process the Int rowcount = stmt.executeUpdate ("delete from employees"); three independent result sets that were J2SE generated at execution. If the applica- Conn.rollback (sv1); // discard the delete statement but keep the inserts tion needed to first report on the proj- ects list – the third of the sequenced Conn.commit; result sets – then it would have to // inserts are now permanent retrieve and discard the first two result sets. This processing methodology is Listing 2 somewhat inflexible and involves pro- // Retrieve the case history for incident 71164 gramming overhead and complexity. It Statement stmt = conn.createStatement(); also doesn’t allow simultaneous access ResultSet rs = stmt.executeQuery ( to any of the result sets generated from "select CaseHistory from Cases where IncidentID=71164"); calling a procedure. That restriction limits the flexibility of a JDBC develop- rs.next(); // position to the row Blob data = rs.getClob (1); er. // populate our Blob object with the data JDBC 3.0 gives developers the flexi- Rs.close(); bility to decide if they want concurrent

Home J2EEaccess to result sets generated from pro- J2ME // now let’s insert this history into another table cedures or if they want the resources to stmt.setClob (1, data); be closed when a new result set is // data is Clob object we retrieved from the history table retrieved (JDBC 2.0 compliant behav- ior). Listing 3 is an example that simul- int InsertCount = stmt.executeUpdate ( taneously processes results from the "insert into EscalatedIncidents (IncidentID, CaseHistory, Owner)" employeeInfo procedure. + " Values (71164, ?, ‘Goodson’) "); Miscellaneous Features // we’re done … CLOB data is now in the database We’ve detailed several new JDBC 3.0 features that range from performance Listing 3 enhancements to development flexibili- // get ready to call the employeeInfo procedure ty. There are other JDBC 3.0 enhance- CallableStatement cstmt = conn.prepareCall ("{call employeeInfo (?)}"); ments, including the ability to retrieve parameter metadata (allows develop- Cstmt.setInt (1,71164); AUTHOR BIO ment flexibility), allowing stored proce- // bind parameter info for employee with id 71164 John Goodson is the dure parameters to be called by name vice president of (simplifies programming), the ability to Boolean RetCode = Cstmt.execute (); // call the procedure research and specify holdable cursors (improves per- // For simplicity we’ll bypass logic for the procedure possibly returning development for formance), and more SQL99 advanced update counts DataDirect data-type alignment. Technologies. For There’s something in JDBC 3.0 that // first result set will be discarded … materialize it and immediately nearly 10 years, John will make every JDBC developer happi- move to the second has worked closely er and it’s available now. Remember, ResultSet DiscardRS = cstmt.getResultSet(); with Sun and JDBC has both required and optional // materialize first result set Microsoft on the features, and I’ve described some of development of each in this article. Before assuming ResultSet EmpListRS = cstmt.getMoreResults (); database access that a feature is supported in your // by default, close DiscardRS standards, and is an favorite JDBC 3.0–compliant driver, // the 2nd result set: list of employees that report to 71164 is now available active member of the check the database metadata to make Expert Panel for the sure optional features are supported. ResultSet ProjectsRS = cstmt.getMoreResults (KEEP_CURRENT_RESULT); JDBC specification JDBC 3.0 is an approved specification – // the 3rd result set is now materialized and we can simultaneously oper- evolution. John earned it’s time to utilize the new features. ate on both his BS in computer Good luck! // the employee list and the project list science from Virginia Tech. [email protected]

60 MAY 2002

Java COM Quintessence Systems Limited www.in2j.com

MAY 2002 61

Java COM J2ME EDITORIALOR J2ME INDEX

Reflections JavaOne is now well and truly over, J and it’s time to sit back and reflect… 62 by Jason R. Briggs J2ME JASON R.BRIGGS J2ME EDITOR Edge to Edge The JXTA for J2ME imple- mentation interoperates with other JXTA implementations and provides a simple API to help J2ME develop- 64 Reflections ers quickly write JXTA applications and services for small devices. avaOne is over, and it’s time to sit back Unfortunately, I’ve been unable to find a by Kuldip Singh Pabla and reflect…and to sift through the “Market Speak”-to-English translator at Jhundreds of press releases and Babelfish, so my apologies if I’ve translated Jini Surrogate as a announcements that ricochet around the incorrectly. Platform for J2ME Games Internet like balls around a pinball From Wedgetail Communications came This article continues the machine. While I couldn’t be there myself, news of a licensing deal with Sony for surrogate architecture tour from when I checked my e-mails each day, I felt Wedgetail’s JCSI Micro Edition SSL security Part 1 (JDJ, Vol. 7, issue 3) and 66 as if I was there in spirit at least. software (designed for J2ME) to be implement- introduces a method through For me, the most significant news to ed in Sony’s new interactive digital TVs. which a J2ME device can use it. come out of JavaOne was talk of Monty – Wedgetail is a Brisbane-based company, which By William Swaney Sun’s next-generation virtual machine for is a bit of problem for me, since I was formulat- mobile devices. Monty is touted as being ing a theory that most software development is OSGi: The Last Mile of up to 10 times as fast as the current KVM, done by people in northern European coun- Software Deployment so it has great potential for multimedia tries where they have winter for most of the Meet the OSGi Service 74 applications and the like when it finally year, and so have nothing better to do with their Platform, Release 2 specification.

Homeappears on J2EE a shipping device. J2SE time. I’m waiting for confirmation from Wedge- by Peter Kriens Among a number of announcements tail that they’ve outsourced most of their pro- from Motorola: they unveiled the i95cl, a gramming effort to a development studio in Keep Mobile Data and Applications in Sync with Java Corpo clam-shaped, Java-enabled mobile phone Antarctica. I mean, they’re Australians! Mobile App l with a 120x160 pixel, 256-color screen; and Shouldn’t they be standing in front of the bar- Java provides the foundation Sync En Middlew their Semiconductor Products Sector (SPS) becue with a couple of bottles of Victoria Bitter for always-available 84 announced support for Bluetooth and for or something? mobile applications. bases Legacy ARM’s acceleration technology in • • • by Jeff Capone Systems their Embedded Reference Implementation One of the joys of returning to the coun- for J2ME. try of your birth after a long hiatus is the job Metrowerks and AGEA announced the hunt. Never really an enjoyable experience, CodeWarrior Wireless Enterprise Studio – as expected, after the dot bomb it’s worse mobile phone that can tell me exactly where the in their words, “the first wireless applica- than ever. I’m not talking about cooling my nearest empty space is. Rather than carrying an tion development solution”; while Kada heels in office receptions while waiting to be annoying pocketful of coins, the mobile phone Systems and Metrowerks (again) partnered interviewed, nor am I whinging about the can credit the meter with the parking fee, and with an integration plan for their respec- fact that it’s difficult (but not impossible) to the meter can message the phone when the tive technologies. find an agent who actually knows what J2EE time limit is due to expire. Kada Systems also wins my award for the means (and in this country, nigh impossible This would be expensive to implement, largest text-based press release to arrive in to find one who has heard of J2ME). but just imagine the convenience. No longer my inbox: 127K…well, mime-encoded No, I’m talking about car parking. I don’t would I drive for 15 minutes just to find a HTML probably accounted for most it, but begrudge someone wanting to make a cheaper space. I’d go directly to the nearest they still win the award. Kada introduced respectable profit, but here in Auckland one available space (I could even be messaged frameworks to optimize deployment of J2ME particular car park conglomerate charges such when a space is about to become available). apps, announced that they had completed high fees you need to take out a small mort- Better yet, the meters would not need to be the certification process for both CLDC and gage to park your car in their buildings. So it’s emptied every few days (a savings in labor MIDP, talked about yet another partnership – necessary to hunt out those precious council costs), and there are a number of ways car this time with Softwired (iBus/Mobile JMS) – car parks – where a few dollars rents the space. park “overstayers” can be handled that result and were demonstrating the combined tech- Which brings me to my killer app for the in major cost savings – so the system could nology at JavaOne. Kada also entered into a stressed car park hunter. A peer-to-peer (per- eventually pay for itself. strategic alliance with Espial, which I believe haps) application linking all car park meters Better yet, those high-priced car park means that Espial’s browser and applications in the city (Java-enabled parking meters, of companies might have to rethink their will be running on Kada’s platform. course) with a GPS/MIDP application on my prices…

[email protected] AUTHOR BIO Jason R. Briggs is a Java analyst programmer and – sometimes – architect. He’s been officially developing in Java for almost four years, “unofficially for five.”

62 MAY 2002

Java COM QUALCOMM Incorporated http://brew.qualcomm.com/ZJD4

MAY 2002 63

Java COM INDUSTRY COMMENTARY

WRITTEN BY KULDIP SINGH PABLA With the next generation of wireless devices entering the market, the opportunities for Java developers are great.Analysts are predicting that the

J2ME demand for wireless applications is set to explode, with over 170 million U.S. users subscribing to wireless services by 2005. Other countries are moving even faster. Fortunately, recent developments have left us well prepared to meet the Edge to Edge inevitable demand for applications that this growth will create.

Already, important technologies like the no standard platform upon which applica- implementation. Once fully deployed, it will small-footprint J2ME are in place to help tions could be crafted. allow a MIDP device to participate in P2P developers create applications for small Project JXTA, incubated at Sun activities with JXTA peers running on larger devices. With J2ME, developers can exploit Microsystems and then quickly placed into platforms. The community’s goals are the established capabilities of Java to write the community development process, has straightforward: (1) wireless P2P applications applications that are secure, interoperate established an early lead in developing the should be easy to use and easy to develop, (2) with existing solutions, and easily port to infrastructure needed to streamline the they should be small enough to be used with new devices, all without sacrificing the flex- development of P2P applications. Unlike cell phones and PDAs, and (3) they should be ibility that Java gives us. other approaches, JXTA provides the build- interoperable with JXTA applications run- Almost in parallel, interest is also grow- ing blocks for creating P2P services and ning on larger systems. A tall order, given the ing in using peer-to-peer (P2P) technolo- applications. In addition, JXTA offers strong constraints of wireless systems. gies for wireless. Made popular by services security and interoperability between appli- The solution is simple. Rather than like Gnutella and Napster, P2P computing cations through well-defined protocols. hosting a complete JXTA environment on a rejects the notion of centralized servers in How can JXTA technology be extended small wireless device, some of the work will favor of peer groups – users bound by a into the wireless space? Most wireless be done elsewhere. JXTA programmers are common interest in processing, sharing, devices have severe limitations on available already familiar with the notion of a JXTA and storing information. With P2P, we can memory, processor performance, and relay, a peer designated to act on behalf of create networks of systems with very high power. Pagers and cell phones can’t be others. JXTA relays help route information

Homelevels J2EE of redundancy, privacy, J2SE and perfor- expected to support a full-blown JXTA envi- across networks and through firewalls. mance. Until recently, however, the growth ronment, at least not anytime soon. We’ve extended this idea to create a JXTA in P2P was threatened because there was Fortunately, we have experience dealing peer service that can act on behalf of a with these limitations. The wireless JXTA peer, store and forward mes- Java developer community sages when polled, and translate and con- tackled this issue some time dense JXTA XML advertisements (the lin- ago and came up with the gua franca of JXTA) into a more compact Connected Limited Device form easily processed by wireless peers. Configuration (CLDC) and This approach is straightforward, yet it’s Mobile Information Device a no-compromise way to allow J2ME devel- Profiles (MIDP), core class opers to extend P2P into the realm of wire- libraries and specialized less. A prototype application was demon- APIs designed to work in the strated at JavaOne Japan in November constrained environments 2001, and work continues on a full imple- of wireless devices. Despite mentation. For details on its status, visit Northwoods their small size, CLDC and http://jxme.jxta.org. MIDP offer developers the The JXTA for J2ME implementation tools they need to create interoperates with other JXTA implementa- powerful wireless applica- tions and provides a simple API to help J2ME Software tions that can interoperate developers quickly write JXTA applications with the most sophisticated and services for small devices. I see opportu- Java solutions running on nities to create some exciting applications in workstations, servers, and areas like gaming, financial services, and Corporation mainframes. instant messaging using this technology. The JXTA developer Check out the Project JXTA Web site at community has taken a sim- www.jxta.org to learn more about peer-to- ilar approach by defining a peer computing, experiment with some www.nwoods.com/go/ set of functions designed to sample applications, download the docs work in concert with MIDP. and code, and start riding the next big wave We call it the JXTA for J2ME of applications development. Join us!

[email protected] AUTHOR BIO Kuldip Singh Pabla is the software engineering manager with the Project JXTA team at Sun, managing various proects including the JXTA for J2ME implementation. Before JXTA, he was the engineering manager for Java Embedded Server, J2ME division at Sun.

64 MAY 2002

Java COM Sprint PCS http://developer.sprintpcs.com

MAY 2002 65

Java COM JINI & J2ME

J2ME Jini Surrogate as aPlatform for J2ME Games

Using HTTP as a communications protocol Part 2

In Part 1 of this article (JDJ,Vol. 7, issue 3) I introduced the idea of using the surrogate architecture within Jini as a platform for J2ME games. I also showed how to start Madison, Sun’s reference WRITTEN BY implementation, and how to connect to it with the provided device WILLIAM SWANEY simulator.

This article continues the surrogate quest/response protocol. This means er games with thousands of players con- architecture tour and introduces a that either we settle for a one-way com- currently connected. In this case, HTTP

Home J2EEmethod through J2SE which a J2ME device munication model where all communi- scales quite well – after all, it’s a proven can use it. cation with the device must come as a technology already handling huge num- To briefly recap, the architecture response to an initial request, or we bers of simultaneous requests. Thus our allows any device, in our case a J2ME have an HTTP server at both the device system should be able to handle more one, to connect to a Jini network and the surrogate object. The second users making requests every few min- through a surrogate object that repre- option is just not possible in J2ME, so utes or so rather than a group of users sents the device in the network. The sur- we’re stuck with the first. who are constantly connected over rogate host provides a mechanism for The second disadvantage is that sockets. It may even be cheaper for the the devices to register themselves and HTTP has no notion of “discovery,” at end user by minimizing the amount of obtain a context that enables access to least in the Jini sense. This means that airtime consumed. the underlying Jini infrastructure. our device must have knowledge, in the Finally, even though I’m advocating Another important reason for choos- form of a URL, of where the surrogate HTTP as the protocol to communicate ing the surrogate architecture is that it host is beforehand. It would be nice to with the surrogate host, it doesn’t have allows us to view the device as a single somehow find a surrogate host but we to be the protocol used to communicate object from the network perspective. can hardly multicast the Internet look- with the surrogate object once it’s There’s no single monolithic portal API ing for one. instantiated. I’ll continue to use HTTP or application running; instead, many The J2ME specification only requires in our project, but the surrogate archi- different surrogate objects with unique support for HTTP connections, though tecture doesn’t require this and other capabilities and representing many implementations of J2ME may support protocols could be used depending on potentially different devices are dis- other types of communication. By the device’s J2ME implementation. played in the Jini network. choosing HTTP we guarantee that any J2ME device will be able to work with Defining Our Protocol How Should We Connect? our surrogate host connector. There In defining a surrogate HTTP proto- The surrogate architecture defines have been many debates as to whether col I’ll rely heavily on what has already the term connector as a means by which J2ME is powerful enough, as well as been defined for the IP connector. That a device will discover and register with a fears that using it results in the loss of specification is already in the review surrogate host. Possible connectors powerful native functionality. Cross- stage of the Jini Decision Process (see might include such protocols as Blue- platform code has its own set of disad- www.jini.org/standards/), and since tooth, USB, or even traditional network vantages, but in our case the portability HTTP is built on IP, there are some simi- ones. Madison comes with an IP inter- is worth the loss in functionality. larities. In addition, doing so is what I connect, useful in many cases but it may To see another advantage, let’s think consider being a “good Jini citizen”: not be the best one for our project. For about our use case. Our goal is to create cooperating and contributing to a com- several reasons I believe HTTP is the a games platform on mobile devices. munity that gives a tremendous amount best protocol to use. Typically, this means many users con- to its members. By building on the IP HTTP? It does have its disadvan- necting with our system simultaneously. connector work, we respect the stan- tages. Foremost of these – it’s a re- It’s not unrealistic to think of multiplay- dards already defined, ensuring that Jini

66 MAY 2002

Java COM Sitraka www.sitraka.com/jprobe/jdj

MAY 2002 67

Java COM JINI & J2ME

limit of 50K, why add unnecessary bloat? It’s a case of evaluating each situ- ation. For now I’ll keep the interface, as The J2ME specification only requires it allows flexibility in adding more pro- tocols for different message formats. Be support for HTTP connections, though aware though that sometimes every lit- “ tle byte counts; I’ve worked on applica- J2ME implementations of J2ME may support tions in which I removed all evidence of object-oriented design in order to bring the size of the code down. other types of communication A further reduction in code size can be obtained, in our case by combining the registration and response protocols services in general will be able to com- col. An example of basic communica- into one object. The reason is simply municate with each other and interop- tion is passing a message that includes that the J2ME device need only send erate without difficulty. some data as a payload. Of course, the registrations to the surrogate host; it As stated earlier we won’t need the device and surrogate object must both doesn’t need to read the registration discovery protocols. We will, however, be aware of the message format,” though protocol. Similarly it only has to read need a registration protocol that allows the surrogate host need not be. The the responses and never needs to send a device to register with the surrogate message protocol might have the follow- them. Again this is a decision to make host. Examining the IP interconnect reg- ing format: based on the situation. By combining istration request protocol we can see • int protocol version the protocols here we lose the reusabili- that it will suit our needs as well for • int message type ty of the registration protocol with an IP HTTP. The registration request protocol • int length of payload data interconnect, as the response is only is sent by the device to the surrogate • byte[] payload data needed with the HTTP interconnect. host and has the following format: See Listings 1 and 2 for J2ME encap- • int protocol version Finally Some Client Code… sulations of the registration and • short length of surrogate code URL Wait a minute, isn’t this supposed to response protocols, respectively. • byte[] surrogate code URL have something to do with J2ME? Well, • int length of initialization data there are still some missing pieces on What Should an HTTP Surrogate Look Like?

Home J2EE• byte[] initialization J2SE data the Jini side, but let’s take a little break Let’s turn back to the Jini side of our • int length of surrogate code first and make use of the protocols project and think about what still needs • byte[] surrogate code introduced earlier. to be defined, what an HTTP surrogate Every game written using the HTTP will look like, and how the surrogate We’ll also need a response to this, interconnect will need to register with host combined with the HTTP intercon- which is something that the IP intercon- the surrogate host and receive a nect will interact with these surrogate nect doesn’t define. The main reason for response. Therefore, it makes sense to objects. defining a response is that if we use encapsulate these two protocols in In this section I’m assuming we’ll HTTP to continue communicating with objects. Since our registration protocol continue to communicate with the sur- the surrogate object, we must somehow is the same as the one for the IP inter- rogate object using HTTP. This means let the device know how to accomplish connect, we may be able to reuse some that either the surrogate must have an this. Why? Once the surrogate object is of our code should we use J2ME over IP embedded HTTP server in its code, or instantiated, we’re no longer communi- in the future. the HTTP interconnect must provide cating with the surrogate host. Instead, The limited resources of a typical that service for the surrogate object. The we’re now communicating directly with J2ME device now force us to make some second case is not unreasonable as it the surrogate object. If HTTP is the only design decisions. It’s tempting to define simplifies the creation of surrogate available protocol, then the device must an interface for our two protocols, objects, which is an important goal in a initiate all communication. We define a something like the following: development platform. It also philo- response protocol in order to pass the sophically fits with the surrogate archi- URL for the surrogate object to the public interface InterconnectProtocol tecture: the host provides a context for device, a different URL than for the sur- { the surrogate object and so does the rogate host. Our response protocol is void read(java.io.InputStream in) interconnect. defined as follows: throws java.io.IOException; This leads to the question of how a • int protocol version void write(java.io.OutputStream out) message is delivered from the intercon- • short length of surrogate connect throws java.io.IOException; nect-provided HTTP server to the surro- URL } gate. The embedded HTTP server pro- • byte[] surrogate connect URL vided by the interconnect and the surro- This allows us a nice layer of abstrac- gate object should have an exclusive Finally, since I intend to continue to tion, and by encapsulating the protocol relationship. At the very least, there use HTTP as the transport for device-to- in an object that accepts streams for should be some separation, and surrogate object communication, it reading and writing, we can use any type depending on the embedded server this makes sense to define some sort of mes- of connection. might be an exclusive handler for HTTP sage protocol. Even though the type of What about those limited resources? requests destined for a specific surro- messages sent may be very different By creating an interface we have one gate object. To pass the message to the depending on the type of game being more file to add to our J2ME JAR. With surrogate object we need to create an played, I’ll define a basic message proto- some phones having an application interface that it should implement:

68 MAY 2002

Java COM Motorola www.motorola.com/developers/wireless

MAY 2002 69

Java COM JINI & J2ME

implementation on that device support them. You’ll notice that the interface By creating an interface we have one extends another surrogate specification interface. This allows the interconnect more file to add to our J2ME JAR. With to assist in defining and enforcing what “ it means to have a live connection J2ME some phones having an application limit between a device and a surrogate. Tell Me What You Think of 50K, why add unnecessary bloat? So far we’ve covered a lot of ground and further detailed some of the ideas introduced in Part 1. We’re still not there, public interface HttpSurrogate net.jini.surrogate.KeepAliveManagement but we’re getting closer to achieving the extends net.jini.surrogate.Surrogate { goal of developing a game platform for { byte[] getInitializationData(); J2ME devices in a Jini network. void handle(java.io.InputStream in, java.net.InetAddress getAddress(); I’m interested in hearing your opin- java.io.OutputStream out) throws } ” ions. Are there pieces missing, whether java.io.IOException; technical or logistical, to this puzzle? } This provides a way to retrieve both How does the Jini/J2ME platform com- the initialization data we may include in pare to others you’ve used for interac- Are there potential problems in the registration protocol and the tive, wireless device applications? Your defining an interface our surrogates InetAddress of the device. We may want thoughts and suggestions are wel- must implement? Other HTTP intercon- the InetAddress in the future, as it will come. nect implementations may have differ- allow the surrogate to create connec- ent designs and we run into a case of tions back to the device should the J2ME [email protected] surrogate objects being incompatible across different surrogate hosts. However, as we are going to further Listing 1 define the relationship between the /** * An encapsulation of an http connector registration protocol. Home J2EEHTTP surrogate J2SE object and the HTTP * interconnect, this seems a small issue. * @author William Swaney The HttpSurrogate interface * @version 1.0 */ extends the basic surrogate interface as import java.io.*; defined in the surrogate architecture public class HttpInterconnectRegistration implements specification (included in the Madison InterconnectProtocol download). This interface is defined as { follows and allows the surrogate host to public static final int VERSION_NUMBER = 1; provide basic life-cycle services to the private short surrogateUrlLength=0; surrogate: private byte[] surrogateUrl; private int initializationDataLength=0; package net.jini.surrogate; private byte[] initializationData; public interface Surrogate { private int lengthOfSurrogate=0; void activate(HostContext private byte[] surrogate; hostContext, Object context) throws private java.io.DataInputStream din; Exception; void deactivate(); public HttpInterconnectRegistration() { } }

The first object in the activate() public void read(InputStream in) throws IOException { method is the HostContext, provided by throw new IOException(); //We should create our own excep- the surrogate host. The second object is tion here } the context, provided by the intercon- nect, and it’s passed as an object; since public void write(OutputStream out) throws IOException { the surrogate host calls this method on if (out == null) throw new IOException(); the surrogate, it doesn’t need to know AUTHOR BIO the nature of the context. if ((surrogate == null && surrogateUrl == null) || (surrogateUrlLength == 0 && lengthOfSurrogate == 0)) William Swaney, a We’ll need to define a context for the throw new IOException(); software developer HTTP interconnect. The context defined specializing in in the IP interconnect fits our needs and DataOutputStream dataOut = new DataOutputStream(out); distributed computing, keeps some consistency between the works for Valaran interconnects. The interface for the con- dataOut.writeInt(VERSION_NUMBER); Corp., where he text is: dataOut.writeShort(surrogateUrlLength); experiments with if (surrogateUrlLength > 0) dataOut.write(surrogateUrl); mobile devices and public interface dataOut.writeInt(initializationDataLength); Jini networks. HttpInterconnectContext extends

70 MAY 2002

Java COM Ashnasoft Corporation www.ashnasoft.com

MAY 2002 71

Java COM Home J2EE J2SE J2ME 72 public classHttpInterconnectResponseimplements import java.io.*; } M AppDev Training */ * @version1.0 * @authorWilliamSwaney * * Anencapsulationoftheresponsemessagesentfromhttp /** AY Listing 2 2002 } { public voidsetSurrogate(byte[]surrogate) } { public voidsetInitializationData(byte[]initializationData) } { public voidsetSurrogateUrl(StringsurrogateUrl) } { public voidsetSurrogateUrl(byte[]surrogateUrl) } connector tothedevice. www.appdev.com/promo/MG00052 lengthOfSurrogate =this.surrogate.length; this.surrogate =surrogate; initializationDataLength =this.initializationData.length; this.initializationData =initializationData; setSurrogateUrl(surrogateUrl.getBytes()); surrogateUrlLength =(short)this.surrogateUrl.length; this.surrogateUrl =surrogateUrl; dataOut.flush(); if (lengthOfSurrogate>0)dataOut.write(surrogate); dataOut.writeInt(lengthOfSurrogate); if (initializationDataLength>0) dataOut.write(initializationData); Company } { InterconnectProtocol } { public byte[]getSurrogateConnectUrl() } { public shortgetSurrogateConnectUrlLength() } { public intgetProtocolVersion() } { public voidwrite(OutputStreamout)throwsIOException } { public voidread(InputStreamin)throwsIOException } { public HttpInterconnectResponse() private java.io.DataInputStreamdin; private byte[]surrogateConnectUrl; private shortsurrogateConnectUrlLength=0; private intprotocolVersion; return surrogateConnectUrl; return surrogateConnectUrlLength; return protocolVersion; throw newjava.io.IOException();//Weshouldcreateour din.readFully(surrogateConnectUrl); surrogateConnectUrl =newbyte[surrogateConnectUrlLength]; surrogateConnectUrlLength =din.readShort(); protocolVersion =din.readInt(); din =newDataInputStream(in); own exceptionhere J ava COM New Atlanta Communications www.newatlanta.com

MAY 2002 73

Java COM J2ME Home J2EE J2SE

When the rubber finally meets the pavement, we usually Windows hardware requirements, or where high reliability find many complicated and awkward problems. Differences in and availability is needed. On top of Java, the specification hardware, operating system configurations, or setup informa- defines a framework that addresses the needs of a platform tion can bring our carefully designed and crafted software to a that’s running continuously, and must run a dynamically halt in an unexpected environment. Other common problems changing set of applications, and react directly – without are versions that don’t match, missing packages or libraries, supervision – to changes in its environment. different names for environment properties, and so on. A key concept in the framework to achieving these desired Most of us who have had to write installation programs or properties is the service. A service is a Java object that’s registered scripts are aware of the sometimes embarrassing amount of with the framework and is to be used by other applications. The time needed to get an already-working software system oper- functionality of a service is defined by the interfaces it imple- ational on different target machines. I remember a colleague ments. This allows many different applications to implement who promised to eat a floppy disk if the installation script the same service type. For example, a service for logging could failed one more time, and was consequently served a tossed be optimized for local storage and another implementation floppy salad a few hours later...with dressing. could use a remote management system. For the user of this log Meet the OSGi Service Platform, Release 2 specification. service, there should be no detectable difference. This specification is the result of two years of intensive collab- On top of the framework, the OSGi has defined a number oration between OSGi members (Sun, IBM, Ericsson, Nokia, of services that can be used by applications. This rapidly Motorola, Oracle, Telcordia, HP, and 70 others). It has already expanding list contains the following services: been implemented by several vendors, and development ver- • Log service: Provides a way to log information from applications sions can be downloaded from Gatespace, IBM, ProSyst, Sun, and a way to receive the log entries while they’re being made. and others. It allows independent application developers to • HTTP service: Provides a Web server (HTTP or HTTPS, develop software that can be remotely managed for different depending on the implementation) that supports servlets standalone computers, processors, and operating systems of and static files. Combined with the other features of the various sizes and configurations. This list includes, but is def- framework and services, this is probably one of the easiest initely not limited to, embedded computers. ways to deploy Java servlets. The specification relies heavily on Java, the obvious choice • Device access: Supports the automatic download of device when the final platform can’t be restricted to Microsoft drivers, allowing for true plug and play.

74 MAY 2002

Java COM Fiorano Software

www.fiorano.com/tifosi/freedownload.htm

MAY 2002 75

Java COM • Configuration management: Allows management systems This list will expand significantly in the near future. OSGi or applications to set the configuration parameters of appli- has many expert groups working in certain areas. These cations in real time, without requiring a restart when the groups adopt existing standards or develop derived specifica- parameters have changed. The specification uses a tions that add to the list of available services. Other groups are metatyping specification that allows applications to discov- working on adopting OSGi specifications or developing their er the (localized) details of data types that are needed for a own specifications for vertical markets. The OSGi is open and particular application. invites companies to participate in this specification process • Preferences: Supports a hierarchy of properties. This simpli- (see www.osgi.org).

J2ME fied database can be stored locally or on a remote back end. Applications can also use standard Java libraries. These • User admin: Provides a repository of users and includes libraries can be wrapped in the application’s delivery file or authentication and authorization of those users. Many dif- referred to from the manifest file. Versioning issues are explic- ferent authentication systems are supported. itly managed by the framework. Figure 1 shows how the different parts are related. It also The following are some of the services that will probably be shows that bundles (the OSGi applications) can use the OSGi added in the next release: Framework and all standard Java libraries, and access the • Wiring admin: Provides a comprehensive model to connect operating system with the underlying hardware. different services into larger function blocks. This allows A key aspect of the OSGi is that there are numerous ven- simple scenarios, such as connecting a switch to a light, but dors (e.g., Gatespace, IBM, ProSyst, and Sun) that implement can also be used to connect a GPS to a navigation system. the specifications while they’re being developed. In addition, Filters can be used to do conversions or thresholding. the OSGi expert groups develop a reference implementation • Position service: Initially targeted at the car industry, it was and test suites for each specification. This means that the found to be useful in other contexts as well. Just think of an specifications are practical, usable, and have multiple electronic vacuum cleaner in your residence. (choice!) industrial-strength implementations available (most

key aspect of the OSGi is that there are numerous vendors that implement the

Home J2EE J2SE specifications while they’re being developed”

“A• Message- and connection-based communication: A special of the vendors actually have free downloadable SDKs for eval- federated address concept that allows OSGi applications to uation purposes). An open source implementation called communicate transparently (under full security control, Oscar (that still has some work to do, especially to match obviously) even when they’re separated by multiple fire- release 2) can be found at http://oscar-osgi.sourceforge.net. walls or use different communication technologies (e.g., IP and SMS of mobile phones). The Framework • Certificate support: Simplifies the validation of certificates The framework is the part that changes a Java Virtual and provides access to the certificates of the local or remote Machine from a single application environment into a multi- management systems. ple one. The advantages are many: running multiple applica- • Execution environment: One or more definitions of what tions in a single VM means fewer process swaps, fast interap- classes and methods minimal environments should sup- plication communication, and significantly less memory con- port. sumption. Protection between the applications is provided by the Java runtime and the framework. The concept of a bundle is used to represent these multiple applications. A bundle is a Java ARchive (JAR) file containing “parts” that are needed to run the application, and a manifest file declaring the parts that should be available when the application is started. These parts are provided by other bun- dles or by the environment. Dependencies are fully managed by the framework. When bundles are started, they usually reg- ister and get services. Services are Java objects defined by a Java interface that can be found in the framework service reg- istry. Bundles can communicate only through these services (see Figure 2). Management Bundle An important concept of the OSGi specifications is the so- called “management bundle.” This is a bundle with adminis- trative privileges. Management bundles are required because the framework is “policy free,” i.e., it provides many mecha- nisms but carefully tries to abstract itself from decision-mak- FIGURE 1 OSGi environment ing. These decisions, the policies, are provided by the man-

76 MAY 2002

Java COM eXcelon Corporation www.exln.com

MAY 2002 77

Java COM agement bundle and will vary from installation to installation. Management bundles are responsible for managing the envi- ronment. Many different types exist: command-line consoles, remotely managed SNMP-based bundles, Web-based inter- faces, and static configuration–based management bundles. One of the management bundle’s many responsibilities is installing bundles. An API is provided that gives the framework a Java InputStream object and a name. The InputStream is con-

J2ME nected to a JAR file that contains the classes and resources that are provided by that bundle. This fits seamlessly with the Java URL and file system model. Uninstalling doesn’t require a com- plicated uninstall script – the framework is fully aware of all the aspects that are part of the bundle and can completely clean up after itself. It even cleans up the private files that were generat- ed by the bundle. Updating the bundle is just as simple. Package Dependencies Once a bundle is installed it needs to be started. However, FIGURE 2 Bundles, services, and the OSGi framework there are dependencies specified in the JAR file that need to be resolved. These dependencies are about packages. Java classes and javax.servlet.http packages. Managing the classpath is one are always contained in a package. This is the first part of the of the framework’s most important tasks. Some people have name of the class (until the last “.”), e.g., the package of said that the OSGi specifications deliver the original promise java.lang.String is java.lang. of classloaders and classpaths. A bundle can use packages in three different ways. First, it can have private packages. All classes of the bundle that don’t Native Libraries need to be shared with other bundles should be private. The JAR files can also contain native libraries. These Different bundles can thus include the same packages. libraries are not restricted to a single hardware/OS architec- Second, classes that need to be shared with other bundles ture. The manifest can contain a specification of which should be exported. Interfaces and classes that are used to libraries are intended for which architecture. The frame- communicate (e.g., the interfaces that define the services) work will find the set of possible libraries and load the best- must be exported or else the bundles will run into fitting one. The framework will handle all complicated

Home J2EEClassCastExceptions J2SE when they exchange objects. Any bundle library path issues that normally plague the deployment of can specify any package for export. The framework will ensure native code. that only one of the bundles at any time will export a specific package. Starting the Bundle Third, the bundle can also specify that it needs certain After the dependencies are resolved and the right bundles packages; for example, that the classes in its JAR file refer to the are picked to export, the bundle needs to be started. For this javax.servlet and javax.servlet.http packages. Imports require reason, the manifest contains a header that points to a special an associated export. The framework will pick only one bundle class: the activator. An object of this class is created and cast to to export a specific package at any time to prevent a BundleActivator. This interface contains a start method and ClassCastExceptions. The decision of which bundle to pick for a stop method that are used to start and stop the bundle. For export is further guided by the versions (all package ref- efficiency reasons, these methods should return quickly or erences can contain a version specifier) and security. they’ll block the system. They normally start a background Figure 3 shows how packages can be thread or get/register some services. The stop method cleans

he framework is the part that changes a from a single application environment into a multiple one”

“ imported from the framework (or up all the parts that the framework can’t directly clean up and Tstandard Java classpath) or other stops any threads. bundles, or exported. The resolving of these packages is under the control Service Registry of the framework and may be subject A started bundle is expected to provide some utility to the to security checks. end user. It’s highly likely that it’s using services to provide this Bundles can also include other JAR functionality to users and other bundles. The services – Java files. The manifest can be used to tell the objects implementing a service interface – are available from framework that this JAR file contains a the framework registry. This registry is searchable with a simple library that must be available on the classpath. but very expressive filter. The syntax of this filter is derived from For example, a bundle could include the the LDAP filter syntax RFC-1960. This type of filter can have servlet.jar JAR file and then export the javax.servlet comparisons for equality (=), magnitude (<=, >=), substring

78 MAY 2002

Java COM Borland Software Corp. www.borland.com/new/optimizeit/94000.html

MAY 2002 79

Java COM (*x*), presence (*), and approximate matches (~=). Expressions can be AND (&), OR (|), NOT (!), and nested to any depth. For example:

( & (service.pid=USB-1232312452)( | (vendor~=ericsson)(vendor~=ibm) ) )

This filter language is used to search the framework, to pre-

J2ME filter events before they’re delivered, and, in many service specifications, to find objects. The properties that are used in a search are given to the framework when a service is registered. Some properties (like the interfaces that the service implements) are automatically set by the framework, some properties have defined semantics (like “service.pid” is a unique identifier for a service), and other properties are defined by the bundles themselves. Each property can, as with LDAP, have multiple values; for example, a device needs to be registered with a property DEVICE_CAT- EGORY. However, a device that fits multiple device categories FIGURE 3 Sharing of Java packages can put the categories in an array or a vector object. bundles, devices, and services available – a must for a stand- Dynamism alone, continuously running server. A cornerstone of the OSGi architecture is dynamism. Bundles can be installed, updated, started, stopped, and unin- Cleaning Up stalled at any time; devices can come in any range and be rep- Running a number of bundles together in a single VM and resented in the framework registry at any time. This makes the sharing the resources is not always easy; therefore, the framework environment extremely dynamic. Therefore, the framework closely tracks the dependencies between the bundles. When bun- offers a comprehensive model for writing applications for such dles are stopped or uninstalled, the framework will use its exten- an environment. All important changes to the environment are sive knowledge of these dependencies to clean up as much as pos- sent to listeners that have specified an interest in these events. sible. Services registered by a bundle are automatically unregis- Installation, start, stop, and update of bundles is sent out tered and services used from the framework are returned. This sig-

Home J2EEas bundle events. J2SE Management bundles can use these events nificantly minimizes the complexity of sharing a VM. to apply their policies (for example, the security settings or installing required support bundles) at the appropriate time. Security Service registrations, unregistrations, and modification of The framework has been targeted to run multiple inde- service properties are sent as service events (see Figure 4). pendent bundles simultaneously. It was assumed from the Bundles use these events to adapt to the changes in the beginning that these bundles couldn’t all be trusted in such an environment. For example, when a digital camera is plugged environment; therefore, security is paramount. That’s the rea-

cornerstone of the OSGi architecture is dynamism. Bundles can be installed, updated, started, stopped, and uninstalled at any time”

“A into a FireWire network, son the OSGi has adopted the Java 2 security model. In this a device service repre- model, a certain “type” of security is represented by a senting this camera is Permissions class. For example, access to the file system is registered. A bundle that guarded by the FilePermission class. These permissions are controls a monitor can associated with the code base, i.e., the place where the code then react to this registra- came from. When a permission needs to be verified, the tion and add this new cam- checker creates an instance of the appropriate Permission era to the monitor’s menu. A class and calls the SecurityManager with this object. This will special class, the ServiceTracker, assure that the stack is crawled, and each caller is checked to is provided to simplify this process see if it has a Permission object. For example, when a file is of tracking services in the registry, opened, the Java IO runtime system creates a FilePermission which makes using this dynamic model trivial. object with the filename as a parameter and with READ as the Though the dynamism undoubtedly introduces a certain action. The caller (and all its callers) are then checked to see if amount of complexity into the programming, the benefits are its set of permissions include a FilePermission object that huge. OSGi-based environments don’t have to be rebooted implies the given filename and action. when configuration changes take place or bundles are Normally, Permission objects are associated with code installed and updated. The environment adapts itself to the bases through the Policy class. The default policy reads the

80 MAY 2002

Java COM Pramati Technologies www.pramati.com

MAY 2002 81

Java COM permissions from a file. Permissions can normally be granted scale installations is complex and error-prone. Therefore, these on a file basis or when certificates are used on the signer basis. tasks should be minimized as much as possible. Having one broad This is so flexible that it’s sometimes quite confusing. permission for administrative tasks was deemed more than suffi- Therefore, the OSGi has simplified the model significantly cient and significantly reduces the administration of permissions. by granting permissions only on a per-bundle basis. As is cus- Bundles can import and export Java packages as explained tomary in the OSGi specification, the mechanism to associate earlier. This is obviously a security risk because malicious the permissions with the bundle are made in such a way that bundles could export an innocent-looking package that’s an operator can use his or her own policies, bought from net- inadvertently used by an important bundle. Also the reverse, a

J2ME work management vendors or rolled by the operator’s staff. bundle importing a package that it might use to do “evil” Management bundles have two mechanisms available for things should be under strict operator control. These threats permission-handling. One, there’s a special service, are mitigated with the PackagePermission class. Package- PermissionAdmin, that permits a management bundle to set, Permission classes can hold the name of a package (including get, and reset the bundle and default permissions. The per- wildcards) and the action export or import. missions are associated with the location (this is normally the As usual, some bundles are more equal than others and the URL where the bundle comes from). This makes it possible to ServicePermission class is intended to differentiate between set the permissions before the bundle is actually downloaded them. Bundles can be given permission to register or get a spe- in the environment. However, there’s also the possibility of cific service (or a wildcard). Conforming frameworks must just-in-time permission-setting. ensure that when a bundle doesn’t have this permission, it Two, a management bundle can register a Synch- won’t be able to detect the existence of such a service. For ronousBundleListener with the framework. This listener is example, when a bundle registers an HTTP service object with called when the bundle is installed but before the bundle has the framework, another bundle that doesn’t have had a chance to do something (including exporting code). At ServicePermission(HttpService,GET) won’t even be able to see this moment, the management bundle can look up the per- the registration event of that service. missions and set them. This is a powerful mechanism that’s broadly used in the As always, using secure systems doesn’t make life easier for OSGi specifications to raise firewalls between bundles. For the developer, but at least the OSGi environment makes the example, in the configuration management specification

hough the undoubtedly

Home J2EE J2SE dynamism introduces a certain amount of complexity into the programming, the benefits are huge “ Java 2 security model significantly less painful to there are two parties: the Configuration Admin service that Tuse in practice. configures clients and the clients that are configured. Both are represented as services in the framework service registry. Framework Permissions However, registering a Configuration Admin service is a privi- The framework introduces three new permission types: leged action, reserved for the bundle designated by the opera- ServicePermission, PackagePermission, and AdminPer- tor. On the other hand, registering as a client is allowed by mission. basically every bundle. Getting the client service is again priv- AdminPermission gives the owner the authority to manage the ileged and getting the Configuration Admin service is not. framework. Management bundles require AdminPermission to per- It turns out that many security schemes don’t require spe- form their numerous duties. This AdminPermission is a broad per- cial Permission classes, but can leverage the expressive power mission class intentionally. Administering and configuring large- of ServicePermission. Applications The framework, though initially targeted at residential gateways, has already found a wider audience. The car indus- try is showing great interest in the OSGi specifications and is currently participating in continuing the effort. The applica- bility of the specifications is even wider than gateways in cars or homes. It can be used to deploy applications in almost any environment where they consist of multiple components that, AUTHOR BIO together, form the needed functionality. The ease of remote Peter Kriens, an OSGi management, a well-defined environment, numerous avail- technical officer, also able tools, security, many industrial-strength SDKs, and the worked for Ericsson dynamic collaborative environment make it interesting for Research in Stockholm, many software deployment problems, from PC-based applica- where he got involved tions to high-end Unix application servers, from servlet-based with home servers and applications to cellular network base station controllers residential gateways. somewhere out in the countryside. Why not give it a try! Peter studied electronics in Alkmaar, Holland. FIGURE 4 Service events [email protected]

82 MAY 2002

Java COM InetSoft Technology Corp. www.inetsoft.com/jdj

MAY 2002 83

Java COM PROFESSIONALLY MOBILE Keep Mobile Data J2ME and Applications in Sync with Java An integral part of your mobile strategy

Here’s a quiz: consider a physician accessing different patients’ histories on a PDA while making rounds at a Manhattan hospital versus a field engineer whose responsibility is to monitor WRITTEN BY and repair sections of an oil pipeline that stretch across 200 miles JEFF CAPONE in Texas.

Which professional is able to have operate in any mode is the result of beauty of synchronization is that it continuous access to data and applica- three overriding business concerns: allows the user to connect to the net- tions – the doctor, who is always con- 1. Limitations in network infrastructure work only if data transmission is neces- nected to the wireless LAN network, or 2. Low wireless connection bandwidth sary, and automatically disconnect the field worker, who experiences only 3. Cost of wireless service when the transmission has been accom- intermittent connectivity? plished.

Home J2EEThe answer is J2SE both. The doctor and the First, current limitations in network In this environment, choosing the field engineer can have uninterrupted coverage make disconnected applica- appropriate synchronization model is access to data and applications, without tions a must-have for the mobile pro- critical to successfully deploying mobile the unrealistic expectation of continuous fessional. Whether a sales representa- applications. wireless connectivity, if they’re equipped tive is traveling on a plane or a field with an “always-available” mobile solution. engineer is in the desert fixing a Mobility Achieved with a Java Java provides the foundation for pipeline, they must all be productive Synchronization Solution always-available mobile applications. with or without the benefit of a wireless There are several synchronization For example, a J2ME-enabled mobile connection. Until wireless connections approaches. File sharing is one common device can operate in both wireless and are ubiquitous and 100% reliable option, but it requires the presence of disconnected modes. Unlike browser- around the world, disconnected func- databases on both the client and the based WAP or HTML applications, J2ME tionality will remain invaluable to the server. This becomes cumbersome if all applications are persistent; a J2ME mobile worker. you want to do is synchronize data application can function on a cellular Low wireless connection bandwidth between enterprise and client applica- phone, laptop, or PDA without a wire- is also an issue with most mobile profes- tions, neither of which stores data in less connection. When a wireless con- sionals. It will continue to be a bottle- databases. It also often requires a pro- nection is established, however, the neck, even with GPRS and 3G networks. prietary file format for transporting the J2ME application can communicate Synchronizing applications only when data between devices. with the corporate network, sending necessary is therefore of great value. A Application-level synchronization is and receiving data changes, additions, field engineer, for example, may not another option, but its shortcomings and deletions. want to update daily job information include the inability to extend the syn- Java’s ability to work in all modes every time he or she enters one line of chronization solution across multiple makes this technology invaluable for all data; the engineer may simply need to applications and back-end databases. types of environments and mobile ensure all jobs have been entered, veri- Since this synchronization solution is applications. In addition, the user inter- fied, and completed intermittently specific to the application, multiple face of a J2ME application can be cus- throughout the day. solutions may need to be supported tomized and enriched with graphics, Airtime minutes will continue to be a when a project requires access to more media components, and more intuitive cost factor until carriers and other wire- than one enterprise application. navigation to improve the user experi- less network providers switch to a true An optimal synchronization solution ence. The challenge, then, is to tailor a data usage–based model. Synchro- would sit between the application and Java-based solution around the business nization eliminates the needless over- database level, allowing objects or com- needs, the nature of the work, and the head of “dead” airtime minutes used ponents to freely synchronize with one mobile environment. during a wireless data session in which a another. This is possible using Java (see user is charged even though no data was Figure 1). By allowing a server’s data Always-Available Mobile Applications exchanged during the wireless connec- access layer to synchronize directly with The need for mobile applications to tion (such as when reading e-mail). The the client’s data-access layer, it doesn’t

84 MAY 2002

Java COM Softwired, Inc. www.softwired-inc.com

MAY 2002 85

Java COM PROFESSIONALLY MOBILE

ory. The memory used for persistence is

Mobile also less than that used by a client data- Java Clients base. Having made the argument for using a caching solution, it’s still impor- tant that your synchronization solution supports the use of a client database should it be needed due to the nature of Intermittent Connectivity J2ME WAP/Browser the work or the application. Based Clients Wireless Gateways • Multiple Enterprise Connections Your synchronization solution Internet should be able to interface with multiple Corporate server-side applications and databases. Firewall Mobile App Avoid using synchronization solutions lication Serv directly from enterprise application Sync Engine er providers; they may work with that par- Middleware ticular application, but are not likely to interface well with other back-end con- Databases tent. Find a solution that’s open and allows you to interface with multiple Legacy back-end solutions; this will save you Systems Enterprise from significant upgrade and mainte- Apps nance headaches. You’ll need to support connections to JDBC, EJB, XML, JCA, JMS, and HTML data sources, among others.

FIGURE 1 Java and synchronization handle all mobile environments • Open APIs Find a mobile solution that allows matter which type of databases or appli- chronization solution to the data-access you to develop using API-level access.

Home J2EEcations need to J2SE be synchronized, or layer of the client application. This This development approach enables which client devices need to be support- method allows your synchronization you to easily integrate with third-party ed. Any database, application, or client solution to remain flexible in light of the software applications and preserves the device can synchronize at the data various client devices, platforms, and flexibility of your current and future access–layer level by communicating applications. mobile strategy. with industry-standard interfaces, including JDBC, EJB, XML, JCA, JMS, • Real-Time and Asynchronous Access • Open Application Development and and HTML. You can extend any J2EE Synchronization should not be a Java Support services existing on the server to a standalone product, feature, or func- Ensure that the applications you mobile client device. tion. Your mobile solution should sup- develop, on both the server- and client- port both real-time (e.g., browser- side, use open architectures and indus- Architecting a Java Synchronization Solution based) and offline access (e.g., client try-standard development methodolo- Conflict resolution during synchro- application and synchronization) to gies. The most fitting solution for this nization usually depends on complex corporate back-end applications and paradigm is J2EE on the server-side, and business rules that are set by the user content. Find a vendor who can provide J2ME/J2SE on the client-side. If you and require a robust solution to appro- both types of products – otherwise you’ll already have Java in the enterprise, your priately handle these rules. Such a solu- be left with integration and incompati- mobile solution should extend this tion should support the following: bility issues between your connected investment to client devices. Look for a and disconnected solutions. solution that allows you to extend your • Multiple Device Support existing J2EE components or services to A robust synchronization solution • Client-Side Data Caching mobile devices without the need to should be functional on multiple client Mobile devices should not require a rearchitect your existing enterprise IT devices that support offline deploy- client database for your synchronization infrastructure. ment. J2ME is only one type of client solution to work. Many devices don’t technology that needs to be supported. even have a file system that supports a • Flexible Business Logic and Syn- Other platforms such as PersonalJava client database (e.g., Compaq iPaq). If chronization Rules (pJava), J2SE, and WABA can also be your synchronization solution does Conflict resolution rules should supported by your wireless platform depend on a client database, it will always take into account the intended without requiring additional or third- require you to add more software prod- functionality of the application. Such party add-on products. ucts than necessary, raising incompati- synchronization rules can’t take a “one Should your synchronization solu- bility and memory-limitation issues on size fits all” approach to resolving con- tion connect directly to the client appli- your client device. flicting data information. In most cases, cation or require a client database, you’ll Using the client’s cache is a more “last in wins” conflict resolution can need to provide for cross-device func- practical solution. Given that the device have a disastrous effect on the applica- tionality. The best way to ensure this will have local memory capacity, you tion data accuracy. Synchronization functionality is to connect your syn- can achieve persistence using this mem- rules should be flexible enough to sup-

86 MAY 2002

Java COM ITtoolbox www.Ittoolbox.com

MAY 2002 87

Java COM PROFESSIONALLY MOBILE

with any software solution, you should not be dependent on the company that produced or sold the software to you, Deciding on a but be able to manage the solution with existing in-house resources. “synchronization solution Conclusion

J2ME When selecting a synchronization solution, many factors play an impor- is not much different than tant role in choosing the solution that’s appropriate for the task at hand. Choosing the best-of-breed synchro- deciding on a real-time nization solution may not turn out to be the correct choice when you consider other factors. You should make your wireless solution decision based on a wide variety of influencing issues that are not limited to just your mobile strategy. First, deter- mine the business requirements of your port the various business logic rules of into shipping J2ME phones worldwide. project. Will a wireless solution without the application, allowing developers PJava is generally used on Pocket PCs offline capability suffice? If not, do you and/or users to decide which priority and takes advantage of the underlying need a mobile solution that can operate settings should be used if a data conflict functionality of the operating” system. It in a disconnected mode? Do you need occurs. can deliver a better user experience than both, allowing certain parts of your a cell phone, due to the additional soft- organization to use one or the other? • Logging Tables ware and hardware functionality of the Second, know your existing enter- Whatever the outcome of the con- mobile device. It appears unlikely that prise and client technology, including flict, log tables are necessary to docu- these two technologies will merge any- both your software and hardware invest- ment the results. They must be reliable time in the near future. In fact, it’s more ments. Do you plan on building a new and easily accessible from within vari- likely that new client technologies will mobile project from scratch? Do you

Home J2EEous administrative J2SE environments, dis- emerge, highlighting the need for a plan on extending an existing enterprise playing results as hierarchical tree views robust mobile and synchronization application? Have you invested in Java of log data, for example. Log tables solution that will take these future technology? Are you looking to integrate ensure that even when a conflict occurs, changes into consideration through the wireless/mobile solution into your none of the data is lost and the subse- open, flexible, and extensible architec- existing IT infrastructure? Are you look- quent rollback of the initial conflict res- tures. ing to build out a completely separate olution can occur. Deciding on a synchronization solu- wireless/mobile island, away from the tion is not much different than deciding corporate IT system? What type of • Security on a real-time wireless solution. The devices do you plan on supporting – just Allowing mobile devices access to solution should be based on open stan- one or many? Are you planning on your corporate networks produces secu- dards, leverage existing investment in mobile-enabling just one or many rity nightmares among your IT staff. technologies, and be flexible enough to enterprise applications? Do you need Make sure your mobile strategy incor- accommodate future changes in tech- direct access to database content from porates industry-standard security tech- nologies or business direction. mobile devices? nology to encrypt the connection There are many add-on synchroniza- Third, evaluate the vendors. Choose between the mobile device and your tion solutions that may work with your one that fits your needs. The more open- corporate networks. existing enterprise and mobile initia- ness and flexibility you (or your vendor) tives. Add-on solutions, however, don’t preserves, the better. Choose a product Understanding Development and provide the most flexible and robust vendor, not a services vendor. Look for a Implementation Issues synchronization as compared to inte- vendor who focuses on and has experi- J2ME is only one type of client tech- grated solutions. An integrated solution ence with mobile technologies. Con- nology that allows for disconnected should provide both real-time and sider the total long-term cost of owner- applications. Due to the variety of offline functionality of your mobile proj- ship of your mobile solution, not just the mobile devices, different technologies ect. Synchronization should be a simple products and/or services cost in the first emerged to take advantage of the differ- extension of your real-time wireless year. AUTHOR BIO ences in functionalities offered by each solution and shouldn’t require a sepa- Synchronization solutions are a Jeff Capone, PhD, is device. The two prevalent technologies, rate technology or software/services must-have for the mobile professional. CTO of Aligo, where both of which happen to be Java-related, vendor. The current limitations in wireless con- he leads are J2ME and PersonalJava (or pJava). Whether add-on or integrated, the nectivity require client applications to the technology J2ME is mostly used on mobile synchronization solution must be based function even in an offline mode of development and is phones and requires a micro Java Virtual on open standards and remain flexible operation to enhance the productivity of principal architect of Machine. While the proliferation of for future changes in technologies, not the end user. Synchronization solutions the M-1 Server. He J2ME phones is currently very low, just synchronization technology. An should therefore be an integral part of has spent the past future mobile phones are expected to open solution is something that can be your mobile strategy. decade researching incorporate this technology. Nokia, for managed without the help of the vendor wireless applications. example, is currently making a big push or specialized systems integrator. As [email protected]

88 MAY 2002

Java COM Oracle Development Tools User Group www.odtug.com

Wireless Subscription www.wbt2.com

MAY 2002 89

Java COM BOOK REVIEW JDJ Labs

I was very impressed with the organization The sample application is developed further of the book, which made it a treat to read. One in these chapters by TravelAgent Bean, of its main strengths is that it stays focused Reservation Process Bean, and associated on specific topics and cleanly separates the workflows. Transaction design for EJBs is cov- 1.1 and 2.0 versions of the EJB specification. ered in Chapter 14. For example, if you’re only concerned with Chapter 15 provides some excellent design Enterprise designing a new application using EJB 2.0, strategies for EJB design, such as using hash codes the information isn’t cluttered with recur- to generate primary keys and dependent value ring references to the EJB 1.1 CMP model, objects to pass objects to and from entity beans. which is discussed in a separate chapter. Chapter 16 is a reference chapter on the deploy- Chapter 1 introduces distributed com- ment descriptor for EJBs. This is followed in puting. Chapter 2 provides an excellent Chapter 17 by an overview of how EJBs fit into the overview of EJBs, including coverage of big J2EE picture. The appendices provide concise J2SE JavaBeans the standard classes and inter- references to the EJB APIs and the state and faces, the types of beans, and sequence diagrams for the different types of EJBs. the deployment descriptor for This is one of the best sources of informa- deploying beans. The author tion on EJBs that I’ve found. It would have has picked a generic applica- been helpful if there were some diagrams of tion to illustrate his examples – the overall picture, but all in all, this is a very a reservation for a cruise. If this well-organized book about using Enterprise chapter had contained an JavaBeans to develop applications. J2EE J2ME overall diagram illustrating the Table of Contents entire hierarchy, including the objects developed throughout Preface 11. The Entity-Container Contract The Primary Key 1. Introduction The Callback Methods the book, it would have been a Setting the Stage EJB 2.0: ejbHome( ) Enterprise JavaBeans Defined perfect chapter on EJB archi- EntityContext Distributed Object Architectures The Life Cycle of an Entity Bean tecture. Component Models Chapter 3 deals with the Component Transaction Monitors 12. Session Beans

Labs CTMs and Server-Side Component The Stateless Session Bean basic services provided by the Models The Life Cycle of a Stateless Titan Cruises: An Imaginary Session Bean J2EE component transaction Business The Stateful Session Bean What's Next? Home monitors or EJB containers. It The Life Cycle of a Stateful Session 2. Architectural Overview Bean REVIEWED BY AJIT SAGAR [email protected] provides a good discussion on such topics as The Enterprise Bean Component 13. Message-Driven Beans the EJB life cycle, object persistence, and the Using Enterprise Beans JMS as a Resource info The Bean-Container Contract Message-Driven Beans bean-container contract. Chapter 4 walks you Summary Enterprise JavaBeans 14. Transactions through developing and deploying some basic 3. Resource Management and the ACID Transactions Author: Richard Monson-Haefel Primary Services Declarative Transaction EJBs and covers application development con- Resource Management Management Publisher: O’Reilly & Associates Primary Services Isolation and Database Locking cepts from object design to basic database table What's Next? Nontransactional Beans Explicit Transaction Management design. Chapter 5 covers the design of a basic 4. Developing Your First Enterprise Beans Exceptions and Transactions client to access the beans developed in Chapter Choosing and Setting Up an EJB Transactional Stateful Session Server Beans 4. The discussion on local versus remote inter- Developing an Entity Bean 15. Design Strategies Developing a Session Bean faces is very helpful. Hash Codes in Compound Primary 5. The Client View Keys Chapters 5–8 were, for me, the most useful Passing Objects by Value Locating Beans with JNDI Improved Performance with chapters in the book. Monson-Haefel walks you The Remote Client API Session Beans through the nuts and bolts of designing entity EJB 2.0: The Local Client API Bean Adapters Implementing a Common Interface 6. EJB 2.0 CMP: Basic Persistence beans with the new EJB 2.0 persistence model. Entity Beans Without Create Overview Methods Chapters 6–7 develop sample entity beans in The Customer EJB EJB 1.1: Object-to-Relational Persistence Fields Mapping Tools lthough I’ve been following EJB 2.0 light of the new persistence model with very Avoid Emulating Entity Beans with Dependent Value Classes Session Beans very closely, it was only recently that I lucid examples. The organization of the text is Relationship Fields Direct Database Access from Session Beans walked into a project that was the per- excellent. Monson-Haefel begins each example 7. EJB 2.0 CMP: Entity Relationships Avoid Chaining Stateful Session A The Seven Relationship Types Beans fect venue for its new features, such as the with the abstract programming model, followed 16. XML Deployment Descriptors 8. EJB 2.0 CMP: EJB QL What Is an XML Deployment much enhanced container-managed persist- by the abstract persistence schema, then the Declaring EJB QL Descriptor? ence and local interfaces. And Enterprise design of the bean interfaces and classes, and The Query Methods The Contents of a Deployment EJB QL Examples Descriptor The Document Header JavaBeans, written by Richard Monson-Haefel, finally the deployment of the bean. Each discus- Problems with EJB QL The Descriptor's Body fit the bill as a reference and learning guide. sion is autonomous and very clear. 9. EJB 1.1 CMP Describing Enterprise Beans This is a “must-have” book if you want an Chapter 7 offers clear guidance on database A Note for EJB 2.0 Readers EJB 2.0: Describing Relationships Overview for EJB 1.1 Readers Describing Bean Assembly introduction to EJBs, are migrating from EJB relationships as they relate to EJB 2.0 CMP. Container-Managed Persistence The ejb-jar File 1.1 to 2.0, or want to build a new application Chapter 8 is a good reference for using EJB-QL. 10. Bean-Managed Persistence 17. Java 2, Enterprise Edition using EJBs. The author provides a brief intro- Chapter 9 deals with EJB 1.1 CMP. The Remote Interface Servlets The Remote Home Interface JavaServer Pages duction to distributed objects and compo- Chapters 10–11 discuss the details of bean- The Primary Key Web Components and EJB The ShipBean J2EE Fills in the Gaps nent models in the first chapter; however, if managed persistence and the EJB container. Obtaining a Resource Connection Fitting the Pieces Together you’re unfamiliar with these concepts or with Chapter 11 has ample coverage of primary Exception Handling Future Enhancements The ejbCreate( ) Method A. The Enterprise JavaBeans API database design, this is not the right book for keys, the entity context, and the life cycle of The ejbLoad( ) and ejbStore( ) Methods B. State and Sequence Diagrams you. Enterprise JavaBeans talks in detail about entity beans. The ejbRemove( ) Method the obvious – Enterprise JavaBeans – and Chapters 12–13 cover the other two types The ejbFind( ) Methods C. EJB Vendors The Deployment Descriptor stays focused on the subject. of EJBs (session and message-driven beans). Index

90 MAY 2002

Java COM LARGEST GATHERING OF DEVELOPERS, PROGRAMMERS, AND i-TECHNOLOGY PROFESSIONALS IN THE WORLD!! JUNE 24-27, 2002 • JACOB K. JAVITS CONVENTION CENTER • NEW YORK, NY $35,000 REGISTER BY MAY 31 WIN A LUXURY CAR! ATTENDEES WILL BE INVITED TO TAKE A GOLF SWING TO WIN TO SAVE $200! AND RIDE OFF IN A $35,000 Sponsored by GO TO WWW.SYS-CON.COM NOW! LUXURY CAR!

Focus on Java Focus on XML Focus on Java, now mainstream, is the dominant back-end JAVA XML is today’s essential technology to develop XML Web Services WEB technology upon which next-generation technologies are and deploy Web services. Here’s your chance to Web Services, the next generation technology that will evolving. IN learn from expert practitioners how XML is making NEXT G enable the Internet to work for you and your business, and SERVICES the next phase of the Web a reality. Hear from the leading minds in Java how this OF finally provide that ROI you have been after, will be put under SKILLS, essential technology offers robust solutions to JUNE Focus on standards, interoperability, content a microscope at Web Services Edge East 2002. STRATEGY, management, and today’s new quest for more effi- ENTERPRISE i-technology professionals and senior IT/IS strategy ESPECIALLY Information-packed sessions, exhibits, and tutorials will exam- AND cient and cost-effective Internet and intranet- DEPLOYMENT decision-makers. IN NEW YORK ine Web Services from every angle and will provide cutting-edge VISION enabled business process integration. solutions and a glimpse at current and future implementations. Hear from the innovators and thought leaders in Web Services. Enjoy a highly interactive CEO Keynote panel that will debate and discuss the realities and promise of Web Services. XML Track: June 25-27 Web Services Track: June 25-27 The Web Services Track will concentrate on the latest emerging standards. It will include Java Track: June 25-27 The XML Track will focus on the various facets of XML technologies as they apply to solving discussions of .NET, Sun ONE, J2EE and App Servers, the role of UDDI, progress of the stan- The Java Track, with something for every developer from beginner to advanced, will also business computing problems. This track targets audiences ranging from beginners to system dards-making bodies, SOAP, and Business Process Management. It is intended for developers, look into the role that Java is playing in building up Web Services. architects and advanced developers. architects, and IT management.

JV1 Java Security Advanced Concepts JV6 .NET vs J2EE XM1 Data - a Key Part of Web Services XM7 XML Web Services: Standards Update WS1 Starting Out In Web Services: WS7 Developments in Web Services JV2 Optimizing Database Performance in JV7 Building Scalable Web Applications and XM2 OASIS Standards Update XM8 Bringing XML to PKI Fundamentals In Web Services Standards J2EE Applications Web Services XM3 A Universal Business Language XM9 Building a Corporate Information Model WS2 State of the Web Services Industry WS8 Unlocking the Value of Enterprise JV3 Detecting, Diagnosing, and Overcoming JV8 Hot Breaking Session XM4 Achieving Standards-Based Mobile in XML WS3 Web Scripting Languages: Options for Web Services the Five Most Common J2EE JV9 Java Tools for Extreme Programming eBusiness Success with XML & Web Services XM10 XML in the Enterprise and Inter- Dynamic Web Development WS9 Guarding the Castle: Security and Web Application Performance Obstacles JV10 Building Truly Portable J2EE XM5 Using XML for Rapid Application Enterprise World WS4 Building a Web Services Application Services JV4 Building Asynchronous Applications Applications Development and Deployment with Web XM11 XML and RDB Relationships Infrastructure WS10 Practical Experiences with Web Using Java Messaging JV11 Security for J2EE Application Servers Services WS5 Deploying a Corporate Portal Services and J2EE JV5 Building “Smart Client” Applications XM6 Open Up Your RDBMS with Open WS6 The Enterprise Service Bus: (ESB): WS11 Designing Web Services Using UML using J2SE and J2ME Standard Technologies Leveraging Web Services

.NET TRACK: June 25-27 IT Strategy Track: June 25-27 Who Should Attend… Combining technology, platform, and architecture, the .NET Track provides The IT Strategy Track will focus on the managerial and design aspects of the various development disciplines. Topics will include • DEVELOPERS, insight on the latest developments for the Windows platform. Standards, Architecture, Design Patterns and Best Practices, Project Planning and Management, and Extreme Programming. PROGRAMMERS, NT1 Configuring .NET for Security, Performance, and Reliability ENGINEERS NT2 Changing Your Environment to .NET IT1 Developing, Deploying and Managing Web Services IT8 Minimizing Risks and Maximizing Investments in J2EE • i-TECHNOLOGY NT3 Going Mobile with .NET IT2 Key Trends and Technologies for Building an Development Through the Use of Reusable Application PROFESSIONALS NT4 .NET on Other Platforms (FreeBSD, MONO, Portable .NET) Enterprise Web Services Architecture Architecture and Frameworks • SENIOR BUSINESS NT5 Inside the CLR IT3 Selecting a Framework: Toolkit, Platform, or IT9 Application Integration – Building a Flexible Web Services MANAGEMENT NT6 Accessing Data from .NET Roll Your Own? Architecture • SENIOR IT/IS NT7 Advanced .NET Web Services IT4 Getting Started with Web Services IT10 The Economics of Web Services MANAGEMENT/C LEVEL NT8 Migrating Legacy Code to .NET IT6 Overcoming the Web Services Barriers IT11 Hooking It All Together - Application Integration Case Study EXECUTIVES NT9 Advanced User Interfaces with GDI+ IT7 The Real Issue: Improving Your Enterprise with Enterprise Web Services • ANALYSTS, CONSULTANTS

Sun Microsystems at JDJEdge 2002: Java Fast Paths & Java UniversitySM Program at the Jacob K. Javits Convention Center, NYC

Java Fast Paths Java University SM Attend fast-paced, code-level, full-day Java technology developer training designed to The Java UniversitySM Program complements this year's JDJEdge Conference by offering three aggressive, full-day, code-level training classes provide you with the skills to confidently approach the industry's core Java technolo- for experienced software developers, architects and engineers. gy certification exams. Don't just say you know it… prove it! Most developers rec- ognize the expanding importance of gaining Java technology certification. If you're Attend code-level training in sessions designed by industry luminaries, and recognized experts. Sessions cover XML and Web services technolo- like those who've already taken the exams, the real hurdle to certification is finding gy. Whether you're a beginning or a veteran developer, architect, or software engineer, you'll benefit from these value-packed full-day courses. time to prepare for the tests. Register now. Seating is limited. Monday, June 24, 2002: • Java™ 2 Platform: Developer Certification Fast Path Tuesday, June 25, 2002 Wednesday, June 26, 2002 Thursday, June 27, 2002 • Java™ 2 Platform: Architect Certification Fast Path Developing Solutions Using Java™ Web Services Programming Using Java™ Java™ APIs for Enterprise Web Services • Web Component Developer: Certification Fast Path Technology and XML Technology and XML

FOR EXHIBIT INFORMATION CONTACT: MICHAEL PESICK 135 CHESTNUT RIDGE RD. • MONTVALE, NJ 07645 • 201 802-3057 [email protected] OWNED AND PRODUCED BY PRODUCT REVIEW JDJ Labs

t’s unfortunate that programmers come “Start” button is clicked, Java-Miner will ana- and go at an alarming rate in the IT lyze the packages and create the roadmap. Iindustry, leaving code that must be An object browser provides a dropdown maintained by someone who quite fre- view of the analysis you’re working on. Many quently had no hand in writing it. Software IDEs work this way so most people will easily engineers using UML have models on how make sense of this. The graphical layout is basi- their programs behave, but the rest of us cally a large blank workspace that’s scrollable. are left to read through reams and reams Within this area you can zoom in and focus on of methods. Most of the time all you need specific components or zoom out for an overall is an overview of how the program is picture. These graphical views can be output to made up, not the finer details. a printer for a permanent copy of the analysis. Working with the analysis is easy, but the Java-Miner blank screen is a little off-putting to the new J2SE CAST’s Java-Miner provides a graph- user. I expected to see some sort of roadmap ical “roadmap” of Java packages, classes, on-screen, which could be customized as and their associated methods and con- required. Instead the user is expected to drag structors. As the saying goes, “A picture the object onto the output screen, which paints a thousand words”; this applica- drops the object onto the roadmap. It’s up to tion can tell the whole story behind Java the user to expand the other methods and classes in a way that’s easy to interpret. constructors of that object by right-clicking and then selecting “Expand.” The parts of the J2EE J2ME Installing and Using Java-Miner object will appear and link together. The Installation is straightforward. A expanded links provide a wealth of informa- self-installing package can be down- tion about where methods are called from and loaded from CAST’s Web site (it’s a 15- which objects they belong to (see Figure 1). day evaluation) or it can be installed For a programmer looking at some code for from the distribution CD. The Help doc- the first time, it’s an enormous benefit to be able

Java-Miner umentation is also installed onto your to learn the program structure without reading Labs system, so you can use Help and pro- through pages and pages of source code. by CAST gram simultaneously. With large applications the amount of Home Java-Miner works via a series of wiz- detail on the roadmap can be overwhelming, REVIEWED BY JASON BELL [email protected] ards that guide you through the process of so you can tailor the amount of detail dis- loading in a Java application to view. When played by setting up a series of layers. For info CAST starting the program you’re asked whether example, you can create a layer to display the 3, rue Marcel Allégot you want to load an existing analysis or cre- relationship links between the methods and ate a new one. Creating a new analysis is a another layer to display the objects, not the 92 190 Meudon simple process, again using a wizard to gath- methods within them. Another useful feature is Paris, France er the required information. A project name Java-Miner’s ability to work its way through a Phone:+33 1 46 90 21 00 is required, which becomes the XML output batch of objects and show a roadmap from one Fax:+33 1 46 90 21 01 filename. This, by default, is saved to the root specified method to another. So if you know directory of the “C” drive on your system, so it’s that an object references a method but can’t Web: www.castsoftware.com very important to use the directory-browsing see how, let Java-Miner do the work for you. function to place the output files somewhere Test Environment sensible. In my opinion, this is a big oversight Summary Computer: Compaq Presario 1920 and perhaps a default directory should be My first impressions were positive, though included somewhere in the proceedings. I was a little surprised about the file locations Processor: 300MHz Pentium III Within this wizard the Java source files and that Java-Miner was using; with a little plan- Hard Drive: 4GB associated classpaths are added. Once the ning this won’t be a problem for most people. Memory: 64MB For those who need to maintain a working Platform: Windows ME application in which time is precious, Java- Miner may be the answer.

Specifications Product Snapshot Platforms: Windows 98, 2000, Target Audience: Java programmers, busi- or NT 4.0 ness analysts Level: Beginner to advanced Pros: • Easy to use • Graphical roadmaps are easy to read. Cons: • No default directory; used defaults to the FIGURE 1 Example Java-Miner roadmap root directory

92 MAY 2002

Java COM Web Services Edge Conference & Expo www.sys-con.com

MAY 2002 93

Java COM APP RELEASE MANAGEMENT ManifestDestiny Simplify the packaging and releasing

J2SE of Java applications

WRITTEN BY eleasing Java applications can be a real challenge. Fortunately, Java provides a rich NORMAN R set of features for packaging and deploying applications that can simplify the release RICHARDS process significantly.

This article presents some of the issues files contain a very basic manifest file by bute to a specific class or package. I’ll J2EEinvolved with packaging J2ME Java code. I’ll default. Try examining the META- show examples of that later. explore the Java manifest file and sug- INF/MANIFEST.MF file using any JAR gest ways it can be used to manage JAR (or ZIP) program. This can be done with Inserting the Manifest file dependencies and to eliminate any ZIP file tool or by using the JAR com- To add a manifest file to a JAR file, the classpath issues normally associated mand directly. “m” option is used and the filename of with cross-platform deployment. I’ll manifest file is passed to the JAR pro- also explain how to use the package- jar xvf myapplication.jar META- gram after the name of the JAR file. versioning features of the manifest to INF/MANIFEST.MF ensure the compatibility of packages jar cvfm myapplication.jar myap- Home used. If your JAR file was created by the JAR plication.mf -C classdir . tool, you should see a simple default What Is a JAR File? manifest file. If you use the Ant build tool, the man- During development, Java classes are ifest can be specified by adding a mani- normally compiled into local directories Manifest-Version: 1.0 fest attribute to the JAR specification: on a disk. Java applications can be run Created-By:1.4.0-beta(Sun and even distributed in this manner, but Microsystems Inc.) it’s not a practical way to work. Fort- bution and execution. manifest file format. The next line tells known archive format makes JAR files manifest file was created, for example, exceptionally easy to work with. Many by the Ant build tool, then you might tools and libraries exist for manipulat- expect to see something like “Created- ing ZIP files, so for the developer the By: Ant 1.2”. When creating your own A Java Executable tool set is very rich. However, since manifest files, put in text that’s relevant Now that you’ve had a small taste they’re in a simple archive format, JAR to your own project. of the manifest, let’s step back and files can’t natively express metainfor- look at a few deployment issues that mation about the applications they The Basic Format can be greatly simplified by the mani- contain. The format of the manifest is simple. fest. To launch a standard Java appli- Each line of the manifest file is a name- cation, I need to invoke a Java Virtual The Manifest Is Born value pair. The attribute name is first, Machine and include the application To provide metainformation that followed by a colon, and then the attri- JAR in the classpath, then specify the describes the archive, the JAR file desig- bute value. Lines should be limited to 72 class I want to invoke. Let’s assume nates a special directory to hold the characters, but if you need more than again that the JAR is myapplication.jar metainformation, the META-INF direc- that, you can continue a value on the and the application main class is AUTHOR BIO tory. For our purposes, I’m concerned next line by starting the line with a com.example.myapp.MyAppMain. Norman Richards with only one file in this directory, MAN- space. Any line that begins with a space The application start script will need works at Commerce IFEST.MF. This is the manifest file for the is considered a continuation of the pre- to invoke: One Labs, the JAR. It describes the contents of the JAR vious line. research division of file and provides application informa- All the attributes at the top of the file java -classpath myapplication.jar Commerce One. tion to the JVM at runtime. Most JAR are global. You can also apply an attri- com.example.myapp.MyAppMain

94 MAY 2002

Java COM SYS-CON Industry Newsletters www.sys-con.com

MAY 2002 95

Java COM APP RELEASE MANAGEMENT

While this isn’t an overwhelmingly complicated task, it’s awkward specifying the main class external to the JAR file. If I were writing a stand- alone application, I’d expect the application to know the class I want to start execution at. I can specify this with the Main-Class attribute in our manifest.

Manifest-Version: 1.0 Created-By: JDJ example Main-Class: com.example.myapp.MyAppMain

Now, if I add the manifest to our JAR, I can invoke our Java application much more simply. J2SE

java -jar myapplication.jar

This is definitely a much simpler and less error-prone way to launch an application. Managing JAR Dependencies This first step is good, but very few Java applications can be distrib- J2EE J2ME uted as a single JAR. Typically, I need support libraries. Suppose my application is using Sun’s Javamail classes and I need to include activa- tion.jar and mail.jar in my classpath. My previously simple Java -jar com- mand becomes a bit less pleasant.

java -classpath mail.jar:activation.jar -jar myapplication.jar

Matters are further complicated by the fact that the classpath specifi- cation varies between operating systems. On Unix, classpath elements Home are separated by a colon, but on Windows, classpath elements are sepa- rated by a semicolon. Again, the manifest file provides a way for me to manage this com- plexity. What I really have is a JAR dependency. myapplication.jar now depends on mail.jar and activation.jar. Anytime I use myapplication.jar I’ll want those two JARs. I can express this dependency in the myapplica- tion.jar manifest.

Manifest-Version: 1.0 Created-By: JDJ example Main-Class: com.example.myapp.MyAppMain Class-Path: mail.jar activation.jar

Now I can once again invoke the application in the original simple manner.

java -jar myapplication.jar

Let’s look more closely at how this works. The Class-Path attri- bute is a space-separated list of relative URLs pointing to JAR files that the current JAR references. Keep in mind that I need to escape spaces and special characters as I would in a URL (a space would be escaped as “%20”). I also need to use a forward slash (“/”) as the directory separator, regardless of the platform preference. Also note that the URL reference is indeed relative. I couldn’t specify C:/some.jar or/usr/local/java/lib/someother.jar as a dependency if my intent is to root my file search path anywhere other than the cur- rent directory. Also, note that when I install the application I still need to make sure that mail.jar and activation.jar are in the same directory as myap- plication.jar, otherwise the application will fail to find the JARs I need. As an alternative, some developers prefer to place support JARs in a sub- directory. For example, suppose that next to the application JAR is a direc- tory ext that contains the support libraries. I could use a manifest like this:

96 MAY 2002

Java COM Simplex Knowledge Company www.skc.com

MAY 2002 97

Java COM APP RELEASE MANAGEMENT

Manifest-Version: 1.0 Created-By: JDJ example Main-Class: com.example.myapp.MyAppMain Class-Path: ext/mail.jar ext/activation.jar

Again, keep in mind that the classpath components need to be spec- ified as if they were a relative URL component and were not using plat- form-specific naming conventions. Multiple Main Classes It’s not uncommon for Java applications to provide multiple entry points. Perhaps you have both a command-line and a GUI version of J2SE your application, or perhaps a main application with several support tools that share a lot of the same code base. In this case, a good approach is to package all the common JARs into a single application code JAR. Separate application JARs could be creat- ed for each entry point, each containing a manifest file with a depen- dency on the library JAR and a main-class entry that represents the entry point. Depending on the development setup, you may find it simpler to keep all the classes (including the front-end classes) in the library JAR or J2EE J2ME to package the front-end classes only in their corresponding JAR. The lat- ter is cleaner, but may be troublesome if you haven’t organized your classes for easy separation. The resulting application would look like the following: the lib JAR con- tains the class files and the dependencies for those class files; the remaining JARs are empty, minus the manifest, and depend only on the classes JAR.

Manifest for myapplicationlib.jar: Manifest-Version: 1.0

Home Created-By: JDJ example Class-Path: mail.jar activation.jar

Manifest for myappconsole.jar: Manifest-Version: 1.0 Created-By: JDJ example Class-Path: myapplicationlib.jar Main-Class: com.example.myapp.MyAppMain

Manifest for myappadmin.jar: Manifest-Version: 1.0 Created-By: JDJ example Class-Path: myapplicationlib.jar Main-Class: com.example.myapp.MyAdminTool Package Versioning After you’ve distributed code, a key issue in release management is figuring out exactly what code you have. What version of the code is run- ning now? What versions of the support libraries are you using? There are a number of approaches to this problem, but the manifest file provides a very elegant solution. In the manifest file, you can describe every pack- age provided in the JAR file according to the Java versioning system. Java is based on the principal of separating the specification of a tech- nology from its implementation. A package’s specification defines what the package is and the implementation defines who is providing the implementation of the specification. The specification and implementa- tion are described by a name, a version number, and a vendor. To get a

PROPERTYPROPERTY VALUE VALUE

java.vm.specification.versionjava.vm.specification.version 1.0 1.0 java.vm.specification.namejava.vm.specification.name Java Java VirtualVirtual MachineMachine SpecificationSpecification java.vm.specification.vendorjava.vm.specification.vendor Sun Sun Microsystems Microsystems Inc. Inc. TABLE 1

98 MAY 2002

Java COM Dynamic Buyer Incorporated www.ibm.com/small business/dynamicbuyer

MAY 2002 99

Java COM APP RELEASE MANAGEMENT

feel for this information, let’s first look at a few JVM system properties (queryable via java.lang.System.getProperty()). Java first defines the version of the JVM specification being used (see Table 1). This explains that the JVM I’m running is an implementation of Sun’s JVM Specification 1.0. It doesn’t tell me who created the JVM, it just states that the JVM conforms to a certain standard. To see implementa- tion details, I have to look at the implementation properties. Table 2 is from a Java 1.3 release from Sun. Again, this states that the JVM is from Sun and is the HotSpot Client JVM. The version is 1.3.0_04, which happens to correspond with the API version number but is not formally related to it. The Java API specifica- J2SE PROPERTY VALUE

java.vm.version 1.3.0_04 java.vm.name Java HotSpot(TM) Client VM java.vm.vendor Sun Microsystems Inc. TABLE 2

tion and implementation are also defined in system properties J2EE J2ME ("java.specification.version", "java.specification.name"), but since I’m focusing on my own releases, not the JVM, I’ll show how to apply Java versioning to the libraries. In the manifest file, I can define both a specification and an imple- mentation version for each package by declaring a named entity and then adding specification and implementation attributes. These attri- butes are: • Specification-Title • Specification-Version Home • Specification-Vendor • Implementation-Title • Implementation-Version • Implementation-Vendor

Specification information is useful primarily when providing a library or programmatic interface to the outside world, or implement- ing a programmatic interface defined by a standards body. However, another candidate for specification information for an application would be a design or requirements document, if your development process calls for it. Implementation attributes can be used to track the internal release information. A common technique is to track internal build numbers in the Implementation-Version field. Let’s extend the manifest to include package information. Suppose I’m releasing build 2002-03-05-A of version 2.4 of MyApp; I could repre- sent this with the following manifest:

Manifest-Version: 1.0 Created-By: JDJ example Class-Path: mail.jar activation.jar

Name: com/example/myapp/ Specification-Title: MyApp Specification-Version: 2.4 Specification-Vendor: example.com Implementation-Title: com.example.myapp Implementation-Version: 2002-03-05-A Implementation-Vendor: example.com

Remember to include a blank line between the main attributes sec- tion and the entity attributes section and to use slashes, not dots, when referring to packages and class-attribute sections. Think of this as refer- ring to the name of the entity as it exists in the JAR file, not by the true package or class names.

100 MAY 2002

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

*Offer subject to change without notice

Java COM APP RELEASE MANAGEMENT

It’s quite likely that the JAR file will provide multiple packages. They can all be specified in the manifest. Just remember to leave a blank line between each section. Querying Package Version Releasing package information in the manifest is good, but ideally I’d like to be able to access package information at runtime. Java provides convenient access to the manifest package attributes via the java.lang.Package class. There are three basic ways to get a package object. 1. Package.getPackages(): Returns a list of all the packages currently defined by the system J2SE 2. Package.getPackage(String packagename): Returns a package by name 3. Class.getPackage(): Returns the package object for a given class

Using these functions, I can provide dynamic logging of package ver- sion information (see Listing 1). It’s very important to note that if no classes have been loaded from a given package by the class loader, then there will be no Package object J2EE J2ME available for the package. That’s why I test for null at the beginning. This is important because you may be tempted to log all the packages in the system at startup. However, it’s unlikely that all the relevant packages in the application will have been loaded yet. Still, package version informa- tion can be quite valuable (particularly for support purposes) so it’s a good idea to make this information readily available. Summary The manifest file provides a wealth of useful metainformation and Home greatly simplifies the task of packaging and releasing Java applications. We’ve seen how to package classes in JAR files, how to track dependen- cies between JARs, how to turn JARs into executables, and how to track the versions of packages in classes. These are the basic tools for applica- tion release management in the Java platform. Making proper use of this functionality can greatly simplify this task. Manifest Tips • Always start a manifest with the Manifest-Version attribute. • Limit lines to 72 characters; if longer lines are needed, use line continuations. • Make sure the last line has a carriage return at the end; otherwise the line will be ignored. • If a Class-Path entry crosses directories, use “/” as the directory sepa- rator, regardless of the platform. • Separate main attributes from entity attribute sections by a blank line. • Use slashes, not dots, to delimit package and class entities. • Class entities should end with .class and package entities should end with a slash (“/”).

[email protected]

Listing 1 void logPackage() { Package package = Package.getPackage("com.example.myapp"); if (package == null) { System.out.println("com.example.myapp not loaded"); return; } System.out.println("com.example.myapp version " + package.getSpecificationVersion() + " build #" + package.getImplementationVersion()); }

102 MAY 2002

Java COM JDJ Store www.jdjstore.com

MAY 2002 103

Java COM Exclusive: Excerpts from JavaDevelopersJournal.com WIRELESS AND WEB SERVICES COMBINE TO KEEP JAVAONE JIVING…AND JAVA THRIVING by JDJ News Desk “My expectations were pretty low,” he says, “ given the econ- “WHAT WERE YOUR OVERALL IMPRESSIONS OF JAVAONE omy. Most shows have been at about 50% capacity.” But he 2002?” we asked a select handful of the movers and shakers of was impressed, he explains, with the scope and results of contemporary enterprise Java-based computing JavaOne.

(April 12, 2002) – It’s a cliché that, in a difficult economy, it is “I was impressed with traffic…which underscores two impor- business leaders and business leaders alone that stand out. But tant items: 1) there are a sufficient number of new folks coming J2SE it’s a cliché that was shown to be at least partly valid by what was into the Java world to sustain and grow the community, and 2) on display – and who was displaying it – at JavaOne 2002, which there is sufficient new content, primarily in the area of Web ser- took place at the end of March in San Francisco’s huge Moscone vices and wireless to hold developers’ interest in the long term.” Center.... “While I remain a huge fan of J2EE,” Roth concludes, “I am utter- ly amazed by the non-PC devices running Java.” JavaOne 2002 Was “Amazing,” Says Gosling James Gosling, the “father” and co-creator of Java and never one Sun’s Own EVP Is “Blown Away” to mince words, was unequivocally jazzed by the whole event: Patricia C. Sueltz, executive vice president of Sun’s Software J2EE“It was amazing,” he says, J2ME simply. Systems Group, is as enthusiastic about JavaOne 2002 as James Gosling is. Her way of explaining it is a little different, “Despite the economy and awkward scheduling,” Gosling con- though, and makes reference to Java processes as much as to tinues, “attendance was strong, and everyone I met was charged products. up. I didn’t encounter anything hat felt like the vapor of past years: just solid companies with actual revenue.” “First, I was blown away by all the different ways that people are using Java and what a huge success it is,” she says. “Java is clear- Exclusive Was there anything that stuck out as being a new killer app of ly the de facto standard for server-side development. I continue Javaland? “The technology has become so broad that it’s hard to to be amazed at how adoption keeps growing and more and Home ‘pick a winner’ – in a sense, they all are,” Gosling replies. “To me, more applications keep appearing that enable enterprise and it’s this broadness that is the real exciting feature these days: the legacy data to be accessed with Java. It’s really a testament to whole end-to-end architecture is there.” what a community working together, like the , can accomplish. But once a geek always a geek, and no one who knows Gosling should be the least surprised to hear him confess: “Then, of “Second,” Sueltz continues, “the momentum of Java technology course, there were those cases at the entrance to the exhibit in the wireless space is really strong. Large wireless carriers halls filled with very cool, very lovely gadgets. Major objects of around the world realize that interactive applications create a geek lust!” whole new revenue opportunity and that Java provides an inde- pendent, standards-based application platform for them. This Web Services and Wireless Are the New Hot Areas combined with the exciting range of phones and mobile devices Bill Roth, Sun’s group marketing manager, is completely can- being offered or on the way will drive Java technology’s accept- did about the realities of the present economic turbulence. ance to unprecedented levels.”

RECEIVE $150 DISCOUNT OFF FULL CONFERENCE WEB SERVICES EDGE REGISTRATION Paolini and Williamson Praise Return to Basics phase of Web services, the definition phase, is drawing to a George Paolini, chief marketing officer of Zaplet, Inc., is in no close.” doubt: “All-in-all a great show,” he affirms. “I saw a focus on back to basics, and that’s a strong reflection of Java’s role in the enter- “Without exception,” he continues, “vendors had already pro- prise, which has been clearly established.” vided the back-end connectivity within their products to allow them to expose a Web service interface.” As Rhody suc- Alan Williamson, who as editor-in-chief of Java Developer’s cinctly puts it, so far as Web services is concerned, “The battle Journal has become famous for calling for just such a back-to- for acceptance is over. The battle for respectability has basics shift for the past year, agrees. begun.”

“This JavaOne was a great one as usual,” enthuses Williamson. It is a battle that is next joined June 24-27 at Web Services Edge “Of all the JavaOnes I can remember,” he continues, “this was 2002 (East) International Web Services, Java, and XML one of the ones that makes this particular event so great.” While Conference & Expo at the Jacob Javits Convention Center in New the overall foot traffic may have been down significantly, he York City (www.sys-con.com/webservicesedge2002east).

Java is clearly the de facto standard for server-side development.... “adoption keeps growing and more and more applications keep appearing that enable enterprise and legacy data to be accessed with Java ” adds, there was “time to talk to people and find out what was Last Word to Scott McNealy happening in the real world with Java.” No wrap-up of JavaOne would be complete without some kind of 65,000-foot view from Sun’s highest flier, chief execu- The major points that Williamson draws attention to are first the tive Scott McNealy. Asked by JDJ what his strongest impres- fact that people seemed to have given up on always-on wireless. sions of the week were, from a Java industry point of view, he “Where in previous years,” he says, “companies were building cuts straight to the chase: “To me, it all comes back to open – software assuming that a network would be there that was and open means interoperability. That’s the promise of Java, always on, this hasn’t transpired, so a lot of those same compa- and we all have to do our best to keep that promise, year after nies are now concentrating on synching software to make use of year.” the network when and if it’s online.” “Every chance I get,” McNealy continues, “I urge developers to Second, Williamson noticed that while in previous years, test their applications for compatibility on at least two app “software tool vendors followed the vogue and produced a servers to make sure they haven’t picked up any proprietary whole raft of UML tools, intimidating all those who didn’t use extensions in the tools they use. Incompatibility is the wrong them, and now the shift has moved to performance and analy- answer. It limits the value of your application and the size of sis tools.” your market.”

“Respectable”Web Services Here We Come? Now who in Javaland could possibly quarrel with that? Williamson’s last point struck a chord, not surprisingly, with the editor-in-chief of Web Services Journal, Sean Rhody, who declares that it was clear to him at JavaOne 2002 that “the first To read the full text, go to www.sys-con.com/java/ Jump-start your Web Services knowledge. Get ready for Web Services Edge East and West! AIMED AT THE JAVA DEVELOPER COMMUNITY AND DESIGNED TO EQUIP ATTENDEES WITH ALL THE TOOLS AND INFORMATION TO BEGIN IMMEDIATELY CREATING, DEPLOYING, AND USING WEB SERVICES. EXPERT PRACTITIONERS TAKING AN APPLIED APPROACH WILL PRESENT TOPICS INCLUDING BASE TECHNOLOGIES SUCH AS SOAP,WSDL, UDDI, AND XML, AND MORE ADVANCED ISSUES SUCH AS SECURITY, EXPOSING LEGACY SYSTEMS, AND REMOTE REFERENCES. PRESENTERS... Anne Thomas Manes, Systinet CTO, is a widely recognized industry BOSTON, MA (Boston Marriott Newton) ...... SOLD OUT! JANUARY 29 expert who has published extensively on Web Services and service-based comput- SOLD OUT! ing. She is a participant on standards development efforts at JCP,W3C, and UDDI, WASHINGTON, DC (Tysons Corner Marriott)SOLD OUT!.....FEBRUARY 26 and was recently listed among the Power 100 IT Leaders by Enterprise Systems, which praised her “uncanny ability to apply technology to create new solutions.” NEW YORK, NY (Doubletree Guest Suites)...... NEW DATE! APRIL 19 Zdenek Svoboda is a Lead Architect for Systinet’s WASP Web SAN FRANCISCO, CA (Marriott San Francisco) ...... MAY 13 Services platform and has worked for various companies designing and developing Java and XML-based products. REGISTER WITH A COLLEAGUE AND SAVE 15% OFF THE $495 REGISTRATION FEE.

EXCLUSIVELY SPONSORED BY Register at www.sys-con.com or Call 201 802-3069 LETTERS TO THE EDITOR

Going IDE-less t was interesting to read in Alan Assembly Line Development IWilliamson’s editorial “Java 1.4 and the think the answer Keith Brown Rest!” (Vol. 7, issue 3) that he has foregone Iis looking for in his editorial the IDE and is going it alone with the JDK. “The IDEal Way Forward for My partner and I started out with JBuilder, Software Development” (Vol. and after a couple of years decided to junk 7, issue 3) is nothing new at it and use UltraEdit and the JDKs. We rea- all, it happens to every pro- soned that JBuilder was keeping us away fession. Programming is from the language and was a barrier to going through the same using third-party code and tutorials. We’ve transition that other pro- J2SE been really happy with the results (it’s been fessions have gone a year) and feel that we have grown in the through in the past. language enormously. I get a lot of strange Craftsman are only a temporary looks (especially from software managers phenomenon in any profession. How who see IDEs as a magic bullet for the “fear often do you visit your local blacksmith of programming” problem) when I tell when you need a new part for your car or them based on the success people that I don’t use an IDE. It’s nice to visit the carpenter to turn a new leg for a they’ve achieved. hear that others also aren’t using it. broken chair. Blacksmiths and carpenters There is one glaring exception. In the J2EE J2ME don’t exist in this capacity anymore. Cars “wounded” category, he names the Frank Cooley are stamped out by other machines and a Preferences API. But this API is brand new! [email protected] whole new chair, assembly-line produced, It did not become final until February is cheaper than the 2002, as part of the Java 2 Standard Edition his is a great editorial. I cost of fixing your bro- Release 1.4. It is simply unknown whether Tcan relate directly to ken one. this API will be a dismal failure, a brilliant what Alan Williamson is Software develop- success, or something in between. In cate- Letters talking about regarding ment is making the gorizing it as wounded, Deadman may be quality Java architects and same transition. stating his hopes or his predictions, but he Home also VisualAge. Craftsman are simply is certainly not stating the facts. The blind leading the too expensive; society Deadman is entitled to his opinion, blind...also the blind teach- can’t afford to have but it is worth noting that other com- ing the blind (offshore tech them building every- mentators don’t share it. For example, schools). And I don’t even day items. As soon as a David Flanagan lists this API as one of want to start on my dislike profession is well- the “Top Ten Cool New Features of Java for VisualAge...I would enough understood, 2SE 1.4” (www.onjava.com/pub/a/onja- never finish this e-mail. engineers will find a va/2002/03/06/topten.html). Although I do enjoy using way for a machine to Time will tell whether the Preferences IDEs such as JBuilder – features such as replace the craftsman. “Hard-core” devel- API succeeds or fails, but responsible having a dropdown method list when you opers do exist: they’re building special- journalism dictates that its failure not be type a period after an object are great. I ized software. But the bulk of the pro- announced prematurely. have to admit, there are some definite grammers today are piecing advantages over the “notepad” IDE. together COTS software and Josh Bloch I’ve been contracting in the industry painting screens with IDEs. [email protected] for some time and have seen It’s simply the profession various hiring tactics. For transitioning from crafts- Josh,first of all let me example, one company manship to assembly line. thank you for your e-mail. searching for a lead archi- You’re a legend in Java cir- tect set their entire focus on Scott Wills cles,and before now,we finding someone who was a [email protected] haven’t had the opportunity guru in VisualAge, to cross paths.It’s a shame WebSphere, and Unix while Preferences API Unfairly the first time is a complaint placing minimal (close to Categorized about one of our articles. zero) focus on actual archi- ichard Deadman’s arti- Richard Deadman tecture experience and tech- Rcle “An API Developer’s was indeed expressing his niques. That’s like giving Primer” (Vol. 7, issue 3) con- own views. As it was the someone a job to write arti- tains many good points, but sort of piece that had to cles for a periodical based I believe the author let his biases get the do this, we allowed him some breadth. solely on the fact that that better of him on one point. The article Although it is fair to note that he did categorize person knows the “ins and purports to divide APIs into three cate- the API as “wounded” as opposed to “dead,” the outs” of Microsoft Word. gories: “dead,” “wounded,” and “victors.” which means he felt it lacking in some respects, For the most part his taxonomy is thus giving it one down from the “victor” status. DJ fair: he picked APIs that have been [email protected] around for a few years and categorized Alan Williamson

106 MAY 2002

Java COM SYS-CON Subscription Offer www.sys-con.com/suboffer.cfm

WebLogic Developer’s Journal www.sys-con.com/weblogic

MAY 2002 107

Java COM JAVANEWS>

SavaJe Attains J2SE Compliance for SavaJe OS JDJ’S APRIL EDITORIAL (Chelmsford, MA) – SavaJe Technologies > RALLIES JAVA CAMP has announced that it is the first Java licensee to provide a commercially avail- (Montvale, NJ) – SYS-CON Media has published a able J2SE-certified operating system for special editorial, written by JDJ’s editor-in-chief handheld and wireless devices, having Alan Williamson, on its Java Developer’s Journal passed all the official Sun Compatibility Web site. It focuses on the .NET versus J2EE ques- Test Suite (CTS) tests required for J2SE tion surrounding the i-technology marketplace. The J2SE compliance. editorial entitled “There May Be Trouble Ahead…” www.savaje.com sheds light on the hottest discussion topic of the year (www.sys-con.com/java/article.cfm?id=1401). ILOG Releases JRules 4.0 This editorial was read by more than 100,000 (Mountain View, CA) – ILOG, a supplier readers within two hours after it appeared on SYS- of software components, has announced CON’s Web site, and over 500 readers responded the immediate availability of ILOG within the first two hours of its publication. It was visualization toolkit. JRules 4.0, an enterprise-class business also instantly picked up and simultaneously pub- JLOOXLayout 3.0 J2EErule engine that brings J2ME customizable lished on the Slashdot.org and JavaLobby.org Web includes three new lay- and comprehensive business rule man- sites. out algorithms for dis- agement to enterprises. www.sys-con.com playing data with pre- Features include the JRules existing classes in addi- Business Rule Repository, a centralized tion to the Layout Editor location for storing business rules and Oracle Combines Java-Enabled Mobile and Layout Manager. all related information, and event man- Devices and the Enterprise www.loox.com News agement features that allow users to (San Francisco) – Oracle Corp. has www.engenuitytech.com create rules for detecting complex announced the immediate availability of Home time-oriented patterns within event the Oracle9i JDeveloper J2ME Add-In Sitraka JClass DesktopViews 6.0 and flows. and the Oracle9i Application Server ServerViews 2.1 www.ilog.com (Oracle9iAS) J2ME Developer Kit. Java (San Francisco) – Sitraka has announced developers can build and deploy mobile the release of Sitraka JClass Borland Debuts Optimizeit Suite and enterprise applications that take advan- DesktopViews 6.0, formerly known as JDataStore 5 tage of the J2ME standard. Both devel- JClass Enterprise Suite, now supporting (San Francisco) – Borland Software opment tools are currently available for Java 2 SDK version 1.4. Corporation announced the expansion a free download from Oracle’s online JClass DesktopViews provides a of the Borland Software Platform for Java developer community, Oracle range of GUI functionality including 2D with the debut of Borland Optimizeit Technology Network (OTN). and 3D charting, layout and reporting, Suite and JDataStore 5 at the JavaOne www.oracle.com GUI enhancements, JAR optimization, Conference. hierarchical data display, tables and Optimizeit Suite is a performance TogetherSoft Delivers Together grids, data connectivity, and data input assurance solution for robust applica- ControlCenter 6.0 and validation. tion development that integrates with (Raleigh, NC) – TogetherSoft Corporation In addition, JClass ServerViews 2.1 development and deployment environ- has announced the availability of has a set of 100% Java server-side com- ments. Together ControlCenter 6.0 for applica- ponents and includes JClass www.borland.com tion development. Key enhancements ServerChart 2.1 and JClass include a new UI builder, improved text ServerReport 2.1. editor, new refactorings, and full J2EE www.sitraka.com RATIONAL’S NEW ADAPTIVE 1.3 certification includ- TEST PLAYBACK TECHNOLOGY ing support for EJB 2.0, JTurbo 3.0 Released > Web services support, (San Francisco) – New Atlanta and a new XML editor. Communications has announced the (San Francisco) – Rational’s new Adaptive Test www.togethersoft.com availability of JTurbo 3.0, the newest Playback technology will provide the industry with release of its Type 4 JDBC Driver for self-correcting object recognition, reducing the LOOX Releases Microsoft SQL Server, which implements need to update existing tests throughout the appli- JLOOXLayout 3.0 the JDBC 3.0 specification. cation’s life cycle. (San Francisco) – Among the added or improved fea- Rational’s Adaptive Test Playback technology can LOOX Software, a tures for JTurbo 3.0 are savepoint sup- automatically find target objects without the need subsidiary of port, statement pooling support, for human intervention and time-consuming object eNGENUITY improved connection pool configura- remapping. Technologies, has tion, retrieval of parameter metadata, www.rational.com/testjava released a new ver- and retrieval of autogenerated keys. sion of its Java-based www.newatlanta.com

108 MAY 2002

Java COM EnginData Research www.engindata.com

WebSphere Developer’s Journal www.webspheredevelopersjournal.com

MAY 2002 109

Java COM What’sOnline... May 2002

JavaDevelopersJournal.com Visit www.javadevelopersjournal.com and learn about the latest news and events from the world’s leading Java resource. Know what’s happening in the J2SE industry, minute by minute, and stay ahead of the competition.

SYS-CON Radio at JavaOne Listen to host Alan Williamson and other JDJ edi- tors as they interview the industry’s CEOs, CTOs, and other top management. Tune to www.sys-con.com/ java/javaone2002.cfm and hear discussions on tech- J2EE J2ME nology, programming, standards, and more with the Java world’s top minds.

JDJEdge 2002 Conference and Expo Register Now for the World’s Largest Independent Java Event! JDJEdge 2002, SYS-CON’s third annual Java- Online focused show, will be held June 24–27 at the Jacob Javits Convention Center along with Web Services Home Edge 2002 and XMLEdge 2002. The shows will be colo- cated with TechXNY/PC Expo. Participate with fellow developers, architects, IT management, and other i-technology professionals in Java Technology Fast Path Certification classes, panel discussions, and three full-day Java classes. Topics include “Java 1.4: What’s New,” “Building Truly Portable J2EE Applications,” “Java Tools for Extreme Programming,” and “.NET vs J2EE.” Register online at www.sys-con.com/jdjedge2002 east/registernew.cfm

2002 Readers’ Choice Awards Make your opinion count. Vote today for the Java Developer’s Journal Readers’ Choice Awards, which have earned the reputation as the most respected industry awards program of its kind. Known as the “Oscars of the Software Industry,” this year’s awards feature an expanded list of product categories and other additions that will make the fifth annual Readers’ Choice Awards the best so far!

Call for Papers SYS-CON Events, Inc., invites proposals for speak- er consideration at Web Services Edge 2002 West, October 1–3, 2002, at the San Jose Convention Center in San Jose, CA. Ideal candidates are Java developers, Web Services developers, XML developers, .NET developers, industry analysts, IT/IS management, and other industry experts who have first-hand expe- rience in the development or implementation of Web services, Java applications, or XML-based technolo- gies. If you have something substantive, challenging, and original to offer, we encourage you to submit a proposal, and become part of the conference faculty for the i-technology event of the year! Deadline is May 15, 2002. 110 MAY 2002

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

ices j GUARANTEED rv ou GUARANTEED e r S b n e a

l W WSJ

Readers’ WEB SERVICES CHOICE World class AWARD AWARD LOWEST PRICES! SOFTWARE NEEDS MICROSOFT MAINSTAY MICROSOFT $2,238.99 Visual Studio .NET Enterprise Architect $124.00 JustEdit Plus 1.0 $1,629.99 Visual Studio .NET Enterprise Developer

Visual Studio .NET provides developers with the most JustEdit Plus is a offering manual With Visual Studio .NET Enterprise Developer, productive tool for building next-generation applications and automatic editing of Web pages anytime, developers can securely version and share their for Microsoft Windows® and the Web. Visual Studio anywhere, using only a Web browser. Manual source code, share best practices, target scalable .NET Enterprise Architect (VSEA) builds on the power of editing of any target Web page is done in the .NET Enterprise Servers, choose from a wide Visual Studio .NET Enterprise Developer by including applet's HTML editing window. range of third-party tools and technologies, and additional capabilities for designing, specifying, and communicating applica- easily tune the performance of their Web applications and Web tion architecture and functionality. It enables software Services through the extensive performance-testing tools in Visual architects and senior developers to provide architectural guidance Studio .NET. and share best practices across the development team. WHIZLABS N-ARY SILVERSTREAM $39.95 WebSphere@Whiz Certification Simulator $145.00 n-ary Ticket System $495.00 Extend Application Server Developer Edition (5 User)

3 Mock Tests (159 Questions). It comes with a test The Ticket System is a Web-based tool that enables you to SilverStream eXtend is the first comprehensive, engine and a question bank of 159 questions on the lat- log & track important information. The system is extremely real-world development environment for creating est pattern of the IBM WebSphere Certification Exam. It flexible and simple to use and can be utilized in numerous Web Services and J2EE applications. The seam- also consists of a diagnostic test which will help you different situations. It is a completely 'hands off' system. less integration of our proven eBusiness engines know your strengths and weaknesses so you can plan This means that you do not have to waste time and and designers gives you the benefits of XML-based, enterprise-wide your preparation accordingly. resources by continuously checking a Web page for integration and the power to create, assemble and deploy service-ori- updates. ented applications.

WWW.JDJSTORE.COM OFFERS SUBJECT TO CHANGE WITHOUT NOTICE SAVE 16% OFF 12 Issues for $89 99 OFFER SUBJECT TO CHANGE WITHOUT NOTICE • Exclusive feature articles • Interviews with the hottest names in ColdFusion • Latest CFDJ product reviews • Code examples you can use in your applica- tions • CFDJ tips and techniques That’s a savings of $17 89 off the annual newsstand rate. Visit our site at www.sys-con.com/coldfusion/ or call 1-800-513-7111 and subscribe today! SAVE 17% OFF

99 OFFER SUBJECT TO CHANGE WITHOUT NOTICE 12 Issues for $149 • New PowerBuilder features • Tips, tricks, and techniques in server-side programming • DB programming techniques • Tips on creating live PowerBuilder sites • Product reviews • Display ads for the best add-on products That’s a savings of $31off the annual newsstand rate. Visit our site at www.sys-con.com/pbdj/ or call 1-800-513-7111 and subscribe today! CAREER OPPORTUNITIES

Women’sWork Competing in the high-tech world J2SE

his month we focus on women in the engineering world. In this competitive, WRITTEN BY T male-dominated world, female engineers face a variety of challenges. Many of these BILL BALOGLU & challenges have less to do with getting the job done than with getting hired, communi- BILLY PALMIERI cating with their male counterparts, and getting recognized for the work they do. J2EE J2ME

We spoke to three female engineers sus builders, wanting the team to get someone who comes in early and leaves with 35 years of combined experience along well,” she says. “The typical male early,” she says. working in the trenches of high tech. engineer wants to win the argument. In “Good engineers are somewhat pun- Each woman has had different experi- design meetings, whoever can yell the ished in this industry,” she says. “When ences and faced numerous challenges. loudest or argue their point best usually you get your work done on time with no But they all agree that the key differ- wins.” problems, you’re less recognized than ence between male and female engi- “In that environment you can’t try to the person who comes in and fixes the neers is not what they do, but how they build consensus, so I’ve had to become bugs at the last minute. That’s who Home do it. more aggressive in arguing my points,” becomes the hero of the project.” Patty W.’s 18 years of industry experi- she says, noting that less outgoing male Sufie would like to see more compa- ence includes writing commodity trad- engineers also have difficulty prevailing nies offer telecommuting opportunities, ing software and Java Internet security, in such meetings. which could help both male and female and working with operating system Grace traces the lack of female engi- engineers strike a healthier balance internals. In her experience, the indus- neers to the way that math and science between their personal and professional try is competitive for men, but for classes are traditionally taught. “In high lives. AUTHOR BIOS women it’s even harder. However, she school and college almost all my math “As a contractor I’ve done two very Bill Baloglu is a believes men’s culture and upbringing and science teachers were male,” she successful projects from home,” she principal at prepares them for it. says. “They taught courses in a direct, says. “But most companies don’t have ObjectFocus Patty has been the sole woman in fact-based way.” formal telecommuting policies, so it’s (www. ObjectFocus many groups. “I’ve felt like I had to “Men are more likely to memorize hard to get approval for it.” .com), a Java staffing work harder to get the job,” she says. facts; women focus more on how will Even if companies make such policy firm in Silicon Valley. “And work five times as hard to get rec- this work in the real world, for the changes, they may come too late for Bill has extensive OO ognized. On one contract, a man with greater good,” she says. “I was a tomboy, many women in the industry. “I’ve been experience and has 10 years less experience was given the which helped me in class and to be more hoping for a change since I’ve been in held software more challenging piece of the job.” competitive in jobs.” the industry,” says Patty, who reads daily development and Although she’s been the senior engi- Sufie S. considers herself fortunate messages on the women in technology, senior technical neer in many groups, Patty notes that that she hasn’t faced many obstacles as a Systers list serv (www.systers.org). management male engineers are less likely to come to woman in a man’s world. Her BS and MS “A lot of women are jumping ship positions at several her with questions. “Even when there’s degrees in computer science and a because it’s so hard to get the respect Silicon Valley firms. another woman in the group, she tends background in object-oriented design they deserve,” she observes. “Many of to compete with me because she thinks have helped her to move from developer them are going into teaching or non- Billy Palmieri is a she’s being compared with the other to senior software engineer in her 10- profit work. These jobs don’t pay as well, seasoned staffing woman.” year career. but they’re not as competitive.” industry executive and Since 1995 Grace’s positions have Balancing her personal and profes- Although she’s not optimistic about a principal at progressed from Web application engi- sional lives is a challenge for this the current state of affairs for women in ObjectFocus. His prior neer to senior engineer to engineering working mother of a four-year-old high tech, Patty does have a vision for a position was at manager. A year and a half ago she made daughter. She’d like to see an engi- brighter future. “If women could get Renaissance the transition to technical marketing neer’s performance measured less by together and start their own company Worldwide, where he manager, developing demo applications the number of hours worked than by with a more nurturing environment, held several senior and giving product presentations. total productivity. you could have a very productive com- management positions Grace cites the different communi- “In the start-up world environment, pany.” in the firm’s Silicon cation styles of men and women as a key people who come in late and work late Valley operations. challenge. “Women tend to be consen- are perceived as working harder than [email protected]

112 MAY 2002

Java COM ADVERTISERINDEX ADVERTISER URL PHONE PAGE

Actuate Corporation www.actuate.com/info/jbjad.asp 800-884-8665 55 Addison-Wesley 37 Altova www.altova.com 31 AltoWeb www.altoweb.com 35 Next Month AppDev Training Company www.appdev.com/promo/MG00052 800-578-2062 72 Apple Computer, Inc. www.apple.com/macosx 1-800-MY-APPLE 4-5 Ashnasoft Corporation www.ashnasoft.com 71 BEA www.bea.com/download 6 Borland Software Corp. www.borland.com/new/optimizeit/94000.html 79 Canoo Engineering AG www.canoo.com/ulc/ 41 61 228 94 44 25 Document Printing in Java Capella University www.capellauniversity.edu 1-888-CAPELLA 34 Compuware Corp. www.compuware.com/products/optimalj 800-468-6342 21 Keith G. Gauthier shares his simplified process DataDirect Technologies www.datadirect-technologies.com 800-876-3101 33 for printing Java documents. Dice www.dice.com 41 Dynamic Buyer Incorporated www.ibm.com/smallbusiness/dynamicbuyer 99 EnginData Research www.engindata.com 109 ESRI www.esri.com/mapobjectsjava 39 eXcelon Corporation www.exln.com 800-962-9620 77 Fiorano Software www.fiorano.com/tifosi/freedownload.htm 800-663-3621 75 InetSoft Technology Corp. www.inetsoft.com/jdj 888-216-2353 83 Interfacing to AIM with Java Infragistics, Inc. www.infragistics.com 800-231-8588 14-15 Jeff Heaton shows how to create a reusable class InstallShield Software Corp. www.installshield.com 847-240-9111 57 that allows access to America Online’s (AOL) Instant INT, Inc www.int.com 713-975-7434 32 Messenger network. Interland www.interland.com 1-866-270-5279 53 ITtoolbox www.Ittoolbox.com 87 JDJEdge Conference & Expo www.sys-con.com 91 JDJ Store www.jdjstore.com 201-802-3012 103 LOOX Software Inc. www.loox.com 800-684-LOOX 59 Metrowerks Corp. www.wireless-studio.com 11 Mongoose Technology www.portalstudio.com 49 Motorola www.motorola.com/developers/wireless 69 Hello World! in 71 Bytes New Atlanta Communications www.newatlanta.com 73 Norman Richards explains how he used Java Northwoods Software Corporation www.nwoods.com/go/ 800-434-9820 64 class files and the Java Virtual Machine to create a Oracle Corporation www.oracle.com/javacode 800-633-1072 19 small Java “Hello World!” program. Oracle Development Tools User Group www.odtug.com 910-452-7444 89 Parasoft Corporation www.parasoft.com/jdj5 888-305-0041 51 Pramati Technologies www.pramati.com 877-PRAMATI 81 Precise Software www.precise.com/jdj 800-310-4777 23 Prentice Hall PTR 45 QUALCOMM Incorporated http://brew.qualcomm.com/ZJD4 63 Quintessence Systems Limited www.in2j.com 61 Rational Software www.rational.com/offer/javacd2 43 Using the Java Native Interface Productively SilverStream Software www.silverstream.com/coals 1-888-823-9700 29 Andrew J. Chalk addresses the problem of using Sitraka www.sitraka.com/jclass/jdj 800-663-4723 17 the JNI in a production situation and presents a set Sitraka www.sitraka.com/jprobe/jdj 800-663-4723 67 of techniques that simplify most of the repetitive Sitraka www.sitraka.com/performasure/jdj 800-663-4723 116 tasks of passing information to the native code and Simplex Knowledge Company www.skc.com 845-620-3700 97 getting it back into your Java program. Softwired, Inc. www.softwired-inc.com 41-14452370 85 Sonic Software www.sonicsoftware.com 800-989-3773 2 SpiritSoft www.spiritsoft.com/climber 27 Sprint PCS http://developer.sprintpcs.com 65 Sun Microsystems www.sun.com/forte 13 SYS-CON Industry Newsletters www.sys-con.com 201-802-3020 95 SYS-CON Subscription Offer www.sys-con.com/suboffer.cfm 107 TogetherSoft Corporation www.togethersoft.com/1/jd.jsp 919-833-5550 8 Broken Windows in the Java World WebGain, Inc. www.webgain.com/toplink_create3.html 1-877-WebGain Ext.15858 115 Small disorders can lead to larger ones, and per- WebLogic Developer's Journal www.sys-con.com/weblogic 800-513-7111 107 haps even to project cancellations and firings. Joe Web Services Edge Conference & Expo www.sys-con.com 93 Xu shares a practical approach to identifying and Web Services Edge World Tour 2002 www.sys-con.com 201-802-3069 104-105 fixing broken Java windows. Web Services Journal www.sys-con.com 800-513-7111 101 WebSphere Developer's Journal www.webspheredevelopersjournal.com 800-513-7111 109 Zero G www.zerog.com 415-512-7771 3 General Conditions: The Publisher reserves the right to refuse any advertising not meeting the standards that are set to protect the high edi- torial quality of Java Developer’s Journal. All advertising is subject to approval by the Publisher. The Publisher assumes no liability for any costs or damages incurred if for any reason the Publisher fails to publish an advertisement. In no event shall the Publisher be liable for any costs or damages in excess of the cost of the advertisement as a result of a mistake in the advertisement or for any other reason. The Advertiser is fully responsible for all financial liability and terms of the contract executed by the agents or agencies who are acting on behalf of the Advertiser. Conditions set in this document (except the rates) are subject to change by the Publisher without notice. No conditions other than those set forth in this “General Conditions Document” shall be binding upon the Publisher. Advertisers (and their agencies) are fully responsible for the content of their advertisements printed in Java Developer’s Journal. Advertisements are to be printed at the discretion of the Publisher. This discre- tion includes the positioning of the advertisement, except for “preferred positions” described in the rate table. Cancellations and changes to adver- tisements must be made in writing before the closing date. “Publisher” in this “General Conditions Document” refers to SYS-CON Publications, Inc. CUBIST THREADS Fear ofthe Dark

As I’m pathologically fond of pointing out – I’m a child of a bygone era. Oh, I’m not old enough to remember the time before Sputnik, light bulbs, or the coagulation of the planets from protostellar dust WRITTEN BY clouds, but I surely do remember GI Joe at 45 caliber, Ray Stevens at 45 RPM, and factory-rolled cigarettes BLAIRWYMAN at 45¢ a pack sold to anxious minors desperate to rebel (just like everyone else). J2SE

It seems ironic to me that this column And, by all means, if I’m so utterly irrele- held! What wonderful cause for hope and – gilding the edge of JDJ’s ultramodern vant or patently offensive that you’re think- optimism and pride in the human race! fabric – deals mostly with dusty memories ing about dropping your JDJ subscription, We cured polio, managed to forestall of my vanished youth. On the other hand, please drop me a line so I can quit this gig. nuclear holocaust (so far), and now were I’ve heard that I should “write about what So, to the task at hand: this month’s “stuff.” on the verge of removing and replacing I know,” so my options are extremely lim- As I think back – searching for this the human heart. ited. Extremely. I mean, how many cab- month’s Thread fodder in that blurring However, lovely evenings during a J2EEdriving stories can J2ME a person take? (Many database of murky self-awareness – cer- South Dakota winter don’t usually last would say that one is already too many.) tain recollections stand out boldly in my very long, and this was no exception. I suppose I could repeatedly spew memory, maintained with (at least the Through the darkly colored glass of the first 50 digits of pi – which I hap- illusion of) crystalline clarity. Some such distant recollection, it seems as though pened to memorize as a teenaged moments are undoubtedly the result of a darkness fell too swiftly, as Mr. Cronkite proto-geek – but that would be almost simultaneous psychic shock – the assas- inevitably turned to the daily body as stupid as the original act of memo- sinations of JFK, MLK, RFK, and John counts out of Vietnam: so many dead, rizing it. I’ve always thought that those Lennon; the first moon landing; the so many wounded, so many missing in brain cells I still use to hold pi might Challenger disaster; 9/11…. Others are action. So very, very many. Reality Home have otherwise created some history- seemingly just random snippets of blends smoothly into surreality, as I making invention, or developed the remembered awareness, inexplicably remember the shards of shattered opti- cure for the common cold, or at least preserved for personal perusal. mism quietly exploding at the sight of been happily sacrificed on the altar of For example, something just remind- graphic footage. Film at 11. top-shelf single-malt Scotch whiskey. ed me of one particular evening in While I can nearly picture Walter’s Never too late to hope, though, I guess. December of 1967. I was 10 years old face in my memory, I can’t remember Uh-oh, here it comes, I feel a recita- and had come home from a friend’s the actual body count from that partic- tion coming on: house in time to see the name of Dr. ular day. One thing is certain, though, Christiaan Barnard as it flashed on the there was a body count that day; there “3.1415926535897932384626433832795028 TV screen. It seemed to me that “Dr. was a body count every day. 8419716939937510” Christiaan Barnard” had a pretty dog- I sure hope I’m wrong, but it looks goned funny way of spelling his first to me as if the world may be in for Boring, eh? name, but the venerable Mr. Cronkite another extended bout of nightly body didn’t even crack a smile as he told us the counts on the “Nightly News.” Is there My sincerest hope, dear reader, is that incredible news: this remarkable man anything we can do to stop it? Should it AUTHOR BIO perhaps I can finally count my own self from South Africa had successfully per- be stopped? Don’t ask me. I’m just a Blair Wyman is a software among the “things I know,” and that you formed the first human heart transplant. family man, computer programmer, engineer working for IBM will enjoy some of these vacuous recollec- Twilight was just giving way to and ersatz freelance writer. in Rochester, Minnesota, tions from the goofy amalgamation of evening as Walter awed us all with this home of the IBM iSeries. quarks that is my personal “main storage.” landmark news. What promise the world [email protected] Java Dudes

138 MAY 2002

Java COM WebGain, Inc. www.webgain.com/toplink_create3.html

MAY 2002 115

Java COM Sitraka www.sitraka.com/performasure/jdj

116 MAY 2002

Java COM