JDJEDGE CONFERENCE & EXPO FINAL PROGRAM INSIDE P.91

TM

Java COM

FINAL CONFERENCE PROGRAM INSIDE PAGE 91 Q&A: An Interview with Jason Hunter Alan Williamson 9 From the Editor Open sourcing Java – what it means to developers Alan Williamson pg. 7 Interfaces: Combining RMI with SOAP Samudra Gupta J2EE Editorial Develop a framework that SOAP-enables RMI services 16 Ajit Sagar pg. 12

J2SE Editorial Feature: Spread Your Wings with Cocoon David Rosenstrauch Keith Brown pg. 42 An innovative and powerful tool for content site developers 28

J2ME Editorial Java Systems: Broken Windows in the Java World Joe Xu Jason R. Briggs pg. 66 The Java bug’s evil twin and how it impacts your system 44 Career Opportunities Bill Baloglu & Billy Palmieri JNI Techniques: Using the Java Native Andrew J. Chalk pg. 112 Interface Productively Simplify repetitive tasks 58 Cubist Threads Blair Wyman pg. 114 Wireless Music:Whole House Audio from Bill Ray RETAILERS PLEASE DISPLAY the Palm of Your Hand It’s only the beginning 68 UNTIL AUGUST 31, 2002 Feature: Adding Commands to Fred Daoud Displayable Components ...the object-oriented way 74 MIDP: Programming Games in J2ME Sami Lababidi The battle for market share in the MIDP games arena 86

SYS -CON Michael Barlotta MEDIA Java Techniques: Java Design Using interfaces and abstract classes to create flexible code 94 Sonic Software Zero G www.sonicsoftware.com www.zerog.com

2 JUNE 2002 JUNE 2002 3

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

4 JUNE 2002 JUNE 2002 5

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

EDITORIAL J2SE EDITOR-IN-CHIEF: To Our CFML Friends: ALAN WILLIAMSON EDITORIAL DIRECTOR: JEREMY GEELAN EXECUTIVE EDITOR: NANCY VALENTINE J2EE EDITOR: AJIT SAGAR J2ME EDITOR: JASON R. BRIGGS We Welcome You J2SE EDITOR: KEITH BROWN PRODUCT REVIEW EDITOR: JIM MILBERY FOUNDING EDITOR: SEAN RHODY “ ly me to the moon...let me walk Keep your eyes open. Look outside your Java among the stars” or at least America. I circle and ask those who haven’t the in-depth PRODUCTION Fam at present sitting in a Continental knowledge you have what their perception of Java J2EE VICE PRESIDENT,PRODUCTION AND DESIGN: JIM MORGAN plane flying over the beautiful Scottish is. I think you’ll be surprised by the responses. ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI islands, sun beaming in through the window, The CFML language has enjoyed years of EDITOR: M’LOU PINKHAM contemplating the week ahead of me. My success as a server-side application imple- MANAGING EDITOR: CHERYL VAN SISE ASSOCIATE EDITORS: JAMIE MATUSOW destination is Toronto where I will be attend- mented in C/C++. Therefore, the move to the GAIL SCHULTZ ing the CFML conference, CFNORTH. Java platform is a controversial one, raising JEAN CASSIDY It has been very interesting to watch how an eyebrow or two within CFML’s loyal user Home ASSISTANT EDITOR: JENNIFER STILLEY the CFML community is reacting to the Java base. The posts by respected CFML people ONLINE EDITOR: LIN GOETZ releases. Their responses serve to illustrate regarding the move to Java are startling; I TECHNICAL EDITOR: BAHADIR KARUV, PH.D. the point I have been banging on about for urge you to check out the official CFML mail- WRITERS IN THIS ISSUE the last few months: outside of the Java com- ing list archives for examples of posts that BILL BALOGLU, MICHAEL BARLOTTA, JASON R. BRIGGS, KEITH BROWN, munity, we still have a long way to go in the will send your blood racing. BEA ANDREW CHALK, FRED DAOUD, SAMUDRA GUPTA, JEFF HEATON, education and perception of our beautiful We have a barrage of posts from people SAMI LABABIDI, BILLY PALMIERI, BILL RAY, DAVID ROSENSTRAUCH, language. Allow me to give you another berating Java, claiming it could never be as AJIT SAGAR, ALAN WILLIAMSON, BLAIR WYMAN, JOE XU example of ignorance. As luck would have it, fast as a native implementation, and it’s no the May issue of the in-flight magazine has wonder CFMX is running slow. I’m assuming www.bea.com/download SUBSCRIPTIONS: an article on Web technologies. This article these people haven’t given CFMX a chance. FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, is, of course, aimed at the masses, but let me In our tests, CFMX outperforms the CF5 ver- PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT give you its paragraph on what JSP is: sion running on the same hardware. So SUBSCRIPTION HOTLINE:[email protected] where these people are getting their facts COVER PRICE: $5.99/ISSUE Like ASP, a specification that allows a from is beyond me. DOMESTIC: $49.99/YR. (12 ISSUES) browser to ask the database for information. What has happened is that the old CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. For example, people play games against each Chinese whispers network has begun. The (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. other on the Internet on JSP pages. focus of conversation has moved from CFML EDITORIAL OFFICES: Advantages: works well behind the scenes. to whether or not Java is up to the task. We all SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 Disadvantages: whereas ASP pages are pro- know that Java is more than up for the job of TELEPHONE: 201 802-3000 FAX:201 782-9600 grammed with PERL, JSP pages are pro- serving dynamic content; this was its calling JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly grammed with a very specific set of tools – one and this is where Java is making serious (12 times a year) for $49.99 by SYS-CON Publications, Inc., 135 Chestnut Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at for which it may be harder to find expert headway, at the server side. Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address maintenance. Although it appears as if we, the Java changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., —Continental, May 2002 community, are the only people who really 135 Chestnut Ridge Road, Montvale, NJ 07645. know this for sure. Our message doesn’t ©COPYRIGHT: Read it? Do me a favor, read it again. seem to be getting out there. Copyright © 2002 by SYS-CON Publications, Inc. All rights reserved. What do you think? Not really selling JSP is There’s a huge movement within the No part of this publication may be reproduced or transmitted in any form or by any it? In fact, you would probably get a bad feel- CFML community to come to Java and sit at means, electronic or mechanical, including photocopy or any information storage and ing about JSP. As we know, the author is our table to share in the delights we offer. retrieval system, without written permission. For promotional reprints, contact reprint coor- wrong; if anything JSP is the easiest way to This is wonderful and we welcome and dinator Carrie Gebert, [email protected]. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its readers to use the articles submitted for publication. get your hands on Java – no compiling, just encourage our new developers. save and surf! How difficult is that I ask you? More power to you. 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.

6 JUNE 2002 JUNE 2002 7

Java COM Java COM An Interview with

Jason Hunter J2ME Open sourcing Java – a Q&A session J2SE

Two: “Is the reference implementation for Java (the JDK) available as open source?” This agreement does not address JDJ caught up with Jason Hunter, Apache that. Apache doesn’t believe in telling Sun or anyone else what Software Foundation vice president, after JavaOne to discuss the license their code must be under. What Apache believes is that if major announcement regarding the controversial issue of open you don’t like a code license, you must have the ability to code it sourcing Java. Jason holds a seat on the JCP Executive yourself. The purpose of this agreement is to allow that. Committee overseeing the Java platform. Three: “Will Java be developed following the open source JDJ asked readers to pose their questions to Jason, so you method?” Right now there’s a formal process by which Java J2EE can hear it straight from the horse’s mouth! specifications are created within the Java Community Process (JCP). The JCP will probably remain as a formal specification- creating body, although Apache hopes it will become more open. : What does this announcement mean? The project I lead, JDOM, is JSR number 102, and with the JSR : It heralds an agreement between Apache and Sun we’re proving you can have open development on a Java speci- regarding open source implementations of Java standards. fication even within the JCP. Now, the clear ability to have open Home Among the items agreed upon: source RIs and TCKs will help this JSR progress. • For Sun-led specifications finalized from here forward (includ- TogetherSoft ing revisions to existing specifications) and for key specifica- Apache saw an explosive growth in the number of proj- tions already released, the license terms will allow independent ects during the last couple of years. What do you see as the implementations under open source licenses. major challenges facing the Apache Foundation in being • The Test Compatibility Kit (TCK) binaries for these specifica- able to maintain the momentum and support all of the exist- tions will be made available at no cost to qualified open source, ing efforts in the long term. nonprofit, and academic groups. [Kirk Pepperdine, [email protected]] Corporation • A three-member board, including a representative from the : Apache only accepts projects that have an established, Apache Software Foundation and a representative from aca- vital, and active community. Put another way, code must come demia, will ensure an impartial qualification process. with a community of coders. Apache doesn’t accept “throw it over • Sun will provide substantial support to aid these qualified the wall” code – no matter how enticing. www.togethersoft.com/challenge/1 groups in the use and execution of the TCKs. So far the policy has worked well. The main challenge is to • Specification leads will be allowed to choose open source effectively integrate the coders into the Apache community. licenses for their Reference Implementations (RIs) and TCKs if they desire. Are you completely satisfied with the substance and level of commitment contained in this announcement? There’s an additional item in the agreement that will be of [[email protected]] special importance to commercial implementers of Java specifi- : Right now it’s an agreement on a course of action. cations: Apache will be much more satisfied when the plan of action has • Sun will make the TCKs for future and key past specifications been executed. available separately from the RI code. Previously, there had been a requirement to license the RI when licensing a TCK, In your opinion, what does Sun stand to gain from this which made true independent implementations impossible. agreement? [[email protected]] For details on the agreement, see Sun’s Letter of Intent at : Apache has been a strong partner of Sun, promoting http://jcp.org/aboutJava/communityprocess/announce/LetterofInt Java on the server side. Projects like Tomcat, Ant, Xerces, Xalan, ent.html and Apache’s press release at http://jakarta.apache. and Axis/SOAP are widely used and vital to the server-side Java org/site/jspa-agreement.html. community. Many Apache projects have Sun developer support, quite a few have implemented Java specifications, and usually Is Java finally open sourced? when that happens the Apache code has been used as a base for [anonymous] the specification RIs. However, the legal issues surrounding open : That depends on what this question means. I believe it source Java implementations absolutely had to be settled for can mean three different things. Apache to continue supporting the Java Community Process One: “Can there be an open source Java implementation?” The (JCP) and the specifications the JCP produces. answer is yes, this agreement should ensure that when J2SE 1.5 is released it can have an independent, open source licensed imple- Does Apache plan on creating a JXTA implementation? mentation. Many Java specifications will have that ability right away. [wwsmithms, [email protected]]

8 JUNE 2002 JUNE 2002 9

Java COM Java COM : JXTA is not a JCP specification. It’s a Sun-backed but Can you explain the finer print on the support that is on independent and language-neutral open source project with an offer from Sun for the open source community? Apache-style license. It’s unaffected by this agreement. [[email protected]] : In the months before the agreement Apache set as a Do you think that this agreement will result in Sun finally minimum requirement that the TCK binaries be “easily available” testing JBoss for J2EE certification? to any open source or academic group. The notion that a specifi- [eric] cation lead could decide to waive TCK license fees was not suf- : JBoss will now have access to the TCKs for J2EE 1.4 ficient, because a busy spec lead might not even respond to a coming later this year. Because JBoss is a for-profit corporation, small group or individual, and we wanted to allow for the next they will probably have to pay for the TCK. When talking with Linus Torvalds to spring up (this time in Javaland). During nego- them they had no objections to that. It’ll be up to them to ensure tiations, Sun was willing to license the TCKs free of charge to compliance with the TCK. these groups, but was concerned that many TCKs are so compli- cated they essentially require support in order to run. Sun could- How does Apache feel/cope when a lot of their n’t grant support to all nonprofits because, unlike TCK binaries, ideas/products are incorporated by other companies? For there’s a real cost for each support customer. J2SE example, an equivalent of the ORO project has been incor- To solve that problem, the proposal is to have a board (con- porated into Java 1.4 as regexp classes. sisting of a Sun member, an Apache member, and an academic [Fintan Conway, [email protected]] member) who would grant free TCK binaries to any qualifying : There are two ways to interpret this question. group, and grant TCK support within some budget limits. The One: “How does Apache feel when its products are incorpo- method for qualifying groups and granting support will be worked rated into products of other companies, e.g., how IBM out by the board members. I personally wouldn’t be surprised if WebSphere uses the Apache Web Server?” Apache uses this open source mailing lists became the common vehicle for support particular license (a very liberal license that allows reuse in com- for open source groups. J2EEmercial products) precisely J2ME because Apache wants its code to be both useful and used by anyone and everyone who is interested. How do you think the major Java players feel about this Two: “How does Apache feel when the JCP creates specifica- move? tions for the Java platform that are in a similar vein to preexisting [Paul] Apache projects?” This question is more difficult to answer : Among the JCP Executive Committee (EC) members because there may be as many opinions as developers within there has been strong support for this change. Apache’s con- Apache. I think it’s fair to say this: people are glad to see Java cerns were listed by EC members as the number one issue to be incorporating functionality such as regular expressions and log- dealt with in the JSPA legal document as it goes from community ging. However, we’ve seen the specifications being created in review toward public review. Several EC members went on Metrowerks Home private and with little community input, compared to the typical, record in support during JavaOne. Apache project. Not surprisingly, when you compare the Java specifications : Tell us a little about Apache. Is it an official compa- with the Apache projects that were created “in the wild” with large ny/body? Do they have offices? Is there a telephone some- amounts of user feedback, the new standards may not seem of where on the planet with someone answering “Good equal quality. What’s more, the incorporated technology will only Morning, Apache, how can I help you?” Corp. fall farther behind as Apache continues innovating and doesn’t : Apache is a nonprofit corporation, with a board, chair- have to wait until J2SE 1.5 for the next release. At the same time, man, president, and assets (servers, trademarks, etc.). There are Apache people realize there’s the Microsoft Windows–style no central offices. As for a number to dial, we prefer e-mail to effect: whatever’s provided with the platform gains the majority phones! For more information, here’s what we put at the end of www.wireless-studio.com marketshare, regardless of its comparative quality. press releases:

Is this the beginning of the end? Are we entering a future The Apache Software Foundation provides organiza- where we’ll be seeing different flavors of Java, like we’ve tional, legal, and financial support for the Apache seen in the C/C++ world, and building specific versions for open-source software projects. Formerly known as specific target JVMs? the Apache Group, the Foundation incorporated as a [George] membership-based, not-for-profit corporation to : It’s important to recognize that the agreement provides ensure that the Apache projects continue to exist for “compatible” open source independent implementations. beyond the participation of individual volunteers, to Apache believes this agreement will improve Java’s portability enable contributions of intellectual property and finan- through the wider availability of Test Compatibility Kits and with cial support, and to provide a vehicle for limiting legal the existence of solid open source implementations on which exposure while participating in open-source projects. vendors can build. Servlet portability has only improved with the For more information on the Apache Software availability of the Tomcat servlet engine. Foundation, please see www.apache.org/.

It may seem like an obvious question but even though : Finally, now that there’s been time for the news Apache is a nonprofit organization, how do they plan to con- to sink in, what has been your feedback from the communi- tinue to deliver excellent, quality offerings in the future? ty at large? [Mark Menzies, [email protected]] : I find people are still asking questions. The issues are : For a good description of how open source projects very complicated, and the deeper you dig, the more details you work, I would recommend a book like The Cathedral and the find. Eventually you wish you hadn’t ventured so deep! Bazaar [by Eric S. Raymond and Bob Youngor], or a research Sometimes I wish I’d taken the blue pill. Happily, things appear to paper like “Open-Source Software Development and Distributed be improving, and I hope Q&A pieces like this help people under- Innovation” at www.smu.edu.sg/research/pdfs/kogut06K1.pdf. stand what’s changing and what it means.

10 JUNE 2002 JUNE 2002 11

Java COM Java COM J2EE EDITORIALOR J2EE INDEXX

J2ME Integrating Development Some years ago, I did all my AJIT SAGAR J2EE EDITOR coding in vi, then later in emacs. I still believe these are great edi- tors; I just don’t use them any 12 more for Java development, especially J2EE application development. I’m much more J2SE IntegratingDevelopment productive if I use an IDE whose sole purpose in life is to facilitate ome years ago I did all my coding in and deploy them into your runtime envi- product development. vi, then later in Emacs. I still believe ronment. That way you can easily share by Ajit Sagar Sthese are great editors; I just don’t your development efforts with your team. use them anymore for Java development, In addition, several IDEs offer refactor- Combining RMI with SOAP especially J2EE application development. ing capabilities that will allow you to mod- Develop a framework I’m much more productive if I use an IDE ify component design after the code has that converts existing RMI whose sole purpose in life is to facilitate been developed. Several IDEs in the mar- services to be SOAP-enabled J2EE product development. I can probably still ket offer a large part of this functionality by keeping the interfaces write code faster if I use vi. However, I out of the box. I’ve worked with Borland’s intact so they can still be doubt I could meet my deadlines if all I JBuilder and IntelliJ’s IDEA. Both are excel- used as normal RMI services. had was a tool that was primarily meant to lent IDEs that support the development Also, write a SOAP message 16 be an editor. Emacs is a great environment features mentioned earlier, including handler that will receive a for setting up and using a development deployment to the main J2EE application SOAP request document, environment. However, it is for all purpos- servers, unit testing using JUnit, support parse it to invoke the

Home es a code editor, not an IDE. for refactoring, and integration with requested service, and con- Sun Developing distributed applications is source control systems. There are several struct a SOAP a complex process, and developing the other J2EE IDEs to choose from (e.g., response document. components that make up the application WebGain’s VisualCafé). Usually applica- by Samudra Gupta requires coordination and integration of tion server vendors’ tools don’t have the different design and development envi- level of sophistication offered by J2EE Spread Your Wings with ronments. The software development IDEs. Cocoon Microsystems cycle for the release of a product warrants Of course, cost becomes a factor. Some Apache Cocoon is one of the use of data and component modeling of these IDEs are fairly expensive and buy- the most interesting, innova- tools; sophisticated code editors; a fully ing enterprise licenses can be a costly tive, and powerful platforms integrated compilation and build environ- proposition. However, for large enterprise for dynamic content genera- 28 www.sun.com/forte ment; deployment tools; fully integrated projects, the benefits accrued by saving tion. This article discusses debugger, unit, and integration testing precious development hours will be well what it is, what it does, and environments; and source code version worth the cost. how to start using it in your control. Nowadays, you have two options What role will the popular editors like own development projects. when developing J2EE software. One, use Emacs and vi have in J2EE development? by David Rosenstrauch your skills to create a development envi- Well, some of the IDE vendors are incorpo- ronment that can use tools from different rating these into their tools. For example, vendors cohesively and effectively. Two, Java Development Environment for Emacs buy something that provides this environ- (JDEE) is a software package that inter- ment out of the box. faces Emacs to command-line Java devel- Which option would you prefer? If opment tools (e.g., JavaSoft’s JDK). you’re the only one developing the mod- Similarly, TogetherSoft is incorporating vi books that has proved very useful in ules, you may have the luxury to go with and Emacs into their tools offerings. developing J2EE software. They’re printed the first option. However, if you’re involved Speaking of development tools, one of as a suite of “CodeNotes” from Infusion in the development of J2EE applications, the requirements for any successful J2EE Development Corporation – guidelines you’re much better off with a true integrat- project is the right references – online and from developers who have obviously ed development environment that allows printed material that gets you the back- spent some time in the trenches. I’ve you to develop components autonomous- ground information you need to get up to looked at the J2EE and XML CodeNotes, ly, unit test them, test them in your appli- speed and hit the ground running. and these are definitely handy references cation framework via integration testing, Recently, I came across a new style of to keep at your desktop.

[email protected] AUTHOR BIO Ajit Sagar is the J2EE editor of JDJ and the founding editor of XML-Journal. A lead architect with Metavonni, LC, based in Dallas, he’s well versed in Java,Web, and XML technologies.

12 JUNE 2002 JUNE 2002 13

Java COM Java COM Infragistics, Inc. Infragistics, Inc. www.infragistics.com www.infragistics.com

14 JUNE 2002 JUNE 2002 15

Java COM Java COM INTERFACES

J2ME Combining RMIwith SOAP Experimenting with SOAP J2SE J2EE At the end of last year,I was given a rather unpleasant assign- ment. This company had several Java Remote Method Invocations WRITTEN BY (RMI) services that were interacting with the legacies of the organiza- SAMUDRA GUPTA tion and I needed to open up an XML interface for them.

My first idea was to use the Simple In this article, we want to develop a element or the root element in an

Home Object Access Protocol (SOAP). But the framework that SOAP-enables the exist- XML-encoded SOAP message. The current W3C specification and imple- ing RMI services by keeping the inter- Envelope may contain any or all of the mentation of the SOAP API from Apache faces intact so they can still be used as following information: the recipient presented only the HTTP binding for normal RMI services. In addition, the of the message, the content of the RemoteApps SOAP. Because of this, the SOAP services framework will demonstrate how to message, and the processing instruc- had to be deployed in a Web server con- write a SOAP message handler that will tions for the message. tainer. The possibility of opening up a receive a SOAP request document, parse 2. Encoding rules: These specify the way SOAP-based interface to the existing it to invoke the requested service, and the application-defined data-type http://portal.remoteapps.com RMI services was limited by the follow- construct a SOAP response document. instances will be exchanged. ing factors: We’ll also develop a mechanism to spec- 3. RPC: These define a convention for • If we convert the existing RMI servic- ify, deploy, and configure the services representing the remote procedure es as SOAP-based and deploy them in with the help of a deployment descrip- calls and the responses to them. a Web server container, the existing tor file. Then we’ll build a client program clients to those services have to be to access these services. To understand the three parts of the rewritten or reconfigured in order to The framework will be developed by SOAP message let’s look at Listing 1.This be able to talk to the SOAP server in a defining a very simple RMI service; we’ll listing shows a typical SOAP message in SOAP-recommended way. In the be using the Apache SOAP implementa- an HTTP request binding. The Envelope worst-case scenario, we can maintain tion (version 2.2) to build a SOAP client element is namespace qualified (SOAP- two interfaces (RMI and SOAP) for the to use the RMI services. Note: This ENV) in order to separate it from any same set of services, which is not framework is just one approach that can other application-specific identifier. It desirable. be used to talk SOAP over RMI. (The also contains information about name- • The services were interacting with source code can be downloaded from space encoding. The immediate child many legacies and in turn with the the JDJ Web site, www.sys-con.com/ element of the envelope in this example native programs, which could not be java/sourcec.cfm.) is the Body element. This element must accessed from the Web server system be present in a SOAP message; it holds for various security reasons. Anatomy of SOAP the information about the name of the SOAP provides a simple and light- remote procedure (GetLastTraderPrice) We could have implemented a pro- weight mechanism to exchange struc- to be invoked and also encodes the prietary XML-based solution to over- tured information in a decentralized parameters required by the remote pro- come the problem. I chose to use SOAP and distributed environment. In cedure. In this particular message the because it’s slowly emerging as the new essence, it’s a model for encoding data remote procedure requires the name of standard for XML-based distributed in a standardized XML format for use in the company (DIS) from which to computing. Moreover, by following a a variety of situations, such as messag- retrieve the last trade price. Optionally, standard, it’s easier for other applica- ing and remote procedure calls (RPC). the Body element contains information tions to use the services without any SOAP consists of three essential parts: about any error that occurred during the particular knowledge of their internals. 1. Envelope: This is the top-level XML RPC and is encoded in a Fault element.

16 JUNE 2002 JUNE 2002 17

Java COM Java COM INTERFACES

The Fault element contains the processes the result or the fault string tion and tutorial of the API, but I’ll error/status information with a SOAP accordingly. As the Apache SOAP scheme through the necessary sections message and, if present, can appear only implementation defines and imple- as and when required. once as a child element of the Body ele- ments the SOAP-HTTP binding, the First, it’s important to understand ment. objects provided in the API are not seri- that to invoke a remote service deployed In complex cases, the Envelope ele- alizable in the context of Java RMI, and as a Web service over HTTP or to invoke

J2ME ment may contain another child ele- there lies the challenge – to overcome a remote service over RMI protocol, as ment named Header. If this element is the present limitation until a more we’ll be doing, we’re essentially making present in a SOAP Envelope, it must be standard implementation of SOAP-RMI a remote procedure call (RPC). In an the immediate child of the Envelope ele- comes up. RPC, we make a call to the remote pro- ment. The Header element can typically cedure and receive a response back. The hold information regarding authentica- The Components API provides us with a call and a tion, transaction management, and Since the requirement is to contin- response object. Also, we often need to more. In our particular example, we ue using RMI services and to add a pass a few parameters to invoke the J2SE would not be using this header informa- SOAP interface around them, we need remote procedure, and these parame- tion. to build a SOAP wrapper around the ters can be encapsulated in the A SOAP response document contains existing RMI services. Also, we need to Parameter object. a similar structure (see Listing 2). The build a SOAP client following the The main task is to provide the Call Envelope element contains the Body Apache SOAP implementation. But at object with the Universal Resource element, which in turn contains the the moment the Apache SOAP imple- Locator or the URI of the remote serv- requested information, or a fault string, mentation handles HTTP binding only, ice, the name of the method to be should there be any fault generated dur- so we need to extend it so it can call invoked as a part of the remote call, and ing the service call. RMI services. Also, on the RMI server the parameters required by the remote J2EE For the purpose of this article we’ll side, we need some mechanism to con- method. The parameters may frequent- develop a remote procedure call frame- figure, deploy, and load these SOAP- ly be complex user-defined data types work to invoke RMI services, and we’ll aware services. Remember, not all the and objects such as a Person or an be using and dissecting the three parts RMI services may need a SOAP inter- Address object. It’s also required to of the SOAP specification. face, so you should be able to specify define a serialization and deserializa- and configure the services that are tion mechanism for these complex Conceptual Framework for Sending required to be SOAP-enabled. Thus, objects. By default, the API provides

Home SOAP Messages over RMI the following components need to be default serializers and deserializers for The basic idea of how to achieve developed: data types such as Boolean, Double, SOAP over RMI relies on the fact that if • SOAP wrapper Float, and Vector. If the data type is we can send and receive SOAP request • SOAP service manager complex and user-defined, as an imple- Sitraka and SOAP response documents over • Configuration file – the deployment menter of the SOAP client we have to the wire using RMI protocol, we’ll be descriptor define our own serializer and deserializ- able to achieve our goal. In the process, • Apache SOAP extension (this will be a er and register it with SOAP by setting a we’ll create a SOAP Envelope docu- custom Call object, as we will see) SOAPMappingRegistry for the particu- www.sitraka.com/jclass/jdj ment, serialize it, and send it to an RMI • SOAP client lar data type. service that will decode the SOAP The term serialization/deserializa- Envelope message, invoke the specified The SOAP Client tion as used in the SOAP context is dif- method on the specified Remote It’s unusual to start with the last ferent from the serialization notion of object, construct a Response object component specified in the list, but it Java RMI. In the SOAP context, serializa- containing the return value or a fault helps me explain the flow better. As tion in a broader term means the XML string in case there’s a problem, and mentioned earlier, we’ll be using the encoding and decoding of the data again serialize it back to the caller (see Apache SOAP API version 2.2 to write a types. Again, our example focuses on Figure 1). The caller then parses the SOAP client. It’s beyond the scope of this how to implement these remote proce- received SOAP response document and article to provide a complete introduc- dure calls over RMI and use simple data types to avoid extra work in defining serializers and deserializers for complex data types. The Call object implemented in the API is tailored to the HTTP binding of SOAP. However, as explained earlier, we want to perform the RPC over RMI. Thus it’s required to customize the Call object and extend it as RMICallObject and build the mechanism to achieve the RPC over RMI. The Envelope object in the API is not serializable to perform an RMI opera- tion. Hence the first step in our frame- work will be to reproduce a SOAP Envelope element in the form of an XML Document object, which is serializable FIGURE 1 The framework in the RMI context.

18 JUNE 2002 JUNE 2002 19

Java COM Java COM INTERFACES

public class RMICallObject extends Call { public Response invoke(URL url, I chose to use SOAP because String s) throws SOAPException private Document buildDocument() J2ME throws IllegalAddException “it’s slowly emerging as the private Response buildResponse (Document doc) throws new standard for XML-based Exception } distributed computing This class structure represents the RMICallObject class that’s designed to J2SE handle the RMI call. The class overrides Document object from the RMI server. alized Document object. As a matter of the invoke() method from the Call class The remote server object processes the fact, this is an RMI service acting as an and defines two private helper methods passed Document object. entry point to all other RMI services to construct the Document object, Once we’ve extended the Call object deployed as SOAP-enabled, so it’s vital which will be serialized over the RMI to the RMICallObject and incorporated to ensure that this service is up” and run- call, and another method to construct a the functionality to perform an RMI call, ning so other services can be accessed Response object out of the returned the rest of the client programming fol- and used. Document object from the RMI call. For lows what we do for a normal SOAP First, declare a Remote interface for ease of use, I’ve used the JDOM API from client (RMIClient.java) (see Listing 4). this RMI service. J2EE Apache for XML data handling. This listing is an example of the The invoke() method takes the URL SOAP client. First, we obtain the refer- public interface SoapRMIInterface of the configuration file where the loca- ence to an RMICallObject, then pass the extends Remote tion and name of the RMI server is spec- target remote service name as it’s bound { ified and looks up and obtains a remote to the RMI registry, pass the name of the public Document reference of the same. As we’ll see later, remote method to be invoked, create the invokeMethod(Document doc) throws this RMI service will act as an entry Parameter object to pass the required RemoteException, RMISoapException;

Home point to all other RMI services we want parameters to the remote method, and, to access (see Listing 3). finally, invoke the remote method by } SOAPRMIInterface is the remote calling the invoke() method on the interface that the RMI service imple- RMICallObject. It’s important to note Our SOAP wrapper RMI service will AccelTree ments in order to parse the Document that we pass the URL as the address of implement this interface, and, as a object that’s passed as a result of the the configuration file (conf.txt) that result, define the invokeMethod() SOAP call. The implementation of the holds the name and location of the method. As we can see, apart from SOAPRMIInterface is given a binding in SOAP server manager. As shown in throwing the usual RemoteException, www.acceltree.com the RMI registry under the name Listing 4, the conf.txt file should be this service also throws a customized assigned through the variable server- placed under the current working direc- RMISoapException to differentiate Name. tory. between normal RMI failures and any A Document object is constructed Once this URL is passed to the SOAP-related ones. This design is guided out of the generated Call object, which invoke() method of the RMICallObject by the fact that to build a Response represents the SOAP Envelope. class, it constructs a Properties file out object, we need to pass the proper fault of the given configuration file conf.txt string information back to the caller //construct a Document object and an RMI lookup URL with the server object. from the Call object entries name and the location. The implementation of the invoke- doc = buildDocument(); Once the returned XML Document Method() method must perform the fol- object is obtained from the RPC, we can lowing tasks: After obtaining a remote reference of analyze the entries of the Document to • Parse the received document and the RMI service, execute the remote obtain the returned result of the method retrieve the Body element of the SOAP method named “invokeMethod()” on call or the fault string associated with request. this reference by passing the Document this method call, and construct the • Identify the name of the remote ser- object to it. This method is responsible Response object out of that to return it vice, the name of the remote method, for parsing the Document object and to the Caller RMI client. and the parameters passed to it. acts as the gateway to all the SOAP RMI • Locate the remote service from the services. SOAP Wrapper registry by analyzing the deployment A major part of building this frame- descriptor (to be discussed in the fol- //calling the invoke work is to develop a SOAP wrapper lowing section). method around RMI services, which can parse • Check whether the method specified is responseDoc = and handle incoming SOAP requests. So, exposed as a part of the given ser- obj.invokeMethod(doc); the basic idea of this framework is to vice and if the service is defined in the serialize the SOAP request over RMI in deployment descriptor. If it can’t locate Once the Document object is hand- the form of an XML Document object, the specified service, it throws an ed over to the remote service, the client- and the SOAP wrapper is required to be exception and eventually propagates it side process waits for a return an RMI service that can accept the seri- as a SOAP fault string back to the caller.

20 JUNE 2002 JUNE 2002 21

Java COM Java COM INTERFACES

• Create a new instance of the specified we need information regarding the vices in a single file, I’ve put the individ- service implementation class and RMI services that are deployed as ual descriptors under a root element invoke the specified method by pass- SOAP-enabled services. called “” (soap.xml). ing the parameters obtained as a part Typically, our deployment descrip- The Apache SOAP implementation of the SOAP request, if the method tor(s) will contain the following infor- provides a utility class called Deploy- specified is a part of the deployed mation: mentDescriptor to load and parse the

J2ME service. If the method name could not • The URN of the service as the name deployment descriptor files. I’ve used be located, it throws an exception and that binds it to the RMI registry the same to load and access my consoli- propagates it back to the caller as a • The name of the Java class deployed dated deployment descriptor file, along SOAP fault string. as the specified service with a ConfigDescriptor class designed • Create and return a response XML • The method that’s exposed as the to parse the file and retrieve everything document to the caller as an RPC interface to the service or a descriptor for a particular service response once the service is success- • Whether or not the method is imple- against its service ID. fully invoked. After receiving this XML mented as static J2SE document, the RMICallObject then The Service Manager constructs the Response object out of The other bits of information that So far on the server side we’ve creat- it and passes it to the SOAP client normally become a part of the SOAP ed the SOAP wrapper RMI service, object. service, such as the scope of the service which is the gateway to all other SOAP- (application/session, etc.), are not rele- enabled RMI services, and have also This process is large in scope; the vant to the framework we’re developing, devised a deployment descriptor to source code for SoapRMIServer is avail- because in this particular framework specify and describe all the services that able on www.sys-con.com/java/sourcec I’ve tried to avoid the complications of are to be deployed and loaded as SOAP- .cfm. To check if the method exists for a session management. enabled. As a precondition to these spe- J2EE given service, the service uses the Java The deployment descriptor is typi- cific services working, we need to load reflection mechanism. It also uses this cally encoded within a top-level ele- all the services specified in the deploy- mechanism when it constructs a ment , which is name- ment descriptor file along with the Response XML Document object out of space-qualified to avoid conflict with wrapper RMI service and bind them to the RMI registry. Binding is straightfor- ward. The only difficulty I faced was in using the DeploymentDescriptor class

Home of the Apache SOAP API, as it doesn’t SOAP provides a simple and accept the fact that more than one ser- vice can be specified within the same lightweight mechanism to exchange descriptor file. Macromedia “ I designed a ConfigDescriptor class structured information in a decentralized (ConfigDescriptor.java) that parses the deployment descriptor XML file and cre- and distributed environment ates an individual DeploymentDes- www.macromedia.com/go/jrun4jdj criptor object by taking each child node of the root element. I added a few convenient methods to the returned value of the service, in case any other user-defined entity. An exam- retrieve all or one particular Deploy- the returned value is an object. While ple of a deployment descriptor is as fol- mentDescriptor object given the service creating a response XML document to lows: ID (the URN) of the service. The maintain the SOAP response specifica- SoapServerManager class uses the Con- tion, it uses the received SOAP request the Java classes specified as the service The Deployment Descriptor the ID attribute of the ele- mation to the SOAP runtime environ- This brings all the specified RMI contains the Universal Resource services up and running, with all the Name (URN) for the service, the name methods specified in the deployment of the method, the Java implementa- descriptor file exposed as SOAP- tion class if the SOAP service is This descriptor particularly defines a accessible remote service methods. deployed as a Java class, and more service named “greetingserver” with an Once this is done, the last job of the regarding serialization and deserial- exposed method “sayHello”, and the SoapServerManager class is to load ization (in a SOAP context and not in implementation Java class of the service the SOAP wrapper RMI service. The an RMI context). The amount of infor- is “Greeting” and the method is nonstat- additional functionality of starting up mation that can and should be sup- ic. an individual service or taking down plied depends on the SOAP runtime The basic idea is to provide an XML one or all of the services can be pro- requirements. In the example we’re file in which we can describe the vided through the SoapServerMan- following, which is a simplistic model, deployed services. To deploy all the ser- ager class.

22 JUNE 2002 JUNE 2002 23

Java COM Java COM INTERFACES

A Simple RMI Service java - Djava.security faultstring...Could not invoke the Consider a simple RMI service. .policy=myPolicy.txt specified method This service is named “addressserv- rmi.server.SoapServerManager er” and the remote service method is It’s important to note that the client “getAddress”, which takes two param- Running the Client will also need all the .jar files to be set in eters – the name and surname of a The client program, as explained, is the CLASSPATH as they’re used by the

J2ME person. Given the name and sur- ready to call the deployed addressservice. Apache SOAP implementation as well name, the service returns the per- We can run the client program using the as our own extended RMICallObject son’s address. To make it a very small following command from a DOS prompt class. example service, I’ve hard-coded the – java rmi.client.RMIClient. address inside the code, although in Conclusion real life this service might interact The address of the rmi server: This framework served my purpose with a database and fetch the rmi://localhost:1099/soapserver very well, and I could use the existing address. I’ve created an Address Target obj: urn:addressserver RMI services both as normal RMI as J2SE object that holds the name, city, and The return value: well as SOAP deployed over RMI. This zip code. The service returns the person...Samudra Gupta framework is tailored to meet my Address object in response to a SOAP city...London requirements, so it may not meet call (AddressService.java) (see Listing post...SS1 2RQ yours. The ability to handle a user- 5). defined data type as a parameter to This listing explains the struc- This shows the result of the client call the remote services is surely one of the ture of the addressserver service, and we receive the address of the speci- main areas to be incorporated; which is also designed as an RMI fied person. although it’s used in the real project, I service. To find out how the framework didn’t explain it here due to space con- J2EE behaves in case of erroneous inputs, I straints. I strongly believe that more Running the Server changed the method name to experimentation with SOAP will even- To run the server, we need to ensure “getLocation” instead of the correct tually help it become a mature and the following: exposed method “getAddress, and robust technology. • Place all the .jar files (mail.jar, received the following error message: xerces.jar, activation.jar, soap.jar, and Resources jdom.jar) under the lib directory of The address of the rmi server: • Apache SOAP API for an API down-

Home your install directory. rmi://localhost:1099/soapserver load, mailing list, and FAQ: http:// Compuware • Set the CLASSPATH to include the Target obj: urn:addressserver xml.apache.org/soap/index.html current working directory and the lib The fault code: SOAP- • An introduction to RMI: http://java. directory under it. ENV:Server.BadTargetObjectURI sun.com/docs/books/tutorial/rmi/in • Generate the stubs and skeletons of The return value: dex.html all the RMI services to be deployed faultcode...SOAP- [email protected] (included in the source code). For the ENV:Server.BadTargetObjectURI Corp. SoapRMIServer, it’s important to pro- vide all the .jar files in the rmic –class- path option. Listing 1 www.compuware.com/products/optimalj rmic –classpath .;c:\your- POST /StockQuote HTTP/1.1 Host: www.stockquoteserver.com directory\lib\jdom.jar; c:\your- Content-Type: text/xml; charset="utf-8" directory\lib\soap.jar; c:\your- Content-Length: nnnn directory\lib\xerces.jar; c:\your- SOAPAction: "Some-URI" directory\lib\mail.jar; c:\your- directory\lib\activation.jar • Run the Service Manager (SoapServer- Manager). This will read the deploy- ment descriptor file, load all the spec- DIS ified RMI services there, and bind them to the RMI registry under the name specified as the ser- vice ID. • Provide the deployment descriptor in Listing 2 AUTHOR BIO the CLASSPATH. HTTP/1.1 200 OK Samudra Gupta is an • Check your security policy for prob- Content-Type: text/xml; charset="utf-8" independent Java lems starting up or accessing the RMI Content-Length: nnnn consultant in the UK, services. For this example, I created He has five years of If you create/use this policy file, pass experience in Java it to the runtime with the following and Web technology. command: 34.5

24 JUNE 2002 JUNE 2002 25

Java COM Java COM call.setMethodName("getAddress"); //set the encoding style to be used call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC); //creating the parameters to be passed to the remote method Listing 3 Vector params = new Vector(); //construct a Properties object and load with it the properties params.addElement(new Parameter("name1", String.class,

J2ME file specified by the URL "Samudra", null)); Properties prop = new Properties(); params.addElement(new Parameter("name2", String.class, prop.load(url.openConnection().getInputStream()); "Gupta", null)); //construct a Document objet from the Call object call.setParams(params); entries //obtaining the current working directory doc = buildDocument(); String workingDir = System.getProperty("user.dir"); //obtain the name and address of the rmi server frm String url = the properties file "file://localhost/"+workingDir+"/conf.txt";

J2SE serverURI = prop.getProperty("serverLocation"); System.out.println("Invoking..."+url); serverName = prop.getProperty("serverName"); System.out.println("The address of the rmi server: //invoking the remote service "+"rmi://"+serverURI+"/"+serverName); Response res = call.invoke(new URL(url), ""); //get the rmi server URI System.out.println("Target obj: "+this.getTargetObjectURI()); Listing 5 //obtain the reference to the rmi server object by public Address getAddress(String personName, String surName) the target object URI { SoapRMIInterface obj = Address add = new Address();

J2EE (SoapRMIInterface)java.rmi.Naming.lookup("rmi:// StringBuffer buffer = new StringBuffer(personName); "+serverURI+"/urn:+serverName); buffer.append(" "); buffer.append(surName); add.setPerson(buffer.toString()); Listing 4 add.setCity("London"); //create a RMICallObject add.setPost("SS1 2RQ"); RMICallObject call = new RMICallObject(); System.out.println("Returning address for: //set the target remote service name "+add.getPerson()+" "+surName);

Home call.setTargetObjectURI("urn:addressserver"); return add; SilverStream //set the name of the remote method to be invoked } Software www.silverstream.com/scale INT, Inc www.int.com

26 JUNE 2002 JUNE 2002 27

Java COM Java COM J2ME J2SE J2EE

Home /n software inc. www.nsoftware.com

It’s not just Cocoon’s use of XML in content generation that this article. Don’t worry too much if you haven’t worked with makes it so interesting; it’s how it uses XML. Cocoon’s authors these technologies, though. I won’t be delving too deeply into clearly have a deep experience with and an understanding of them and will try to make any examples easy to understand. XML – what it is and isn’t good for – and Cocoon’s simple but powerful architecture reflects that experience. XML isn’t used What Is Cocoon? here just “because everyone’s using it.” Rather, Cocoon Although at heart Cocoon is “yet another dynamic content- exploits XML’s strength for separating content from presenta- generation platform” (technically putting it in competition tion. (As we know now, the lack of that separation made it with the many other content-generation technologies out increasingly difficult to do Web page development in straight there such ASP, JSP, PHP, and Struts), Cocoon adds some new HTML.) The result is an innovative and powerful tool for con- twists to this category that make it stand out. tent site developers. Cocoon’s core difference is its use of XML throughout the This article will familiarize you with Cocoon and some of content-generation process. Each request sent to the Cocoon its related technologies: what it is, what it does, and how to framework is processed using the same three steps: start using it in your own development projects. 1. Generate XML content (either statically or dynamically) A basic understanding of the core concepts behind XML, 2. Optionally transform it SAX, and XSL (and, of course, HTML) is helpful when reading 3. Format it for output

28 JUNE 2002 JUNE 2002 29

Java COM Java COM Along with this simple, easy-to-understand architecture Cocoon 2.0 comes great power and flexibility for developers. Although Enter Cocoon v2.0. This version (released as alpha in Cocoon is most often used for generating Web pages, it’s by no March 2001, with the first production release completed in means limited to that. It can generate any type of output you November) seems to be almost a complete rewrite of the desire for any type of client device you like: HTML, XML, text, application. It addresses the performance issues from version WML for WAP-enabled devices such as mobile phones, SVG 1 as well as being a much cleaner architecture conceptually. images, Postscript, Adobe PDF, etc. And, of course, you can The first notable improvement is the substitution of the

J2ME “roll your own” add-ons for Cocoon to generate any type of event-driven SAX XML standard for the memory-intensive custom output format you need. DOM API. In addition to the improvements in memory effi- Another major plus of Cocoon’s XML-orientation: it pro- ciency and scalability, the SAX model also allows output to be vides for excellent separation of content and presentation – generated incrementally. This provides a faster response time that holy grail of software applications. Content is kept as since a response page is returned little by little, rather than presentation-free XML data for as long as possible during pro- waiting until all processing is complete to return a page (as the cessing, and then formatted into the appropriate output for- DOM model required). The second major improvement concerns the inter- J2SE nal architecture of the Cocoon application. Originally structured using a Reactor design pattern, this structure apparently caused conceptual as well as implementa- tion difficulties. Instead, version 2.0 substitutes a pipeline architecture (described later) that proved far more flexible to code as well as much clearer conceptu- ally. The result is a solid, well-tested, powerful, and more efficient framework for just about any type of content J2EE generation under the sun. At the same time it manages to elegantly achieve true separation of presentation and content. In short, Cocoon really rocks! FIGURE 1 A simple Cocoon pipeline How Does Cocoon Work? mat just before being returned to the user. Let’s take a closer look at Cocoon and how it works, and see

Home In fact, Cocoon strives for an even greater separation of how you can put it to use in your own development. Canoo concerns. Its philosophy is to look upon the process of content generation as three separate realms: content, logic, and style. A Servlet at Heart This type of division makes a great deal of sense, especially Although Cocoon is a powerful framework for XML pro- when you consider that completely different teams of people cessing, it’s just a servlet at heart. Its job is just like any other are frequently assigned to each of these functions: logic to servlet’s: to receive requests, process them, and then generate software developers, content to users and data entry staff, and a response. Cocoon accomplishes this by taking each request, Engineering AG style to graphic designers. finding an appropriate “pipeline” to handle it, executing the pipeline, and returning in its response any output that the How Cocoon Was Hatched pipeline generated. The pipeline’s function is to generate the Inception response output for a particular request, using XML process- www.canoo.com/ulc/ Cocoon began its life in 1999 as a far less ambitious ing internally to accomplish this task. endeavor than it is now. Pioneered by Apache developer Stefano Mazzocchi, Cocoon was initially just a “proof of con- The Pipeline Architecture cept” – a servlet that used XML and XSLT transformations to The pipeline, a simple and elegant paradigm, fits in generate its output. extremely well with the XML SAX processing model. A pipeline at its simplest consists of a sequence of the three Cocoon 1.0 core Cocoon components – generators, transformers, and By the time Cocoon made it to version 1.0, it had pro- serializers – arranged in a chain (see Figure 1). XML data (SAX gs gressed into a full-fledged framework for XML content gener- events) is passed down the chain, with each component per- ation and was starting to receive a good deal of recognition forming its own processing on the data as needed. At the end and use by site developers. of the chain the events are serialized out to the response’s Win

As with all early-version software though, it’s often difficult OutputStream and returned to the client making the request. r to foresee the potential usability problems that will crop up in practice while the software is still being developed. It’s also dif- Generators,Transformers, and Serializers ficult to envision how popular your application will be at such The first component in the chain is always the generator. an early stage. Cocoon was no different. Version 1.0, although The generator’s job is to create the stream of XML events that functional, had its usability hampered by design decisions will be fed through the rest of the pipeline. There are prebuilt made early on, most notably its reliance on the memory- generators available to create the XML events from a number intensive XML DOM architecture. (The SAX model, and the of possible sources: an XML file on disk, an HTML file (the

th Cocoon APIs and tools needed to use it, were still in their infancy at HTML is tidied up and turned into XHTML in order to be XML- i

Spread You w that point.) compatible), a JSP page, an XSP page (more about XSP later), Since Cocoon was proving to be quite popular, demands etc. In fact, there are over a dozen varieties of generators for new features and improved performance kept coming in. It included with the Cocoon distribution. And you can easily soon became clear that the initial architecture was not ade- create new ones if you need to generate events from a non- quate to address these issues. standard source.

30 JUNE 2002 JUNE 2002 31

Java COM Java COM The last component in the chain is always the serializer. except for the XSL instruction xsl:apply-templates. This The serializer’s job is to turn the stream of XML events into instruction simply commands the XSL processor to begin pro- some form of output that will be returned in the response. cessing any child nodes here, applying other templates as Prebuilt serializers are available to create output in the most needed. The net effect of the instruction then is “transform popular formats: XML, HTML, text, WML, an SVG image, and any child nodes here.” more. Again, over a dozen varieties of serializers are included In this case there’s only one node in the XML file, a node, and only one remaining template in the stylesheet

J2ME your own to support just about any output format you like. (xsl:template match="message"), which is looking to match As an option, a sequence of one or more transformers can nodes. Since the stylesheet’s template matches the lie in between the generator and the serializer. Transformers XML file’s node, we’ll perform the second transformation: allow the developer to manipulate the XML events coming • Write a

opening tag down the pipeline – adding, removing, or modifying events as • Write the value of the text attribute in the node needed – before the serializer finally sends them back in the (in this case “Hello World”) response. • Write a

closing tag The XSLT transformer is the most common – and most J2SE powerful – transformer. It runs an XSL stylesheet against the Note the conceptual separation of concerns between the stream of XML events coming down the pipeline, allowing the XML file and the XSL stylesheet. The XML file contains data only developer to use the powerful XSLT language to transform the – the text of a message – with no indication as to how it should XML from pure data into styled output. be formatted for output. The stylesheet, on the other hand, con- You can place multiple transformers in a row in the tains formatting only – instructions on how a text message pipeline, each of which will operate on the XML events one at should be displayed – that can be applied to any XML data con- a time. This allows you to style the data incrementally, and can taining text messages. As a Cocoon developer, you’ll get the most help keep your stylesheets smaller and simpler. out of the framework if you structure your sites in this fashion. Although Cocoon uses several other types of components Once Cocoon executes this pipeline and performs this J2EE as well (which are beyond the scope of this article), these three transformation, the result is the following HTML: “The result is a solid, well-tested, powerful, and Home more efficient framework for just about any type of content generation under the sun” SpiritSoft components are the core of its architecture. Pretty simple, huh? But it sure is powerful! By assembling combinations of these core components – along with your own custom-built server pages and stylesheets – you can build pipelines to gen- you like, and rendered in whatever output format you like. A Message From Cocoon Putting It All Together Let’s look at a sample “Hello World” pipeline and see how

Hello World

this all ties together in practice. Our “Hello World” pipeline will work as follows: • Use the file generator to read XML from a file HelloWorld.xml This HTML is then serialized using the HTML serializer • Use the XSLT transformer to run a stylesheet Style.xsl (which takes care of the few incompatibilities between strong- against the XML data and translate it into formatted HTML ly formatted XML and loosely formatted HTML) and the whole gs • Use the HTML serializer to return the resulting HTML page thing is sent back in the response to end the request. to the user The Sitemap Win

Let’s start by looking at the files mentioned earlier: Great! So how do we write the code for this pipeline? r Cocoon uses a file called sitemap to define all the pipelines HelloWorld.xml in your application. The sitemap is just that, a map of your Cocoon Web site. It defines which pipeline will be run in response to each site request, and how exactly each pipeline will generate its response page. The sitemap is written in, guess what? XML, just like every- The HelloWorld.xml file is very simple, consisting of a sin- thing else in Cocoon. Let’s look at it piece by piece.

th Cocoon gle node () that contains a single attribute (text). First, all sitemaps must contain the root element: i

Spread You w The Style.xsl stylesheet (see Listing 1) is also very simple, consisting of only two formatting transformations. The first one (xsl:template match="/") is called when the XSLT proces-

32 JUNE 2002 JUNE 2002 33

Java COM Java COM Java COM Then the sitemap lists which Cocoon components your can be found on the installation page at the Cocoon Web site: site will use (see Listing 2). In this case we’ll be using only http://xml.apache.org/cocoon/installing/. three components: Once Cocoon has been installed, running it is just a matter 1. The file generator of accessing a URL that’s handled by the Cocoon servlet. When 2. The XSL transformer a request to such a URL is made, it is routed to the Cocoon 3. The HTML serializer servlet. Cocoon matches the URL against its sitemap and then executes the appropriate pipeline.

J2ME Each of these components is labeled as being the default To run our Hello World site, we first need to take the component of its type (more about this later). sitemap we just wrote and overwrite the sample We’ll also have to define an additional component, a sitemap.xmap file that Cocoon provides us by default. Then matcher, to get this sitemap to work. A matcher is used to we just point our browser to http://localhost:8080/cocoon/ match the URL that the user enters and route it to the appro- HelloWorld.html and – voilà – Cocoon serves up our dynami- priate pipeline. (We won’t discuss matchers in this article cally generated “Hello World” page. though.) Then we define the pipelines used in the site. In this case The Power of Cocoon J2SE we have only one, our Hello World pipeline, which we will set Our “Hello World” pipeline is an extremely simple exam- up to be executed when a request arrives for page ple. However, it’s not hard to see how applying these concepts “HelloWorld.html”. can enable us to create more complex sites with Cocoon. The pipeline calls the file generator to read from the Since Cocoon provides complete separation of content HelloWorld.xml file, then calls the XSL transformer to apply from style, you can take the same content and format it in the Style.xsl stylesheet, and finally calls the HTML serializer to many different ways. There’s no need to create new logic or properly format the XML event stream as HTML. content in order to create different looks for your site. Just cre- Since earlier in the sitemap we defined each of these com- ate a new stylesheet for each output format, and you can serve ponents to be the default of its type (see Listing 2), we can use up completely different-looking sites from the same content. J2EE a shortcut and not explicitly write which component we’re How could this be useful in practice? Imagine the following using; Cocoon assumes we’re using the default. (However, if possibilities, all of which can be accomplished with ease using we were calling a generator other than the file generator, a JSP Cocoon. You could create sites that serve out the same content page, for example, we would need to write something like formatted completely differently based on: .) • Various devices that clients use to access the site (a PC with The full pipeline reads like this: a Web browser, a WML-enabled phone, a PDA using the HandWeb browser, etc.)

Home • Different browsers that clients use to access the site (e.g., display the site differently if the user is using , IE, or Opera; provide special support for old versions of these browsers; take advantage of the advanced features of newer AltoWeb versions of these browsers, etc.) • Machine-readability: the site can generate both a user- readable version (in HTML) and a machine-readable ver- sion (in XML) www.altoweb.com • The user’s language (you could internationalize your site using stylesheets) Finally, we write a closing tag for the root element: • Different security levels • And more Clearly, Cocoon’s ability to do dynamically styled page gen- And that’s it. Our complete Hello World sitemap reads like eration is a powerful tool for site designers! Listing 3. XSP Installing and Running Cocoon Another key innovation to come out of the Cocoon project, How Do We Run This Site? which I mentioned briefly above, is Extensible Server Pages gs As mentioned earlier, Cocoon is just a servlet at heart. It (XSP). Inspired by JSP, XSP provides all the power of JSP while can be easily run on any servlet engine that supports version removing one of that technology’s major drawbacks: the inter- 2.2 or later of the Servlet API. I’ve used it with Apache Tomcat, mingling of content and style. Win

but it can also be run on WebLogic, Resin, and many others, As discussed earlier, Cocoon heavily stresses the separa- r even on Microsoft IIS (using ServletExec). tion of content, logic, and presentation. If there’s one place Installing Cocoon onto the server is pretty easy for most that logic and presentation are often intermingled it’s in serv- servlet engines and usually consists of the following: er pages. By definition, both ASP and JSP freely intermix logic • Download one of the Cocoon binaries (e.g., cocoon-2.0.1- and presentation, i.e., source code and HTML. Although the bin.zip) from http://xml.apache.org/cocoon/dist/. use of beans and taglibs in JSP can minimize this to some • Unzip the archive. extent, there’s still inherently some intermingling of logic and • Grab the cocoon.war file that was extracted from the presentation, due to the use of HTML.

th Cocoon archive and copy it to the appropriate directory on your Cocoon’s solution is, once again, elegant: use XML instead i

Spread You w servlet engine (e.g., for Tomcat, the “web apps” directory). of HTML in your server pages. Unlike HTML, XML is presen- • Restart the servlet engine; it will automatically install tation-free; it’s just data. So writing a server page using XML cocoon from the .war file when it’s restarted. makes a lot more sense. An XSP page therefore consists of XML data tags, along More details and instructions for specific servlet engines with intermingled logic (Java code). As with JSP, the Java logic

34 JUNE 2002 JUNE 2002 35

Java COM Java COM 36 Home J2EE J2SE J2ME J UNE Spread Your Wings

2002 with Cocoon drawbacks: while removingoneofthattechnology’s major “XSP database) Irealized thatIcoulddesigntheGUI extremely were fairlysimpleandsimilar(just rows offields from the could saveagood bitofdevelopmenttime. Since thescreens with XMLenabledmetocomeup withanideathatIrealized good fit. readingproject, Istarted up onCocoon toseeifitwould bea Cocoon before, andhadworked heavilywithXMLonarecent more cutting-edgetechnologiesaswell. AsIhadheard of leading candidates, butIalsowantedtoconsidersomenewer, ger question.OffthetopofmyheadJSPandStruts were the no software installationorupgrade procedures needed. ment, minimaltraining required for the rest of thestaff,and gained from a Web-based system,includingeaseofdevelop- easy decisionforme, asthere wouldbeseveral benefitstobe based systemover anapplicationinMSAccess. This wasan ence. tions andwashappy todefer tomyknowledge andexperi- Access), hewaslookingtomefortechnologyrecommenda- had recently mockedupaprototype forthenewsysteminMS cation wouldconsistoflessthanadozen screens. end forthelegalcasefilesintheirdatabase. The entire appli- update, anddelete)thatwouldprovide auser-friendly front complex –abasicCRUD system(functionalityforcreate, read, Works…for DOS!). The systemfunctionalitywasnotterribly ly usingandgettingincreasingly lockedinto(Microsoft replace theancientandinflexiblesoftware theywere current- onyour owndevelopment platform projects. insight astowhenyou mightwanttochooseCocoon asa choosing Cocoon are here described tohelpprovide some law firm. The project, itsdesign,andsomeofmyreasons for A Cocoon CaseStudy section ifyou’d liketoread more aboutXSP. a goodoverview though,andyou canrefer totheResources could easilyfillupanentire onitsown.) article This shouldbe efits. Java code. Using taglibraries withXSPprovides thesameben- pages helpstokeepthemfrom becomingtoofilledupwith As JSPdevelopersknow, callingreusable taglibraries inyour for taglibraries (oftenreferred toas “logicsheets” inCocoon). eventually classfiles),andlikeJSP, XSPalsoprovides support (suchasHTML). outputformat priate the XSLT transformer usinganXSLstylesheet)intotheappro- usingaCocooncally styledandformatted transformer (e.g., erated XMLstream, theappropriate thestream isthentypi- events inapipeline. Oncethe XSPpagehasexecutedandgen- the logicwillgenerate, notHTML. ference here isthat,onceagain,presentation-free XMLiswhat modules) dynamicallycreates thepagetobeoutput. The dif- (through theuseofeither embeddedcodeorcallstoexternal Cocoon’s andmyexperience technologywasintriguing, But which Web tochoose wasabig- developmentplatform My firstrecommendation tohimwaschoosea Web- wasfairlycomputer-savvyAlthough theheadattorney (he waslookingforanewpieceofsoftwareThe lawfirm to I recently usedCocoon todevelopasiteforNew York City XSP istoobigatopictodiscussinmore detailhere. (It Like JSP, XSPpagesare compiledintoJava code(andthen All XSPpagesare Cocoon generators –thesource ofXML provides allthepowerof the interminglingofcontentandstyle” document for a particular pieceofcontent andchangethe document fora particular scratch. What typeofsoftware couldIusetoscanthrough a could already dothissoIwouldn’t itfrom havetowrite thought, itwouldbeniceifthere wassome existingcodethat retrieved from thedatabaseformerge fields?Boy, I they could),hewasfinewithit. use theMS Word applicationtoeditthedocuments(which mat insteadof Word, andhedidn’t. Aslongastheycouldstill tomakesurethe headattorney hedidn’t mindusingRTF for- ments andfindthemail-merge fieldsinthem.Icheckedwith parser generator, Iwasabletosuccessfullyread RTF docu- spec andafterspendingacoupleofhourswiththeJavaCC aparsertodoit.IreadI couldprobably write thoughtheRTF mat, wastext-basedandwouldbemucheasiertoread. In fact, an RTF (Rich Text Format) file?RTF, unlikethe Word .docfor- aware ofanyJava libraries thatcoulddothat.But whatabout identified, andtheactualdatasubstitutedin. template documentwouldneedtoberead in,themerge fields easyenough.Afterthat,Ireasoned,database wascertainly the pen? behind thescenes. What wouldberequired tomakethishap- withallthemerge substitutionsalreadyment arrive done button labeled “create merged document” andhavethedocu- would bemuchsimplerforthemiftheycouldjustclickona a mail-merge utility, Ifeltitwouldbeclumsyfortheusers. It nicely. launch andopentothatdocument. This wouldwork outquite ment, theword processor (MS Word) wouldautomatically opened, soeachtimetheusergenerated amail-merge docu- applicationwhenanattachmentis to launchtheappropriate “open-attachment” functionalityisautomaticallyconfigured Web page. This wouldbesimplefortheusers. Most browsers’ upthemerged documentsasadownloadsite toserve from a late aplan. based system.But asIthoughtit through Ibegantoformu- had noideahow Iwouldprovide amailmerge ina Web- need toprovide mail-merge functionalityaswell. At first,I If theywere goingtoabandon Works, thenewsystemwould frommerge thedatabaseintoadocument. theinformation stuck withMS Works alltheseyears wasitsabilitytomail reams ofdocuments, andoneofthereasons had thisfirm sure how toaccomplish.Lawfirms, aswe allknow, generate er, wasanadditionalrequirement, onethatIinitiallywasn’t in thetable. The ideaappealedtome. into anHTMLtable, andeach tagcouldbecomearow for anHTMLpage, each

tagcouldbetransformed HTML. Eachtagcouldbetransformed intoaskeleton asinglestylesheet thatwouldtransform theXMLinto writing allthescreencould turn mock-ups into Web pagesjustby rendered usingHTMLtables). Listing 4,amock-upof Web pageinXMLthatwilllaterbe quickly andeasilyby justmockingupthescreens inXML(see That leftmewiththelastbit:How tosubstitutethedata Reading anMS Word documentwasatallorder –I wasn’t Having thesiteretrieve datafrom theappropriate the But how todothemailmerge itself?AlthoughMS Word has First ofall,Irealized thebestapproach wouldbeforthe What finallyclinchedthedecisiontouseCocoon, howev- Then switchinghatsandputtingmyselfin “style” mode, I J ava JSP COM 37 J ava M AY 2002 www.rational.com/offer/javacd2 COM Software Rational J UNE 2002 37 value of that content before outputting it again? Then it hit the efficiency gains significant enough, the performance issue AUTHOR BIO me: I could use an XSL stylesheet! XSL was built to easily han- is outweighed. Cocoon is no different – its power comes at a David Rosenstrauch, a dle tasks like this. price. Although many Cocoon components are eventually software developer, Suddenly the whole idea began to come together, and my compiled down to class files (allowing optimizers like JITs and has been providing decision to use Cocoon was clinched. I would write a new gen- HotSpot to do their magic) all that XML and XSL processing development and erator that would parse an RTF file and turn it into a stream of does take a performance toll. (Cocoon does utilize techniques consulting services to XML events. I would generate a stylesheet in response to each to make this processing as efficient as possible, such as an Fortune 500 mail-merge request that substituted database values for the extensive caching mechanism.) You need to decide for your-

J2ME companies and merge fields and I’d use the XSL transformer to apply this self if it’s worth it. For a law firm’s document processing sys- start-ups for over stylesheet. Then I would use the text serializer to write out the tem I felt that the answer was yes. For building a high-volume 13 years. new mail-merged RTF file data, I’d set the appropriate MIME site where performance is critical, like Amazon.com or a type for RTF documents (“application/rtf”), and the user stock-trading system, your answer might very well be no. would get served up a mail-merged RTF document. I put together another proof-of-concept and, sure enough, it • The sitemap/pipeline examples I gave here were very sim- worked. ple and fit cleanly into Cocoon’s generator-to-transformer-to- Writing the application using Cocoon worked out well, serializer paradigm. But many sites require more complex J2SE though it did have its share of challenges. As the application functionality than that to respond to a request, such as condi- was not particularly complex, the code was not particularly tional processing, loops, etc. The sitemap does have other difficult. The biggest challenge, however, was getting up to capabilities that can accommodate these needs. (In fact, the speed in some of the new technologies I was using, primarily sitemap is beginning to resemble a full-fledged program Cocoon and XSL. I wound up learning them incrementally, as itself.) As a result, it can sometimes be a bit challenging for needed, when I hit roadblocks in various pieces of the devel- developers to make the sitemap do what they need, and its opment. (“Hmmm. How do I do this in XSL?”) The online doc- simplicity and readability can be sacrificed somewhat. umentation I found for XSL and Cocoon was helpful, as was Cocoon’s developers are aware of this problem, however, and Michael Kay’s book, XSLT Programmer’s Reference 2nd Edition. working to address it. They are now deciding how best to J2EE (And, of course, I also posted my share of “Help me!” messages redesign the sitemap to handle these issues, and various ideas to the Cocoon Users mailing list.) about the redesign have been discussed on the Cocoon The system was finally completed and installed in Developers mailing list in recent months. As with all open December 2001, and got a big thumbs-up from both the users source software, ideas from the development community are and the head attorney. It is now used daily by the entire staff. invited. From my perspective, I give Cocoon a big thumbs-up. I chose it as the core technology for this project, and it accom- For More Info

Home plished everything I needed. I found that using XML and We’ve only scratched the surface of the Cocoon technology Cocoon on the project allowed me to deliver it faster, as well as here. I’ve omitted a great deal of material for brevity’s sake. helping out tremendously in the conception and design There’s much more to Cocoon, and a detailed discussion phase. While designing I was able to focus completely on what could easily fill a book. (Indeed, the Cocoon Developer’s Altova type of content I was going to display on each page and how it Handbook, by Sue Spielman, is due out this year.) would be generated, and completely ignore all presentation If you’re intrigued by what you’ve read here, I’d encourage and style concerns until a later time. I found this separation of you to start using Cocoon. There’s no better way to learn than concerns during design to be quite a refreshing change! by hands-on development. The best way to approach Cocoon www.altova.com is to start with a small, simple site and build it up incremen- Cocoon Concerns tally from there, learning as you go. Although I found Cocoon to be an excellent technology for There’s also loads of additional documentation available site development, it’s not without some drawbacks. You about Cocoon online, in fact, probably too much for a novice should be aware of the following concerns when you’re decid- user. Again, I’d encourage you to approach it incrementally. ing whether to use Cocoon in your development: Read a little at a time, learning more about each of the various components and techniques as you need them. • Cocoon is still a fairly new and less established technology. And there’s still a risk that it might not catch on and achieve a Resources large user base. This translates into several direct risks for sys- At the Cocoon Web Site (http://xml.apache.org/cocoon/): tems built with Cocoon: • Understanding Apache Cocoon: http://xml.apache.org/ gs – It’s still more difficult to find developers experienced in cocoon/userdocs/concepts/ Cocoon and its related technologies than in more main- • Cocoon 2 Idiots Guide: http://xml.apache.org/cocoon/ stream technologies like JSP or Struts. ctwig/ Win

– If it doesn’t catch on, it may be difficult to continue enhanc- • How to develop Web applications with Cocoon: http://xml. r ing and supporting applications built with it. apache.org/cocoon/tutorial.html • Cocoon Users mailing list: cocoon-users-subscribe • Cocoon, like many new technologies, is still undergoing @xml.apache.org. (Details about acceptable content for the development. Although most of the major redesign work list at http://xml.apache.org/cocoon/mail-lists.html) appears to be behind it, the functionality and APIs may con- • Cocoon Users mailing list archives: http://xml.apache.org/ tinue to change in the future, forcing developers to update cocoon/mail-archives.html their applications to be compatible with new releases. XSP Tutorials:

th Cocoon • www.suranyami.com/XSPtutorial/ i

Spread You w • As with many technologies, making life easier for the devel- • Spielman, S. (June 2002). Cocoon Developer’s Handbook. oper often comes hand-in-hand with a performance penalty. Sams: www.amazon.com/exec/obidos/ASIN/0672322579/ As we know, even our choice of using the Java language comes with a performance hit. But if the hit is minimal enough and [email protected]

38 JUNE 2002 JUNE 2002 39

Java COM Java COM /> Listing 1 /> J2ME A Message From Cocoon name="wildcard" src="org.apache.cocoon.matching.WildcardURIMatcher" />

J2SE Listing 3

xmlns:map="http://apache.org/cocoon/sitemap/1.0" > Listing 2 name="file" src="org.apache.cocoon.generation.FileGenerator" J2EE src="org.apache.cocoon.generation.FileGenerator" label="content" /> name="xsl" src="org.apache.cocoon.transformation.TraxTransformer" name="xsl" Quintessence Home src="org.apache.cocoon.transformation.TraxTransformer" Systems Limited www.in2j.com Capella University Listing 4

www.capellauniversity.edu

40 JUNE 2002 JUNE 2002 41

Java COM Java COM J2SEJ EDITORIALOR J2SE INDEXX

Stress-Free Java KEITH BROWN J2SE EDITOR I’ve recently taken up Yoga – calmness in the mind, strength in the body, peace in the soul (or words to that effect). I mention this 42 Stress-Free Java because I’ve felt the need to relax more outside the office, J2SE his month I’m at peace with the special effects” – the 3D guys’ eyes widen- and this seemed the perfect world so this editorial may seem ing in disbelief and panic as they realize way. Tsomewhat relaxed and, dare I say, they’ll have to animate 2,000 reptile-like by Keith Brown floppy. I’ve recently taken up Yoga – calm- creatures by next Tuesday.) ness in the mind, strength in the body, However, as I said, I am now at peace Broken Windows in the peace in the soul (or words to that effect). with the world, so let’s move on. Java World I mention this because I’ve felt the need to Should I have been worrying? That’s If a broken window sounds relax more outside the office, and this the question. I guess not. The start of the just like another name for a seemed the perfect way. year came and my software trundled on Java bug, it’s not – it’s the 44 I know this is common in certain jobs with no problems. What would have hap- more evil twin of a Java bug where perhaps a lot of money is at stake pened had it gone wrong? Well, fortu- that we don’t usually hear with every minor decision. The kinds of nately, because I was using Java, I didn’t about. Here’s how to identify jobs that frankly provide way too much need to worry about the blue screen of and fix them. stress and people problems. death being presented to the user. Java’s by Joe Xu I never expected stress as a Java devel- error-handling is a joy to behold, and the

Homeoper! J2EEfact that J2ME it doesn’t take down the whole Interfacing to AIM New Atlanta Strange, is it not, that in this day and system has gone a long way to cement with Java age, when most of us have satisfied the Java as a serious 24/7 language of How to communicate with first four human needs of Maslow’s choice. America Online’s (AOL) Hierarchy by the time we’re of working Recently our development team has Instant Messenger, known as age, that we still feel stressed and require been approaching the final stages of quite AIM, by creating a reusable 50 outside influences to relax us. an extensive piece of software. To analyze class that allows access to Communications As a developer, where does the stress and hopefully improve performance, we the AIM network, which you come from? engaged the use of a profiler and, by jove, can use to create an instant Last year I was involved in a project it worked a treat! There it was as clear as messaging application. that required a sales reporting tool for an day! Line x to Line y took way too long. by Jeff Heaton www.newatlanta.com accounts department. The beginning and Sure enough, with a few tweaks the per- end of their financial year was the first formance improved significantly. Using the Java Native Monday in April – so what would happen Profilers are something I mentioned in Interface Productively to the system when the year rollover came a previous editorial, with reference to Every developer along? what the latest vogue was at JavaOne. who has used the JNI is Despite testing and testing until the They’re something that every developer aware that it’s powerful and cows came home, there’s always just a little should have in his or her arsenal. It’s real- comprehensive. However, the bit of doubt that creeps into your head and ly down to personal preferences as to price of these features is an perhaps a sleepless night on the first what stage in your development you inordinate amount of work to Sunday in April, anticipating the dreaded begin using a profiler. Some argue it accomplish some very mun- phone call the next morning saying the should be from day one, while others use dane tasks. In this article I system has gone pear-shaped. Not quite as it more toward the end of a project. The address the problem of using 58 stress-free as coding a Space Invaders first step is to become comfortable with the JNI in a production situa- applet. the benefits a profiler can bring. The first tion and present a set of tech- Oh well! As Dennis Leary would say, time you use one, you’re presented with a niques that simplify most of “Join the club” (with a few more expletives plethora of information that can take the repetitive tasks of passing I grant you). At least I’m not a 3D graphics some time to digest. information to the native code artist on the next Star Wars film. (I’ve heard But once you come to grips with it, and getting it back into your from certain sources that the approach on you’ll wonder what you ever did without Java program. set is, “Oh, we’ll just put that in later with one. by Andrew J. Chalk

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

42 JUNE 2002 JUNE 2002 43

Java COM Java COM JAVA SYSTEMS Broken Windows in the Java World The Java bug’s evil twin J2SE

Not long ago I went with a couple of friends to a bar in lower Manhattan. While we were sipping Coronas, Jerry, our sys- tem architect friend, told us he had just inherited a high-profile WRITTEN BY J2EE system, along with one of the top Java teams in his company. JOE XU “Now we know who’s buying the beers tonight,” we cheered.

Instead of a round of beers, Jerry passersby observing it will conclude that Some broken Java windows are just decided to surprise us: “My first J2EE no one cares or no one is in charge. In plain inefficient. They work, but there project might very well be my last.” time, a few will begin throwing rocks to are better ways of doing them (e.g., an Apparently, Jerry had overestimated the break more windows. Soon all the win- optimized sorting algorithm imple- flexibility of the project’s code base, and dows will be broken, and now passersby menting a comparable interface). for a guy obsessed with time lines, it cost will think that not only is no one in Others are like time bombs that could him dearly – he missed his first deadline charge of the building, no one is in blow away your whole system at any

Home J2EEby weeks. What bothered him more was J2ME charge of the street onto which it faces. time; a security loophole comes to Ashnasoft the fact that the team seemed to be giv- So more and more citizens will abandon mind. When triggered, these sort of bro- ing up. “There are bandages every- the street to those they assume prowl it. ken windows tend to be very costly, as where,” one developer told him before Small disorders lead to larger ones, and we’ve seen in the past with eBay, whose taking off. “But I thought the team was perhaps even to crime.” The net result of 22-hour server downtime cost more very good,” I said. “They still are, but this strategy, Giuliani observed, was a than $5 million in return auction fees. they just can’t seem to keep up with the transformation “that’s improving the Contrary to popular belief, broken Corporation changes. The next thing you know, bro- lives of millions of New Yorkers.” Java windows are not always the result of ken structures have mushroomed every- a manager or developer not knowing where.…And now I’m working late every The State of Many Java Neighborhoods Java technologies any better, not drink- day.” Broken windows exist not only in the ing enough Java to do the job. Some win- www.ashnasoft.com As we were trying to raise Jerry’s spir- real world (possibly in a neighborhood dows are broken by inexperienced pro- its, Ben, our project manager friend, near you), but also in the Java world, grammers who lack Java skills or by sea- pointed to a nearby TV and said cheer- taking on various forms under the cover soned Java programmers who lack time fully, “He can help you.” It was a news of functional code. Some broken Java and political support. A conversation clip about Time’s man of the year – windows are easy to spot and are better like, “Hey bud. Hard wire Favorite Mayor Rudolph Giuliani. known in the industry as spaghetti code: Customer Inc. in the code. We’ll all be massive nested if-else, code duplica- out of here if we don’t do this for them by Mayor Giuliani and Broken Windows tions across modules, and dead code, to next Monday. BTW, the big gun was just Turns out that Ben wasn’t joking. If name a few. On more than one occasion asking about this earlier,” is not uncom- there is one tip Mayor Giuliani can share I’ve run across component instantiation mon. with Java developers, it’s the power and routines with over 200 if-else, which can Some windows are broken the simplicity of the “Broken Windows” the- easily be replaced with one line of minute they’re installed (early in the ory. In a speech he gave at Lincoln Class.forName(). development stage), while others “creep Center in 1998, Giuliani pointed out that Other broken Java windows are more in” later when dealing with high-speed, New York City had turned around, with subtle and require some digging. One high-frequency business changes. The overall crime dropping 44% over the last such example is premature abstractions. success that most Java systems enjoy four years, and the “Broken Windows” Good abstractions make Java systems has to take some blame for some of theory, “an integral part of our law more flexible, but sometimes developers these changes. As a successful system enforcement strategy,” made this possi- fall into the trap of trying to solve becomes more popular, it attracts more ble. abstract problems before they even users, who in turn demand more fea- First written about in 1982 by politi- understand the concrete ones. The net tures and more flexibility quickly. The cal science professor James Q. Wilson result is unnecessary complexity that once ever-changing Java specifications and criminologist George Kelling, the gets in the way later down the develop- are a good case in point. Also, most of “Broken Windows” theory states that “If ment stream (if you think no abstraction the Java systems find their homes in a factory or office window is broken, is bad, try bad abstraction). Internet-driven business. Unfortunate-

44 JUNE 2002 JUNE 2002 45

Java COM Java COM JAVA SYSTEMS

rate so high that no one really knows about the system anymore. As Giuliani pointed out, if a climate of disorder is allowed to take root, more Broken Java windows are given serious antisocial behavior will increase. “There’s a continuum of disorder.” “ Obviously, bugs and broken windows a license to do whatever they are two different “disorders.” But they are part of the same continuum, and a like for as long as they like climate that tolerates one is more likely to tolerate the other. “…A city in which an increasing number of people respect and are willing to accommodate the ly, the Internet industry is constantly all over the subsystem and its neighbor rights of others is a city that’s moving in reinventing itself with businesses trying subsystems. a progressive direction.” By the same J2SE different models. Some models deal Small disorders lead to larger ones, token, a Java system in which broken with how you charge, some with how and perhaps even to project cancella- windows are “arrested” is a system that’s you deliver the services. Some work, tion and firings. In other words,” broken moving in a progressive direction with some don’t. The dynamic nature of this Java windows create a delusion of dys- true Java spirit. environment can break all windows if functional systems, even though a sys- Does that mean that as Java develop- not managed carefully. tem might be perfectly fine up to that ers, our new mission is to “hunt down” point. Once developers are convinced all broken windows mercilessly ASAP? In What’s the Big Deal About a Few that the current system is crap, it a time-starved society, that’s often Broken Java Windows? becomes a license for them to break impossible. What we need instead is a Despite their diverse appearances, some more Java windows. In contrast, if different approach, an approach that all broken Java windows seem to be developers are convinced otherwise, allows us to make steady progress sticky – they have a tendency to stay they would think twice about breaking toward our real goal – delivering func- around for a long time, sometimes even any window – after all, we Java develop- tionality and, at the same time, fixing throughout the whole system’s life cycle. ers are no different than any other artist broken Java windows, an approach that Although developers are not particularly – we love and appreciate beautiful says a Java team should only fix win-

Home J2EEfond of them, they don’t lose sleep over J2ME things. With that appreciation, we do dows at natural project breaks, and pri- Parasoft them either. After all, broken windows everything we can to preserve them. It’s oritize their broken windows before try- do work with respect to specified behav- these two characteristics that enable ing to fix them. iors, and what’s a better alternative to broken Java windows to accelerate their not delivering the system on time? damages. Identify Broken Java Windows This also explains the fact that devel- Some Java developers react to bro- opers generally don’t introduce bugs The Little-Known Evil Twin of the Java Bug ken windows by installing a “broken Java Corporation intentionally, but the same thing can’t If a broken window sounds just like window detector.” Since broken win- be said about broken windows. People another name for a Java bug, it’s not – it’s dows are a legitimate concern through- on the business side don’t seem to mind the more evil twin of a Java bug that we out development, no new functionality them either – they might not even be don’t usually hear about. A bug is usual- can be considered done until it has www.parasoft.com/jdj6 aware of their existence. And if they do, a ly defined as something that’s not func- passed the detector. This practice might typical response is along the lines of tional and is visible to the business. On sound good and complete on paper, but “Does it work?” “Yes, but it’s a bad thing the other hand, a broken window is in real life it is the recipe for killing a to do.” “Well, if it ain’t broke, don’t fix it. functional and often invisible, but has a good Java system. The first symptom is We are way overloaded already.” So bro- mid- to long-term negative impact on the fast-dropping development velocity. ken Java windows are given a license to the health of the system and the devel- And instead of listening to the users’ do whatever they like for as long as they opment team. needs, concentrating on business sce- like. In many ways comparing a Java bug narios, and getting functionality done Another common characteristic is to a broken window is like comparing a right, every thought is now interrupted that broken Java windows “replicate” cold to an early-stage terminal disease – by the question “Is this a broken win- fast. Like worms, they spread swiftly, without warning signs it’s harder to dow?” A team will most likely miss the leaping from module to module detect (remember why your doctor rec- chance to make a big leap in their devel- throughout the whole system. But how? ommends regular checkups), but in the opment progress. If an object or routine is broken, devel- end it proves far more lethal than a cold. Plan on identifying broken windows opers observing it will conclude that no Like any terminal disease, broken win- toward natural breaks, such as when a one cares or is in charge. In time, a few dows slowly deteriorate system internals module is expected to be complete, or will conclude further that the system is over time, until one day the system is before every minor release. Allocate not worth the effort (i.e., “All the rest of completely drained. In other words, it time in your project plan to do so. It this code is crap”) and more routines becomes so “bloated” or badly struc- helps keep your team and project stake- will get broken. Soon all the routines will tured that you’ll find yourself spending holders informed of your priorities so be broken, and now developers will an enormous amount of time and effort they’ll act accordingly. think that, not only is no one in charge to implement a simple change. At the of the object, no one is in charge of the same time, it “deteriorates” the most Categorize Broken Java Windows subsystem to which it belongs. So more precious resource of all – the develop- Once identified, you could “arrest” and more broken windows will pop up ment team. It bumps up the turnover broken Java windows one at a time. In

46 JUNE 2002 JUNE 2002 47

Java COM Java COM JAVA SYSTEMS

my experience though, some Java win- them. Now is also a good time to involve in Java bugs, shouldn’t we do the dows are broken due to a particular project stakeholders. They might dislike same for their evil twin? If broken design or approach that spans multiple certain broken windows more than oth- windows in your Java world are not areas. For instance, without a class fac- ers. On one project, just when I thought getting fixed, maybe it’s time to seri- tory, you might find component instan- everyone would care less about exe- ously think about moving to a new tiation code scattered over multiple sub- cutable size than memory footprint, Java neighborhood. After all, who systems. In this case, if we arrest broken some stakeholders were more than likes to have a time bomb in their Java windows one at a time, we might have happy to indicate otherwise. And of backyard? ended up with different fixes, as the win- course they were right. dows might get assigned to different References developers. In other words, we miss the Arrest Broken Java Windows • Giuliani, Rudolph W. “The Next Phase benefit of finding commonality. Another Once prioritized, we know we’ll be of Quality of Life: Creating a More approach is to profile all identified bro- arresting the ones that offer the biggest Civil City”: www.nyc.gov/html/rwg/ ken windows, take into account several bang for the buck. There are many ways html/98a/quality.html modules in which the same type of bro- to actually fix broken Java windows. The • Wilson, T. (1999). “The Cost Of J2SE ken window occurs, and you may find best-known technique is probably refac- Downtime.” InternetWeek. July. www. yourself a different fix. toring and JUnit. internetweek.com/lead/lead073099.h Profile your broken windows, cate- If we can’t fix all identified broken tm gorize them, and you just might be able windows, what do we do with the rest of • Wilson, J.Q., and Kelling, G.L. (1982). to fix two or more windows at one time. them? Keep them in your ongoing bro- “Broken Windows: The police and ken windows list. More important, do neighborhood safety.” The Atlantic Prioritize Broken Java Windows the little things that show the team Monthly. March. www.theatlantic. AUTHOR BIO Once all broken windows are catego- cares. My personal favorite is to write com/politics/crime/windows.htm Joe (Leizhou) Xu, an rized, our gut reaction is to “arrest” them down a little comment next to the code • Hunt, A., and Thomas, D. (1999). The AVP with Credit all. Unfortunately, due to time con- starting with the word “FIXME” for bad Pragmatic Programmer: From Journey Suisse First straints, that would force you to either functionality or “TODO” for a missing man to Master. Addison-Wesley. Boston, delivers commit to less functionality than you one. That would buy the team some • Gamma, E., Helm, R., Johnson, R., large-scale J2EE should be implementing or fail to deliv- time psychologically, until the next time and Vlissides, J. (1995). Design systems for Fortune er the system on schedule, in which case slot for broken Java windows comes Patterns: Elements of Reusable 1000 and e50 no one would care about broken win- around. Object-Oriented Software. Addison-

Homecompanies. He holds J2EEdows anyway. J2ME Wesley. an MS and a BS in Prioritize your broken windows Conclusion computer science. before putting a lot of energy into fixing If we’re investing time and money [email protected] Dice www.dice.com

Northwoods aqriaus Software www.nwoods.com/go/ p/u

48 JUNE 2002 JUNE 2002 49

Java COM Java COM Many clients are appearing that can often send messages over various protocols. But do other models exist, besides Create a reusable class that allows access to the AIM network simply sending instant messages between human users? Several companies are already putting computers on the receiving end of . One such company, ActiveBuddy (www.smarterchild.com), put several “screen names” online that allow users to ask “virtual buddies” about such things as movies, weather, and stock quotes. Programs Interfacing to such as this require intimate knowledge of how the instant messaging system works. This article shows you how to communicate with America Online’s (AOL) Instant Messenger, known as AIM, by creating a reusable class that allows access to the AIM network, which you can use to create an instant messaging application. AOL Protocols J2SE There are many instant message clients that can talk to the AOL network, for example, programs such as , Jabber, and GAIM. In the past few months these programs have come under fire from America Online as AOL tries to keep unautho- rized programs off their network. Why does AOL try to stop some clients and allow others to continue? The answer has to do with what protocol the instant messaging client uses. When America Online first allowed Internet users to access the AIM network, they had to provide a protocol that would AIM allow the Internet version of AIM to communicate back to the AOL network. This protocol is called OSCAR – Open System for Communication in Realtime – a misnomer. OSCAR is not an open system, or at least not “open” in the sense of GNU- style licensing. OSCAR is a closed protocol, as AOL has never published its

Home J2EE J2ME specification. Any large-scale use of the OSCAR protocol has always been vigilantly blocked, but this has not stopped pro- grammers. A great deal of information is available on the Internet about the OSCAR protocol and many third-party with instant message clients are based on it. I wrote an OSCAR Java client in Java that communicates with AOL using this proto- col. However, if this client runs longer than 5–10 minutes, AOL sends me the following instant message just before their net- work disconnects my client. written by Jeff Heaton You have been disconnected from the AOL Instant Message Service for accessing the AOL network using unauthorized soft- ware.You can download a FREE, fully featured, and authorized client here, http://www.aim.com/index.adp.

nstant messaging has become very This article is not about how to use the OSCAR protocol. popular in recent years, earning it a If you’re interested in OSCAR, you can download my client from www.jeffheaton.com/im. If you use the OSCAR proto- deserved spot with the “killer apps” – col for a large-scale project, you’ll be playing “cat and mouse” with AOL. AOL’s actions indicate that they do not browsing and e-mail. Most of the want third parties using it. Products such as Trillian use the OSCAR protocol, and, as a result, users must frequently Internet’s killer apps have spawned a upgrade to a new version of Trillian that thwarts AOL’s latest host of accessories to be used in attempt to block them. This article focuses on another AOL protocol named TOC conjunction with the app. Instant (Talk to Oscar). TOC was created by America Online to allow open access to their instant message network; it was created messaging is just starting this process. prior to their merger with Time Warner. One of the conditions for this merger, set out by the U.S. government, was for AOL to open its instant messaging protocol. So AOL in essence creat- ed a wrapper. The TOC protocol sits on top of the OSCAR pro- tocol and allows third-party applications to access the AIM network. AOL also released an open source, instant message client that’s capable of using the TOC. The structure of the AOL network is shown in Figure 1.

50 JUNE 2002 JUNE 2002 51 I JJavaava COMCOM JJavaava COMCOM As you can see from this figure, AOL subscribers connect eral reasons for this. First, OSCAR was available long before directly to the AOL internal network. The AOL AIM clients go TOC. Many third-party programs were already written when directly to the authentication and BOS (used for load balanc- TOC was released. Second, AOL has not been that good about ing) servers, and the TOC clients connect through the TOC adding all the latest features to TOC. To be able to send files server. This results in three connection classes that can all and access the advanced “broadband” streaming content that communicate with each other. AIM now contains, you must use the OSCAR protocol, since The open source AIM client released by AOL was written in such features have not been added to TOC. However, for basic Tcl, and was called TiC (TOC is Cool). AOL no longer officially instant messaging and chat, TOC has all the necessary fea- supports the TiC client, so it can’t be downloaded from the tures. AOL site. TiC is now maintained as an open source client on Source Forge (www.sourceforge.com). Logging into TOC Clients that use the TOC protocol do not face the same The complete source code for my implementation of the blocks that OSCAR clients face. Unfortunately, there aren’t any TOC protocol can be found in the files “JavaTOC.java” and popular clients available for the Windows platform that make “Chatable.java”. These two files can easily be added to any use of the TOC protocol. Trillian, for example, uses only the project that requires the use of instant messaging. To see how J2SE OSCAR protocol. Perhaps the most common client that sup- the JavaTOC class was constructed, you must first see how the ports the TOC protocol is GAIM. Unfortunately, it’s written in TOC protocol works. C and supports only the UNIX platform. There’s not much To log in to AIM you must have a screen name and pass- open Java source code for using the TOC protocol, which is word. If you don’t have an AIM screen name, you can easily why I wrote JavaTOC as an example for this article. Using the obtain one for free from http://aim.aol.com. The JavaTOC JavaTOC class, you can communicate with both the TOC pro- class defines a method called “login” that accepts a screen tocol and the AIM network. This article presents a sample name and password. When you call login, it begins the login AIM-compatible client (see Figure 2), and the complete process. source code is available on the JDJ Web site, www.sys-con. To log in to TOC you’re required to send and receive data com/java/sourcec.cfm. using FLAP, a special packet type. (It’s unknown what FLAP If TOC is the protocol that AOL wants developers to use, stands for, as AOL has always used this name.) FLAP also why do most third-party programs use OSCAR? There are sev- forms the foundation of the OSCAR protocol. A FLAP packet consists of a header of six bytes followed by a variable length data packet (see Figure 3). The first byte of a FLAP packet is always the asterisk (*), which is hex code 0x2b. Following the

Home J2EE J2ME identity byte is the frame type. TOC uses two frame types. One LOOX frame type indicates a “sign-on” packet, and the other a nor- mal “data” packet. Most packets are data packets. Following the first two bytes is a word representing the sequence number. Why AOL needed a sequence number on a protocol that uses TCP/IP is unknown. However, you must always provide an ever-increasing sequence number or your Software Inc. client will be abruptly disconnected. Sequence numbers can begin with any number and must always increase by one. The sequence numbers used by the client are completely separate from the sequence numbers sent to you by AOL. Following the www.loox.com sequence number is a word that specifies the length of the data section only and does not take into account the size of the FLAP header. Both the length and sequence numbers are stored as little endian numbers, which means the last byte is the least signif- icant. For example, the value 1024 would be stored as the byte FIGURE 1 The AOL network 0x04 followed by 0x00, not the other way around. For more information on little and big endian numbers, see my article “A Class for Reading Binary Files” (JDJ, Vol. 6, issue 7). To allow these words to be written correctly, JavaTOC contains a method called “writeWord” that will write a word to an “InputStream” in a format that’s correct for TOC.

protected void writeWord(short word) throws IOException { os.write((byte) ((word >> 8) & 0xff) ); os.write( (byte) (word & 0xff) ); FIGURE 2 The example program }

The JavaTOC class also contains a useful method for writing FLAP packets to a socket. This handles the sequence number and lengths for you. Simply pass the string the writeFLAP method FIGURE 3 Format of the FLAP packet you’d like transmitted and the frame type (signon or data).

52 JUNE 2002 JUNE 2002 53

Java COM Java COM protected void sendFlap(int type,String str) TOC currently supports only English; as a result “english” is throws IOException the only value that should ever be sent as a language. The ver- { sion field specifies which client is logging in and can be any int length = str.length()+1; value. If the login is successful, TOC server will respond with sequence++; “SIGN_ON:version”. If a failure happens, an “ERROR:error os.write((byte)'*'); number” response is returned. os.write((byte)type); At this point the user is not signed in yet. To complete the writeWord(sequence); login process the user’s client must send the “toc_init_done” WriteWord(length); within 30 seconds of beginning the login process. Before the os.write(str.getBytes()); login method sends the “toc_init_done” command, a few con- os.write(0); figuration items are taken care of. First the “toc_add_buddy” os.flush(); command is sent to specify the user who’s logging in as a } buddy. Then the “toc_init_done” command is sent to com- plete the signon process. All the TOC commands are strings. The only part of the TOC After signon, a few configuration settings must be sent. The J2SE protocol that’s binary is the FLAP packets that enclose the TOC “toc_set_caps 09461343-4C7F-11D1-8222-444553540000 09461 commands. Now, with the FLAP packet defined, we can log 348-4C7F-11D1-8222-444553540000” command is sent. The into TOC. The first step is to open a socket to the TOC server. two GUIDs specify the ability to send messages and buddy sup- The host name for the server is “toc.oscar..com”, and the port. Finally, the permit and deny lists are cleared by sending the port is 9898. Once a socket connection has been opened, the “toc_add_permit” and “toc_add_deny”. These are lists that allow string “FLAPON\r\n\r\n” must be sent to the TOC server. you to include or exclude certain people. With this complete, the Upon receiving this, the TOC server will reply with a FLAP pack client may now send and receive instant messages. containing the data bytes 0x00, 0x00, 0x00, and 0x01. This is the Logging out of TOC is easy. Simply breaking the socket current version of FLAP being used, version one. connection by using the “close” method of the “Socket” class Next a FLAP signon packet must be sent. This is a normal is sufficient. FLAP packet with a data section that contains the following: first, the version numbers 0x00, 0x00, 0x00, and 0x01, then a Sending and Receiving Instant Messages word of 0x0001. This indicates that a user name will follow. Sending and receiving instant messages with TOC is fairly easy. The next word represents the length of the screen name. To send, the send method of the JavaTOC class should be called: Following the length is the normalized representation of the

Home J2EEscreen name – all spaces are removed J2ME and the entire name is public void send(String to,String msg) InstallShield converted to lowercase. { Once the FLAP signon packet has been sent, the first TOC try {

command must be sent. This is the “toc_signon” command. this.sendFlap(DATA,"toc_send_im " + normalize(to) + " The exact syntax for this is: \"" + encode(msg) + "\""); } toc_signon catch(java.io.IOException e){ “ Software Corp. } } Any large-scale use of the OSCAR www.installshield.com protocol has always been vigilantly blocked, but this has not stopped programmers”

Some of these fields will This method accepts two parameters that specify who the “ require a description to message is going to and what the actual message is. The tar- understand their use. First the get’s screen name is normalized, as previously defined. The authentication host and authorizer port refer message is encoded to fit inside quotes. Encoding the mes- to the authorization server shown in Figure 1. sage involves setting any carriage returns to HTML
com- These values are always sent as “login.oscar mands and putting a \ in front of characters such as quotes. .aol.com” and “5190”, respectively. This specifies AIM messages may contain HTML code. which OSCAR authentication server to use. The user Receiving an instant message is accomplished by the event name is simply the normalized user name. loop contained in “JavaTOC”. Because events can be received The password is sent in a format that AOL refers at any time from the TOC server, the program must be ready to as roasted, so it’s not transmitted as “clear text” to handle them. The JavaTOC class contains a method, over the wire. Still, roasted passwords are trivial to processTOCEvents, to do this: decode. The OSCAR protocol uses a more advanced MD5 challenge system. The process of roasting is per- public void processTOCEvents() formed by first xoring each byte in the password with the throws IOException equivalent modulo byte in the roasting string, which is { I “Tic/Toc”. The result is then converted to ASCII hex with a for(;;) leading “0x”. For example, the password “password” roasts to { “0x2408105c23001130”. String str = this.getFlap();

54 JUNE 2002 JUNE 2002 55

Java COM Java COM if(str==null) ger–type chat window. If you’re talking to more than one per- continue; son at a time, multiple windows are displayed. if(str.toUpperCase().startsWith("IM_IN:")) { The “ChatBuddies” class contains the background thread handleIM(str); that processes all TOC events by calling the “process- } TOCEvents” method of the “JavaTOC”. The “run” method of else if(str.toUpperCase().startsWith("ERROR:")){ this thread is shown here. handleError(str); } public void run() else{ { owner.unknown(str); try { } } if(toc.login(login.userID.getText(),login.password.getText } ())){ this.setVisible(true); As you can see, this code is an endless loop. This method is this.setTitle("Logged in: " + login.userID.getText() J2SE intended to be run as a background thread. This is the approach ); taken by the example client presented with this article. As login.setVisible(false); instant messages come in through the TOC “IM_IN:” command, } they’re routed back to another class that’s waiting for them. This else class must implement the “Chatable” interface. These interfaces return; specify the TOC events that will be sent to a class that’s using the toc.processTOCEvents(); JavaTOC class. This interface is shown here. } catch(Exception e) interface Chatable { { } public void unknown(String str); } public void error(String str,String var); public void im(String from,String message); First the user is logged in. If the login fails, a TOC error event } will occur and be displayed by the “processTOCEvents” method.

This background thread handles all incoming messages.

Home J2EEAs messages are received, they’re J2ME routed to the “error” Actuate method if the event is a notification of an error. If the event is Conclusion

an instant message, it’s sent to the “im” method. All other A lot can be done with instant messaging technology. By event types are sent to the “unknown” method. There are using the Java code provided in this article, you can write many other event types, and the “toc.txt” file contained with instant messaging–enabled programs. This code implement- the source code defines them all. For ed a client. It’s also possible to write server type applications example, this program currently that wait for connections and provide data. An example of this “ Corporation doesn’t work with buddy lists. would be a program that sends an instant message to indicate Buddy list support would something failed on a server. www.actuate.com/info/jbjad.asp Clients that use the TOC protocol do not face the same blocks that OSCAR clients face

require the addition The example program provided here is not a complete of“ buddy events. instant message application. Adding such features as a buddy list, HTML, and saved configurations would greatly enhance its The Example Client usability. Yet, despite these limitations, it shows the fundamen- An example program is provided to show tals of how to work with AOL’s instant message architecture. how to use the JavaTOC class. It implements a simple AIM-compatible client that doesn’t support References buddy lists. To start the program you must start the main • Glossary of terms used by Oscar/ToC given by AOL: AUTHOR BIO class “ChatBuddies” using the command “java ChatBuddies”. www.aim.aol.com/javadev/terminology.html Jeff Heaton, a software A JAR file named “JavaTOC.jar” is included and can be execut- • The GNU protocol specification by ToC as released by AOL: designer for the ed in order to see the example. Some computer systems allow www.jeffheaton.com/im/toc.txt Reinsurance Group of you to simply double-click this file to execute the example. • One ofI the more complete documents describing the inter- America (RGA), is a The example program (shown in Figure 2) is implemented nals of the OSCAR protocol: http://aimdoc.sourceforge.net/ member of the IEEE and using three Swing “JFrame”-derived objects. The main frame OSCARdoc/section2.html a Sun-certified Java used is the “ChatBuddies” class. This class would normally be • The TiC client: http://sourceforge.net/projects/tik/ programmer. He’s the where a buddy list would be. Instead, it displays an input field • Ethernet packet analyzer: www.ethereal.com author of Programming that allows you to specify the screen name of the person you’re • The AOL instant messenger (AIM): http://aim.aol.com Spiders, Bots, and sending the message to. Clicking OK will launch the Aggregators in Java. “ChatWindow” frame, which is the typical instant messen- [email protected]

56 JUNE 2002 JUNE 2002 57

Java COM Java COM JNI TECHNIQUES Using the Java NativeInterface Productively Simplify repetitive tasks

Although we try to make our applications pure Java, out- side forces sometimes make this impossible. We had such a case WRITTEN BY recently in our shop when we had to interface to an external J2SE ANDREW J.CHALK device with an API that supported C language calls.

This is a typical case for the Java interpreting Java classes in C++, han- rapidly as long as its use is confined to Native Interface (JNI). The JNI provides dling structure alignment and data for- passing primitives. Java programs with a gateway to other mat issues, and implementing code that • The native code may require modifica- languages and enables applications is source compatible with both 32-bit tion for different platforms. While ISO written in other languages to invoke the and 64-bit processors. standardization has made C++ source Java Virtual Machine. code fairly portable, we’re out of the This article focuses on the first of The JNI,Power – at a Price area of Java binary compatibility. these two uses. Specifically, it discusses Every developer who has used the supporting a C/C++ API in Java to allow JNI is aware that it’s powerful and com- Most data types are more complicated a Java application to use it. This is prob- prehensive. However, the price of these than primitives. In Listings 3 and 4 the ably the situation in which the JNI is features is an inordinate amount of work Java and native code for passing and most frequently employed in produc- to accomplish some very mundane returning a string type are shown. The fol- tion environments. Indeed, the seminal tasks. In particular, parameter handling lowing is the output from these listings.

Home J2EEwork on the JNI, The Java Native J2ME is a time- and code-intensive business Interface: Programmer’s Guide and that’s subject to errors and latent bugs. Value is Hello World Specification by Sheng Liang, devotes a Consider the code in Listing 1, which Value returned is Goodbye World chapter to this question. There’s no the- might be described as the simplest func- HiT Software ory involved, but if you use the following tion to access a JNI. The native function While there’s virtually no change in the techniques you should save yourself is declared at (1) in the listing. (In Java code (essentially just a change of the many hours of work. Listings 1, 4, and 6 I’ve numbered specif- operative variable type from int to string), Phase one of the JNI programmer’s ic lines for reference purposes.) the native code is substantially more www.hitsw.com/xmlrdb acclimatization process: dump the The method passes one integer to a involved. Because a string is neither a sacred principle of Java development – C++ native function. The native function primitive type nor architecturally the platform independence. It must, as a prints the passed parameter to stdout and same as any string in the native language, purely logical implication, go out the also returns it. The native code is shown it must be handled differently. First, the window. All the C/C++ code in this arti- in Listing 2. Note the obscure function JNI function GetStringUTFChars() [at (1) cle compiles under GNU C/C++ on name, which is generated by javah. in Listing 4] both converts the string to the Solaris and Microsoft Visual C++ on the The native function just prints the C++ single-byte character set and retrieves Win32 platform. Other platforms would integer parameter to stdout. How this a pointer to the resultant object (other JNI have to be tested individually. appears depends on your Java develop- functions can handle conversion to C++ I’ll focus on the practical problem of ment environment. In Borland JBuilder wide, e.g., Unicode, strings). Second, the implementing a large and complex API the output from the native code and the JNI function ReleaseStringUTF() frees the using the JNI within a production envi- System.out.println()call both appear in memory allocated for the converted ronment. Space constraints required the IDE message window, as shown string. Third, the JNI function NewString- Liang to discuss passing parameters that below. UTF() allocates a Java string from a C++ consisted of Java primitives from Java to single-byte character string to return a C/C++ (hereafter C++, unless the dis- Value is 5 string to Java. The important point about tinction matters) and sending the C++ Value sent and returned is 5 Listing 3 is that passing strings increase return code to the Java application. the amount of native code necessary to However, most APIs are more complex. The native code prints the first line process the parameter. This is something not frequently and Java prints the second. The impor- String parameters don’t present even addressed in the literature, despite its tant points about this example are: the normal level of variable complexity. prevalence in the real world. APIs are • The integer parameter is passed from Real-world data types are likely to be not restricted to primitives as parame- Java to C++ as a primitive, so the represented as classes in Java and struc- AUTHOR BIO ters but pass structures and classes to native code can access it directly. tures or classes in C++. Listings 5 and 6 Andrew J Chalk, is the device. They not only use return • The same rule applies to all other Java provide the Java and C++ code for pass- president of Magna statements but also assign values to the primitives. ing a simple class. Carta Software, Inc., in passed parameters for use by the calling • The use of the JNI is straightforward, The Java code in Listing 5 is very sim- Plano,Texas. program. They present questions for and the native code can be developed ple. It just instantiates instances of

58 JUNE 2002 JUNE 2002 59

Java COM Java COM JNI TECHNIQUES

ClassAccess and Device2 where Device2 allocated memory for the structure and (see Listing 10). Listing 11 can then be aggregates an instance of Device1, instantiated the fields with the request- replaced with Listing 12. (Listings 11 and which it instantiates in the constructor ed data. This worked well for the C++ 12 can be downloaded from the JDJ Web chain. The code is straightforward, programmer who could examine the site, www.sys-con.com/java/sourcec.cfm.) indeed mechanical. However, the native data by dereferencing the pointer after method (see Listing 6) is completely dif- the API function call returned. Benefits ferent. While not conceptually sophisti- The Java programmer acquired a The family of Parse… functions has cated, it’s a complicated tangle of repet- new set of problems. We decided to substantially reduced the amount of itive operations on different data types. define a Java class for each C++ structure code required to make the necessary First, at (1), the code fetches the class of (a practice recommended by Bloch). assignments to the Java object passed as the object passed to the native function. Each field of each API structure had to jOutput and its contained objects. This is the Device2 object passed in the be assigned to a member of the corre- Furthermore, we’ve moved the intricate Java line classAccess.accessClass(dev2). It sponding Java class, passed as a param- code in which errors can occur into a set then proceeds to retrieve each parameter eter. The one-to-one mapping of Java of reusable functions. This expedites the in turn. The block at (2) retrieves the int classes to C++ structures gave us over 60 implementation of a large vendor API in J2SE field intValue. The code at (3) retrieves the Java classes. The number of structure Java and makes maintenance more long field longValue. The block at (4) is members meant that over 500 member straightforward. These functions are more involved as it retrieves the string field assignments had to be made. Code extensible to other variable types as nec- stringValue and resembles Listing 3. resembling that in Listings 1–5 would essary. We’ve implemented only the Finally, the block that begins at (5) shows have to be written and, more important, ones that we need. the more involved case of obtaining a field maintained – a daunting prospect. from an object contained within another We turned to a set of functions like Summary object. In this example the Device2 object those in Listing 7. However, now these The JNI is a powerful, comprehensive contains a Device1 object. It’s the int mem- functions would read a member variable solution to the problem of accessing an ber of Device1, intValue, that we wish to from a C++ structure and assign the value API written to support other languages, eventually obtain. [This is obtained at (6).] to the Java class (see Listing 9 for an exam- especially C or C++. That power comes at ple). For continuity, we continue to use the price of intricate parameter manipu- Simplifying the Implementation the Java classes Device1 and Device2 lations. In this article we addressed the Code like this will be repeated unless defined earlier. Their C++ equivalents are: problem of using the JNI in a production we find a way to move its regularities situation and presented a set of tech-

Home J2EEinto separate functions. The string and J2ME struct Device1 niques that simplify most of the repeti- contained object cases generate the { tive tasks of passing information to the most overhead, so they’re the ones cho- int intValue; native code and getting it back into our sen in Listing 7. Now the native code in }; Java program. These techniques reduced Sitraka Listing 5 can be abbreviated to that by around two-thirds the amount of C++ shown in Listing 8. struct Device3 code that had to be written. These tech- Furthermore, the two access func- { niques can be extended to cover other tions repeat the simplification that they int intValue; constructs, and it’s a pragmatic choice as www.sitraka.com/jprobe/jdj provide here in each native function long longValue; to which should be implemented in a they’re called in. In each instance that char * stringValue; particular project. we use this code we reduce the amount Device1 dev1Value; of code required to be implemented in }; Postscript the project by roughly two-thirds. After completing the project in Assume that at runtime they contain which these techniques were developed, the values shown below: another JNI project came up. Implementation of the native parts of struct Device1 dev1 = {10}; the project took about a quarter of the The JNI is a powerful, time that we had forecast, based on raw struct Device3 dev3 = { coding of JNI function calls. The code comprehensive solution 5, also passed all unit tests on Solaris and “ 8, Windows the first time, an indication of "Hello World", the reliability gains of a unified method {10} of handling parameter passing. While an }; unscientific estimate (different APIs, Assigning Data to Java Structures etc.), the difference in terms of schedule Now we’re at the point at which pro- Listing 9 is the Java program that will improvements was very noticeable. ductive use of the JNI became a major print out these values. issue in our shop. The vendor” API that The C++ code (see Listing 10) shows References we supported required some structure the implementation of the native method • Liang, S. (1999). The Java Native passing and what we discussed earlier assignClass. One interesting feature is that Interface: Programmer’s Guide and proved useful for this. However, the API’s it shows how to make assignments to nest- Specification. Addison-Wesley. main purpose was to return data from ed objects (Device1 is aggregated by • Bloch, J. (2001). Effective Java the vendor’s device, which it did by pro- Device3 in Listing 9). Just as in the case of Programming Language Guide. viding over 100 functions that required a passing parameters from Java to C++ we Addison-Wesley. pointer to an API structure to be passed provide a set of routines to expedite the [email protected] to an API function. The vendor library process and make the code more reliable

60 JUNE 2002 JUNE 2002 61

Java COM Java COM public class Device2 { Listing 1: Passing an int to the JNI public Device2 () { package jni_article_; intValue = 1; longValue = 11; public class IntegerAccess { stringValue = new String("Hello World"); static { dev1Value = new Device1(5); System.loadLibrary("EasyJNI"); } } private int intValue; private native int accessInt(int value); // (1) private long longValue; private int value; public IntegerAccess() { value = 5; String stringValue; } Device1 dev1Value; } public static void main(String[] args) { IntegerAccess integerAccess1 = new IntegerAccess(); System.out.println("Value sent and returned is " + Listing 6: Native code called in Listing 5 integerAccess1.accessInt(integerAccess1.value)); // Headers omitted… } // ClassAssign.AccessClass(Device2) } JNIEXPORT jint JNICALL Java_jni_1article_1_ClassAccess_accessClass__Ljni_1article_1_Device 2_2 Listing 2: Native code called in Listing 1 (JNIEnv *env, jobject jo, jobject jOutput) // Headers omitted… { JNIEXPORT jint JNICALL Java_jni_1article_1_IntegerAccess_accessInt // get the class of the object parameter J2SE (JNIEnv *, jobject, jint jInt) jclass cls0 = env->GetObjectClass(jOutput); // (1) { if (cls0) { cout << "Value is " << jInt << endl; // get the field ID of the "intValue" field of this class jfieldID fidInt = env->GetFieldID(cls0, "intValue", "I"); return (jInt); // (2) } if (fidInt) { // get the value of the field in this instance of the above Listing 3: Passing a string parameter from Java to C++ class package jni_article_; jint valInt = env->GetIntField(jOutput, fidInt); cout << "Value is " << valInt << endl; public class StringAccess { static { // get the field ID of the "longValue" field of this class System.loadLibrary("EasyJNI"); jfieldID fidLong = env->GetFieldID(cls0, "longValue", "J"); } // (3) private native String accessString(String stringValue); if (fidLong) { public StringAccess() { // get the value of the field in this instance of the above } class jlong valLong = env->GetLongField(jOutput, fidLong); public static void main(String[] args) { cout << "Value is " << (long) valLong << endl; StringAccess stringAccess1 = new StringAccess(); System.out.println("Value sent and returned is " + // get the field ID of the String field of this class stringAccess1.accessString("Hello World")); jfieldID fidString = env->GetFieldID(cls0, "stringValue", } "Ljava/lang/String;"); // (4)

Home} J2EE J2ME if (fidString) { Borland // get the value of the field in this instance of the above class Listing 4: Native code called in Listing 3 // Headers omitted… jstring valString = (jstring) env->GetObjectField(jOutput, JNIEXPORT jstring JNICALL fidString); Java_jni_1article_1_StringAccess_accessString if (valString) { (JNIEnv *env, jobject jo, jstring jStringValue) const char * str = env->GetStringUTFChars(valString, { NULL); jstring jStr = 0; if (str) { Software Corp. const char * str = cout << "Value is " << str << endl; env->GetStringUTFChars(jStringValue, NULL); // (1) env->ReleaseStringUTFChars(valString, str); if (str) { cout << "Value is " << str << endl; // get the field ID of the Device1 object field jStr = env->NewStringUTF("Goodbye World"); of this class env->ReleaseStringUTFChars(jStringValue, str); www.borland.com/new/jb7/5068.html } jfieldID fidObject = env->GetFieldID(cls0, "dev1Value", "Ljni_article_/Device1;"); // (5) return (jStr); } if (fidObject) { // get a reference to this field in this instance of the class Listing 5: Passing a class parameter from Java to C++. jobject valObject = env- package jni_article_; >GetObjectField(jOutput, fidObject); if (valObject) { public class ClassAccess { // get the class of the static { object parameter System.loadLibrary("EasyJNI"); jclass clsObject = env- } private native int accessClass(Device1 devName); >GetObjectClass(valObject); private native int accessClass(Device2 devName); if (clsObject) { public ClassAccess() { // get the field ID } of the "intValue" field of this class jfieldID fidInt = public static void main(String[] args) { env->GetFieldID(clsObject, "intValue", "I"); ClassAccess classAccess = new ClassAccess(); if (fidInt) { Device2 dev2 = new Device2(); // get the classAccess.accessClass(dev2); value of the field in this instance of the class } jint } valInt = env->GetIntField(valObject, fidInt); // (6) cout << "Value is " << valInt << endl; // In device1.java } package jni_article_; } } public class Device1 { } public Device1 (int value) { } intValue = value; } } } int intValue; } } } } // In device2.java package jni_article_; return (0); }

62 JUNE 2002 JUNE 2002 63

Java COM Java COM System.out.println("Integer value in Device 1 is " + Listing 7: Functions to handle fetching string and object members of a Java dev3.dev1Value.intValue); of a Java } // class } void AccessString(JNIEnv *env, jclass clsContaining, jobject jContaining, LPCTSTR lpszFieldName, string & strOut) { Listing 10: Functions to handle assignment of C++ data types to Java fields jfieldID fidString = env->GetFieldID(clsContaining, lpszFieldName, Java fields "Ljava/lang/String;"); // get the field ID of the field of // Get an object reference to a Java object type contained within this class a containing if (fidString) { // Java object. jstring valString = (jstring) env->GetObjectField(jContaining, jobject GetObjectReference(JNIEnv *env, jclass clsStruct, jobject fidString); joStruct, LPCSTR lpszJavaFieldName, LPCSTR lpszSignature) // get the value of the field in this instance of the above class { if (valString) { // Get the field ID of the field in the Java object const char * str = env->GetStringUTFChars(valString, NULL); jfieldID fidField = env->GetFieldID(clsStruct, lpszJavaFieldName, if (str) { lpszSignature); strOut = str; if (fidField) { env->ReleaseStringUTFChars(valString, str); // get a reference to the SymAPIDirector object } jobject joField = env->GetObjectField(joStruct, fidField); } return (joField); } } } return (0); } void AccessObject(JNIEnv *env, jclass clsContaining, jobject

J2SE jContaining, LPCTSTR lpszFieldName, LPCTSTR lpszFieldSig, jclass /* *clsContained, jobject *oContained) Assign a C int value to a Java int field. { The Java class is cls0. The Java object is oOutput. The C int // Code defensively. Initialize with "failure" values for safety value is uiMember. *clsContained = static_cast(*oContained = 0); The Java class member name is lpszJavaFieldName. // get the field ID of the field of this class Usage: jfieldID fidObject = env->GetFieldID(clsContaining, lpszFieldName, Return value: lpszFieldSig); 1 => success; if (fidObject) { 0 => failure; // get the value of the object field in this instance of the */ above class int ParseIntField(JNIEnv *env, jclass cls0, jobject oOutput, *oContained = env->GetObjectField(jContaining, fidObject); unsigned uiMember, LPCSTR lpszJavaFieldName) if (*oContained) { { // get the class of the object parameter int iRc = 0; // failure *clsContained = env->GetObjectClass(*oContained); } // Get the field ID of the field in the Java object. } // Note the "I" JNI signature for an int. jfieldID fid0 = env->GetFieldID(cls0, lpszJavaFieldName, "I"); return; if (fid0) { } // assign the (C++) int field to the Java object env->SetIntField(oOutput, fid0, uiMember); iRc = 1; // success Listing 8: Listing 5 modified to use the access… } // functions

HomeJNIEXPORT J2EEjint JNICALL J2ME return (iRc); InetSoft Java_jni_1article_1_ClassAccess_accessClass__Ljni_1article_ } 1_Device2_2 (JNIEnv *env, jobject jo, jobject jOutput) /* { Assign a C long value to a Java long field. // get the class of the object parameter The Java class is cls0. The Java object is oOutput. The C long jclass cls0 = env->GetObjectClass(jOutput); value is lCMember. if (cls0) { The Java class member name is lpszJavaFieldName. // int and long code here...(omitted for clarity) Return value: string sOut; 1 => success; Technology Corp. AccessString(env, cls0, jOutput, "stringValue", sOut); 0 => failure; cout << "Value is " << sOut.c_str() << endl; */ int ParseLongField(JNIEnv *env, jclass cls0, jobject oOutput, long jclass clsContained; lCMember, LPCSTR lpszJavaFieldName) jobject oContained; { AccessObject(env, cls0, jOutput, "dev1Value", int iRc = 0; // failure "Ljni_article_/Device1;", &clsContained, www.inetsoft.com/jdj &oContained); // get the field ID of the field in the Java object if (clsContained && oContained) { jfieldID fid0 = env->GetFieldID(cls0, lpszJavaFieldName, "J"); // get the field ID of the intValue field of this if (fid0) { // class // assign the (C++) long field to the Java object jfieldID fidInt = env->GetFieldID(clsContained, env->SetLongField(oOutput, fid0, lCMember); "intValue", "I"); iRc = 1; // success if (fidInt) { } // get the value of the int field in this instance // of the above class return (iRc); jint valInt = env->GetIntField(oContained, fidInt); } cout << "Value is " << valInt << endl; } /* } Assign a C single byte string value to a Java object field. } The Java class is cls0. The Java object is oOutput. The C string is lpszCMember. The Java class member name is lpszJavaFieldName return (0); and it's signature is lpszSignature. } Return value: 1 => success; 0 => failure; Listing 9: Assigning C structures to Java classes */ package jni_article_; int ParseStringField(JNIEnv *env, jclass cls0, jobject oOutput, LPCSTR lpszCMember, LPCSTR lpszJavaFieldName) public class ClassAssign { { static { int iRc = 0; // failure System.loadLibrary("EasyJNI"); // convert C-string member to a java String object } jstring str0 = env->NewStringUTF(lpszCMember); private native int assignClass(Device3 devName); if (str0) { public ClassAssign() { // get the field ID of the String field in the Java object } jfieldID fid0 = env->GetFieldID(cls0, lpszJavaFieldName, "Ljava/lang/String;"); public static void main(String[] args) { if (fid0) { ClassAssign classAssign = new ClassAssign(); // assign the (C++) string field to the Java object Device3 dev3 = new Device3(); env->SetObjectField(oOutput, fid0, str0); classAssign.assignClass(dev3); iRc = 1; // success System.out.println("Integer value is "+ dev3.intValue); } System.out.println("Long value is " + dev3.longValue); } System.out.println("String value is " + dev3.stringValue); return (iRc);

64 JUNE 2002 JUNE 2002 65

Java COM Java COM J2ME EDITORIALOR J2ME INDEX

The Longer-Life Pen You may be wondering why

J2ME someone involved in Java for mobile JASON R.BRIGGS J2ME EDITOR devices is relying on primitive, tree- killing technology like pens and J paper; the short answer to this is that 66 I am still embarrassingly PDA-less. There are, of course, a number of The Longer-Life Pen reasons (excuses). by Jason R. Briggs ’ve been thinking a PhD student should Java, of course. Now it’s not quite a PDA, consider doing a thesis on the life but coupled with the right Java applica- Whole House Audio from Iexpectancy of a pen after it’s pur- tions, it could be close. the Palm of Your Hand chased. I’ve come up with an approximate Nokia has another phone that also dou- It started with the conversion of my calculation for mine: LE (Life Expectancy) bles as an MP3 player (the model number CD collection to MP3 to make it =DWU (Date of Wanting to Use)-1; in other temporarily escapes me); if they could some- easier to find tracks and automate words, a pen will go missing the day before how merge that phone with the 7210 and add playback. As the owner of a PDA 68 you really need to use it. There’s definitely a a pop-open cover that hides a touchscreen with a Wi-Fi card, I thought it would paper there somewhere waiting to be written. so you can enter data like a Palm, then I’m be nice to control my This might (or might not) lead you to sure I’d purchase one on the spot. playback wirelessly. wonder why someone involved in Java for As you can see, it’s a bad case of What’s- by Bill Ray mobile devices is relying on primitive, tree- just-around-the-corner-itis. killing technology like pens and paper; the • • • Adding Commands to short answer to this is that I am still embar- In the “editor-eats-his-hat” department, Displayable Components rassingly PDA-less. There are, of course, a after mercilessly “sticking the boot” into This article introduces which dis-

Homenumber of J2EE reasons (excuses): J2SE Ericsson a few months back for their lack of playable components are available QUALCOMM 1. I am still waiting for a Sharp Zaurus to Java support in the T68 mobile phone (and in J2ME and explains how com- review (and play with). (As you’re proba- other models as far as I can tell), it seems mands are associated with them. In bly aware, the Zaurus is Sharp’s the forthcoming P800/802 will include Java particular, it examines how to create Linux/PersonalJava PDA.) However, it support. It should be a damned nice phone commands, add them to dis- 74 won’t be a long-term solution to the with an integrated digital camera, color playables, and define command problem as, short of changing my name screen, MMS, and Bluetooth support, behavior in CommandListeners. Incorporated and moving to Antarctica, I’ll have to among other features. (Note: It seems the Then it demonstrates how the give the unit back. Perhaps the fact that I new T62u also supports Java.) resulting code is typically procedur- look shifty has contributed to Sharp’s • • • al and quickly becomes cluttered unwillingness to deliver…? On a more sober note, those of you wait- when too many commands http://brew.qualcomm.com/ZJD5 2. I suffer from a common IT affliction ing for the next installment in Bill Swaney’s are created. known as “What’s-just-around-the-cor- “Jini Surrogate As a Platform for J2ME by Fred Daoud ner-itis.” The main symptom of this Games” series will have to wait a bit longer probably genetic disorder is that when- than expected. Bill was recently involved in Programming Games ever I find a device that might “fit the a horrific car accident, so it will probably be in J2ME bill,” so to speak, I’m immediately hit at least a few months before he will be able J2ME’s Mobile Information with the thought, “But wait, what about to complete the next article. Our best wish- Device Profile (MIDP) promises device X, rumored to be released in a few es go out to Bill for a speedy recovery. to become one of the most months? It’s slightly faster and can con- In this month’s issue, you’ll find a widespread computing platforms nect directly to my cortex…” beginner J2ME article from Fred Daoud over the next few years. 3. In true Scrooge McDuck fashion, I don’t on OO methodology for adding com- However, while learning the want to dish out the cash. mands to displayable components within basics of MIDP is simple enough MIDP. Sami Lababidi from Macrospace for most developers, under- 86 On top of those three points, I’ve also talks about programming J2ME games. standing the constraints of the suddenly changed my tune on the idea of And in the tradition of do-it-yourself- platform and the tricks to get convergence. Before, I looked at the idea of electronics-in-the-garage, Bill Ray dis- around them is crucial for effi- all-in-one devices as nice but mostly cusses controlling MP3 playback through cient development. This article is flawed in execution; now I’m starting to see wireless technologies – just the thing for a collection of lessons I’ve movement in the right direction. Nokia’s the couch potato who can’t be bothered learned from coding games for new 7210 has a color display, FM stereo to reach farther than the PDA on the cof- the first generation of radio, MMS (Multimedia Messaging) – and fee table. J2ME devices. by Sami Lababidi [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.”

66 JUNE 2002 JUNE 2002 67

Java COM Java COM WIRELESS MUSIC

J2ME Whole House Audio from the Palm of Your Hand It’s only the beginning Part 1 of 3

In this business we often talk about how easy it is to get com- puters to talk to each other; computers without networks are WRITTEN BY almost inconceivable. Despite being standardized as little as five BILL RAY years ago, we now expect them all to play nicely together.

Even in the home, a CAT-5 connec- select one would be good. already doing so I could see who pro- tion isn’t too remarkable, but mobile I should also point out that I’m very duced a song when using WinAmp or devices still spend most of their time in lazy, and the idea of entering the details similar applications. I know there are lonely isolation. of each recorded track doesn’t appeal to various standards for embedding infor-

Home J2EEOf course, many J2SE technologies exist me; the application must be able to cope mation about an MP3 file within the file for connecting handheld devices to net- with additional tracks being added auto- itself, but I decided it would be quicker works and other devices, but costs and matically and notice if any have been to simply use the file name, especially as limitations often cause people to ques- removed. this was all the information I required. Sprint PCS tion if it’s really necessary: Why should a Given this set of requirements, it’s Once I decided on how the music handheld be talking to the world? Well, I obviously important that all my music is was to be stored and what my require- came up with one idea, and this article stored in a standard format, something ments were for playing it back, I started shows how I implemented it. that most of the MP3 ripping software is working out what my application would http://developer.sprintpcs.com It starts with the conversion of my ideally suited to. I had used an applica- look like and how it would work. A for- CD collection to MP3 to make it easier to tion called Audio Catalyst, but this cur- mal design process probably would find tracks and automate playback. rently has some problems with Windows have helped at this point, but since the Once your collection is on your com- 2000, so now I use AudioGrabber, which application was only intended for my puter, you need software to organize it works well for my needs. This applica- use (something that will be obvious if and play it back; many freely available tion grabs tracks from a CD, converts you care to examine the source code, applications will do that with varying (rips) them to MP3 format, picks up the which can be downloaded from the JDJ amounts of control. track listing information over the Web site, www.sys-con.com/java/ Random playback is all very well, but Internet, and is able to provide the MP3 sourcec.cfm), I felt that as long as I had it can lead to some very strange combi- file names that correspond to the track the overall structure defined, I could get nations if your collection is broad names. Because of the way I intend to on with coding, something I came to (jumping from Beethoven to Aerosmith use the tracks, I decided to organize regret later, as you will see. can be something of a shock), and it them into directories by bands, then Obviously, the application would occurred to me that it should be possi- into subdirectories by album, and final- have two major components: a server ble to come up with something better. ly form the track name from the name of and a client. The server would have a As the owner of a PDA (actually, several, the band and the name of the track sep- minimum GUI, just enough to ensure it but for the moment it’s a Compaq iPaq) arated with a hyphen (“-”). Thus a sam- was working properly, while the client with a Wi-Fi card, I thought it would be ple listing looks something like this: would have controls for changing the nice to control my playback wirelessly. volume, pausing playback, and selecting My requirements were pretty basic; Blur\Park Life\Blur - Badhead.mp3 the next track (see Figure 1). random play does work for me most of Blur\Park Life\Blur - Bank The inclusion of a GUI on the server the time, but I would like to be able to Holiday.mp3 side was, strictly speaking, unnecessary, pause playback and adjust the volume. Blur\Park Life\Blur - Clover Over as it should be easy to run up a second There are also occasions when I’d like to Dover.mp3 client on the server if local control is select the next track to be played – when … etc. … needed. I also decided that it was impor- the mood takes me or when talking to tant for the server and the client not to guests about music – so some facility for Including the name of the band in be in constant contact for two reasons: browsing through the available tracks to the title of the file was something I was first, the battery life on an iPaq using a

68 JUNE 2002 JUNE 2002 69

Java COM Java COM WIRELESS MUSIC

Wi-Fi link is laughable, measured in and what kind of responses would be held on the server. This is used to identi- minutes not hours (in Part 2 or 3 of this expected? As all communication was fy the track when requests are sent back article I’ll discuss moving the applica- client-initiated, it was obvious that the to the server from the client. It was pos- tion over to Bluetooth with its much server would be using a ServerSocket lis- sible to use the track name, and then improved power consumption), so it tening on a specific port (1710, for no search the ArrayList for a matching track was important to be able to turn the other reason than it happens to be my (and, indeed, this proved necessary in client off without affecting playback. birthday). The client would connect to another context), but it seemed easier at

J2ME Second, I wanted to be able to run sev- that port and send a request, the server the time to use numbers. There was no eral clients with the same server. would respond, and the client would attempt to optimize the protocol to The motivation for this second break the connection. While it’s possible reduce network traffic. Given the short requirement is less clear. I have several to send several requests and receive sev- requests and responses this seemed computers and a wife with her own PDA, eral responses in one go, it was not unnecessary, and a human-readable so while the thought of being in sole deemed necessary (this is not a very protocol makes for easier testing. control of our listening choices time-critical application). The other commands are displayed appealed to me, it would be less popular On connection the server should in much the same way, allowing the user with others in the house. respond with a message to confirm that to pause, resume, adjust the volume, This decision has several implica- it exists (“+OK”), then wait for the client and play the next and last tracks. I did tions: primarily, it was not to send a request for it to respond to. I decide that the response to the status possible for the client to con- adopted the Internet convention of request would be useful in many other stantly display the track play- starting all successful responding mes- contexts, so several of the commands ing currently. I decided the sages with a “+”, while those that gave an respond with the same list. easiest solution was to add a error of any type start with a “-”; this A request to play the previous track button to update the display allows the client to simply check the first would lead to a lag as this track would on request (see Figure 2). It character of a response to see if the not be prepared to play unless it main- was possible to set up some request has been honored. I also decid- tained its prepared state, something I’d sort of registration system for ed that all network communications have to decide later on once I knew how clients and establish an out- would be case-insensitive. While this long the lag was and if it was tolerable going connection from the can slow things down slightly, it makes (as it turned out it’s only a couple of sec- server to all interested clients testing easier and avoids irritating prob- onds, which I can tolerate). whenever a new track start- lems with the use of the wrong case. I set This covered the basic commands,

Home J2EEed, but J2SE I decided this was too about mapping out all the network com- but I also wanted to be able to browse Fiorano complex at the moment; it munication I’d be using, starting with the available tracks and pick one to be could always be added later if the ability to display which tracks were played, so I had to add commands to it seemed important. being played on the client: retrieve a track listing and to play a spe- FIGURE 1 The server interface It was clear that cific track indexed by number. objects would repre- [server] +OK The track listing returns the file sent the tracks, and on [client] status names of the tracks held on the server in Software the server side these [server] +Last Playing 292#Clannad - the order in which they occur in the objects would exist in Ta Me Mo Shui ArrayList (so no index number is need- some sort of ArrayList [server] +Playing 866#Men Without ed). It also returns the full filename of (I like ArrayLists). Hats - 01 - In the 21st Century the track. The client, on receipt of this www.fiorano.com/tifosi/freedownload.htm The intention was [server] +Next 1057#Steeleye Span - data, can copy it into a local vector (no that on launch, once The Victory ArrayList in PersonalJava) with the fed with a directory to knowledge that the index numbers will start from, the server Note that the response not only con- match those used on the server. The would scan this direc- tains the track playing currently, but also data is terminated with a full-stop (“.”) tory and any subdirec- the last played and the intended next alone on a line, the same as the SMTP tories looking for MP3 track. It also occurred to me that while protocol. files that it could use to Java Media Framework (JMF, the API The play request is numerically FIGURE 2 Update display on request build the ArrayList. from Sun for audio playback) does a indexed; the word “play” is followed by a Requests to play a spe- good job of playing back MP3 files, space and the number of the track to be cific track were then there’s a distinct lag while the track is played. This track then replaces the pre- indexed by its position loading and preparing to play, leading to viously considered next track, and the in the ArrayList. Clear- unwanted gaps between tracks. I there- server responds with a status response ly, this meant that fore resolved to load each track before it listing the last, current, and next tracks. tracks could not be was needed; so while the current track is If the intention is to start the chosen added without stop- playing, the server is loading the next track immediately, a “next” message will ping and relaunching one in preparation. Obviously, I’ll have need to be sent. the server, but this was to write the server in such a way that a At this stage it’s important to docu- a minor point and not track that’s in the process of loading can ment your network protocol in as much considered important. be played, even if it means a short delay, detail as possible. I went to the extent of The first stage was in case the user swiftly chooses and printing up examples and pinning them to consider the net- starts a track. to the wall above my desk. Any changes working model: What The response is split with the “#” to the protocol should be recorded FIGURE 3 Track and album list kind of communica- symbol, the number before it indicates immediately and extensions added to tion would take place the position of the track in the ArrayList the written record.

70 JUNE 2002 JUNE 2002 71

Java COM Java COM WIRELESS MUSIC

up button click events using Personal- Java on the iPaq (the Sun implementa- tion, though the problem also manifest- I can now listen to music and ed itself using JEODE). Clicks don’t always make themselves heard, and I “control what comes next, but was eventually forced to switch to MouseDown events to ensure usable

J2ME interaction. that is only the beginning… This had the side effect of making the buttons less responsive (they don’t depress when clicked), but functionality won out over appearance. When you’re working with a team of track for playback, which was done with Getting the track browsing and selec- programmers this is common sense, but the following code: tion to work was considerably more when you’re working alone it’s easy to effort, just working out what the inter- think you’ll remember all the details, public void release() { face should look like was a task in itself. and then promptly come unstuck later loaded = false; ” I started thinking that a treeview would when you discover you can’t. p.stop(); work well, but the thought of having to Having worked out what the client p.deallocate(); write one held me back, and I wasn’t and the server are going to do, it was p.close(); convinced that it would scale well (by time to start writing them. Getting the } this time I was working with several JMF installed and working was very hundred CDs comprising over 1,600 smooth, and while the API can appear This way a track could exist in the tracks). I eventually went for two lists, confusing, it’s actually easy to get the ArrayList using few resources, then both held in a single dialog frame hang of it. By making the tracks respon- when it was known that it would be (remember that in PersonalJava you can sible for their own preparation and played soon, it would be prepared to have only one dialog and one frame vis- playback, I was able to encapsulate all start when the previous track had com- ible at a time, so the main application is the JMF functions into a single class. pleted. The Boolean loaded is used to in a frame and the PickTracks object is a Probably the most complex part is check if a track has been loaded. This is dialog). Album names are held in the top preparing the track for playing, which set to true on receipt of a list, while track names are displayed at

Home J2EEis accomplished J2SE with the following PrefetchCompleteEvent that’s passed to the bottom (updated when a different code: the ControllerListener (as specified dur- album is selected) (see Figure 3). I decid- ing track preparation). ed against having any buttons in this details = new File(fname); I also decided that Track objects part of the GUI as simply clicking (or Altaworks URL u = new URL("file:///" + fname); should be responsible for deciding if tapping, as we will be using a pen) will Manager.setHint(Manager.PLUGIN_PLAYER, they would play, so I added another be sufficient to select the next track to be new Boolean(true)); method called willYouPlay(), which played. p = Manager.createPlayer(u); returns the Boolean “true” every time. This gave me a working application. I www.altaworks.com p.realize(); This was intended to provide a more used the PersonalJava emulation envi- p.prefetch(); complex choice mechanism that I ronment to make sure it was all compat- p.addControllerListener(this); added later and will discuss in Part 2 of ible (and thus discovered the vector this article. problem, which was easily fixed) and The String variable fname is simply Once I got the server working, I test- transferred the application to my iPaq. It the full path and filename of the MP3 ed it using Hyperterminal (connecting works; I can now listen to music and file. The final line indicates that the to 127.0.0.1, the TCP/IP loopback control what comes next, but that is only Track class itself is the one to be address), then set about creating a the beginning… informed of playback events (such as client. When developing applications In Part 2 of this article I’ll show how I AUTHOR BIO when the track finishes or has com- such as this it’s always best to start with added a profile to each track, enabling Bill Ray has worked pleted its preparation). Once the track the server, so it can be tested using a ter- me to set my mood and have suitable for several is prepared, the following methods minal application. tracks chosen by preference. I’ll also telecommunications allow control from the main applica- On the client side I developed the show how Bluetooth is a better network companies around tion: application using normal Java, being solution for this kind of application, and Europe, including careful to use only constructs that are how it can be made to work with Java. In Swisscom where he public void start() { available in PersonalJava (so no beloved Part 3 I’ll discuss how I added the next was responsible for p.start(); ArrayList). stage of control and enabled my mobile the development of } While PersonalJava is a cutdown ver- device to switch speakers on and off their Java-compatible public void pause() { sion of Java, as long as you’re not using around my house. DTV platform. He is p.stop(); Swing and check before using any of the security editor for } more recent APIs, you can develop in Useful Links Wireless Business & public void stop() { Java and then test in PersonalJava with- • Java Media Player: http://java.sun. Technology and p.stop(); out too many problems. In this respect I com/products/javamedia/jmf/index. coauthor of p.setMediaTime(new Time(0)); did pretty well, falling down only on html Professional Mobile } remembering to use elementAt when • Personal Java: http://java.sun.com Java Development, accessing a vector. The basic controls /products/personaljava/ published by It’s also important to be able to were easy enough with a simple GUI and Wrox Press. release the resources being used by a buttons; the only issue was with picking [email protected]

72 JUNE 2002 JUNE 2002 73

Java COM Java COM J2ME

Home J2EE J2SE Pramati Technologies Using object-oriented principles and the ates high-level GUI components. Like the Command pattern, I present two new class- Canvas class it’s abstract, but it has four es that provide a simple solution to this direct subclasses that are concrete and problem. These classes provide structure ready to use: Alert, List, TextBox, and Form. www.pramati.com and reusability to the process of creating All but the Form, which is quite blank on its commands for displayables, resulting in own, are shown in Figure 2. The Alert class code that’s cleaner and easier to maintain. displays a message similar to a dialog box. The List presents choices using one of the Overview of Displayable Components following schemes: EXCLUSIVE, MULTIPLE, In the Mobile Information Device Profile or IMPLICIT. The TextBox allows the user to (MIDP) there’s no AWT (and certainly no enter text and can optionally restrict the Swing) for creating graphical user inter- input format; for example, permit numbers faces. Instead, GUIs are created using class- only. es from the javax.microedition.lcdui pack- The Form class, unlike its three siblings, age. As shown in Figure 1, the abstract is not a specific GUI component; rather it Displayable class is the superclass from serves as a container for the other compo- which you create objects that can be dis- nents, making it possible to build more played on the screen of a MIDP device. complex user interfaces. The components The two immediate subclasses of that the Form contains are subclasses of the Displayable are Canvas and Screen. The Item class. These include the ChoiceGroup Canvas class creates GUI components that (equivalent to the List), DateField, Gauge, use low-level graphical primitives to draw ImageItem, StringItem, and TextField. There themselves. To use the Canvas class you are no layout managers in MIDP; instead, must subclass it and implement its paint() the device automatically handles the layout, method, which receives a Graphics parame- traversal, and scrolling of the items that are ter. The Graphics class, similar to its J2SE added to a Form. In most cases, the compo- counterpart, provides methods to draw nents are laid out vertically. lines, rectangles, arcs, strings, and images. Besides having graphical representation, The Screen class, on the other hand, cre- displayable components can also have

74 JUNE 2002 JUNE 2002 75

Java COM Java COM tance of the command with respect to other commands. Commands with a smaller number are given a higher priority. When adding more commands than the maximum that the device can dis- play at one time, commands with a higher priority will be shown and

J2ME those of a lower priority will be avail- able only by other means (a menu, for example). After creating a command, add it to the displayable by using its add- Command() method. For example:

Command command = new Command("Go", Command.SCREEN, 0); displayable.addCommand(command);

The Command class is not where you define what happens when the command is invoked. Instead, you must create a class that implements the CommandListener interface, which contains one method:

public void commandAction(Command c, Displayable d);

FIGURE 1 Abstract Displayable class This method is called when a command that was added to a displayable is invoked, so this is additional behavior associated with them. To do this, add where you place the behavior for your commands. After creat-

Home J2EEcommands and J2SE set a CommandListener that will be notified ing your CommandListener, associate it with the displayable Rational User when the commands are invoked. by using the setCommandListener() method. Notice that the method is not addCommandListener() as would have been “Besides having graphical representation, displayable components Conference 2002 can also have additional behavior associated with them” www.rational.com/ruc

the norm in J2SE. As stated earlier, in J2ME there can be only Commands and CommandListeners one CommandListener per displayable. This means that the Figure 3 shows the relationship between the Displayable behavior for every command of a displayable must be defined class, commands, and CommandListeners. Notice that multiple in one implementation of CommandListener. commands may be added to a displayable, but only one CommandListener may be set. I’ll Procedural Example examine some of the consequences I’ll use an example to illustrate the use and consequences of this later. For now, let’s look at how of the current Command–>CommandListener process. to create commands and Command- Consider a simple MIDlet that displays the three different Listeners. types of Lists: EXCLUSIVE, MULTIPLE, and IMPLICIT. The To create a command, specify MIDlet displays an empty Form with four commands: one for the label string, type, and priority of each type of List, and an Exit command. the command. The label string rep- When the user selects a type, a List of that type with arbi- resents the command in the user trary choices is displayed. The user interacts with the List and interface. The command type gives can select OK or Cancel. OK displays a confirmation of the a hint to the device on the seman- selected List item(s), while Cancel goes back to the Form that tics of the command. It’s up to the offers the List type choices. device implementation to decide Listing 1 shows the code for this example. In line 6, I create which scheme to use for commands the initial Form. Lines 8–11 define the items that will be dis- of a certain type. The defined com- played in each List and a Boolean array that will contain flags mand types are BACK, CANCEL, indicating the selected items. Lines 13–20 create the four EXIT, HELP, ITEM, OK, SCREEN, commands for the Form. and STOP. And the priority is an Lines 22–25 define the OK and the Cancel commands for FIGURE 2 Concrete subclasses integer that indicates the impor- the Lists.

76 JUNE 2002 JUNE 2002 77

Java COM Java COM In the startApp() method, I add the four commands to the Command Pattern and CommandAction Form and set its CommandListener, defined on lines 44–69. In Creating commands and their behavior the OO way and this code, note that I determine the List type according to the solving the problems enumerated in the previous section invoked command. I then create a List of that type and add the meant opening my copy of Design Patterns (see Resources sec- OK and Cancel commands. Finally, I set the CommandListener, tion) and reviewing the Command pattern. Its intent is to defined in lines 71–100, and display the List. encapsulate a request as an object by providing a method that Note that line 79 tests for the OK command as well as will be invoked to execute the command. Refactoring (see the special List.SELECT_COMMAND; this command is Resources) confirms this by identifying a series of if/else state-

J2ME invoked when the user makes a selection on a List of type ments (or switch statements) as a “bad smell” in the code that IMPLICIT, so we must test for it. should be refactored. The proposed solution is to “Replace Listing 1 demonstrates the process of adding com- Conditional with Polymorphism”: move each leg of the condi- mands to displayables and associated Comm- tional to an overriding method in a subclass and make the andListeners to define the behavior for the com- original method abstract. mands. However, defining the behavior separate To do this, I created the CommandAction class, which con- from the command, combined with the restriction tains a command and provides the aforementioned method: of having only one listener per displayable, yields procedural code that prevents us from leverag- public abstract void execute(Displayable d); ing OO principles. Resulting problems include: • The CommandListener’s commandAc- This method makes it possible to associate the behavior of tion() method quickly becomes monolithic the command with the command itself. For convenience, the and littered with if/else statements. CommandAction class (see Listing 2) provides two construc- “After creating a few MIDlets, I became frustrated by these problems in the command creation process. There had to be a better way” • If you dynamically remove a command from a tors, one that accepts a command and one that accepts the displayable, the corresponding conditional state- label, type, and priority and creates a command from those ment in the commandAction() method remains and parameters. Now, the command and its behavior are encapsu-

Home J2EEwill needlessly J2SE be tested when other commands are lated in an object. For example: invoked. • The CommandListener is tightly coupled with the com- private CommandAction goCommand mands that it services. To add another command to a dis- = new CommandAction("Go", Command.SCREEN, 0) Jinfonet playable, you must not only add the code for the command, { but also modify the CommandListener. public void execute(Displayable d) { • The command and its behavior are defined in two separate // behavior code for the Go command places in the code, hindering readability. } www.jinfonet.com • You can’t create objects that define the behavior for your }; commands. So you can’t take advantage of features that OO provides, like inheritance and polymorphism. The CommandManager Class The second class I needed was one that accepts After creating a few MIDlets, I became frustrated by these CommandActions, adds the commands they contain to dis- problems in the command creation process. There had to be a playables, and invokes their execute() method when the better way. command is invoked. I called this class CommandManager. It provides a method to add a CommandAction to a dis- playable:

public void add(CommandAction cmdAction, Displayable dis playable);

In your MIDlet, create a single CommandManager that will handle all CommandActions for all displayables. A remove method is also provided:

public void remove(CommandAction cmdAction, Displayable d);

In the CommandManager class, I use three Hashtables, one to answer each of the following questions: • Hashtable 1: Given a displayable, how many commands have been added to it? • Hashtable 2: Given a command, what is its corresponding CommandAction? • Hashtable 3: Given a CommandAction, to how many dis- FIGURE 3 Displayable class, commands, and CommandListeners playables has it been added?

78 JUNE 2002 JUNE 2002 79

Java COM Java COM When a CommandAction is added to a displayable, the Benefits CommandManager adds the command contained by the I find that using the CommandAction and Command- CommandAction to the displayable and increments the Manager classes yield benefits at all stages of cod- counter for that displayable in Hashtable 1. If this counter, ing: creation, modification, and maintenance. after being incremented, is 1, the CommandManager registers These benefits are the results of making the itself as the CommandListener for this displayable. If the process more object-oriented. The key is to encap- counter is greater than 1, the CommandListener is already reg- sulate a command and its behavior in a single istered. class. Having the two close together in code also

J2ME Similarily, every time a CommandAction is removed from a improves readability. displayable, the CommandManager removes the correspond- The CommandManager is a helper class that ing command from the displayable and decrements the defines once and for all the mechanism of adding counter. If this counter goes back to 0, the CommandManager and removing commands to displayables and set- removes itself as a CommandListener for that displayable by ting the CommandListener. This reuse reduces clut- calling setCommandListener(null). The entry is also removed ter in client code. from Hashtable 1. OO principles can now be put to use when creat- Hashtable 2 is necessary because the commandAction() ing commands. Since commands and Command- method receives a command parameter and we must deter- Listeners are loosely coupled, adding or removing mine the corresponding CommandAction in order to call its commands does not require changes to a Comm- execute() method. andListener. Your code becomes more modular, and Hashtable 3 tells us whether upon removing a command, you can add new commands to your system without we can remove the Command–>CommandAction mapping having to modify or recompile existing classes. from Hashtable 2. Since it’s possible that the same command is used for more than one displayable, we must make sure that Conclusion no displayables use the command before removing the entry J2ME is an exciting platform for writing appli- from Hashtable 2. cations that run on wireless devices. After writing The complete code for the CommandManager class is several MIDlets, I realized that there was a better shown in Listing 3. Note: The Hashtables use 1-element int way to create commands and CommandListeners. arrays for counters because they require object values; Since these are used in just about every MIDlet, I when using integer objects you have to create new integers felt it was worthwhile to carefully consider the each time, which results in a lot of garbage to be collected. issue.

Home“OO J2EE principles J2SE can now be put to use when creating Quintessence commands. Your code becomes more modular, and you can add new commands to your system without having to modify or recompile existing classes” Systems Limited

Object-Oriented Example When a situation like this arises, add some utility Let’s now implement the previous example using the classes to help you program using the design you find www.in2j.com CommandAction and CommandManager classes (see Listing most advantageous. Take the time to do this once and for 4). all; you’ll be glad you did when you’re using those classes Line 7 creates the CommandManager that will be used for over and over again. all commands of all displayables. I hope I’ve encouraged you to strive for object-orien- Now, instead of having the if/else statements to deter- tation in general and to continue exploring J2ME in par- mine which type of List the user chose, we can define a ticular. class that extends CommandAction and constructs a com- mand and its behavior based on the List type (lines Resources 14–27). • Gamma, E., Helm, R., Johnson, R., and Vlissides, J. (1995). Lines 29–34 define the Exit command. Design Patterns: Elements of Reusable Object-Oriented Remember that the OK command can be directly Software. Addison-Wesley. invoked by the user, but the special List.SELECT_COM- • Fowler, M. (2000). Refactoring: Improving the Design of MAND can also be invoked when the List type is IMPLICIT. Existing Code. Addison-Wesley. AUTHOR BIO Lines 36–60 define the OK command as a subclass of • Knudsen, J. (2001). Wireless Java: Developing with Java 2, Fred Daoud is an CommandAction because we have to create two types, one Micro Edition. Apress. independent contractor for the OK command and one for the List.SELECT_COM- • Java 2 Platform, Micro Edition: http://java.sun.com/products and a Sun Certified Java MAND. For convenience, I provided both of the /j2me developer. He uses J2SE, CommandAction constructors. • Mobile Information Device Profile: http://java.sun.com/ J2EE, design patterns, and Lines 62–67 define the Cancel command. products/midp OO principles to develop Lines 70–73 show how easy it is to add the List • Java 2 Platform Micro Edition, Wireless Toolkit: http:// networked GUI CommandActions to the Form using the CommandManager. java.sun.com/products/j2mewtoolkit applications. Fred holds a You don’t have to bother with CommandListeners; the com- • Java 2 Platform, Standard Edition, version 1.4.0: computer engineering mand behavior is defined in the CommandAction. Similarily, http://java.sun.com/j2se/1.4 degree from McGill lines 20–22 add the OK and Cancel CommandActions to the University in Montreal. List. [email protected]

80 JUNE 2002 JUNE 2002 81

Java COM Java COM 93. else if (cmd == _cancelCmd) { Listing 1 94. list.removeCommand(_okCmd); 1. import javax.microedition.lcdui.*; 95. list.removeCommand(_cancelCmd); 2. import javax.microedition.midlet.*; 96. list.setCommandListener(null); 3. 97. _display.setCurrent(_form); 4. public class ListDemo1 extends MIDlet { 98. } 5. private Display _display; 99. } 6. private Form _form = new Form("Choose a type of List:"); 100. }; 7. 101. } 8. private static final String[] _items 9. = {"J2ME", "J2SE", "J2EE"}; 10. private static final boolean[] _flags Listing 2 J2ME 11. = new boolean[_items.length]; 1. import javax.microedition.lcdui.*; 12. 2. 13. private Command _exCmd = new Command("EXCLUSIVE", 3. public abstract class CommandAction { 14. Command.SCREEN, 0); 4. private Command _command; 15. private Command _multCmd = new Command("MULTIPLE", 5. 16. Command.SCREEN, 0); 6. public CommandAction(String label, int type, 17. private Command _impCmd = new Command("IMPLICIT", 7. int priority) { 18. Command.SCREEN, 0); 8. _command = new Command(label, type, priority); 19. private Command _exitCmd = new Command("Exit", 9. } 20. Command.EXIT, 0); 10. public CommandAction(Command command) { 21. 11. _command = command; 22. private Command _okCmd = new Command("OK", 12. } 23. Command.SCREEN, 0); 13. 24. private Command _cancelCmd = new Command("Cancel", 14. public Command getCommand() { 25. Command.SCREEN, 0); 15. return _command; 26. 16. } 27. public void startApp() { 17. public void setCommand(Command command) { 28. _form.addCommand(_exCmd); 18. _command = command; 29. _form.addCommand(_multCmd); 19. } 30. _form.addCommand(_impCmd); 20. 31. _form.addCommand(_exitCmd); 21. public abstract void execute(Displayable d); 32. _form.setCommandListener(_formListener); 22. } 33. 34. _display = Display.getDisplay(this); 35. _display.setCurrent(_form); Listing 3 36. } 1. import javax.microedition.lcdui.*; 37. 2. import java.util.*; 38. public void pauseApp() { } 3. 39. 4. public class CommandManager implements CommandListener { 40. public void destroyApp(boolean unconditional) { 5. private Hashtable _dToC = new Hashtable(); 41. notifyDestroyed(); 6. private Hashtable _cToD = new Hashtable(); 4. } 7. private Hashtable _commands = new Hashtable(); 43. 8. Home J2EE J2SE CTIA 44. private CommandListener _formListener 9. public void add(CommandAction cmdAction, 45. = new CommandListener() { 10. Displayable displayable) { 46. public void commandAction(Command cmd, 11. int[] cmdCount = increment(_dToC, displayable); 47. Displayable displayable) { 12. if (cmdCount[0] == 1) { 48. if (cmd == _exitCmd) { 13. displayable.setCommandListener(this); 49. notifyDestroyed(); 14. } 50. return; 15. increment(_cToD, cmdAction); 51. } 16. WIRELESS I.T. 52. int listType = -1; 17. Command command = cmdAction.getCommand(); 53. if (cmd == _exCmd) { 18. displayable.addCommand(command); 54. listType = Choice.EXCLUSIVE; 19. _commands.put(command, cmdAction); 55. } 20. } 56. else if (cmd == _multCmd) { 21. 57. listType = Choice.MULTIPLE; 22. public void remove(CommandAction cmdAction, www.ctiashow.com 58. } 23. Displayable displayable) { 59. else if (cmd == _impCmd) { 24. Command command = cmdAction.getCommand(); 60. listType = Choice.IMPLICIT; 25. displayable.removeCommand(command); 61. } 26. 62. List list = new List("Select an item:", 27. int[] cmdCount = (int[]) _dToC.get(displayable); 63. listType, _items, null); 28. cmdCount[0]--; 64. list.addCommand(_okCmd); 29. if (cmdCount[0] == 0) { 65. list.addCommand(_cancelCmd); 30. _dToC.remove(displayable); 66. list.setCommandListener(_listListener); 31. displayable.setCommandListener(null); 67. _display.setCurrent(list); 32. } 68. } 33. 69. }; 34. int[] dispCount = (int[]) _cToD.get(cmdAction); 70. 35. dispCount[0]--; 71. private CommandListener _listListener 36. if (dispCount[0] == 0) { 72. = new CommandListener() { 37. _commands.remove(command); 73. public void commandAction(Command cmd, 38. } 74. Displayable displayable) { 39. } 75. List list = (List) displayable; 40. 76. if (cmd == _okCmd || cmd == List.SELECT_COMMAND) { 41. public void commandAction(Command command, 77. list.getSelectedFlags(_flags); 42. Displayable displayable) { 78. StringBuffer msg 43. CommandAction cmdAction 79. = new StringBuffer("You selected:"); 44. = (CommandAction) _commands.get(command); 80. for (int i = 0; i < _flags.length; i++) { 45. if (cmdAction != null) { 81. if (_flags[i]) { 46. cmdAction.execute(displayable); 82. msg.append("\nItem "); 47. } 83. msg.append(String.valueOf(i + 1)); 48. else { 84. msg.append(" - "); 49. System.err.println("No command action for command!"); 85. msg.append(list.getString(i)); 50. } 86. } 51. } 87. } 52. 88. Alert alert = new Alert("Info", 53. private int[] increment(Hashtable ht, Object target) { 89. msg.toString(), null, AlertType.INFO); 54. int[] count = (int[]) ht.get(target); 90. alert.setTimeout(Alert.FOREVER); 55. if (count == null) { 91. _display.setCurrent(alert); 56. count = new int[1]; 92. } 57. ht.put(target, count);

82 JUNE 2002 JUNE 2002 83

Java COM Java COM 58. } 40. public OkCommand(Command command) { 59. count[0]++; 41. super(command); 60. return count; 42. } 61. } 43. public void execute(Displayable displayable) { 62. } 44. List list = (List) displayable; 45. list.getSelectedFlags(_flags); Listing 4 46. StringBuffer msg = new StringBuffer("You selected:"); 1. import javax.microedition.lcdui.*; 47. for (int i = 0; i < _flags.length; i++) { 2. import javax.microedition.midlet.*; 48. if (_flags[i]) { 3. 49. msg.append("\nItem "); 4. public class ListDemo2 extends MIDlet { 50. msg.append(String.valueOf(i + 1)); 5. private Display _display; 51. msg.append(" - "); J2ME 6. private Form _form = new Form("Choose a type of List:"); 52. msg.append(list.getString(i)); 7. private CommandManager _cm = new CommandManager(); 53. } 8. 54. } 9. private static final String[] _items 55. Alert alert = new Alert("Info", 10. = {"J2ME", "J2SE", "J2EE"}; 56. msg.toString(), null, AlertType.INFO); 11. private static final boolean[] _flags 57. alert.setTimeout(Alert.FOREVER); 12. = new boolean[_items.length]; 58. _display.setCurrent(alert); 13. 59. } 14. private class ListCommand extends CommandAction { 60. }; 15. private List _list; 61. 16. public ListCommand(int type, String label) { 62. private CommandAction _cancelCmd = new CommandAction( 17. super(label, Command.SCREEN, 0); 63. "Cancel", Command.SCREEN, 0) { 18. _list = new List("Select an item:", 64. public void execute(Displayable displayable) { 19. type, _items, null); 65. _display.setCurrent(_form); 20. _cm.add(new OkCommand("OK", Command.SCREEN, 0), _list); 66. } 21. _cm.add(new OkCommand(List.SELECT_COMMAND), _list); 67. }; 22. _cm.add(_cancelCmd, _list); 68. 23. } 69. public void startApp() { 24. public void execute(Displayable displayable) { 70. _cm.add(new ListCommand(Choice.EXCLUSIVE, "EXCLUSIVE"), _form); 25. _display.setCurrent(_list); 71. _cm.add(new ListCommand(Choice.MULTIPLE, "MULTIPLE"), _form); 26. } 72. _cm.add(new ListCommand(Choice.IMPLICIT, "IMPLICIT"), _form); 27. } 73. _cm.add(_exitCmd, _form); 28. 74. 29. private CommandAction _exitCmd = new CommandAction( 75. _display = Display.getDisplay(this); 30. "Exit", Command.EXIT, 0) { 76. _display.setCurrent(_form); 31. public void execute(Displayable displayable) { 77. } 32. notifyDestroyed(); 78. 33. } 79. public void pauseApp() { } 34. }; 80. 35. 81. public void destroyApp(boolean unconditional) { 36. private class OkCommand extends CommandAction { 82. notifyDestroyed(); 37. public OkCommand(String label, int type, int priority) { 83. } 38. super(label, type, priority); 84. } Home39. } J2EE J2SE iSavvix www.community.isavvix.com SYS-CON Media www.sys-con.com

84 JUNE 2002 JUNE 2002 85

Java COM Java COM M I D P Programming Gamesin J2ME J2ME The battle for market share

J2ME’s Mobile Information Device Profile (MIDP) promises to become one of the most widespread computing platforms over WRITTEN BY the next few years as an increasing number of mobile phones SAMI LABABIDI include a Java Virtual Machine.

Given the popularity of preinstalled game API for the 101x80 pixel screen of Generating an abstraction layer is, of games on mobiles, Java games are likely the SL45i will be very difficult to port to course, an option, but with a maximum to captivate a large audience. The first the Nokia 6310i if portability has not JAR file size of 30KB for typical low-end commercial download services for been designed into the code from day handsets, this type of layer must be MIDP applications or “MIDlets” have one. extremely light. MIDP NG (Next already been launched and the market is One of the most notable shortcom- Generation), scheduled for public set to grow at an explosive rate. Nokia ings of game development in MIDP 1.0 review in the JCP in the near future, will alone expects to sell more than 50 mil- is its lack of advanced graphical fea- fix some of these problems. Similarly, lion of these devices by the end of 2002, tures. The Graphics class does not pro- the Open Mobile Architecture initiative so the opportunities associated with vide any form of transparency, whether driven by Nokia promises much, but it

Home J2EEwriting good games J2SE for Java-enabled you’re using an image mask or defining remains to be seen whether it will be SYS-CON devices are staggering a transparent color. There’s also no way enough to make handset manufacturers However, while learning the basics of to read or write to individual pixels, converge on APIs. MIDP is simple enough for most devel- which prevents even basic image When programming fast-moving opers, understanding the constraints of manipulations, such as fading an image games, there are a few additional points the platform and the tricks to get around to black. to keep in mind. Anyone who has done them is crucial for efficient develop- These limitations may not seem too game programming knows that double Media ment. Creating compelling content, serious at first, as the obvious way buffering is an important tool to achiev- especially the type that uses the mobile around them would be to read in local ing smooth and “tear-free” animations. network, involves a lot of trial and error. image files directly using the “javax The implementation of the Graphics This article is a collection of lessons I’ve .microedition.io” package and write class is double-buffered on many www.sys-con.com learned from coding games for the first decoders of JPEG or GIF or other image devices, as can be seen by a quick call to generation of J2ME devices. file formats. You could then map out the the Canvas.isDoubleBuffer() method. The key factor to consider when bytes of the image manually and over- This means that any graphics draw- designing a MIDP game is your target come the above limitations. While this ing functions are buffered off-screen audience and hence the set of target would result in full control over the before they’re displayed on-screen. devices. If your MIDlet needs to run image pixels, it’s prohibitively slow. However, as double buffering usually across devices with varying perfor- MIDP does not provide a fast pixel plot- refers to switching between one back- mance and graphical abilities, you need ting function and there’s no quick way of screen buffer and one front-screen to take this into account in the design of getting the resulting image buffer paint- buffer, not buffers for individual your code. This is especially important ed onto the screen. In fact, the only Graphics calls, this has been the source when it comes to the use of libraries pro- option is to draw lines 1 pixel in length of some confusion. Since all the screen prietary to a handset manufacturer, the with the drawLine() function. Filling a paintings are done within the paint use of graphics, and CPU-intensive AI 100x100 screen with 10,000 drawLine() (Graphics g) method, it’s not hard to calculations. If the aim is to capture the calls on a mobile device is just not feasi- imagine what happens when there are mass market, the game needs to be ble with near future device perfor- many Graphics drawing calls and each playable on the lowest common denom- mance! drawing call is displayed onto the screen inator device – currently a 64x95 pixel 1- Most device manufacturers have one by one. bit screen, a slow, low-end CPU, and less responded to the limitations of the It’s not difficult to write a double- than 100KB of heap memory. Modifying native graphics in J2ME by adding addi- buffering system. First set up an off- the code to cater to high-end devices tional classes in their own proprietary screen buffer in the form of a should then ideally be a matter of modi- API. However, it’s dangerous to rely on “javax.microedition.lcdui.Image”, then fying only a clearly defined portion of these, as it breaks the portability of the do every drawing operation using the the application. It pays to spend some code and is likely to result in lengthy and Graphics obtained from this buffer additional time on design. For example, frustrating modifications to the code for instead of from the actual screen. After a game written using the full Siemens different manufacturers’ handsets. you’re done with the drawing, emulate

86 JUNE 2002 JUNE 2002 87

Java COM Java COM M I D P

the “flipping” of the buffers by drawing being Connector, Connection, and server. A socket server is faster than an the whole offscreen buffer onto the HttpConnection. The best way to com- HTTP server, as there’s no HTTP over- actual screen in one go with one municate with a Web server is to use head, but it can be used only for those drawImage() call (see Listing 1). POST requests. Listing 2 shows an out- devices that support sockets. In addi- Another issue to take into account is line of an HTTP POST connection. tion, using HTTP helps the long-term CPU speed and speed throttling. Since Alternatively, Listing 3 provides an scalability of the service, as the number speed can vary markedly between outline of a sample socket connection. of active devices polling for moves and

J2ME devices, speed throttling should be The J2ME communication API has messages increases. As the client is writ- applied to any games with animations. some notable limitations. It does not ten in Java, it’s easy to connect to Some people calculate their own timed implement “java.io.Serializable” and servlets and to implement the server in delays in their animation thread, while neither does it support HTTP session Java: the HTTP requests coming from others prefer simply using the functionality. If these features are J2ME devices are exactly the same as “java.util.Timer” to schedule a “java.util required, there’s no option but to re- other HTTP requests. The standard Java .TimerTask” for all the animation duties. implement them. Serialization API cannot be used in this Depending on the type of game, you Figure 1 provides an overview of the case, but it’s very easy to write your own. may want to try scheduling the Timer to elements in a networked J2ME game XML is a standard way to communicate go off with a 50–100ms delay (10–20 fps). architecture using either GSM CSD or with other types of Web servers like PHP GPRS as a carrier. Relatively good per- or CGI, but it’s obviously much less effi- Designing Networked J2ME Games formance can be achieved even on a cient. The prospect of providing multiplay- GSM network, if the size of the message Using a standard Web server like er games for mobile phones is exciting. transmitted is kept to a minimum. Apache/Tomcat or Jetty has the However, before you write your first line However, GPRS is the carrier of advantage of leveraging the scalability of code for your multiplayer first person choice, as the user doesn’t need to wait that has already been achieved for shooter, keep in mind some important to connect and pays only for the data other Web/WAP applications. How- limitations. A good place to start is to transmitted. While bandwidth is unlike- ever, due to the nature of the wireless look at the constraints of the network ly to be a problem, achieving an accept- client and the wireless network infra- and what is possible using the J2ME able average latency over the network structure, some modifications need to communications library. can pose a significant challenge. A be made in order to optimize the data Simplex The oft-cited limitations in the band- round-trip time of 10 seconds over a traffic, as Web server providers have width of current 2G and 2.5G networks CSD call on GSM and 4 seconds over yet to fully adapt to the wireless mar-

Home J2EEare an important J2SE bottleneck for net- GPRS can be considered average even ket. In the short term, the use of open worked games. However, lesser-known with some optimizations. This limits source products may be a good solu- but equally significant constraints are games to the turn-based type that utilize tion. packet latency and variability in net- only current network infrastructure. An even better solution is to use a Knowledge work performance. A limited bandwidth Real-time multiplayer games will be- Java application server as a back end. AUTHOR BIO implies that communication over the come a reality only when 3G networks EJB/JMS/J2ME integration is a very Sami Lababidi is chief network should be reduced to a mini- promising sub-100ms latencies are active topic at the moment and this is technology officer at mum, while packet latency and variabil- launched. definitely the way forward to ensure Macrospace, Ltd., a ity mean that the code must run and be Despite the limitations, there are speed, availability, fault tolerance, and Company provider of J2ME playable even in vastly variable network many things you can do with the net- quality of service for all networked wire- solutions. Sami has conditions. The problems are com- work. Shared high scores or level down- less applications, including multiplayer focused on pounded by the implementation of net- loads are a good example. Another is the games. This will also require some J2ME since its work communication in MIDP 1.0. possibility of playing against advanced tweaking in these early days. For exam- inception and has All J2ME devices implement HTTP game servers. Because of hardware limi- ple, a combination of J2ME, Jetty, and skc.com developed and connections and some also offer a sock- tations it’s sometimes not feasible to JBoss is a good open source (nearly) deployed J2ME prod- et API. The package containing the com- develop a sufficiently powerful AI on 100% Java solution. ucts and services munication classes is “javax.microedi- mobile devices. Game servers have a These are just a few technical issues throughout Europe. tion.io”, with the most important classes vast advantage in computing power, to consider in the development of MIDP which makes utilizing a server-side AI a games. Many times an equally challeng- compelling proposition. Take a scenario ing task is handling the creative and where the user plays locally and the AI business side of MIDP game develop- uses a minimax alpha beta algorithm ment. With so many game ideas already with a depth of two. On low-end devices exhausted and brands becoming this takes between 20 seconds and 2 increasingly important in the mobile minutes to calculate, and the game is marketplace, coding a clone of an ’80s hardly playable. Compare that to a sce- hit is no longer enough to convince an nario in which the user plays against a operator or download portal to resell remote game server where the AI uses your application. the same algorithm with a more power- A solid technology base and a good ful search depth of four. The server com- creative team is a must for a successful putes the move instantaneously, it takes company in the MIDP games arena. But 4–8 seconds to get the move from the as in all things, it’s on the business side server, and the game is much more where the battles for market share will playable. eventually be won and lost. The game server itself can be imple- [email protected] FIGURE 1 Networked J2ME game architecture mented as an HTTP server or a socket

88 JUNE 2002 JUNE 2002 89

Java COM Java COM Listing 1 javax.microedition.lcdui.*;

public class gameCanvas extends Canvas { … PUBLISHER,PRESIDENT,AND CEO Image backBuffer; FUAT A. KIRCAALI [email protected] Graphics backBufferGraphics; CHIEF OPERATING OFFICER … MARK HARABEDIAN [email protected] public gameCanvas() VICE PRESIDENT,BUSINESS DEVELOPMENT {

J2ME GRISHA DAVIDA [email protected] …. // initialize the back-buffer to be the same dimension as ADVERTISING the canvas, SENIOR VICE PRESIDENT,SALES AND MARKETING // and get the Graphics of the buffer for off-screen CARMEN GONZALEZ [email protected] drawing VICE PRESIDENT,SALES AND MARKETING backBuffer = Image.createImage( getWidth(), getHeight() ); backBufferGraphics = backBuffer.getGraphics(); MILES SILVERMAN [email protected] …. ADVERTISING SALES DIRECTOR } ROBYN FORMA [email protected] …. ADVERTISING ACCOUNT MANAGER public void paint(Graphics g) MEGAN RING [email protected] { ASSOCIATE SALES MANAGERS … CARRIE GEBERT [email protected] // do all the Graphics drawing onto the back-buffer KRISTIN KUHNLE [email protected] backBufferGraphics.draw… … ALISA CATALANO [email protected] // now "flip" the back-buffer to the front LEAH HITTMAN [email protected] // by drawing the whole back-buffer image onto the EDITORIAL screen. EXECUTIVE EDITOR // since individual Graphics call is "double-buffered", NANCY VALENTINE [email protected] // this won’t create any "tearing" on the screen. EDITOR g.drawImage( backBuffer, 0, 0 Graphics.TOP|Graphics.LEFT ); } M’LOU PINKHAM [email protected] …. MANAGING EDITOR } CHERYL VAN SISE [email protected] ASSOCIATE EDITORS JAMIE MATUSOW [email protected] Listing 2 GAIL SCHULTZ [email protected] HttpConnection c = null; Simplex JEAN CASSIDY [email protected] InputStream is = null; ASSISTANT EDITOR OutputStream os = null; try JENNIFER STILLEY [email protected] ONLINE EDITOR Home{ J2EE J2SE // open http connection LIN GOETZ [email protected] c = (HttpConnection)Connector.open( url, Connector.READ_WRITE ); PRODUCTION VICE PRESIDENT,PRODUCTION AND DESIGN // Set the request method and headers Knowledge JIM MORGAN [email protected] c.setRequestMethod( HttpConnection.POST ); LEAD DESIGNER c.setRequestProperty( "User-Agent" , "Profile/MIDP-1.0 Configuration/CLDC-1.0" ); LOUIS F. CUFFARI [email protected] c.setRequestProperty( "Content-Language" , "en-US" ); ART DIRECTOR c.setRequestProperty( "Connection" , "close" ); ALEX BOTERO [email protected] ASSOCIATE ART DIRECTORS // write request CATHRYN BURAK [email protected] os = c.openOutputStream(); RICHARD SILVERBERG [email protected] Company .... AARATHI VENKATARAMAN [email protected] ASSISTANT ART DIRECTOR // get response TAMI BEATTY [email protected] is = c.openInputStream(); ... WEB SERVICES WEBMASTER skc.com ... ROBERT DIAMOND [email protected] } WEB DESIGNERS finally STEPHEN KILMURRAY [email protected] { CHRISTOPHER CROCE [email protected] try{ os.close(); }catch( Exception e ){} CATALIN STANCESCU [email protected] try{ is.close(); }catch( Exception e ){} try{ c.close(); }catch( Exception e ){} A CCOUNTING } CHIEF FINANCIAL OFFICER BRUCE KANNER [email protected] ASSISTANT CONTROLLER Listing 3 JUDITH CALNAN [email protected] StreamConnection connection = null; ACCOUNTS RECEIVABLE InputStream is = null; JAN BRAIDECH [email protected] OutputStream os = null; ACCOUNTS PAYABLE try JOAN LAROSE [email protected] { ACCOUNTING CLERK Connection aConnection = Connector.open( "socket://" + host + ":" + port); BETTY WHITE [email protected] connection = (StreamConnection) aConnection; SYS-CON EVENTS os = connection.openOutputStream(); VICE PRESIDENT,SYS-CON EVENTS .. CATHY WALTERS [email protected] is = connection.openInputStream(); CONFERENCE MANAGER ... MICHAEL LYNCH [email protected] } finally SALES EXECUTIVES,EXHIBITS { MICHAEL PESICK [email protected] try{ os.close(); }catch( Exception e ){} RICHARD ANDERSON [email protected] try{ is.close(); }catch( Exception e ){} C USTO MER RELATIONS/JDJ STORE try{ c.close(); }catch( Exception e ){} MANAGER,CUSTOMER RELATIONS/JDJ STORE } ANTHONY D. SPITZER [email protected]

90 JUNE 2002 JUNE 2002 91

Java COM Java COM Available July 1*

EnginData’s research is invaluable to leading IT Don’t go astray. In the vast sea of Internet technology, market conditions change constantly. Will Java remain the hot vendors, integrators, platform it is today? Will C# rapidly gain ground? What are the world’s foremost Java developers aiming their sights Fortune 500 companies, toward? Which companies come to mind when planning their next project? How can their thinking direct your efforts? trade-show organizers, publishers, and e-business EnginData Research has studied the IT industry extensively, spotting many key trends organizations worldwide. and alerting industry leaders along the way. In the first quarter of 2002, they embarked on their most challenging mission ever: the most in-depth study ever done of the Java development marketplace.

After months of analyzing and cross-referencing more than 10,500 comprehensive questionnaires, the results are now available.

Here’s just a sample of the critical data points the Java report delivers... ✔ Current and projected usage of languages and platforms

✔ Multiple rankings of hundreds of software vendors and tools As an IT specialist, EnginData Research focuses exclusively ✔ Types of applications being developed on three leading drivers in IT today – Java, Web services, and ✔ Databases being used wireless development. Coming soon, our Web services ✔ Purchasing patterns survey will deliver such critical knowledge as: ✔ Company size ✔ Time frame for developing Web services – enabled apps ✔ Development and purchasing timelines ✔ Percentage of apps with Web services today ✔ Perceptions and usage of Web services ✔ Sourcing and hosting Web services ✔ Preferred Java IDE ✔ Perceived leaders in Web services tools and solutions ✔ J2EE, J2ME, J2SE usage comparisons

Navigate your company through the challenging IT marketplace with the trusted knowledge and intelligence of EnginData Research. Order your copy of the 2002–2003 Java market study by calling Margie Downs at 201-802-3082, or visiting our Web site. www.engindata.com

*A limited number of preview copies will be available at our booth (#624) at JDJEdge International Java Developer’s Conference & Expo, June 24–27, at the Jacob Javits Convention Center in New York. JAVA TECHNIQUES

% off the annual newsstand rate SAVE 30 JavaDesign Creating flexible code WRITTEN BY MICHAEL BARLOTTA

ava classes should be designed to enhance their reusability and flex- ibility. Coding to an object type rather than an implementation by Jusing interfaces or abstract classes can help us achieve both flexibili- ty and reusability.

Offer subject to change without notice What Is an Abstract Class? J2SE ANNUALANNUAL NEWSSTAND COVER PRICE RATE Everything in Java is an object, so to write Java programs we need to define classes. A Java class in turn defines the type and the available $71.88 methods for that type. It also provides the implementation of the meth- ods that it defines. This kind of class is called a concrete class. An abstract YOU PAY class, defined in section 8.1.1.1 of the Java Language Specification (JLS), $49.99 defines the type and the available methods but is not required to imple- YOU SAVE ment any of the methods that it defines. Off the The following code shows a simple abstract class named Base. J2EE30% Newsstand J2ME Rate public abstract class Base { DON’T MISS AN ISSUE! public abstract String f1(); public String f2(String s) { Receive 12 issues of Java Developer’s Journal return "Base.fs("+s+")"; for only $49.99! That’s a savings of $21.89 off } } the cover price. Sign up online at An abstract class is denoted by the keyword abstract in the class decla- www.sys-con.com or call 1 800 513-7111 and ration and usually contains one or more abstract methods. An abstract SYS-CON Home subscribe today! method declaration defines the method name, number and type of param- eters, return type, and throws clause, but does not have an implementation. In the declaration an abstract method is denoted by the abstract keyword, Here’s what you’ll find as is the case with method f1 in the class Base defined earlier. in every issue of JDJ: Why design with an abstract Media class instead of a concrete class? • Exclusive coverage Using an abstract class allows you to define the interface of a type and J2EE J2SE J2ME still provide method implementa- www.sys-con.com tions without having to implement • Exclusive feature articles the entire set of methods. The term interface is used here to mean the • Interviews with the hottest publicly accessible functions on the class, not the Java interface, which names in Java we’ll look at next. The abstract class represents a type at a very generic • Latest Java product reviews level. Although operations can be defined for the type, the abstract • Industry watch FIGURE 1 Relationships of simple objects in this article class can’t provide all the functional- ity without becoming too specific. An abstract class is incomplete and relies on its subclasses to complete the implementation. In the following code sample the class X inherits from the class Base by extending it. The class Base is considered the superclass of class X. The class X is considered the subclass (or subtype) of class Base. For X to avoid being declared abstract, it must implement the abstract method f1 defined in the class Base. The definition of class X is listed below:

public class X extends Base{

public String f1() { return "X.f1()"; }

94 JUNE 2002 JUNE 2002 95

Java COM Java COM Compete against your fellow CO-SPONSORED BY JAVA TECHNIQUES developers, the clock and our BATTLEBATTLE host in a JavaTM technology public String f3() { trivia contest to see who is the CHECK OUT THE return "X.f3()"; } “strongest geek!” NEW XML-J! } ITIT OUTOUT!! Some important points to remember about abstract classes: • An abstract class cannot be instantiated. • An abstract class can implement zero, one, or more methods. • A class with an abstract method must be declared abstract. 1 • A class can be declared abstract even if it has no abstract methods. • Methods that are static, private, and/or final cannot be abstract.

Offer subject to change without notice J2SE What Is an Interface? ANNUALANNUAL NEWSSTAND COVER PRICE RATE A Java interface defines a type and the available methods for that $83.88 type. It does not, and, in fact, cannot provide an implementation for any 2 of the methods it defines. An interface is defined in section 9 of the Java YOU PAY Language Specification. $77.99 The following is a simple interface, iBasicType: YOU SAVE public interface iBasicType {

J2EEOff J2ME the Newsstand Rate public String f1(); GRAND PRIZE

$5.89 TO CHOOSE FROM... 3 public String f4(); WINNER } DON’T MISS AN ISSUE! The interface and all the methods on it are automatically considered Receive 12 issues of XML-Journal for only abstract and do not require the abstract keyword. $77.99! That’s a savings of $5.89 off the ALSO... To be of any use a Java interface must be implemented by a Java class. WINNERS annual newsstand rate. In the following code sample, the class Basic implements the interface WILL RECIEVE Sign up online at www.sys-con.com or call iBasicType. The class Basic must provide an implementation for every 66 A COPY OF 1 800 513-7111 and subscribe today! method in the interface, otherwise it must be declared an abstract class. RATIONAL XDE

Home PROFESSIONAL, AND public class Basic implements iBasicType { IBMIBM STUDIOSTUDIO APPLICATION Wait till you see June... public String f1() { DEVELOPER return "Basic.f1()"; ENHANCED industry and technical } coverage Expanded BUSINESS focus public String f4() { return "Basic.f4()"; Dynamic new EDITORIAL TEAM } SECTION-SPECIFIC COVERAGE: PRESENTED BY public String f2(String s) { CONTENT MANAGEMENT Document XSLT – Automatically return "Basic.fs("+s+")"; How to document conditional text processing for business users } by Karl B. Schwamb & Kenneth J. Hughes } DATA MANAGEMENT A class implementing an interface can also declare additional meth- Hosted JDJ Editor-in-Chief Managing Data Sources with XSLT ods that aren’t part of the interface. This is shown in the Basic class defi- An approach to transform any type of data source to XML nition by defining method f2, which isn’t part of the iBasicType interface. by Alan Williamson by Craig King Some important points to remember: • An interface cannot be instantiated. ENTERPRISE SOLUTIONS • An interface has no implementation. • All the methods on an interface are considered public and abstract. OWNED AND UBL and Web Services PRODUCED BY The gaps in Web services, and the steps to resolve them, • All the fields on an interface are considered public, static, and final. need to be assessed • An interface can extend other interfaces. by Matthew Gertner • A class can implement one or more interfaces.

XML LABS THE ULTIMATE The Power of Dealing with Types Desperately Seeking… Java is a strongly typed language, so every object in Java has a type. BRAND NEW Help for XML Schema The type associated with any particular object is its class name. For BRAND NEW Are the complexities…too complex? example, when the class Customer is instantiated, the object is said to be by Tom Gaven XML of the type Customer. Each instance of an object may have a different state, but all objects of the same type have the same set of methods JUNE 24-27, 2002 $10K JACOB JAVITS CONVENTION CENTER • NYC ENTERPRISE because they’re created from the same class. Abstract classes and inter- faces give us more flexibility in our programs because they allow us to 2002 2002BMW PLAY THE GAME AT THE WORLD’S RESOURCE HARLEY DAVIDSON LARGEST IT CONFERENCE AND EXPO AT CASH! “SPORTSTER” “MINI COOPER” JACOB JAVITS IN NEW YORK CITY 96 JUNE 2002 MOTORCYLE! 2YR LEASE! Java COM JAVA TECHNIQUES

% off the annual look at an object as a different type instead of just using its class name. newsstand rate For example, the object Y, shown in Figure 1, can be created from the SAVE 30 following line of code: Y myYObj = new Y();

The variable myYObj contains an object reference of type Y that points to a Y object in memory after this code is executed. Through the Y object reference all the methods defined on the Y object and any class it extends can be invoked. Since Y extends the class X, they’re related and we can treat the subclass Y as if it were actually any one of its superclass- Offer subject to change without notice es, in this case X or Base; e.g., the following code is completely valid: J2SE ANNUALANNUAL NEWSSTAND COVER PRICE RATE X myXObj = myYObj; $71.88 The variable myXObj contains an object reference of type X, but the YOU PAY reference points to a Y object in memory after this line of code is execut- $49.99 ed. This allows us to look at the Y object as if it were really of type X. The compiler can safely place references to subclasses into a variable that’s YOU SAVE declared to be a superclass of that subclass, since the subclass is guaran-

J2EEOff J2ME the 30% Newsstand Rate teed to contain all the methods and variables that can be called on the superclass. Simply, Y extends X, so the compiler is assured that any DON’T MISS AN ISSUE! method that can be called on X can also be called on Y. However, the reverse is not guaranteed to be true so the following code is not valid: Receive 12 issues of Wireless Business & Technology for only $49.99! That’s a Y anotherYObj = new X(); // This is not valid savings of 30% off the cover price. Sign up online Dealing with a subclass object as if it were really one of its superclass- at www.sys-con.com or call 1 800 513-7111 es is called upcasting or narrowing. It’s important to understand that the Home and subscribe today! object reference, which points to an object in memory, does not deter- mine the type of the object that gets the request to invoke a method, nor In June WBT: does it change the type of the object that was instantiated. The object ref- erence does, however, affect how the object it points to can be operated Tech Update: What’s Hot in Wireless on. The object reference defines the type through which the calling pro- We can look forward to tangible, near-term gains that will gram sees the object in memory. You can think of the X object reference change how and where we use wireless technologies in 10 key as a filter that allows only calls to methods that are defined in the X class areas. and any class it extends. Looking at the class diagram in Figure 1, we can call the f1, f2, and f3 methods through the X object reference. But we Retailers Check Out Portable Point of Sale Systems couldn’t call the f4 method even though this is a valid method on the Y Wireless terminals such as PalmPilots can emulate the cash register and enable credit card customers to skip the lines. object, because it’s not defined by the class X or any of its superclasses. When we call methods through the X object reference using the The Wizard of Wireless myXObj variable, we’re actually invoking methods in the object that the Applications such as voice-activated dialing, voice portals, and reference points to in memory. In this case it’s a Y object instance. handsfree conferencing may help the wireless industry in its quest for killer apps. myXObj.f1(); // returns "Y.f1()" myXObj.f3(); // returns "X.f3()" Mobile Browser Roundup If your IT department is planning to offer remote users enter- These method calls give the results shown in the comment sections prise access via a mobile browser, you need to know what’s based on the following definition of the Y class: available and the unique characteristics they offer. public class Y extends X implements iBasicType {

public String f1() { return "Y.f1()"; }

public String f2(String s) { return "Y.fs("+s+")"; }

public String f4() { return "Y.f4()"; } }

98 JUNE 2002 www.JDJSTORE.com OFFER EXPIRES JUNE 30, 2002 Java COM JAVA TECHNIQUES SELECT THE INDUSTRY NEWSLETTERS THAT MATCH YOUR NEEDS!

Notice that the implementation of the f1 method on the Y class is run SUBSCRIBE even though we’re using an X object reference. In this example, the Y

class does not define its own f3 method, so the implementation of the f3 CHOOSE ONE OR TRY THEM ALL! AND SAVE method on the X class is executed. It’s possible to point an object reference to an object that is its subclass because Java performs dynamic binding. Objects communicate by sending messages to each other through references. This is basically a means of call- ing methods on the object. Dynamic binding allows messages to be sent to an object without knowing the exact type of the object that the message will be sent to when the code is written. When the code is executed and a method is invoked, the JVM determines which method is actually executed based on Offer subject to change without notice which object is being pointed to by the object reference at runtime. J2SE The message to execute a particular method cannot be sent to just any ANNUALANNUAL NEWSSTAND COVER PRICE RATE object. Java is a strongly typed language so the compiler makes sure the $83.88 assignment is type-safe. A variable has a type that never changes, so the myXObj variable will always hold an X object reference. When the variable YOU PAY FREE type is a reference type (arrays, classes, and interfaces), it can point to dif- $69.99 ferent objects that are related via inheritance or an interface. Specifically, a E-Newsletters reference variable can be assigned a reference to any object whose class is: YOU SAVE • Of the same type as that of the reference variable declaration

J2EEOff J2ME the SIGN UP $13.89 Newsstand Rate • A subtype of the type that the reference variable is declared to be Go to www.SYS-CON.com TODAY! DON’T MISS AN ISSUE! Or any object that implements: • The same interface that the reference variable is declared to be The most innovative products, new releases, interviews, industry developments, and Receive 12 issues of Web Services Journal • An interface that is a subtype of the interface that the reference vari- plenty of solid i-technology news can be found in SYS-CON Media’s Industry Newsletters. for only $69.99! That’s a savings of able is declared to be Targeted to meet your professional needs, each e-mail is informative, insightful, and to the $13.89 off the annual newsstand rate. An Example with an Interface point. They’re free, and your subscription is just a mouse-click away at www.sys-con.com. Sign up online at www.sys-con.com or call We can declare variables to have a type that is defined as an abstract Exclusively from the World’s Leading i-Technology Publisher Home 1 800 513-7111 and subscribe today! class or an interface even though they can’t be instantiated. Given the class hierarchy shown in Figure 1, a variable can be declared as follows:

In June WSJ: iBasicType myBasicObj; Business Process Management and Web Services Design deploy, execute, analyze, and optimize business The variable, myBasicObj, holds an object reference to the interface processes as Web services iBasicType. We can instantiate objects that implement the interface using the code sample below: Making Business Processes Manageable The need to take advantage of explicitly defined processes iBasicType myBasicObj = new Basic();

Business Process Management: Tools The variable, myBasicObj, holds an iBasicType reference that points for Eliminating Waste and Adding Value to a Basic object in memory. Since the class Y also implements the inter- Making a technology investment face iBasicType, the following code is also valid:

Web Services and Business Process Management iBasicType anotherBasicObj = new Y(); • Real-World Web Services: Is It Really XML's Killer App? Start thinking in terms of the process – not the application • Demystifying ebXML: A Plain-English Introduction Accelerating the Adoption of Web Services By implementing an interface, the object is also declaring that it is of • Authentication, Authorization, and Auditing: Securing Web in Your Enterprise that type. For example, the class Y can be said to be of type Y, its class Services Think ahead and you can avoid the pitfalls name, as well as of type iBasicType, since it implements that interface. • Wireless: Enable Your WAP Projects for Web Services Like the variable that holds an object reference to a class type, an • The Web Services Marketplace: An Overview of Tools, Engines, and Servers object reference to an interface type defines the way the calling program • Building Wireless Applications with Web Services sees the object in memory. So we can call the f1 and f4 methods through • How to Develop and Market Your Web Services the iBasicType object reference. But we could not call the f2 method even • Integrating XML in a Web Services Environment though this is a valid method on both the Basic and the Y object, because • Real-World UDDI it’s not defined by the interface (see Figure 1). • WSDL: Definitions and Network Endpoints Wrapping It Up • Implementing SOAP-Compliant Apps • Deploying EJBs in a Web Services Hopefully, you’ll begin to see the potential flexibility we can design into Environment our applications by coding to different types. Applying this in a practical • Swing-Compliant Web Services sense will be the focus of our next article, until then, happy coding. • and much, much more! AUTHOR BIO Michael Barlotta is the director of technology at AEGIS.net Inc (www.AEGIS.net).

[email protected]

100 JUNE 2002

Java COM “Just calm down,” adds Norman. “In five years, neither Java Where are they now? Gone.…JDJ is the only honest Java maga- Exclusive: Excerpts from JavaDevelopersJournal.com nor .NET (if it is still around) will be anything like they are now. zine out there.” This whole debate will seem silly and pointless.” SPECIAL REPORT: JAVA DEVELOPER’S JOURNAL APRIL EDITORIAL Tools Are the Key Critically Important Commentary or Soul Selling? British developer Nick Riordan ([email protected]) “THERE MAY BE TROUBLE AHEAD FOR JAVA...” RALLIES JAVA CAMP Miles Parker ([email protected]) is in no doubt: returns the discussion to a more technical level. “I spent 10 “What an incredibly important commentary,” he declares. “It is years building apps exclusively for the Microsoft platform by Jeremy Geelan literally laughable to suggest that Alan has some kind of pro-MS, using Microsoft tools (C and C++),” he explains. “Two years ago it; OS/2 had some great apps too. If C# makes even small inroads anti-Java bent. Instead, what he’s offering is something we all I changed jobs and have since been working with Java/CORBA ALAN WILLIAMSON’S APRIL EDITORIAL was read by more than on the server and on the desktop, Java is in real trouble. need to hear.” and EJB. I like Java, but I think C# offers similar benefits. It has 100,000 people within two hours of its posting at www.sys- Microsoft doesn’t need massive wins; once they have their foot “Strangely,” Parker continues, “companies and developer already been said in this discussion that the client is impor- con.com/java. Over 500 readers responded within hours of its in the door on both, they will start to squeeze on all sides. Don’t communities have never lost by overestimating Microsoft; they tant, and let’s face it, Swing is probably the weakest area of publication. The editorial was instantly picked up and simultane- hide your heads in the sand or hold them so high in arrogance have always lost by underestimating them!…Please, please, let Java.” ously published at the Slashdot.org and JavaLobby.org Web sites. in the belief that because they haven’t already, Microsoft won’t us not be like Netscape (“we own the browser market”), IBM, “But my real issue,” Riordan goes on, “is the lack of proper find a way.” Sybase, (soon to be Palm), and so many companies in between.” tools for Java. If you’ve spent any time working with MS tech- J2SE The Great Java Debate has been raging as a direct result of Developers like to think about the look and feel of an app Referring to some of the criticisms that the editorial pro- nologies, you really appreciate the properly integrated, high-per- the technical points raised by Alan Williamson, Java Developer’s they plan to develop, and they like to think about the algorithms voked, Parker comments: “That Alan has received such a load of formance, polished feel – it makes development a pleasure. Journal editor-in-chief, in his editorial (Vol. 7, issue 4) about C#, that will make it run efficiently. If Java happens to be the best BS because he is willing to ask real questions is dismaying, to say Recently I moved across to IDEA as my IDE in Java – it’s the best Microsoft’s rival language to Java. language for the job, then that’s what they’ll use. But they’re not the least, and makes me think that Java developers are more Java IDE I’ve found so far (I want to like NetBeans, but it never Everyone had been talking about C#, Williamson felt, and in tied to any language, and this is why – as Williamson was trying concerned about living in a state of comfortable and smug seems to be finished and the performance stinks). IDEA is about true Microsoft “Chinese whispers” style, it spread rapidly. “We to point out – it’s important for Javaland to consider the poten- denial than fighting to protect the diversity and strength that as good as Visual C++ 4.2 – a product that shipped five years ago.” felt it was time for JDJ to find out the real truth behind this new tial rise of C# very carefully. Java and associated tools have provided.” “I want seamless end-to-end debugging (client, middle tier, language and present the facts as we found them,” he says. “If we aren’t honest with ourselves and willing to fight this SQL),” says Riordan. “I want high speed – and no performance J2EEThere will always be J2ME particularly virulent controversy when- Java Will Benefit from Some Healthy Competition battle day to day in the trenches,” he continues, “we will lose, degradation when running under the debugger. I want folding ever an industry commentator mentions Java and Microsoft “He’s right on the money!” says Michael Julson and indeed there will not be much left of Java in five years. Ask editors, proper dialog editing, etc., etc. This is the point: you can Corp. in the same breath. Comments posted to the Java ([email protected]). “I agree with Alan’s suggestions and yourself, what did you think of the prospects of Netscape in be so much more productive under C# just because of the tools.” Developer’s Journal Web site (www.sys-con.com/java/article. beliefs of where Java might be in the future. Sun has been busy 1997? Now we know that they were already doomed, due in large cfm?id=1401) range from praise such as this from business con- fracturing the language into so many pieces with the hope that part to their own arrogance. We can’t afford to have our heads in Is a “Religious” Following a Symptom of Decline? sultant David Bolsover ([email protected]) who writes, “I it will be the language for all situations and all needs. Because of the sand! .NET is a very real threat.” What does this whole passionate discussion of the future of have to agree with much of what Alan wrote in his editorial – the this fracturing, it’s become a weaker language and has suffered.” Christophe de Dinechin ([email protected]) believes Java mean? A very thought-provoking perspective comes from Exclusive level of ignorance and misunderstanding among so-called IT “I welcome C#,” Julson continues. “With its similarities to professionals is astounding” to dramatic criticism such as this Java, it puts some tougher competition to Sun, IBM, et al, and Home from Canadian software developer Christian Ouellet (chris- will make the language better off for it. Beyond that, I’ll be able “ The feedback generated falls into two camps: those who [email protected]), who strongly believes that such an edi- to use it for desktop apps that don’t crawl at a snail’s pace.” torial “is not what the Java community needs” to the extent that, David Bolsover, mentioned earlier, echoed this theme of the feel the writing is on the wall for Java, as he says: “that’s why I will burn all my JDJ issues…” responsibility that Java supporters have to spread the word. Well, Java always did evoke strong emotions! “The Java community must make renewed efforts to communi- “Java Developer’s Journal is proud to take the lead in peering cate the merits of Java to the wider community if it is to survive,” and those who believe that Java has never been stronger over the horizon; that’s what readers (developers) expect from he says. “Personally, I think Sun must take the lead in this – a few us,” says editor-in-chief Williamson. “That makes me kind of well-placed full page ads in national daily papers wouldn’t go ” chief scout on behalf of the readership, heading up the gullies amiss, free CDs on magazine covers – anything that promotes no computer language can expect immortality, Java included. Mark Miller ([email protected]), who sees what he claims are and reporting back on what I find.” the Java message.” “Yes, Java is going to die,” he says, “and five years might be a signs of an oft-repeated cycle of behavior. “The Java community is one of the most passionate and And Aisha Fenton ([email protected]) too feels that good time frame. But C# is not the reason. The reason is that we “I’ve seen this happen too often in the technological world,” open set of people I have seen in my life,” he says, “and this Williamson is sounding a very timely rallying cry: “C# is set to will need to do things in five years that Java doesn’t do well. A he says, “and I’ve been in it since the early 1980s. It’s a pattern. A strength will ensure that Java will be a formidable force against become the dominant client-side language,” she explains. “MS new environment will replace Java, just as Java replaced C++ technology starts faltering, and the ways part. Some people use the alternatives that come up on the radar, such as Microsoft’s will make it very fast and a natural choice to program in for when the Internet became the place to be, just as C++ replaced it until they feel its usefulness is exhausted and then move on to C#.” Windows (even games could be easily written in it, since they’ll C, just as C replaced Pascal, etc. New tasks=new programming something else. The others form a cultlike following that is dead The feedback generated falls into two camps: those who feel have good Direct X support). We can’t just ignore it and attack language.” set against using any other technology aside from the one they the writing is on the wall for Java, and those who believe that anyone that tries to talk about it. We have five years to make Java “By this reasoning, however,” de Dinechin adds, “C# should love.” Java has never been stronger and that never before have we seen better, let’s get going.” not displace Java, simply because it only does what Java does, It’s this cultlike behavior that Miller claims to discern in the so many applications and general forward movement in the Java with a little more. Naturally, C# has the capability to evolve.” current behavior of what he sees as Javaland’s die-hards and in space as we see today. Nobody Knows What’s Going to Happen Avram Aelony ([email protected]) disagrees that Java has their reactions to Alan Williamson’s editorial. “It’s just branding. Get over it,” advises Jason Norman only five years left. “There seem to be quite a few elderly lan- “They say things like, ‘If only they would do X, then people Sun Needs to Wake Up and Smell the Java ([email protected]), a health systems software engineer at guages with less promise than Java,” he points out, “that refuse would see how great it is and start using it’…They don’t look at “Alan Williamson is right and many are too blind to see,” Vanderbilt University Medical Center in Nashville, Tennessee. to die. Diversity is good. If you could write an app in your integrating other useful technologies, because, of course, theirs writes Steven Tower ([email protected]). “I’ve been a Java “Let’s face it,” Norman says, “nobody knows what’s going to favorite idiomatic language and the compiler’s task was to is so wonderful. They develop strong biases against outside developer for almost seven years now,” he continues. “I was very happen. On the one hand we have MS. They have a pretty strong make it run fast anywhere, then there’s also room for C# in the technologies, in fact. They don’t see their own technology’s lucky to have gotten in on the ground floor. However, I have dis- following in the business world. Their branding is fantastic. world.” weaknesses; they don’t want to see them.” cussed lately with other developers that we really are at a cross- They have all sorts of cool commercials (however cryptic and For Sarwar Mansoor ([email protected]), however, C# “Don’t make this a religious or social movement,” he con- roads. Sun has been arrogant to the point of insult and has uninformative they may be) and for some strange reason, lots of is simply not something to be mentioned in polite company. cludes, “Make it a wake-up call to Sun that they need to fun- shrugged off real concerns and problems. Sun needs to com- people believe in them.” “After reading this I have lost faith in JDJ,” he complains. “I damentally change the way they approach Java’s develop- pletely embrace their community, open source and otherwise. “On the other hand,” he continues, “we have Java, billions of thought this was a true journal on Java. I am reading Java Pro ment.” They need to wake up and smell the Java, so to speak.” lines of Java code floating around the Internet. There are lots of from now on. I code for a living and love coding, but I am not Tower explains: “I hope and expect Java to be my language of enterprise applications and systems in place, millions and mil- selling my soul.” What do you think? What is the future of Java? What should be choice for years to come. But I can’t deny a viable alternative. lions of dollars already invested. Who will want to basically flush John Harrisburg ([email protected]) takes issue with this. done to boost Java? Can Java and C# coexist peacefully? To add Sun has completely failed on the desktop. Yeah, you can argue, away everything they already have just to jump on MS’s latest “You can read JavaPro until they go out of business just like your comments, go to www.sys-con.com/java/article.cfm?id oh look at this great app and that one, but truth be told Sun blew buzzword?” JavaReport did,” he retorts. “Do you remember Java Report? =1401.

102 JUNE 2002 JUNE 2002 103

Java COM Java COM TO REGISTER: www.sys-con.com or Call 201 802-3069 SHARPEN YOUR PROFESSIONAL SKILLS. IF YOU MISSED THESE... FREETH WITH TUTORIAL WEB SERVICES EDGE JUNE 27 BOSTON, M A (Boston Marriott Newton) SOLD OUT! WASHINGTON, DC (Tysons Corner Marriott) SOLD OUT! 2002 EAST REGISTRATION. LIMITED OFFER! KEEP UP WITH THE NEW YORK, NY (Doubletree Guest Suites) SOLD OUT! TECHNOLOGY SAN FRANCISCO, CA (Marriott San Francisco) CLASSES ADDED $195 SOLD OUT! REGISTRATION EVOLUTION! FOR SYS-CON Presented an excellent overview of Web BE SURE NOT TO SUBSCRIBERS “services. Great inside knowledge of both the BEST EDUCATIONAL VALUE new and old protocols. Great insight into the code piece.” MISS THESE... FOR THE HOTTEST – Rodrigo Frontecilla TECHNOLOGY SKILLS! Each city will be sponsored by a leading Web services company Very articulate on the Web services SOAP topic …COMING TO A CITY NEAR YOU TakeTake YourYour “and well-prepared for many questions. I've learned a lot from this seminar and I appreciate this seminar for my job. Thank you!” 2002 – Kenneth Unpingco, Southern Wine NEW YORK AT WEB SERVICES EDGE 2002...... EAST JUNE 27 CareerCareer toto thethe & Spirits of America BOSTON...... JULY 10 I liked the overview of Web services and the SAN FRANCISCO ...... AUGUST 6 “use of specific tools to display ways to SEATTLE...... AUGUST 27 distribute Web services. Good for getting up to speed on the concepts.” AUSTIN ...... SEPTEMBER 10 NextNext Level!Level! – B. Ashton, Stopjetlag.com LOS ANGELES ...... SEPTEMBER 19 SAN JOSE AT WEB SERVICES EDGE 2002 ...... WEST OCTOBER 3 Echoed over and over by Web Services Edge World Tour CHICAGO ...... OCTOBER 17 Attendees: ATLANTA...... OCTOBER 29 MINNEAPOLIS...... NOVEMBER 7 “Good balance of theory and demonstration.” NEW YORK...... NOVEMBER 18 “Excellent scope and depth for my background SAN FRANCISCO...... DECEMBER 3 at this time. Use of examples was good.” “It was tailored toward my needs as a novice 2003 SEATING IS LIMITED. REGISTER NOW FOR THE CITY NEAREST YOU! WWW.SYS-CON.COM to SOAP Web services – and they explained CHARLOTTE...... JANUARY 7 everything.” MIAMI...... JANUARY 14 LearnLearn HowHow toto Create,Create, Test Test andand DALLAS ...... FEBRUARY 4 WHO SHOULD ATTEND: BALTIMORE...... FEBRUARY 20 BOSTON...... MARCH 11 RECEIVE • Architects DeployDeploy Enterprise-ClassEnterprise-Class REGISTER WITH A COLLEAGUE AND SAVE 15% OFF THE LOWEST REGISTRATION FEE. 4$345 • Developers VALUE! FREE • Programmers TOPICS HAVE INCLUDED: WebWeb ServicesServices ApplicationsApplications 1-YEAR SUBSCRIPTIONS Developing SOAP Web Services • IS/IT Managers Architecting J2EE Web Services TAUGHT BY THE INNOVATORS AND THOUGHT LEADERS IN WEB SERVICES OR 1 2 3 4 OR 4 • C-Level Executives EXPERT PRACTITIONERS TAKING AN APPLIED APPROACH WILL PRESENT TOPICS INCLUDING BASIC On May 13th, the San Francisco TECHNOLOGIES SUCH AS SOAP,WSDL, UDDI AND XML, PLUS MORE ADVANCED ISSUES SUCH AS • i-Technology Professionals SECURITY, EXPOSING LEGACY SYSTEMS AND REMOTE REFERENCES. tutorial drew a record 601 registrations.

REGISTRATION FOR EACH CITY CLOSES THREE BUSINESS DAYS BEFORE EACH TUTORIAL DATE. DON’T DELAY. SEATING IS LIMITED. NON-SUBSCRIBERS: REGISTER FOR $245 AND RECEIVE THREE FREE ONE-YEAR SUBSCRIPTIONS TO WEB SERVICES JOURNAL, JAVA DEVELOPER’S JOURNAL, AND XML-JOURNAL, PLUS YOUR CHOICE OF BEA WEBLOGIC DEVELOPER’S JOURNAL OR TO REGISTER: www.sys-con.com or Call 201 802-3069 WEBSPHERE DEVELOPER’S JOURNAL, A $345 VALUE! LETTERS TO THE EDITOR We’ve got ’em all Java Anthem The C (VS.NET) Community is that the meat of my app performs well Missed an issue? for you on CD! As far as I can tell, many developers and, most important, adheres to relevant In the April issue of JDJ, I made a call www think Java is dead because “VS.NET is business rules. to readers to come up with a possible JDJ The Complete Works Web Services Resource CD CFDJ The Complete Works CFA The Complete Works Order Online and Save 10% or More! such a great IDE” and “C# is such a bet- Don’t get me wrong, I learned Java Java song, something that we could all Reg $119.99 Reg $119 Reg $79.99 Reg $79.99 ter language” (“In Search of The with TextPad, but I became much more maybe hum and sing along to. We Buy Online Buy Online Buy Online Buy Online Community” by Keith productive in NetBeans received some really great responses, but Only Only Only Only . Brown [Vol. 7, issue 4]). than I ever was in this one seemed the best. $ 99 $ $ 99 $ 99 JDJ The problem is that they TextPad. –Alan Williamson 71 79 71 71 don’t understand why we I wonder what those STORE use Java. C# is a good lan- “hard-core” code-gurus The melody is “Nobody Does It Better” guage and VS.NET is a will say when they see

J2SE by Marvin Hamlisch, from the James Bond great IDE, but there are how quick it is to publish movie The Spy Who Loved Me. some things I don’t like a Web service with Visual about it and I don’t think Studio .NET versus the SPECIAL

OFFER: .com it’s any better than Java hours of coding it would “The Language That Loved Me” Buy CFDJ & CFA The Complete Works and my favorite IDE. take to do it by hand in No code does it better For Only 99 Also, only VS.NET is Java. I’m sure Java IDEs $ Makes me feel sad for the rest. 129 .NET. Everything else is will do the same in time. still COM, etc. Which No code does it half as good as you. J2EEmeans in all reality it will J2ME Reuben Cleetus Java, you’re the best. be quite a while before [email protected] everything MS is .NET-ed (MSMQ, MTS, I wasn’t looking but somehow you COLLECT SQL Server, Exchange, etc.). So for those IDEs Have Their Own Niche found me. hoping or saying that .NET/C# will soon Coming from my personal experience I tried to hide from your interpreter, FOR ALL be available on Linux – well, if it’s taking I would prefer a powerful text editor to ONLY$ 99 Like heaven above me, the language 229 MS this long with all their resources, any IDE, especially in the Java world. The JDJ, WSJ & XML-J, Letters how long do you think it will take less- problem with an IDE is you have to learn that loved me CFDJ, & CFA OFFER SUBJECT TO CHANGE WITHOUT NOTICE funded and less-supported projects such it, and it has bugs and perks of its own to Is keeping all my software safe 4 Home as Mono? Plus, MS has no interest in overcome. When you’re a beginner, an tonight. seeing .NET succeed on any platform IDE is perfect with all its wizards and other than Windows. In fact, they can’t graphical buttons, etc. As you become have it happen. more professional, you stop using wiz- And no code does it better SYS-CON Media, the The weird thing is that from what I ards and feel uncomfortable with limited Though sometimes I wish C# could. world’s leading publisher of can see, more people are using VB.NET text-editing functions and doing the mis- No code does it quite the way you do. than C#. cellaneous things the IDE doesn’t do. i-technology magazines for Did you have to be so good? Once you’re a pro, you throw them away developers, software Mark and take Emacs/Ant and live happily architects, and via e-mail ever after. The way that you recover whenever e-commerce professionals, IDEs Generally Lead to Admiral you crash. brings you the most There’s some kind of magic inside you comprehensive coverage of The Better Productivity [email protected] That keeps me from VB but just keep it WebSphere. World’s I wonder if all those Leading easy. so-called hard-core pro- First of all, IDE stands Independent grammers (who proudly for “Integrated How did you learn to debug the way WebSphere Developer proclaim that Notepad is Development you do? Developer better than any IDE) ever Environment,” not Resource bothered to stop and “Interactive.” So what if WebSphereDevelopersJournal.com think about what they there are wizards? Most And no code does it better were justifying (“Is the experienced engineers Makes me feel sad for the rest. Graphical IDE a Good never use them anyway. No code does it half as good as you. Thing” [Vol. 7, issue 3]). The real benefit to an IDE Java, Java you’re the best. Basically, what is the productivity – all Java you’re the best. they’re saying is that it’s your editing, debugging, better to continually compiling, etc., are “inte- Java you’re the best. Introductory rewrite the basic plumbing than to use grated” (hence “IDE”) into a single envi- Java you’re the best. “intellisense” or some other feature that ronment. This is much more productive Java you’re the best. an IDE provides, which takes care of the than crawling on your hands and knees Java you’re the best. Charter Subscription banal and lets you focus on the task at with a text editor and command-line Java you’re the best. hand. I would much rather focus on the debuggers and the like, jumping around SUBSCRIBE NOW AND SAVE $31.00 business rules I have to implement than in various utilities, etc. Java, Java you’re the best. edit a deployment descriptor by hand, or OFF THE ANNUAL NEWSSTAND RATE submitted byJohn Chamberlain write the basic Java code for the GUI of a Scott ONLY $149 FOR 1 YEAR (12 ISSUES) REGULAR RATE $180 . Swing application. What I care for most [email protected] [email protected] OFFER SUBJECT TO CHANGE WITHOUT NOTICE

106 JUNE 2002

Java COM JAVANEWS> SYS-CON’s Web Services Edge FULCRUM NOW MAKES World Tour Attendance Quadruples > THE U.S. SCENE (Pune, India) – Software tools company AccelTree in San Francisco has debuted FULCRUM, an intelligent Java code builder, in the United States. Neither an IDE nor a code generator, FULCRUM is a Java development J2SE >>>> tool that uses a proprietary concept of code tem- plates that can be used as building blocks to con- struct Java objects and applications. (Montvale, NJ) – SYS-CON Events, Inc., developers with all the Among the reported benefits are faster coding presented the fourth stop of their Web tools and information they time and the ability to implement your own coding Services Edge World Tour, SYS-CON’s need to immediately begin standards. In addition, the need for skilled program- popular one-day tutorial series, to a sold- creating, deploying, and mers is reduced, and no runtime software needs to out audience in San Francisco. The series using their own Web serv-

J2EE J2ME be purchased. The tool also integrates with existing was organized in response to developers’ ices. Upon completion of or external objects. eagerness to plan ahead for SYS-CON’s the program, expert practi- Web Services Edge 2002 International tioners will be able to take www.AccelTree.com Conference & Expos East and West, an applied approach and which will take place June 24–27 in New cover base technologies such as SOAP, York City and October 1–3 in San Jose, WSDL, UDDI, and XML, as well as more Next Stop:Thursday,June 27,2002, CA, respectively (www.sys-con.com/ advanced topics such as security, J2EE New York City News WebServicesEdge2002East). integration, exposing legacy systems, The next stop of the education tour is The first four cities of the Web and integrating Web services into an June 27, 2002, in New York City. There SYS-CON Home Services Edge World Tour tutorial series existing IT infrastructure. will be 12 new cities named before the entitled “Developing SOAP Web Due to an overwhelming interest in end of this year, covering additional Services” are exclusively sponsored by the tutorial in San Francisco, SYS-CON stops in North America and introducing Media www.sys-con.com

Systinet Corporation (www.sys-con. Events increased the originally planned several new cities in Europe, Asia, and com/education). The tutorial curricu- single-session program to four simulta- Australia. lum is designed to equip professional neous sessions of which two were pre- www.sys-con.com sented by Oracle and focused on the topic of “Architecting J2EE Web Quintessence and Cape Clear REMOTEAPPS LAUNCHES Services.” Announce Alliance XYRIAN 2.2 (Berkshire, UK / Dublin, Ireland) – > SYS-CON Offers New Opportunities Quintessence Systems and Cape Clear in San Francisco Software will work together to enable cus- (London) – RemoteApps has announced the launch SYS-CON Events also brought leading tomers to migrate and connect existing Web services vendors and the attendees Oracle applications to Web services both of Xyrian 2.2 Enterprise and Developer Editions, of the Web Services Edge World Tour inside the corporate network and across the supported by an advanced Tech Portal. together. More than 800 attendees of San Internet. Customers can use Quintessence’s Xyrian, an application development tool, fea- Francisco’s one-day tutorial were excited in2j tool to automatically migrate their tures an advanced programming environment, the to meet with IONA, AltoWeb, Sonic Oracle legacy code into Java. Once in Java, Software, ObjectFocus, Systinet, and Cape Clear’s CapeConnect platform can be Framework persistence engine, and Team View, a Oracle representatives. They received a used to expose the migrated Java code as browser-based content management system. unique chance to ask questions and Web services. www.remoteapps.com examine these companies’ Web services www.in2j.com offerings. www.capeclear.com

108 JUNE 2002 JUNE 2002 109

Java COM Java COM What’sOnline... June 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 industry, J2SE minute by minute, and stay ahead of the competition.

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

Search Java Jobs Java Developer’s Journal is proud to offer an employment portal for IT professionals. Get direct access to the best companies in the nation and discov- er the “hidden job market.” If you’re an IT professional Online curious about the job market, this is the site to visit. Simply type in the keyword, job title, and location Home and get instant results. You can search by salary, com- pany, or industry. Need more help? Our experts can assist you with JDJ Store retirement planning, putting together a résumé, immigration issues, and more.

Web Services Edge 2002 Conference and Expo www.jdjstore.com Sign up for the Web Services Edge 2002 West International Conference and Expo, October 1–3, at the San Jose Convention Center, San Jose, California. This year’s event is expected to be the biggest and best ever with the top IT professionals in the business speaking about the hottest industry topics. The Web Services Edge 2002 Conference and Expo will feature presentations prepared for a diverse audience. Whether you consider yourself a beginner or at the top of the IT world, this conference is for you!

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 of its kind. Known as the “Oscars of the Software Industry,” this year’s awards feature an expanded list of product categories and other addi- tions that will make the fifth annual Readers’ Choice Awards the best so far!

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

110 JUNE 2002 JUNE 2002 111

JJavaava COMCOM Java COM CAREER OPPORTUNITIES ADVERTISERINDEX ADVERTISER URL PHONE PAGE

AccelTree www.acceltree.com 21 Actuate Corporation www.actuate.com/info/jbjad.asp 800-884-8665 57 Altaworks www.altaworks.com 603-598-2582 73 Altova www.altova.com 39 Next Month AltoWeb www.altoweb.com 35 Apple Computer, Inc. www.apple.com/macosx 1-800-MY-APPLE 4-5 Contract-to-Hire Ashnasoft Corporation www.ashnasoft.com 45 BEA www.bea.com/download 6 Borland Software Corp. www.borland.com/new/jb7/5068.html 800-252-5547 63 That was then,this is now Canoo Engineering AG www.canoo.com/ulc/ 41 61 228 94 44 31 Programming Restrictions in EJB Development Capella University www.capellauniversity.edu 1-888-CAPELLA 40 Programming restrictions can have a significant Compuware Corp. www.compuware.com/products/optimalj 800-468-6342 25 impact on your usual coding techniques. Leander J2SE CTIA WIRELESS I.T. www.ctiashow.com 83 van Rooijen reviews some of the restrictions as Dice www.dice.com 49 defined in the EJB specifications 2.0 and offers an EnginData Research www.engindata.com 201-802-3082 93 alternative approach. Fiorano Software www.fiorano.com/tifosi/freedownload.htm 800-663-3621 71 HiT Software www.hitsw.com/xmlrdb 408-345-4001 59 InetSoft Technology Corp. www.inetsoft.com/jdj 888-216-2353 65 WRITTEN BY s staffing professionals in the technology industry, we’ve seen the focus for Infragistics, Inc. www.infragistics.com 800-231-8588 14-15 BILL BALOGLU & A InstallShield Software Corp. www.installshield.com 847-240-9111 55 many staffing firms shift from placing senior consultants in contract positions (while J2EEBILLY PALMIERI J2ME occasionally filling the odd full-time job) to placing them in full-time jobs. INT, Inc www.int.com 713-975-7434 26 iSavvix www.community.isavvix.com 866-ISAVVIX 85 Over the past several years, compa- opens back up, he or she will be the ning stages, from its requirements gath- JDJEdge Conference & Expo www.sys-con.com 95 Combating the ‘Object Crisis’ nies felt that paying contract consultants first one gone. ering to issues of scalability and security, JDJ Store www.jdjstore.com 201-802-3012 107,111 The phenomenal success of Java as an enabler a high hourly rate to execute one piece of Managers are under the illusion that to find the problem he or she was hired Jinfonet www.jinfonet.com 79 of enterprise-wide, Web-deployed applications has a project was a great way to get the job they’ll be able to keep people in full- to solve. In that respect you may very LOOX Software Inc. www.loox.com 800-684-LOOX 53 compelled a countless number of organizations done without committing to the salary, time positions, but full-time employees well have a strong understanding of Macromedia www.macromedia.com/go/jrun4jdj 23 and individuals alike to seek proficiency with Java. benefits, and responsibilities that go are just as likely to leave a job if the work project life cycles. Metrowerks Corp. www.wireless-studio.com 11 Jacquie Barker notes that many, however, are ill- along with hiring a full-time employee. is not challenging. The average full-time \n software inc. www.nsoftware.com 29 prepared to harness Java’s power as an object-ori- Home But that, as they say, was then. And employee in Silicon Valley lasts 18 3. Contractors don’t get involved in a New Atlanta Communications www.newatlanta.com 43 ented programming language due to a lack of this is now. months in one job. company’s internal process and don’t Northwoods Software www.nwoods.com/go/ 800-434-9820 48 understanding of object concepts. This may change again as the econo- Convince the manager that if the usually deal with issues of internal Parasoft Corporation www.parasoft.com/jdj6 888-305-0041 47 my and the industry readjust in the work is challenging and interesting, politics. But I need someone with that Pramati Technologies www.pramati.com 877-PRAMATI 75 coming months, but for the time being, you’ll stay. But if it’s not, then the aver- experience. QUALCOMM Incorporated http://brew.qualcomm.com/ZJD5 67 companies are looking to fill full-time age full-time employee isn’t likely to stay You may not have dealt with the Quintessence Systems Limited www.in2j.com 41, 81 positions. Period. either. internal politics of a company, but a Rational Software www.rational.com/offer/javacd2 37 AUTHOR BIOS Many of you who are reading this are Your résumé is important. A lot of savvy contractor knows that he or she Rational User Conference 2002 www.rational.com/ruc 888-889-0074 77 Bill Baloglu is a seasoned contract consultants. You’ve three-, four-, or five-month contracts on will be dealing and communicating with RemoteApps http://portal.remoteapps.com 44(0)20 7680 7689 17 principal at invested time and money into becoming a résumé can lead managers to wonder different people on the project in order SilverStream Software www.silverstream.com/scale 1-888-823-9700 27 Certificate Authorization in Your J2EE PKI ObjectFocus incorporated, and you’ve grown accus- if the contracts were actually completed, to examine the problems. Sitraka www.sitraka.com/jclass/jdj 800-663-4723 19 Eric Simmerman demonstrates how he built a (www. ObjectFocus tomed to the benefits of being a “hired or why they weren’t renewed. Many contractors are typically Sitraka www.sitraka.com/jprobe/jdj 800-663-4723 61 PKI implementation in which his client acted as the .com), a Java staffing gun” contractor. Nine-month to one-year contracts brought in once the project is in trouble Sitraka www.sitraka.com/performasure/jdj 800-663-4723 116 Certificate Authority. He then integrated this PKI firm in Silicon Valley. Working on two or three contracts a look good. They suggest that your work and internal tensions are high, so the Simplex Knowledge Company skc.com 845-620-3700 89, 91 with J2EE systems via JSSE to provide secure com- Bill has extensive OO year has exposed you to many more was valued and that you stayed on as internal staff is eager to avoid blame for Sonic Software www.sonicsoftware.com 800-989-3773 2 munication services among multiple platform experience and has types of technologies than you would long as was necessary. It’s always good to the problem. You could make a case for SpiritSoft www.spiritsoft.com/climber 33 boxes distributed across three continents. held software have worked with as a full-timer at just be able to tell managers that you never your experience in handling internal Sprint PCS http://developer.sprintpcs.com 69 development and one company. And while full-time left a contract before it was finished. politics on that level. Sun Microsystems www.sun.com/forte 13 senior technical employees have grappled with corpo- SYS-CON Industry Newsletters www.sys-con.com 201-802-3020 87 management rate dynamics and politics, you’ve been 2. Contractors are used to coming in 4. Contractors are used to making a lot SYS-CON Subscription Offer www.sys-con.com/suboffer.cfm 109 positions at several able to walk away from it all when your and working for a limited time on more money than I can pay. TogetherSoft Corporation www.togethersoft.com/challenge/1 919-833-5550 8 WebGain, Inc. www.webgain.com/toplink_create3.html 1-877-WebGain Ext.15858 115 Silicon Valley firms. contract was finished. just one piece of the project. They In a full-time position, you won’t be WebLogic Developer's Journal www.sys-con.com/weblogic 800-513-7111 109 However, if you’re looking to make don’t have a hands-on understand- earning $125 an hour (as you may have Web Services Edge Conference & Expo www.sys-con.com 104-105 Billy Palmieri is a the change from a contractor to a full- ing of the full life cycle of a project. as a contract consultant). You’re more Optimizing Java Performance in Heritage Designs Web Services Edge World Tour 2002 www.sys-con.com 201-802-3069 108 seasoned staffing time employee, there are several issues On the issue of project life cycles, it likely to earn $125K a year plus benefits. Dr. Carl Barratt discusses the introduction of Java Web Services Resource CD www.jdjstore.com 201-802-3012 99 industry executive and you need to overcome in order to be could be helpful to bring up the follow- A senior position could pay more, but into multilanguage heritage designs, focusing on Web Services Journal www.sys-con.com 800-513-7111 100 a principal at considered a viable full-time candidate. ing points. don’t count on it. Make it abundantly the advantages and disadvantages of deploying WebSphere Developer's Journal webspheredevelopersjournal.com 800-513-7111 107 ObjectFocus. His prior When managers look at a long-time As a contractor you may not have clear to the hiring manager that you’re each solution. Zero G www.zerog.com 415-512-7771 3 position was at contractor’s résumé, they raise some of been around when the project was aware of these economic realities and General Conditions: The Publisher reserves the right to refuse any advertising not meeting the standards that are set to protect the high edi- Renaissance the following objections, and we’ve pro- architected and developed or when it you’re okay with them. torial quality of Java Developer’s Journal. All advertising is subject to approval by the Publisher. The Publisher assumes no liability for any Worldwide, where he vided some points you can respond was time to fix bugs and release it, as If you’re not, feel free to keep holding 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 held several senior with. most people don’t hire a contractor until out until it changes back to a contrac- 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. management positions they have a problem. tor’s world. 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 in the firm’s Silicon 1. I don’t want to hire a contractor The experienced contractor is often of their advertisements printed in Java Developer’s Journal. Advertisements are to be printed at the discretion of the Publisher. This discre- Valley operations. because when the contract market required to review the project’s begin- [email protected] 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.

112 JUNE 2002

Java COM CUBIST THREADS ‘Subversion,One Point Oh’

ometimes I think the world is getting fundamentally goofi- J2SE S WRITTEN BY er, at an ever-increasing pace. On the other hand, I’ve only been here a brief while (in geologic terms, at least), and can’t help BLAIRWYMAN believing that the world has always been pretty doggone goofy.

Sputnik and I happened to arrive laughing is fun; it feels good. So, if you “goofiness.” the same year, 1957, though Sputnik happen to have a particularly outra- Some years later, during that brief made a much bigger splash in the geous – or even subversive – point to and shining time when I knew it all, my press. Here is a testament to the magni- make, why not make it with humor? taste in music was singularly insular. J2EEtude of orbital velocity: J2ME a 183-pound It was a Saturday afternoon when Music, of all things, certainly wasn’t device, accelerated into Earth orbit, buoyant humor rescued me from what funny. Rather, music was a profoundly can drag an entire surprised world right had, so far, been a pretty mainstream ponderous accompaniment to the along with it. F=ma, indeed. float through childhood. Flipping equally grave business of unbridled At the time a key parameter in the through the channels (I think we got teenage lust: an ear-pounding back- acceleration of global goofiness was five or six), I happened upon a starkly drop to the perpetual pursuit of pul- surely the simultaneous acceleration of rendered warning: chritude. the space race. We learned to count Then, a great friend of the family backwards – “T-minus” one second at a It is the stated position of the U.S. Air introduced me to the musical genius of Home time – most of us blissfully unaware of Tom Lehrer. I had found the contra- the meaning of “T”. One of the first Force that their safeguards would pre- puntal companion to Strangelove, pok- things I vividly remember is watching ing furtive fun at soberly spooky WebGain,Inc. an Atlas-6 rocket lift John Glenn into vent the occurrence of such events as are specters like irreverent Boy Scouts (“Be Earth orbit. My equilibrium had been Prepared”), Dahmer-esque dismem- forever punctuated. (I’d never seen a depicted in this film… berment (“I Hold Your Hand in Mine”), color TV before.) and nuclear conflagration (“We’ll All Go www.webgain.com/toplink_create3.html There was a lot happening during And so began Stanley Kubrick’s dark Together When We Go”). That familiar those goofy years, and not all the voices comedy, Dr. Strangelove, or: How I melody, with a new lyric – “Down by the were counting down in synchronized Learned to Stop Worrying and Love the old maelstrom…” – inevitably evokes unity. While it’s true that conformity Bomb. an irrepressible grin. was king, the muzzles of McCarthyism On the surface, it’s an unsettlingly So, dear reader, I implore you: were loosening. Diverse voices once scary premise: a plausible scenario, in don’t fear goofiness, embrace it. After again posed probing questions, flatly which human frailty leads to nuclear all, it has been with you your whole eschewing pat answers. Of course, as Armageddon. (I am reminded of that life and always will be, so laugh at it AUTHOR BIO soon as someone uses the word “Buffy” episode, in which Giles says, when you can. In the words of Mary H. Blair Wyman is a software “eschew,” half their audience is history. “It’s the end of the world. Everyone Waldrip, “A laugh is a smile that engineer working for IBM How, then, to make people listen? dies. It’s rather important, really.”) So bursts.” in Rochester, Minnesota, It seems that if you make people why was it so outrageously funny? One home of the IBM iSeries. laugh, they will listen to you. After all, possible explanation springs to mind: [email protected] Java Dudes

114 JUNE 2002 JUNE 2002 115

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

116 JUNE 2002

Java COM