WEB SERVICES WORLD TOUR DON’T MISS IT! P.83

TM

Java COM

COMING TO A CITY NEAR YOU SEE PAGE 83 FOR DETAILS 2002 BOSTON ------JULY 10 SAN FRANCISCO - - AUGUST 6 SEATTLE ------AUGUST 27 AUSTIN ------SEPTEMBER 10 LOS ANGELES - - - - SEPTEMBER 19 SAN JOSE ------OCTOBER 3 AND MANY MORE! Secure Communication: Eric Simmerman Certificate Authorization in Your J2EE PKI Integrate self-certified certificates with J2EE systems via JSSE 8 From the Editor Alan Williamson pg. 5 Feature: Building Transformational Bill Dettelback Web Services... with J2EE and an XML database 16 J2EE Editorial EJB Spec 2.0: Programming Restrictions Leander van Rooijen Ajit Sagar pg. 7 in EJB Development Building scalable enterprise applications 24 J2SE Editorial Jason Bell pg. 40 Showdown: Are You Ready to Rumble? Michael Deasy .NET vs J2EE Smackdown: the raging debate in the developer community 36 J2ME Editorial Java Class Files: Hello World! in 70 Bytes Norman Richards Jason R. Briggs pg. 62 Take the challenge – create the smallest Java class 44

Industry Commentary Data Security & Mobility: Java Card 2.2 Joseph Smith Ken Greenwood pg. 64 Specifications Overview Java Card engineering with RMI specifications 66 Cubist Threads Feature: Optimizing Java Performance Carl Barratt Blair Wyman pg. 94 in Heritage Designs The advantages and disadvantages 70

SYS -CON MEDIA JDJ Labs: BEA WebLogic Workshop Joseph A. Mitchko Create and deploy Web services 76 Sonic Software Zero G www.sonicsoftware.com/jdj www.zerog.com

2 JULY 2002 JULY 2002 3

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

EDITORIAL J2SE EDITOR-IN-CHIEF: ALAN WILLIAMSON EDITORIAL DIRECTOR: JEREMY GEELAN Java ina Flash! EXECUTIVE EDITOR: NANCY VALENTINE J2EE EDITOR: AJIT SAGAR J2ME EDITOR: JASON R. BRIGGS J2SE EDITOR: JASON BELL PRODUCT REVIEW EDITOR: JIM MILBERY hen I wrote my last editorial I farewell to Keith and thank him for his FOUNDING EDITOR: SEAN RHODY was on a plane to Toronto. What insight over the last few months. He’ll still be I neglected to tell you was popping up from time to time when his

PRODUCTION W J2EE where I was off to after Toronto. It was to schedule permits, so you haven’t heard the VICE PRESIDENT,PRODUCTION AND DESIGN: JIM MORGAN Redmond, Washington, as the guest of last of him. The J2SE mantel will be taken up ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI EDITOR: M’LOU PINKHAM Microsoft, where they showed me the virtues by Jason Bell, a JDJ writer of old, who will MANAGING EDITOR: CHERYL VAN SISE of their .NET framework. It was a very inter- give his slant on the whole Java space. That’s ASSOCIATE EDITORS: JAMIE MATUSOW esting visit and I learned a lot. I’m in the two Jasons we have on the editorial staff…it’s GAIL SCHULTZ throes of writing up my report on the whole an invasion! JEAN CASSIDY shebang and once I have my facts straight, One of the best parts of this job is talking ASSISTANT EDITOR: JENNIFER STILLEY Home I’ll publish them in JDJ. So keep an eye out to you. Over time I have had some wonderful ONLINE EDITOR: LIN GOETZ TECHNICAL EDITOR: BAHADIR KARUV, PH.D. next month for that. conversations with people from all walks of By the time you’ve read this, the World life – people now engaged in the world of WRITERS IN THIS ISSUE Cup will be over and another country will Java, with origins from the strangest of BILL BALOGLU, CARL BARRATT, JASON BELL, JASON BRIGGS, MICHAEL DEASY, be heralded as the greatest football nation places. For example, I had a delightful BEA Systems BILL DETTELBACK, KEN GREENWOOD, JOE MITCHKO, BILLY PALMIERI, for the next four years, until they thrash it exchange with a Bill Reister who took me NORMAN RICHARDS, AJIT SAGAR, ERIC SIMMERMAN, JOSEPH SMITH, out again in 2006 in Germany. Why do I into the world of flying military jets. Another RAZVAN SURDULESCU, LEANDER VAN ROOIJEN, ALAN WILLIAMSON, BLAIR WYMAN draw attention to this you ask? Well, it’s a exchange was with a Razvan Surdulescu who great test of the technology we’re all build- came to us with a great idea for a story that www.bea.com/download SUBSCRIPTIONS: ing. It’s at times like these that you realize we all instantly jumped at. Razvan has writ- FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, just how powerful and far reaching the ten an emulator for the ZX Spectrum in Java. PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT Internet has become. No matter how much His proposal got my vote for many reasons. I SUBSCRIPTION HOTLINE:[email protected] capacity sites prepare themselves for, owe my current life choice to that little Z80- COVER PRICE: $5.99/ISSUE sometimes it’s just not enough. Take the based machine. When I was just 11-years old DOMESTIC: $49.99/YR. (12 ISSUES) BBC Web site. On the first day of the World it whetted my appetite for the world of com- CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. Cup they experienced some 8 million hits, puters. (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. three times more than normal traffic. Some How many of you remember program- users complained of being locked out, but ming in those days? It’s funny to look at it EDITORIAL OFFICES: on the whole it coped. now, especially when we look at the power SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 TELEPHONE: 201 802-3000 FAX:201 782-9600 What I find wonderful about this tale is Java has laid before us. For example, for a JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly that a lot of the BBC site is run with Java long time I couldn’t figure out how programs (12 times a year) for $49.99 by SYS-CON Publications, Inc., 135 Chestnut technology – a great success story about the could ever work without the notion of line Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address power of Java. A shot across the bow of the numbers! Remember choosing 10, 20, changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., anti-Java brigade I say! While this sort of traf- 30…giving yourself enough spacing in case 135 Chestnut Ridge Road, Montvale, NJ 07645. fic peak is something the majority of devel- you had to add in additional statements. opers will never experience, it is nice to know For those of you who are aware of the ©COPYRIGHT: that should such a flood come our way, we’ve Spectrum, check out Razvan’s article this Copyright © 2002 by SYS-CON Publications, Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any chosen a technology that’s beautifully scala- month; I think you’ll enjoy the trip down means, electronic or mechanical, including photocopy or any information storage and ble. memory lane. For those of you who aren’t retrieval system, without written permission. For promotional reprints, contact reprint coor- • • • familiar with that machine, read it anyway; 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. This month we have a new J2SE editor it’s a great piece on emulation. taking over the reins from Keith Brown. I bid Until next month. Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. SYS-CON Publications, Inc., is independent of Sun Microsystems, Inc. All brand and product names used on these pages are trade names, [email protected] service marks or trademarks of their respective companies. AUTHOR BIO Alan Williamson is editor-in-chief of Java Developer’s Journal. During the day he holds the post of chief technical officer at n-ary (consulting) Ltd, one of the first companies in the UK to specialize in Java at the server side. Rumor has it he welcomes all suggestions and comments.

4 JULY 2002 JULY 2002 5

Java COM Java COM J2EE INDEXX J2EE EDITORIALOR

Team Spirit Here’s a short pop quiz: Have

you ever built an application in J2ME 7 J2EE and taken it through the entire product life cycle? by Ajit Sagar AJIT SAGAR J2EE EDITOR Certificate Authorization in Your J2EE PKI When a client recently requested secure communi- Team Spirit J2SE cation among multiple plat- form boxes distributed ere’s a short pop quiz: Have you However, the colloquial interpreta- 8 across three continents, I ever built an application in J2EE tion of a J2EE application is one that uses decided to leverage the Hand taken it through the entire the J2EE object model – EJB. Typically, 100% Java-based security product life cycle? Or, for that matter, any EJBs apply to large-scale business appli- available via Java Secure distributed computing application? If the cations, and an EJB-based project Socket Extension. answer is “Yes,” then answer this one: Have requires a mix of skillsets. In fact, the J2EE by Eric Simmerman you handled all the facets of the applica- J2EE application server vendors have tion on your own – as a one-man team? If cornered the market on the J2EE frame- Building Transformational you answered “Yes” to both questions, my works and component containers. The Web Services response is: I don’t believe you. You can do Java IDEs offer the code development Web services is intended to one or the other, but not both, if we’re talk- environment. The data and business create the synergy of many ing about a real-world application, that is. modeling tools enable design and analy- applications working together J2EE offers a platform for developing sis. The vendors offer a mix of options for – the whole is greater than applications whose components or sub- developing J2EE applications, all based Home 16 the sum of its parts. These systems can be distributed across the dif- on the J2EE Blueprints. Rational types of Web services must ferent tiers of the computing network. To effectively utilize the tools in the be resistant to change and The obvious advantage is the decoupling market, you need to first define an appro- quickly adaptable to new of the programming logic that leads to priate team for your application. The types of users who want to reusable and scalable solutions. The other skillsets you’ll need can be broadly classi- use it on their own terms and main advantage is that development proj- fied into the following areas: with their own data formats. ects can structure their teams so that each • Front-end graphics Software by Bill Dettelback member is assigned to develop the sub- • JSP/servlet/HTML/Web development system that utilizes his or her particular • EJB/middle-tier Java components Programming Restrictions skillset. The operative word here is team. • Database and application server admin- in EJB Development J2EE projects are team-oriented projects. istration www.rational.com/offer/javacd2 This article states some of the Of course, J2EE development can mean programming restrictions as different things to different folks. There’s a The following is an example of an EJB- defined in the EJB 2.0 specifi- plethora of configuration options for appli- based project. If your application requires cations (almost the same as cation components and a variety of APIs development using Web services, JMS, 24 the 1.1 spec) and tries to that can be applied to their development. JCA, or other Java platform APIs, you’ll explain the reason for the Sun’s Java Blueprints outline the different have to define your team accordingly. restriction. Where possible it ways to skin the n-tier. It all depends on the While it’s possible to “overload” develop- also includes an alternative business requirements of your application, ers to work across the different areas, in a approach to reaching your goal the technologies available at your company complex application the pragmatic without violating the restriction. (or the ones that your corporation is willing approach is to assign developers to spe- by Leander van Rooijen to invest in), and the external systems you cific areas and migrate them to other will have to integrate with. areas when needed. Are You Ready to It’s true that a J2EE application can be Fortunately, there are resources in the Rumble? built by a one-man team. For instance, if market that will aid you in defining the There is a raging debate in you’re building the Pet Store application, appropriate architecture. The J2EE ven- the developer community: the airline reservation application, or the dors have mature offerings that help you Microsoft’s new platform typical bank account two-phase-commit develop reusable components, as well as .NET versus the Sun stan- example, you can do it yourself. Or if your environments that enable you to migrate dard J2EE. On April 25, application consists of a few business components across the tiers. Several 36 2002, Microsoft and Sun flows built on simple business logic and online and print resources for applying came together on one stage textbook data schemas, one or two devel- good design patterns and best practices (together again, for the first opers with similar skillsets will suffice. are available too. time anywhere) – and the [email protected] battle was joined. AUTHOR BIO by Michael Deasy Ajit Sagar is the J2EE editor of JDJ and the founding editor of XML-Journal. A lead architect with a software solutions firm based in Dallas, he’s well versed in Java,Web, and XML technologies.

6 JULY 2002 JULY 2002 7

Java COM Java COM SECURE COMMUNICATION Certificate Authorizationin Your J2EE PKI J2ME Integrate self-certified certificates with J2EE systems via JSSE J2SE

When a client recently requested secure communica- tion among multiple platform boxes distributed across three con- WRITTEN BY tinents, I decided to leverage the 100% Java-based security avail- ERIC SIMMERMAN able via Java Secure Socket Extension.

JSSE requires trusted certificates for secure Internet communications via of impersonation, their distribution authentication services, but my client Secure Sockets Layer (SSL) v3 and must be governed by a trustworthy enti- J2EE had no Public Key Infrastructure (PKI) in Transport Layer Security (TLS) 1.0 pro- ty. These entities are known as certifi- place for certificate generation and dis- tocols. cate authorities (CAs). tribution. So I built a PKI implementa- Netscape developed SSL in 1994 and When you participate in a client- tion where my client acted as the certifi- subsequently transferred control of the authenticated TLS or SSL conversation, cate authority and then integrated this protocol to the Internet Engineering you receive your counterparticipant’s PKI with J2EE systems via JSSE to pro- Task Force. The IETF renamed SSL to certificate. The certificate specifies the vide secure communication services. In Transport Layer Security (TLS), and identity of your counterparticipant and

Home this article, I’ll demonstrate how you can released their first specification in guarantees it by providing a certificate do the same. (The source code is avail- January 1999. TLS 1.0 is a modest authority’s signature. The CA in this case able on the JDJ Web site, www.sys- upgrade to the most recent version of acts much like a notary. If you trust the con.com/java/sourcec.cfm.) SSL, version 3.0, and the differences notary, you can trust the certificate. CAs Metrowerks between the two are minor. for the uncontrolled communication PKI/JSSE Overview SSL and TLS use public key cryptog- encouraged by the World Wide Web are If you already have a PKI in place or raphy to provide authentication, secret typically independent third parties who have other experience with key-based key cryptography to provide privacy, charge hundreds of dollars for the www.wireless-studio/com cryptography, you may want to skip this and a message authentication code to issuance of a single certificate. This section. For those new to the subject, provide data integrity. While in this arti- expense is not due to the cost of produc- the following brief overview provides cle I focus on the use of a key pair for ing a certificate, but to the costs some of the key terms and acronyms authentication purposes, all these cryp- involved in ensuring that an entity used throughout this article. There’s a lot tographic processes require only one. requesting a certificate is in fact who it to absorb here, but the actual applica- One key in the pair is made public claims to be. tion of these concepts in the following and the other is held strictly private. For In an enterprise system where multi- sections should make matters more authentication purposes, the public key ple communicating parties are con- clear. in a key pair is associated with a certifi- trolled by a single entity, it makes little One of the additions to the upcom- cate. A certificate in a PKI implementa- sense to incur this expense. You can save ing release of J2SDK 1.4 will be Java tion is an electronic document used to time and money while maintaining Secure Socket Extension 1.0.2. Currently identify a communicating entity by its internal control of your PKI by establish- available as an optional add-on, JSSE is association with a public key. Since cer- ing yourself as the CA in your secure a set of Java packages that enables tificates are used to address the problem communications. So let’s get to it. Becoming a CA JSSE was not included in Java Development Kits prior to version 1.4, You can save time and money while so you may need to install JSSE as an optional extension to your Java plat- maintaining internal control of your form. Luckily, the JSSE distribution “ includes explicit installation instruc- PKI by establishing yourself as the tions, making this step a breeze. Next, you’ll need an SSL toolkit capable of issuing X.509 certificates. I recommend CA in your secure communications OpenSSL because it’s open source, well documented, and free. There are several other options available including man-

8 JULY 2002 JULY 2002 9 ” Java COM Java COM SECURE COMMUNICATION

aged services, but I’ll be using OpenSSL OpenSSL generates base64 encoded When you execute this command, for demonstration purposes. certificates between “-----BEGIN-----” you’ll be prompted for the keystore Once you have the necessary soft- and “-----END-----” lines by default. password. The default cacerts password ware installed, the next step is to create This format is commonly but mistaken- is “changeit”. your certificate authority private key ly referred to as PEM format. True As you can see in Listing 2, the and certificate. I’ll create mine with the Privacy Enhanced Mail format is actual- default cacerts contains certificates

J2ME single-line command: ly used by some SSL servers like old from VeriSign and Thawte, which Lotus Domino and 4D WebSTAR Server, together issue the vast majority of Web openssl req -new -x509 -newkey so I’ll refer to the OpenSSL format as site certificates. Our JVM recognizes rsa:2048 -config openssl.cnf -key- OSSL. The JSSE integration tools expect most Web-based e-commerce certifi- out rootCAKey OSSL-formatted certificates. Regardless cates already. Now let’s add our CA cer- -out rootCACert -days 3650 -rand of which SSL toolkit you used to com- tificate to the keystore. "install.log:sunnyday.gif" plete this step, your final product should be an OSSL certificate and a private key. keytool -import -alias newCA -file J2SE The first option “req” signifies that These two components, along with your rootCACert -keystore cacerts we’re performing an X.509 certificate SSL toolkit, provide all you need. management operation, followed by Congratulations, you’ve successfully When asked if you wish to trust this “new” and “x509” showing that we’re become a certificate authority. certificate, answer “yes”. If you examine creating a new certificate without a cer- the cacerts keystore again, you’ll find tificate request. The “newkey” parame- JVM Integration that your CA certificate is listed under- ter specifies the type of private key Your next step is to tell your JVM that neath the alias you provided. You’re now along with its size in bits. The “days” you’re a trusted CA so it will inherently registered as a CA in your JVM. Let’s use parameter specifies that this certificate trust any certificates you issue. This is our new power as a CA to facilitate an J2EE will be valid for 10 years, and the “rand” accomplished by adding your CA certifi- SSL conversation between two parties. parameter points to a couple of files cate to your JVM’s CA certificates key- used to help randomize my key genera- store. The default CA certificates key- SSL Demonstration tion. store is found in your runtime environ- To demonstrate that your JVM will Once you execute this command, ment’s security directory, found under- trust certificates that you issue, we’ll you’ll be prompted for a pass phrase neath the lib directory. It’s intuitively set up an SSL-enabled conversation that will be used to encrypt and decrypt named “cacerts”. We’ll be modifying the between Alice and Bob. Alice and Bob

Home your new private key. When choosing a cacerts file, so make a backup copy represent two servers in an enterprise Sun pass phrase and restricting access to before continuing. system that need to communicate your CA private key, keep in mind that The keytool utility distributed with securely. For this demonstration you can your private key is a cornerstone of your J2SDK allows us to perform operations use, but do not need, two separate PKI and that its safekeeping is vital. After on any JVM keystores, so let’s use it to boxes. To keep things simple, we can just confirming your pass phrase, you’ll be examine the default cacerts. launch two JVMs on the same box and prompted for the attributes of your CA share the same local cacerts file (see Microsystems certificate as shown in Listing 1. keytool -list -keystore cacerts Figure 1). In this figure, configuration A shows the setup for the demo running on separate boxes. Configuration B shows the setup for the demo running www.sun.com/forte on one machine. Regardless of your hardware setup, both Alice and Bob will need access to a cacerts that we inserted our CA certifi- cate in. Each communicating entity also needs a personal keystore. Let’s make two copies of our cacerts file and place them in a working directory. Name the first copy aliceStore and the second bobStore. Next, we’ll generate a public and private key pair for Alice and store the pair in her personal keystore. A screenshot of this process is shown in Listing 3. Alice now has a 1024-bit RSA key, which will be valid for 365 days. This key pair allows Alice to participate as an unauthenticated client in an SSL con- versation. However, in our demonstra- tion system, we want to guarantee the identity of all conversation participants. Since Alice needs a certificate to partici- pate as an authenticated client, she’ll need to generate a certificate request to FIGURE 1 Possible configurations for the SSL demonstration send to her certificate authority.

10 JULY 2002 JULY 2002 11

Java COM Java COM SECURE COMMUNICATION

keytool -certreq -alias alice -sigalg Great, Alice is all set. Now just repeat Let’s put the code into action and MD5withRSA -file aliceCSR -keystore the same procedure for Bob. Once you step through an SSL conversation. First aliceStore have Bob’s certificate stored in bobStore, start the BobServer with client authenti- Enter keystore password: changeit it’s time to work with some code. cation enabled. There are four classes that we’ll use Note that my keytool utility balks on in this demonstration. The first, java BobServer true

J2ME this step if the key generated in the last SSLDemoException, is a simple wrapper Bob is listening on port: 4242 step has spaces in any Distinguished around the Exception class. There’s Name attributes. So, I used “Tallán” for nothing to it. The other common class is Then invoke AliceClient my organization name since “Tallán, the abstract base class SSLDemo, which Java AliceClient "Hello Bob, this is Inc.” threw an exception. If you com- contains some common features of the Alice" plete this step successfully, you’ll have client and the server. The first item of Sending message to Bob: Hello Bob a certificate request for Alice. Now we interest in SSLDemo is the static initial- Bob's Reply: RE: Hello Bob - Hello can put our CA hat back on and gener- izer, where I dynamically add the Alice, this is Bob. J2SE ate a certificate according to Alice’s Cryptographic Service Provider “Sun- Done... request. JSSE” to my list of security providers, as described in the JSSE installation The result seems a bit anticlimactic openssl x509 -req -CAcreateserial - instructions. I also override the default from the outside, but Figure 2 details the CAkey rootCAKey -days 365 -CA keystore used by the TrustManager. This more impressive internal workings. rootCACert -in step designates the keystore that holds As you can see, client authentica- aliceCSR -out aliceReply all my trusted CA certificates. tion simply requires that the client in Loading 'screen' into random state - To improve performance for multi- the client/server conversation also done ple connection conversations, my con- presents a valid certificate. Since Alice J2EE Signature ok structor preseeds a pseudorandom has a valid certificate, AliceClient can subject=/C=US/ST=Connecticut/L=Glaston number generator that will be used to talk to BobServer with client authenti- bury/O=Tallan/OU=Server/CN=Alice generate each SSLContext. I also load cation enabled or disabled. However, if Getting CA Private Key my personal keystore upon construc- Alice only had a public/private key pair Enter PEM pass phrase: [passphrase] tion. My personal keystore holds the in aliceStore with no certificate, then certificate chain needed to validate my Alice would only be able to converse The resulting aliceReply is a certifi- own certificate. As an example, Alice’s with Bob with client authentication

Home cate that’s valid for 365 days. We return personal keystore must hold Alice’s cer- disabled. That demonstration is left as this certificate to Alice, which needs to tificate and our CA certificate. an exercise for the reader. So Alice store this certificate alongside her key Since a good portion of the JSSE-spe- accepted Bob’s certificate and Bob pair in her personal keystore. cific logic is encapsulated in my base accepted Alice’s. They both trusted cer- Sitraka class, my client and server classes are tificates that we issued as the CA in our keytool -import -alias Alice -trust kept relatively clean of JSSE-specific PKI. cacerts -file aliceReply -keystore code. Each must define its personal key- aliceStore store and use SSL-specific socket facto- Conclusion www.sitraka.com/jclass/jdj Enter keystore password: changeit ries. In addition, the BobServer condi- We’ve provided you with the ability Certificate reply was installed in tionally sets client authentication on its to act as a CA in a minimalist PKI imple- keystore SSL-enabled server socket. mentation, and demonstrated how you can integrate your self-certified certifi- cates with J2EE systems via JSSE. Before you rush off to develop SSL-enabled enterprise systems, be aware that I’ve AUTHOR BIO only exposed you to some fairly complex Eric Simmerman is a material. There’s a lot more to develop- senior consultant in ing enterprise PKI than simple certifi- the development cate generation and distribution. I’ve division of Tallán, Inc., detailed enough to make you danger- where he designs and ous, but security is only as good as its implements numerous weakest link. Careful consideration enterprise systems in must be given to all areas of a system’s the U.S. and abroad. security to avoid negating any that SSL He’s a Java 2 might provide. Sun Certified programmer and a Resources Cisco Certified • Java Secure Socket Extension: Network Associate http://java.sun.com/products/jsse/ and has been • The OpenSSL Project: www.openssl. developing org/ professionally for • Netscape’s Secure Sockets Layer: seven years.. He holds www.netscape.com/security/tech- a BS in computer briefs/ssl.html engineering from Virginia Tech. FIGURE 2 SSL protocol in action [email protected]

12 JULY 2002 JULY 2002 13

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

14 JULY 2002 JULY 2002 15

Java COM Java COM J2ME J2SE J2EE

Home There are two types of Web SilverStream services: RPC-based and mes- sage-based. RPC-based Web services are synchronous in nature and functionally similar to making a remote method invocation. Message-based Web Software services are asynchronous and used primarily to pass business messages (or documents) be- W eb services is intended to tween services. To make a J2EE www.silverstream.com/coals Ocreate the synergy of many analogy, an RPC-based Web ser- applications working together. vice is very similar to invoking a The whole is greater than the method on a session bean, and a sum of its parts. Web services message-based Web service is must be resistant to change and very similar to placing a message quickly adaptable to new types on a JMS queue. of users who want to use them Web services are described on their own terms and with using an XML dialect called Web their own data formats. Services Description Language These transformational Web (WSDL). WSDL provides a vo- services, as I’ll call them, will rely cabulary for defining exactly how heavily on XML to meet this to access a Web service, whether demand. There’s a good reason it’s RPC or message-based, what why current Web services proto- parameters to provide, the URL cols such as SOAP and WSDL are to use, and so forth. defined using XML. XML is an Middleware providers have excellent format for storing and quickly adopted Web services managing information in a stan- and included tools with their dard, extensible manner that is products for managing SOAP also flexible. In this article, I’ll messages with EJBs and servlets. look at why a native XML data- Many of these tools focus on base can be a powerful comple- shielding the J2EE application ment to certain types of Web from the XML as much as possi- services. ble, minimizing the amount of

16 JULY 2002 JULY 2002 17

Java COM Java COM the service in detail, message-style Web services have the flex- ibility to accept any structured information in the SOAP mes- sage body. This makes them very attractive for implementing Web services that deal with more complex data whose struc- ture might change over time or depending upon the caller. Unlike RPC-based, message-based Web services have direct access to the different parts of the SOAP message that

J2ME invoked them. This provides a great deal of flexibility in how the Web service chooses to process the message. It also means that the service might be doing a lot of work with raw XML (e.g., DOM programming) if the document is complex or large. is an excellent format for storing and managing J2SE “ information in a standard, extensible XML Omanner that is also flexible” SOAP-specific information that the developer must deal with. If many different partners use the Web service, it’s cumber- In particular, RPC-based Web services can be implemented some for the developer to change the business logic of the Web with EJBs and servlets that have no idea they’re being invoked service every time a new partner is added. In addition, it’s a J2EE by SOAP. The tools provide facilities where an XML-to-Java challenge to store the data found inside the XML document if mapping can take place and the Web services implementation every caller is going to provide a document adhering to a dif- deals exclusively with Java data types. ferent XML Schema. To make life simpler, many applications This is a worthy goal, as a lot of SOAP programming is low simply discard the XML after parsing out the relevant bits of level and tedious. However, it’s important to remember that in information and storing them in a relational database. But some cases there’s real value to preserving the XML associat- sometimes it makes sense to keep not only the relevant data, ed with a SOAP message. By discarding the XML that com- but the XML document itself, as parsing and storing destroy

Home poses the SOAP body, a Web service is throwing away the abil- the structure of the document (and add considerable over- Compuware ity to manage extensible information. This extensibility (an head to the process). inherent trait of XML) is key to building a Web service whose This is where native XML databases fit in. A native XML interface is not tightly bound to a particular document struc- database operates very much like a familiar relational data- ture. base. However, instead of managing data as rows and Message-based Web services provide convenient gateways columns, it manages data as XML. A native XML database is for applications that need to submit requests and then get built from the ground up to store and manage XML in a parsed Corporation notified of the response at some point. There’s loose coupling format. This means there’s no conversion taking place from between these Web services and the caller. Unlike RPC-based the XML to some external storage format (either rows and Web services, where the caller must know each parameter of columns or “BLOBS” of text). Native XML databases typically outperform relational databases when it comes to storing and www.compuware.com/products/optimalj retrieving XML because they store the elements of a document in a preparsed format. An XML database is a perfect fit for the needs of the mes- sage-based Web service outlined earlier. It provides a transac- tional, secure place to hold incoming messages that won’t bog down the application’s database of record. But there’s another key reason for using an XML database – native XSLT support. XSLT is a language that describes stylesheets for transform- ing XML into other formats. Most applications that process XML in some fashion use XSLT primarily to format the XML before presenting it to a user. XSLT can do far more than sim- ply convert XML into HTML or the like. XSLT is ideally suited to transform XML from one dialect to another. When we con- sider the needs of a Web service that must handle multiple incoming messages that may be in different formats, XSLT is the natural choice for solving this problem. A native XML data- base that has a built-in XSLT processor has a major advantage over in-memory transformations, namely the ability to handle large document sizes without excessive memory consump- tion. Let’s focus on a concrete example. Imagine a warehouse that serves a variety of retail suppliers. It contains numerous inventory types and is constantly expanding the types of FIGURE 1 Warehouse Web service in BEA Workshop 7.0 Beta inventory it contains. At different times during the year the

18 JULY 2002 JULY 2002 19

Java COM Java COM service is intentionally vague about what the purchase order should look like so it can handle different kinds. Currently, the warehouse provides inventory for two sup- pliers, Acme and BigRetail. The Acme purchase order in its entirety can be found in Listing 2, the BigRetail purchase order in Listing 3. Notice that while they’re structurally different, both documents express basically the same information. What

J2ME is important is that both suppliers expect the Web service to behave the same way for their purchase order. I implement the method in Workshop by accepting a DOM node for the document, a string for the poNumber, and an integer for the supplier code: ative XML databases typically J2SE outperform relational ON databases when it comes to storing and retrieving XML” “ warehouse will focus on certain types of inventory more regu- public void requestShipment( Node doc, String poNumber, larly than others, which means the population of users is con- int supplier ) throws Exception J2EE stantly shifting. The warehouse exposes the ability to request an order via a message-based Web service. I’ve chosen to This method needs to store the purchase order somewhere implement this example using the beta version of BEA and then begin the process of filling the order (checking WebLogic Workshop. inventory levels, etc…). Since these processes will need to As you can see in Figure 1, the Web service has a few meth- refer to the particulars of the purchase order, it would be ods: checkAvailability(), which finds out whether an order can unwieldy to write parsing code to handle so many different be filled with current inventory, and requestShipment(), which types of documents. A cleaner approach is to convert each

Home starts an order process. For now we can ignore shipNotice(), incoming purchase order into a “canonical” format and oper- Oracle which is a callback when the order is ready to be shipped. ate only on those documents (see Figure 2). Suppliers will invoke the requestShipment() method via Let’s examine the requestShipment method in detail (see SOAP invocations. The signature of the requestShipment() as Listing 4). First the code takes the incoming purchase order seen in Workshop is shown in Listing 1. (Listings 1–5 can be and serializes it into an XML string using Apache’s downloaded from www.sys-con.com/java/sourcec.cfm.) org.apache.xml.serialize.XMLSerializer class. This string is This service lets suppliers provide their own identifier then passed to the XML database’s createXMLFile method. I’ve Corporation (), an identifier for their purchase order (), and, finally, the purchase order itself (). The the XML database. I’ve “wrapped” a subset of the XIS’s API using a Web service control named XMLDatabase. This is a technique specific to Workshop and lets us keep the database- www.oracle.com/ad specific API out of our Web service code. The XIS presents a filesystem metaphor for storing XML in folders and docu- ments. The createXMLFile() method takes an XML database name as the first parameter (“Warehouse”), a path to the file- name indicating where to store the XML (using the PO num- ber as the filename in the “incoming” directory), the XML string itself, and finally an argument indicating whether or not to trim white space. Once the original purchase order is stored in the database, the method can perform a transformation to a canonical for- mat. The XSLT stylesheet to use for this transformation is cho- sen based upon which supplier number was received. The transformed purchase order document is returned by the applyTransform() method as a string that’s also stored in the database, this time in the “toBeShipped” directory. The code then invokes the processOrder() method (the details of which I have omitted for brevity) that starts the busi- ness process of filling this order. Once the system has started processing the order, it can make the callback to issue the ship notice for the client. One detail I have not discussed is how to write the XSLT that transforms the Acme and BigRetail purchase orders into our canonical format. These stylesheets are not terribly complicat- FIGURE 2 Handling multiple partner documents using XSLT ed to write, however, they can be rather tedious to construct.

20 JULY 2002 JULY 2002 21

Java COM Java COM cessing to an external entity, this Web service can be used by many suppliers simultaneously without concern for mem- ory consumption issues. Unlike an in-memory XSLT processor, the database server will process large docu- ments, not the application server hosting the Web service. For extremely large (multimegabyte) documents, this can have a profound effect on scalability.

J2ME 4. Extensibility is preserved: For example, if BigRetail decided to change the element to include children (for instance ), this could cause major code changes at the warehouse. To make matters worse, if ransformational Web services can J2SE be easily constructed by leveraging “ OT the strengths of a native XML database and XSLT”

The XIS comes with a tool called Stylus Studio that helps build BigRetail expected that the warehouse would respond with stylesheets visually. Figure 3 shows the XML mapper in Stylus an XML invoice using the same element-child structure, J2EE for the Acme purchase order; Listing 5 is the resulting XSL the impact to the code could be widespread. By localizing stylesheet code. These tools can be helpful for large documents the XML transformations into XSLT, such extensions are with many processing rules; however, for simple documents, quickly handled in a single spot without massive code hand-coded XSLT can be more than adequate. changes. There are several benefits to using an XML database as the 5. Knowledge can be gleaned from a supplier’s behavior: intermediary for these types of Web services: Related to the first point on persistence, because everything 1. Everything is persistent: Every business document is pre- is retained by the system, reports and analysis can be per-

Home served in the database in the event of a system failure. This formed on the purchase orders to gain knowledge about the Precise includes the supplier’s original purchase order that can be business. For example, if a particular supplier is repeatedly referred to as needed if there is a dispute or question after requesting the same item during the same week each an order has been shipped. month, you might want to target that supplier with dis- 2. The Web service does not get involved in transformations: The counts on related products the week prior to help increase role of the Web service is straightforward and does not change sales. Without retaining this information, such opportuni- much when a new supplier is brought on board. The way I ties would be lost. Software have coded, the requestShipment() method would require a new case statement to be added for a new supplier. However, Summary even this could be parameterized by storing the stylesheet Transformational Web services can be easily constructed by names in the database keyed by supplier identifier. leveraging the strengths of a native XML database and XSLT. www.precise.com/jdj 3. Scalability is greatly enhanced: By offloading the XSLT pro- This architecture lends itself to building Web services that adapt to new types of incoming messages and are tolerant of change. While the previously discussed example involving process- ing purchase orders is relatively simple, you can imagine more complex Web services that rely on the transformational power of XSLT and the persistence of an XML database. For example, imagine a Web service that provides a unified view of a loan application, taking financial information from a variety of banks and institutions for an individual and providing most of the application prepopulated. Another example might be a Web service that acts as a middleman and clearinghouse for exchanging documents pertaining to complex legal transactions. It would be nearly impossible to provide an infrastructure for such services with- out the flexible storage and transformation facilities provided by XSLT and a native XML database.

AUTHOR BIO Bill Dettelback is a systems architect with eXcelon Corporation. Prior to joining eXcelon, he worked as a senior member of the technical staff at AT&T building AI-based customer care applications. Bill holds a BS and an MS in computer science from the New Jersey Institute of Technology.

FIGURE 3 XML to XML mapping in Stylus Studio [email protected]

22 JULY 2002 JULY 2002 23

JJavaava COMCOM Java COM Home J2EE J2SE J2ME 24 J ULY VAN RTE BY WRITTEN Programming Restrictions 2002 L R EANDER OOIJEN of programming. However, there are developers willbe exposedtothislevel restrictions duetothefactthatfew won’tarticle elaborate onthesetypesof ServerSocket are rarely used,and this of changing thesocketfactory tions. ch18, EJB2.0ch24)listthese restric- environment (EJB1.1 of theruntime to theJava developer. The specifications tain features thatare available normally This meansthere are restrictions oncer- work provided by theEJBspecification. expected tooperate withintheframe- tiple vendors, theEJBdeveloperis across containersfromportability mul- comesatacost. services To ensure Programming Restrictions resources provided by it. only withthecontainerand es, it’s thattheEJBinteract mandatory component withtheselow-level servic- and datacaching. To provide theEJB handling, security, exception handling, such asinstancepooling,transaction sible forallthesystem-levelservices, the environmentcontrolled called runtime EJB componentsmustoperate withina tem-level services. To achievethisthe and shieldhimorherfrom complexsys- concentrate businesslogic onwriting simple: lettheapplicationprogrammer Some restricted features suchas Not system-level havingtowrite The conceptbehindtheEJBAPI is container . This containerisrespon- forms withoutrecompiling oralteringthe source code. EJB componentcanbebuiltonceandthendeployed ondifferent plat- by theEJBspecificationisundoubtedly amajorfactorinitssuccess.An runanywhere”out theindustry.The philosophy embraced “write once, hasseenawidespread theEJBtechnology acceptancethrough- then, Since architecture underthenameofEnterpriseJavaBeans (EJB). I n 1998Sunintroduced theirdistributedserver-side component is acorrect assumption;however, the If you’re operating within one JVM,this your instancestoaccessthesame field. youstatic field(classvariable) expectall codingroutines.normal When usinga the greatest impactonaprogrammer’s enterprise beanclassbedeclared asfinal. ommended thatallstaticfieldsinthe itisrec- Therefore, static fieldsisallowed. Using read-only read/write staticfields. restrictions. container are subjecttothesame withinthe hence allclassesthatrun withinthecontainer,components run component. This is wrong. The EJB not thehelperclassesusedby theEJB withintheEJB’sthey write classesand these restrictions applyonlytothecode EJB programming. Many believethat one ofthegreatest misconceptionsin restrictions, it’s to clearup important violating therestriction. approach toreaching your goalwithout possible I’ll alsoincludeanalternative the reason fortherestriction. Where toexplain same asthe1.1spec)andtry the EJBspecifications2.0(almost programming restrictions asdefinedin niques. impact onyour usualcodingtech- restrictions thatcanhaveasignificant This restriction issimplebutithas An enterprisebeanmustnotuse Before divingintothedetailsof In I’ll statesomeofthe thisarticle EJB SPEC2.0 in EJBDevelopment Building scalable androbust nonblocking and read-only and service EJBenvironments.in distributed Singleton shouldnottobeused pattern and faulttolerance, Ibelieve the architecture isallaboutloadbalancing single pointoffailure. Since theEJB container, and thatmeansintroducing a EJB wouldby inasingle definitionrun contend with.Furthermore, aSingleton you stillhavetheconcurrency issueto be dealingwiththesameinstancebut implementation thatworks. You might problem, butIhaven’t seenafoolproof reference toyour instancecansolvethis Some argue thatusingaJNDItostore a when theuseofstaticfieldsisrestricted. class inthewholeapplication)anEJB (oneinstanceofaparticular pattern mers ishow toimplementtheSingleton will now beconsistent. initialized, andinstancesacross allJVMs field cannotbechangedafterithasbeen declare ittoberead-only. Afinalstatic able (more onthislater). synchronization mechanismsare avail- threading API isalsorestricted, sono the EJBspecificationuseof rent accesstothestaticfield,becausein addition, there’s theproblem ofconcur- no longerreference thesamefield.In instances oftheEJBandthese Now eachJVMcontainsoneormore orload-balancingreasons.performance multipleJVMsfor canrun EJB server If you wanttouse aSingleton fora One problem facingmanyprogram- To useastaticfieldyou’ll haveto enterprise applications J ava COM J ava COM AccelTree www.acceltree.com J ULY 2002 25 EJB SPEC 2.0

use the classloader. The container has granted the classloader permission to use the java.io package, therefore it’s According to the possible to use the getResource() or getResourceAsStream() method defined in java.lang.Class to load in a file.

J2ME specifications the file “ When using a file system it’s best to access it through a resource manager system is not an appropriate the same way you use the javax.sql.DataSource connection factory mechanism to access data to obtain a connection. To gain access to a resource (any entity that can be accessed through a URL string) use a it’s not a problem having one instance in java.io operations so the container has JNDI lookup to get a handle to the J2SE each JVM or for each deployed ejb-jar’s no control. Now if an EJB uses files on a java.net.URL object and use it to obtain classloader, then the use is warranted. system with heavy client loads, there’s a URLConnection. By using this mecha- An example of these services is the the chance of running out of file nism to access a file, the resource is caching of data retrieved through descriptors and bringing down” the sys- decoupled from the application code expensive JNDI calls. You just have to tem. using the resource. For the application realize that it’s not a Singleton in the Java developers are accustomed to that’s using the resource, there’s no dif- classic form and use it accordingly. using property files in their applications ference between the local file system because they’re helpful in specifying and one located on the opposite side of An enterprise bean must not use configuration settings. A simple mecha- the world. J2EE thread synchronization primitives to nism within EJBs called environment To achieve the flexibility and scala- synchronize execution of multiple entries provides these parameters. These bility of using a resource manager for instances. environment entries are placed in the URL entities, a resource manager must deployment descriptor and consist of a be set up in our application server. The As mentioned before, the same EJB name, type, value, and description. The method to declare a resource manager is can be run in different JVMs. It’s up to type can be any of the seven primitive vendor-dependent, so consult the con- the container to take care of the object’s wrapper classes (Integer, Boolean, etc.) tainer’s documentation. Once this is

Home life cycle and any concurrency issues. or a String object. The entries are done, all that remains is adding an entry Therefore, declaring an EJB compo- retrieved through the bean’s environ- in the deployment descriptor of the nent’s method to be synchronized is a ment, naming context. The following bean and the application can use the violation of the specification. The utility code provides the deployment descrip- resource. The following code provides Altoweb classes used within the EJB, such as the tor of an EJB: the deployment descriptor of an EJB Collection classes, are allowed to use the using a URL resource: synchronized keyword on its methods or blocks of code because these are all www.altoweb.com dealing with single instances. … YourBeansName … An enterprise bean must not use the … YourBeansName AWT functionality to attempt to output … information to a display, or to input the example environ information from a keyboard. ment entry< description> the URL of the entryname This one is obvious. The whole con- entry-name> url/TheResourceURL cept of separating the GUI layer from the business logic layer is compromised type>java.lang.String java.net.URL if direct interaction is permitted. Most entry-type> Container EJB servers will allow you to print to the myValue screen from within the container, which entry-value> can be useful at times during the devel- opment process (debugging, etc.); how- ever, it should not be required in a pro- To retrieve the resource in your code duction system. use: To retrieve the entry in your code An enterprise bean must not use the use: Context ctx = new InitialContext(); java.io package to attempt to access files java.net.URL url = (java.net. and directories in the file system. Context ctx = new InitialContext(); URL)ctx.lookup Context env = (Context)ctx.look- ("java:comp/env/url/ According to the specifications the up("java:comp/env"); TheResourceURL"); file system is not an appropriate mecha- String myValueString = java.net.URLConnection conn = nism to access data. Since file systems (String)env.lookup("entryname"); url.openConnection; are not transactional by nature, it’s a //Now create an input stream for valid argument. Another problem is that A legal method to read information reading there’s no resource manager involved in from files within an EJB component is to java.io.InputStream is =

26 JULY 2002 JULY 2002 27

Java COM Java COM EJB SPEC 2.0

Conn.getInputStream(); responsible for managing all access to text, or any other required parameter // or an output stream for writing to the EJBs. By intercepting all method from the request. If an EJB were to create the resource calls on the entities, the container can new threads, the required information java.io.OutputStream is = use the Java 2 platform security policy might not be propagated correctly to the Conn.getOutputStream(); mechanism to prohibit certain func- new thread, potentially causing serious tionality. To be able to perform this the errors.

J2ME An enterprise bean must not attempt container must have a stable execution Not having to manage threads is a to listen on a socket, accept connections environment that it creates by using a relief for most developers, but not being on a socket, or use a socket for multicast. set of classloaders and security policies. able to use custom threads has its draw- If we were to make runtime changes to backs. For example, if you have a bean that In other words, an EJB is not allowed them, the container would lose control needs to query different multiple external to act as a network server. This makes over the execution environment and systems (ERP, legacy, etc.), it will have to be sense since clients are supposed to con- security could not be guaranteed. done in a series. Since these systems will nect to the EJB using a specified remote take time to process your request, the time J2SE protocol that’s in-line with the imple- The enterprise bean must not attempt spent waiting can add up. mented security permissions. When a to manage threads. The enterprise bean If you could use threads, you would client uses a socket to connect to the must not attempt to start, stop, suspend, be able call these requests in parallel, sig- EJB, it’s a potential security hole. This or resume a thread; or to change a nificantly reducing the overall time need- does not limit the use of a network sock- thread’s priority or name. The enterprise ed to process your request. There’s talk of et client from within your EJB. An exam- bean must not attempt to manage thread introducing a limited threading model ple of such a socket client is a stateful groups. into the EJB architecture, and it will most session bean that queries an existing likely be in the form of an EJB retrieving a inventory system that can be accessed The reason for not being able to sus- thread from a thread pool managed by J2EE only through a TCP connection. pend, resume, start, stop, or create new the container. No threading mechanism threads again has to do with the con- has been mentioned in the EJB 2.0 speci- The enterprise bean must not attempt tainer’s ability to control the runtime fications, so it could still be a long way off. to query a class to obtain information environment. When dealing with a high- about the declared members that are not transaction environment, performance The enterprise bean must not attempt otherwise accessible to the enterprise is an important issue. If there’s no strict to pass this as an argument or method bean because of the security rules of the management of resources, like the use result. The enterprise bean must pass the

Home Java language. The enterprise bean must of threads, there’s a good chance that the result of SessionContext.getEJBObject(), Improv not attempt to use the Reflection API to application will use too many resources SessionContext.getEJBLocalObject(), access information that the security rules and slow the system down to unaccept- EntityContext.getEJBObject(), or Entity- of the Java programming language make able levels. Or worse, the server is no Context.getEJBLocalObject() instead. unavailable. longer able to serve client requests. Thread-specific storage is another The life cycle of all bean instances is One feature provided by the EJB problem with using the threading API. managed by the container. That’s why Technologies architecture is a security model. It’s pos- For an EJB container to do its work we always access the bean through the sible to declare programmatic or declar- properly, it needs to track information EJBObject, never directly. The container ative security roles on methods that can for the current request. In a system with can activate or passivate a bean at any be called by clients. These clients must thousands of simultaneous requests time, and the client is never aware that www.iimprov-tech.com/jdj/download have a required role to be granted per- being processed, it’s important to have this is taking place. While a client has a mission to invoke the method. By using an efficient and manageable way of get- reference to the EJBObject, the contain- the reflection API, it’s possible to bypass ting at the required information. er can passivate the actual bean these security restrictions and invoke Since the Java 2 platform, there’s a instance. When the client invokes a methods that you should not have class called java.lang.ThreadLocal for method through the EJBObject, the con- access to. Any other use of the Reflection storing information associated with a tainer intercepts the call and performs API is unrestricted. specific thread. Most container vendors tasks such as activating the bean and use a single thread dedicated to servic- reassociating it with the EJBObject. The enterprise bean must not attempt ing a single request, and hereby they can This programming restriction is ques- to create a classloader; obtain the current use the ThreadLocal class to store the tionable when you’re dealing with helper classloader; set the context classloader; current user, transaction, security con- classes. Since the helper classes execute set security manager; create a new securi- ty manager; stop the JVM; or change the input, output, and error streams.

This basically states that you are not Not having to manage threads is allowed to alter the runtime environ- ment of the container. In enterprise a relief for most developers, but applications, security is one of the most “ important issues, and the security man- not being able to use custom agers and classloaders are at the root of protecting applications from unautho- threads has its drawbacks rized access of the runtime entities. Again, the EJB architecture has dealt with security by having the container be

28 JULY 2002 JULY 2002 29 Java ”COM Java COM EJB SPEC 2.0

only while the bean is active, theoretical- ly, the use of the “this” reference should not cause any problems when used in this manner, but Sun Microsystems The EJB technology has put the might want to clarify the issue. building of scalable and robust J2ME In Practice “ Most programming restrictions are enterprise applications within reach of clear and concise, but a few restrictions are open to interpretation. This is prob- a great number of Java programmers ably why not all containers enforce these restrictions rigorously. The con- tainer from the J2EE reference imple- mentation throws SecurityExceptions J2SE when the restrictions are violated. Many that you should stick to the specification ity to reuse generic components that commercial EJB servers, such as BEA’s not just because of the portability issue, have been tested and proven to work WebLogic and IBM’s WebSphere, don’t but because reliability can also be across multiple EJB servers can save you seem to enforce a lot of these restric- affected. Unfortunately, reliability prob- significant amounts of time. ” AUTHOR BIO tions. These servers are still valid imple- lems always become apparent near the The EJB technology has put the Leander van Rooijen mentations because according to the end of the development phase when building of scalable and robust enter- is a senior EJB specifications, the container may there’s little time left. If it turns out that prise applications within reach of a great consultant for Cap allow more or fewer permissions to the some components need to be reengi- number of Java programmers. Un- Gemini Ernst & enterprise bean instance, which can neered because they violate the pro- fortunately, a number of EJB developers J2EE Young in the prevent portability across different con- gramming restrictions, it will be a lot have never read the specifications and Netherlands. A Sun tainers. more time-consuming to fix them than are unaware of all the programming Certified Java When developing EJB components to verify them against the reference restrictions. Hopefully, this article has developer, he’s a it’s best to test them against the refer- implementation from the start. cleared up some issues that Java devel- specialist in ence implementation to verify that they One more reason to adhere to the opers face during their road to profi- server-side conform to the specifications. Un- programming restriction of the EJB cient EJB development. Just remember, technology. Leander fortunately, most development projects specification is reuse. When you’re in the EJBs are only portable if you write them

Home holds a degree in are governed by strict deadlines and business of building solutions for your that way. Jinfonet mechanical portability is not always at the top of the clients, you’ll undoubtedly deal with EJB [email protected] engineering. list. However, some developers forget servers from multiple vendors. The abil- Software www.jinfonet.com/JDJ7.htm INT, Inc www.int.com

30 JULY 2002 JULY 2002 31

Java COM Java COM IBM IBM www.ibm.com/websphere/winning www.ibm.com/websphere/winning

32 JULY 2002 JULY 2002 33

Java COM Java COM IBM IBM www.ibm.com/db2/rocks www.ibm.com/db2/rocks

34 JULY 2002 JULY 2002 35

Java COM Java COM S H O W D O W N Are You Readyto Rumble? J2ME .NET vs J2EE Smackdown J2SE There is a raging debate in the developer community: Microsoft’s new platform .NET versus the Sun standard J2EE. J2EE WRITTEN BY has been around for a few years, while Microsoft’s attempt is decid- MICHAEL DEASY edly the new kid on the block.

While the comparisons may be Weapon” Daly. They were all seasoned lot of invective and vitriol, and the defined by some as purely technical, veterans of the software Ring Wars, and intention of making this debate about some have deemed it a battle of corpo- brought with them their colorful styles the stark differences in their corporate J2EE rate cultures. Sun has certainly chosen and insights. Microsoft chose “Eye of the cultures and goals. to consider that the battle. Tiger” (from Rocky III) as their theme The debate began with five-minute During a lunch discussion with my song, and as it poured out of the speak- introductions. Microsoft came on first, fellow officers in the Tulsa Java User er systems they came proudly down the providing a somewhat detailed and very Group, we explored the issues. We also aisle of the theater, their Microsoft colorful blanket overview of .NET. They decided to see if we could get some logo’d button-down finery on display. gave a strong summary of what their vendors to come in and discuss the Sun chose an old Sly and the Family systems could do, how they connected

Home issues from both perspectives. This Stone song “Freedom” as their mantra together, and what we had to gain from expanded into a formal debate, and and came boldly to the stage during their use. thus the .NET vs J2EE Smackdown was their song. Sun came out with a copy of “the law- born. Our group started to plan this The rules for the Smackdown were as suit” and began talking about the differ- ESRI event; we contacted Microsoft and Sun follows: eight questions that each team ences between the corporate cultures at and both sides were more than willing had to answer; they were required to Microsoft and Sun. They said, “Point of to engage. give software examples, state their case fact…” and then quoted the lawsuit On April 25, 2002, in the Williams clearly, and show their stuff. Both teams regarding Microsoft’s predisposition for www.esri.com/mapobjectsjava Theater in downtown Tulsa, Microsoft had the questions ahead of time and disposing of the competition and using and Sun came together on one stage had veto rights over anything they unfair trade practices. There was not (together again, for the first time any- deemed unworthy. Each team had five much in the way of information about where) – and the battle was joined. The minutes to present their case, then the J2EE. officers of the JUG decided to consult other team had a five-minute rebuttal. with the officers of the PBUG, and we They each had two yellow cards to raise Top Questions from Our Home Office held the meeting as a joint venture – as penalties on the other side if they in Enid,Oklahoma… sponsored by both user groups as well as deemed a question worthy of an imme- The following are the questions posed Oaktree, Inc., a consulting company that diate, two-minute rebuttal. It goes with- to each side and the approximate sponsors our groups extensively. We had out saying that these two teams pulled responses. two podiums, many microphones, LAN their cards and used the maximum on 1. What sets your platform apart from connections, and team theme songs. It each and every question. that of your competitor? was exciting to watch as over 200 people The crowd was eager for the words, Microsoft talked about the speed with filled the theater to see the Tulsa lines of code, and interfaces to fly, and which they could deploy their product, Smackdown, to find out what this so we began with introductions, prizes, the multiple language and platform debate was really about. and a lot of good cheer, then the debate independence of .NET, and how easily began. integrated it could be. What If They Held a Raging Debate and Sun talked about customer service, Nobody Showed Up? Two Companies Separated by a Common Coast feeling a warm commitment from your Microsoft and Sun showed up in Sun and Microsoft brought some of vendor, and avoiding the evil demons force. Microsoft sent three of their tech- their strongest speakers and came with that live in the Seattle area. They also nical evangelists: Mark “The Doctor” a sense of anticipation that reportedly talked about unfair trading practices McLoughlin, Dave “Brick Wall” White, went far up the chain in their respective and monopolies. and Dino “Hannibal” Ciesa, while Sun corporate worlds. And both came with sent a team of four of their faithful (and their own specific agenda. Microsoft 2. CMP TechWeb defines the term Web faith spreading): Bill “The Liberator” came intent on showing a room full of services as “Web-based applications that Day, Max “The Preacher” Goff, Rima programmers what their product can do dynamically interact with other Web “The Instigator” Patel, and Tom “Secret and how truly RAD it is. Sun came with a applications using open standards that

36 JULY 2002 JULY 2002 37

Java COM Java COM S H O W D O W N

include XML, UDDI, and SOAP. anyone who didn’t choose what he con- Microsoft did a similar slide presenta- Microsoft’s .NET and Sun’s J2EE are the sidered the slower but stronger path to tion and was frustrated by the lack of a major development platforms that growth and money by learning Java. mini camera to display their phone natively support these standards.” What Addressing a room full of analysts and screen. They did a decent presentation, is your platform’s level of support for Web developers with regard to learning skills but again, because they chose to demon- services? Can you show us using your quickly and becoming more profitable, strate their technological capabilities,

J2ME platform and tools? he could have chosen his words differ- point and set to Sun on this question. Microsoft created a Web service, ently. Also, the path to quick money deployed it, and brought data in from a does not typically lie in the use of tools. 7. The cost of development, deployment, database with a few simple keystrokes. Java does have a huge market share and maintenance significantly impacts They had to uncomment some code in advantage; perhaps they don’t have a software development projects. How does predeveloped areas, and it took a few ready-made platform for their tools, but your platform stack up in terms of these seconds for the data to return their no one in the room doubted that they had costs when compared to your competi- request across the Web, but it was an the upperhand in this phase of the dis- tor’s platform? J2SE extremely impressive demonstration. cussion. They simply chose, again, not to The question of cost caused a rousing Sun did show some slides on this one, present the strong things that they could debate, and as time was running out we and brought up lists of powerful clients do. They continued railing about too made question seven the last of the they had serviced or who had used Sun’s much filthy lucre in the Microsoft camp. Smackdown. products. Microsoft had some very strong points 5. Security is becoming increasingly about the cost of their server software 3. Designing and constructing a multi- more important to organizations. and .NET platform in general – bringing tier transactional Web-based application Explain your platform’s security infra- their totals in at under $10,000 for a well- to support hundreds (if not thousands) of structure and how it differs from your equipped enterprise tool. They were very J2EE simultaneous users is a very daunting competitor’s platform. critical of Sun and BEA for the costs of task. How does your platform address This question was really Sun’s chance servers and O/S software, quoting num- these complexities and empower organi- to shine. Sun began with a lot of facts bers in the hundreds of thousands and zations to build such applications quick- and figures about Microsoft’s security tearing into their opponent a bit. ly and with minimal expense? Can you issues. This has been pretty widely dis- Sun retorted with a strong presenta- show us using your platform and tools? seminated in the press and Microsoft tion touting both Linux and Apache as Sun approached this with some very quickly confessed that they had indeed free and J2EE-compliant. They attempt-

Home strong examples of Web sites they built been working very hard at bringing ed to demonstrate this with slides, Canoo or support involving hundreds and/or themselves up to speed. This also led to which was interesting. However, the Sun thousands of users. The most impressive an argument over who had raped the Pet sales reps are not pushing Apache or was probably the ESPN Web site, a site Shop application most thoroughly. Both Linux – they’re driving the market that definitely has a huge fan base. They sides did a lot of finger pointing, and toward their O/S, their flavor of UNIX. did give an example of how to throw they both pointed to a number of bench Microsoft held the advantage in this connectivity together very quickly; tests. piece of the debate and so our competi- Engineering AG unfortunately, it never did load. Microsoft and their failing Passport tion came to a close. Microsoft again showed some system did have a decided disadvantage PowerPoint and explained how .NET on this question. While it may be true In the final analysis, both teams made can be made more flexible. There was no that you don’t have to use Passport, it’s a strong showing. The general consen- www.canoo.com/ulc/ time for either contender to get into a very difficult to get around in a lot of Web sus was that Microsoft did a better job of whole lot of detail but they both showed areas without it. It does seem like anoth- showing off their technological capabili- good examples. er area where Microsoft was attempting a ties. They used more samples, and their coup. Big points to Sun on this question. actual program examples were breath- 4. Many of our audience members are taking. There was a bit of disappoint- software developers who are constantly 6. Gartner estimates that there will be ment in Sun’s approach – attacking looking to hone their skills and learn the 901 million mobile phone users world- Microsoft’s character – and any time latest technologies. Ultimately, each one wide by 2003, while Palm, Inc., continues they used their technology to advantage of us will try and decide which platform to report record sales of their Palm Pilot they looked very strong, probably will produce the most marketable skill handheld. In short, handheld devices are stronger and older in their product life- set. Do you think your platform offers the here to stay and the market is expected to time. most marketable skills and if so, why? experience continued growth. Does your The various camps gathered around This question brought about surpris- platform support the development of the myriad reps out front and collected AUTHOR BIO ing and unexpected responses. mobile clients? If so, provide the details. trinkets into their bags: pens, books, and Michael Deasy worksMicrosoft gave a two-minute talk on This question saw great presentations T-shirts. The Microsoft crowd was very in the Seattle area ashow to leverage your current skill set from both sides. Sun had programs they pleased with their presentations, and a project manager,and make use of your C++ and Visual had written, then downloaded into their the Sun crowd felt very vindicated and Web designer, and freelance writer. HeBasic knowledge. They addressed their cell phone during the presentation. The righteous. It was a strong event on the has been workingtraining program and the wide availabil- ease with which the tech displayed whole, educating at times, frustrating at with PowerBuilderity of classes and skill-building tools, movie sites for Tulsa, letting us all know others. No matter whose side you might since version 3. Mikefrom online to college classes. what was showing at the AMC 20, was fall on though, you got to see some holds an MBA from Southern Nazarene Sun took the stance that if you decid- very cool. It was not really clear how this sparks and hear a couple of major play- University.ed to become a .NET developer, you was directly J2EE-related. But he did ers tell their tale. were just in it for the quick buck, the show a lot of slides regarding their flexi- easy money. The speaker was critical of bility with many phones. [email protected]

38 JULY 2002 JULY 2002 39

Java COM Java COM J2SEJ EDITORIALOR J2SE INDEXX

Learning from History JASON BELL J2SE EDITOR There’s no escap- ing that the evolution of pro- gramming languages has its advantages and disadvan- tages. And I believe it’s time 40 Learningfrom History for us to ask ourselves hon- estly how our own evolution J2SE is progressing. Are we con- stantly learning or are we stuck in a loop? Evolution: A gradual process in which something changes into a different and By Jason Bell usually more complex or better form.

Hello World! in 70 Bytes here’s no escaping that the evolu- that certain artists are being influenced by The Austin Java tion of programming languages other artists. You’ll always have pioneers, User Group recently spon- Thas its advantages and disadvan- however. The Beatles were musical pio- sored a contest to create the tages. The addition of the java.util.regex neers and a multitude of bands have since smallest Java Hello World! package to the JDK1.4 API is a perfect been influenced by them. program. The rules were sim- example of Java’s development since 1995. There are parallels we can draw on as ple: create the smallest Java However, there’s a group of programmers Java programmers. We study the APIs and class that when executed will who know only Java and no other lan- try numerous examples and routines to display the text “Hello World!”

Homeguage, so J2EE it’s difficult for them to see why satisfy J2ME ourselves that we have grasped the (and only that text) to the things like regular expressions are includ- concept so when the time arises, we can console. In this article, I 44 ed. It all boils down to how your own transfer our knowledge to the situation at explain how I arrived at my career evolved. hand. The success of any musical per- 70-byte solution and hope Parasoft My own personal evolution is a stran- formance is based on the ability of the that in the process you learn gled route through a number of languages: performers to interpret a piece of music; a bit about Java class files Perl, Unix shell scripting, C, and PHP. I the success of any Java project is based and the Java Virtual Machine. added Java to my skillset halfway through, the ability of the programmers to inter- I also urge you to take the www.parasoft.com/jdj7 and I was constantly trying to adapt my pret the requirements of a project plan. challenge before viewing my thought patterns from Perl to Java code. Where does our programming history solution. After many late nights trying to get things come from? Well, there’s plenty of informa- by Norman Richards to work in Java, it all paid off in the end. tion available on the Internet, mailing lists, However, I always wondered why the Java books, CDs, as well as from your colleagues. API didn’t have any regular expressions. Have you ever searched Google, for ZX Spectrum Emulator Until I found third-party packages, such as example, in an attempt to solve that illu- in Java gnu.regexp and OROMatcher classes, I sive problem, and then been presented Recently, I embarked on a always went back to Perl and completed with seven different ways of dealing with project to write an “emula- the job that way. it? We need to easily pick out the dia- tor” (in Java) that could run I believe that it’s time for us to ask our- monds from the dust, the documents that some favorites from the pro- 50 selves honestly how our own evolution is will encourage and educate people who lific library of Spectrum soft- progressing. Are we constantly learning or need it the most. What are we doing to lay ware. This article is about the are we stuck in a loop? this foundation down for future program- challenges encountered and Musicians spend hours perfecting their mers? my accomplishments during skills by practicing scales and arpeggios this adventure. and familiarizing themselves with their Site References by Razvan Surdulescu instruments. Before any musician joins an • Dictionary.com: www.dictionary.com orchestra (or a garage band for that mat- • JDK1.4: http://java.sun.com/j2se/1.4/ ter), he or she needs to achieve a certain • OROMatcher classes: http://jakarta. skill level. apache.org/oro/index.html Musicians also have access to history, • gnu.regexp package: www.cacas.org/ and as seasons come and go you’ll notice java/gnu/regexp/

[email protected] AUTHOR BIO Jason Bell is a programmer based in York, England. He has been involved in numerous Web projects over the past five years, the last two of which have been servlet-based.

40 JULY 2002 JULY 2002 41

Java COM Java COM New Atlanta New Atlanta Communications Communications www.newatlanta.com www.newatlanta.com

42 JULY 2002 JULY 2002 43

Java COM Java COM JAVA CLASS FILES Hello World!in 70 Bytes Take the challenge

The Austin Java User Group recently sponsored a contest to create the smallest Java Hello World! program. The rules were J2SE WRITTEN BY simple: create the smallest Java class that when executed will dis- NORMAN RICHARDS play the text “Hello World!” (and only that text) to the console.

The restrictions were that the class default. Debugging can be disabled with First Steps must execute under Sun’s 1.3 JRE. It may the “-g:none” option to reduce the byte To have maximum control over what make use of any class or file distributed count to 336 bytes, but to go much further goes in the class file I decided to gener- with the JRE, but any additional files we have to look at exactly where those ate the class file directly. Normally a tool (excluding arguments on the command bytes are going. such as Jakarta Bytecode Engineering line) count against the byte total of the Figure 1 shows the basic compo- Library (BCEL) would be the best choice Java class file. nents of a Java class file. In the initial to generate the class, but in this case I In this article, I explain how I arrived Hello World program, as with most Java wanted maximum control (and under- at my 70-byte solution. I hope that in the classes, the bulk of the bytes come from standing) of each byte that goes into the process you learn a bit about Java class the constant pool. The method declara- class file. files and the Java Virtual Machine. I also tions are the next largest chunk, but My first attempt was to simply gener- urge you to take the challenge before most of the information used in a ate a basic Hello World program, mini-

Home J2EEviewing my solution. J2ME method declaration is stored in the con- mizing constant pool references and stant pool. Table 1 shows the constant removing any unnecessary portions of Getting Started pool from the first class. the class. There are three main steps. Let’s first look at the canonical Java Note that the constant pool contains First, I wanted to make sure I gener- Macromedia Hello World! program. most of the details of our code. The class ated only the main method. When com- name and method names are all there as piling a class, the Java compiler will public class Hello are the names and types of all the exter- insert a default constructor if you don’t { nal classes, methods, and variables we specify one. However, this is only neces- www.macromedia.com/go/jrun4jdj public static void touch. Constant values (such as our sary if you need to create an instance of main(String[] args) “Hello World!” text) are included too. the class. If you just need to use the { Also, note that constant pool entries link main method, you don’t need to be able System.out.println to other constant pool entries. For to create an instance and can remove ("Hello World!"); } example, a method reference entry links the constructor. } to a class reference entry (which in turn Next, I wanted to inherit from an references a UTF8 text entry holding the already referenced class. Every class ref- Compiling this class with javac pro- name) and a name and type entry erenced in the class file requires entries duces a 416-byte Java class file. That’s quite (which links to the UTF8 text entries in the constant pool. I can remove the a few bytes just to print “Hello World”. Javac holding the name and the method sig- java.lang.Object constant pool reference generates debugging information by nature). I would normally get (remember, even if To realize how this is used, consider you don’t specify it in your Java source the Hello class expressed as bytecode code, your class extends java.lang with constant pool references indicated .Object) by specifying some other class by the number sign (“#”) and the con- already referenced in the class file. The stant pool index number. Don’t be choices were java.io.PrintStream and scared off by the bytecode. It’s not as java.lang.System. (java.lang.String is complicated as it looks. If you’ve ever used as a parameter only so we don’t programmed an assembler of any sort, have class information for it in the con- this should look quite natural. If not, stant pool.) Since java.lang.System is don’t worry. The important thing to note final and cannot be extended, the choice is that in terms of size, the actual byte- was java.io.PrintStream. code is very small (the constructor is 5 Finally, since the name of the class is bytes and the main method is 9) also stored inside the class file, instead because almost everything we do refer- of naming the class “ReallySmall- ences a field or class or constant defined HelloWorldClass”, I wanted to choose a in the constant pool, which is quite large name whose text is already in use in the FIGURE 1 Java class file (see Listing 1). constant pool. Some choices were

44 JULY 2002 JULY 2002 45

Java COM Java COM JAVA CLASS FILES

248 bytes. The following code # TYPE VALUE snippet shows the bytecode, 1 METHOD REFERENCE class=#6 signature=#12 and Table 2 shows the constant 2 FIELD REFERENCE class=#13 signature=#14 pool. 3 STRING CONSTANT value=#15 4 METHOD REFERENCE class=#16 signature=#17 public class Code 3: aload_0 5 CLASS REFERENCE name=#18 extends java.io.PrintStream 6 CLASS REFERENCE name=#19 ;; constant int value 0 { 7 UTF8 TEXT "" 4: iconst_0 8 UTF8 TEXT "()V" public static void main(String[] args) 9 UTF8 TEXT "Code" ;; get args[0] { 5: aaload 10 UTF8 TEXT "main" ;; System.out.print 11 UTF8 TEXT "([Ljava/lang/string;)V" ;; ("Hello World") 12 NAME/TYPE name=#7 type=#8 ;; invoke print 6: invokevirtual #15 13 CLASS REFERENCE name=#20 ;; get System.out J2SE 0: getstatic #13 14 NAME/TYPE name=#21 type=#22 sun.misc.MessageUtils9: return 15 UTF8 TEXT "Hello, World!" Even }at 231 bytes the class file is still ;; get the String 16 CLASS REFERENCE name=#23 quite} large. Most of the bloat is associat- ;; "Hello World!" 17 NAME/TYPE name=#24 type=#25 ed with retrieving the static field out on 3: ldc #18 18 UTF8 TEXT "Hello" java.lang.System and invoking the print

19 UTF8 TEXT "java/lang/Object" ;; invoke print method method on java.io.PrintStream. With 20 UTF8 TEXT "java/lang/System" 5: invokevirtual #16 that in mind, I scoured the JRE-provided 21 UTF8 TEXT "out" classes for code that would either get 22 UTF8 TEXT "Ljava/io/PrintStream;" 8: return System.out for me or print some given 23 UTF8 TEXT "java/io/PrintStream" } text to stdout. Fortunately, there is such 24 UTF8 TEXT "println" } a class, sun.misc.MessageUtils, that pro- 25 UTF8 TEXT "(Ljava/lang/String;)V" vides a static method “toStdout” that will print a string to System.out. Using TABLE 1: Constant pool for Hello World this, I can replace the static field refer- Hello Command Line ence (System.out) and the method invo-

Home J2EE J2ME Next, remove the “Hello cation (java.io.PrintStream.print) with # TYPE VALUE World!” from the constant one single static method invocation 1 CLASS REFERENCE name=#3 pool and pass it in as an argu- (sun.misc.MessageUtils.toStdout). Of 2 CLASS REFERENCE name=#10 ment on the command line. It course, since java.io.PrintStream is no /n software inc. 3 UTF8 TEXT "Code" takes 3 bytes (aload_0, icon- longer in the constant pool, a new 4 UTF8 TEXT "main" st_0, aaload) to reference superclass is needed. Fortunately, the 5 UTF8 TEXT "([Ljava/lang/String;)V" args[0] as opposed to 2 bytes MessageUtils class is now available to 6 UTF8 TEXT "Hello World!" to load a constant (ldc) string take on this job. Code to generate this www.nsoftware.com 7 UTF8 TEXT "java/lang/System" from the constant pool; how- class is in GenClass3.java. The resulting 8 UTF8 TEXT "out" ever, not needing to store the class file is 171 bytes. The following code 9 UTF8 TEXT "Ljava/io/PrintStream;" text in the constant pool frees snippet shows the bytecode, and Table 3 10 UTF8 TEXT "java/io/PrintStream" up two constant pool slots shows the constant pool. 11 UTF8 TEXT "print" and brings the total size 12 UTF8 TEXT "(Ljava/lang/String;)V" down to 231 bytes. Code to public class Code 13 FIELD REFERENCE class=#14 signature=#15 generate the class is in extends sun.misc.MessageUtils 14 CLASS REFERENCE name=#7 GenClass2.java. { 15 NAME/TYPE name=#8 signature=#9 The constant pool is similar public static void main(String[] args) 16 METHOD REFERENCE class=#2 signature=#17 enough to the first example that { 17 NAME/TYPE name=#11 type=#12 we can skip it, but keep in mind ;; toStdout(args[0]) 18 STRING CONSTANT value=#6 that some of the positions in the constant pool have changed. TABLE 2: Constant pool GenClass 1 ;; args The following is the new byte- 0: aload_0 code. ;; constant 0 “print”, “out”, and “main”, the names of public class Code 1: iconst_0 methods and fields referenced. I chose extends java.io.PrintStream ;; get args[0] “Code”, which is the constant pool tag { 2: aaload associated with the Code attribute in the public static void main(String[] args) method. The Code attribute is where the { ;; invoke toStdout bytecode that’s associated with the ;; System.out.print(args[0]) 3: invokestatic #9 method is stored. Code to generate this first class is in ;; get System.out 6: return GenClass1.java. (The source code and 0: getstatic #12 } Listing 1 can be downloaded from the } JDJ Web site, www.sys-con.com/java/ ;; args variable sourcec.cfm.) The resulting class file is

46 JULY 2002 JULY 2002 47

Java COM Java COM JAVA CLASS FILES

mand-line argument. Applet a class name. Unfortunately, there are # TYPE VALUE viewer will silently ignore the no other text fields to use in the con- 1 CLASS REFERENCE name=#3 input since it contains no stant pool. Since every class must have 2 CLASS REFERENCE name=#4 applet tags. The only drawback a superclass, and a class cannot be its 3 UTF8 TEXT "Code" to this is that “Hello World!” had own superclass, we have to add an entry 4 UTF8 TEXT "sun/misc/MessageUtils" to go back into the constant to the constant pool for the name. 5 UTF8 TEXT "toStdout" pool, bringing the solution up However, it turns out that the Sun JVM 6 UTF8 TEXT "(Ljava/lang/String;)V" to 194 bytes (see Table 4). Code allows for a class to have a zero length 7 UTF8 TEXT "main" to generate this class is in name, allowing us to keep the new con- 8 UTF8 TEXT "([Ljava/lang/String;)V" GenClass4.java. stant pool entry as small as possible. If 9 METHOD REFERENCE class=#2 signature=#10 this weren’t the case, we would have to 10 NAME/TYPE name=#5 type=#6 public class Code choose a name like “a”. extends sun.applet.Main The code to generate this class file TABLE 3: Constant pool for GenClass 3 { is GenClass5.java. The resulting byte- static { code is 70 bytes, consisting of four con-

J2SE ;; sun.misc.MessageUtils stant pool entries (two for the class ;; .toSdout("Hello # TYPE VALUE spec and two for the superclass spec) World!") 1 CLASS REFERENCE name=#3 and no fields, methods, or attributes 2 CLASS REFERENCE name=#4 ;; get String "Hello (see Table 5). 3 UTF8 TEXT "Code" World!" 4 UTF8 TEXT "sun/misc/MessageUtils" 0: ldc #9 extends 5 UTF8 TEXT "toStdout" sun.security.util.PropertyExpander 6 UTF8 TEXT "(Ljava/lang/String;)V" ;; invoke toStdout on { 7 UTF8 TEXT "" ;; sun.misc.MessageUtils} 8 UTF8 TEXT "()V" 2: invokestatic #10 9 STRING CONSTANT value=#12 Of course, we could throw out the 5: return 10 METHOD REFERENCE class=#2 signature=#11 } generated class file completely and sim- 11 NAME/TYPE name=#5 type=#6 } ply invoke Java with the class directly. 12 UTF8 TEXT "Hello World!" 13 UTF8 TEXT "sun/applet/Main" java sun.security.util.PropertyExpander Home14 CLASS J2EE REFERENCE name=#13 J2ME OPC – Other People’s Code 'Hello World!' TABLE 4: Constant pool for GenClass 4 Despite making the class file larger, this was still an impor- However, this wouldn’t be a legal Altova tant step. What I needed was to submission, so the 70-byte solution was # TYPE VALUE find a way to further leverage the best one I could come up with. 1 CLASS REFERENCE name=#3 hidden classes in the JRE. I’d 2 CLASS REFERENCE name=#4 already found a class with a Conclusion www.altova.com 3 UTF8 TEXT "" main method to use that did Although hacking class files doesn’t 4 UTF8 TEXT "sun/security/util/ nothing, allowing the static ini- have much practical relevance, I found PropertyExpander" tializer to do its magic, but what the challenge to be quite a lot of fun. And, I really needed was a class with even if you have never touched a class file TABLE 5: Constant pool for GenClass 5 a main method that would just or Java bytecode, the Hello World prob- print out “Hello World!” lem is small enough that you should be Apparently, that’s not such a able to gain a better understanding of Goodbye Main far-fetched idea. Nestled deep within how the internals of Java work. At this point, I began to lament the size Sun’s 1.3 JRE is sun.security.util.Property- of the signature of the main method – Expander with the following method: Acknowledgments “([Ljava/lang/String;)V”. I decided to try I’d like to thank Jeff Schneider and removing the main method entirely and public static void Momentum Software for devising the echoing the text in a static initializer block. main(String args[]) Hello World problem and the Austin “”, the internal name for the static throws Exception Java Users Group for sponsoring the initializer, is a few bytes longer than “main”, { contest. System.out.println( but the size of the static initializer’s method expand(args[0])); signature “()V” is much shorter than Resources } main’s. For this to work, I needed to find a • Java Virtual Machine Specification: class with a main method that doesn’t echo http://java.sun.com/docs/books/vm any text to the console to extend, so we still The expand() method doesn’t alter spec/ have an accessible main method. the text “Hello World!”, so we’re effec- • Jakarta Byte Code Engineering Library The shortest named one I found tively just printing args[0] by itself. As (BCEL): http://jakarta.apache.org/ AUTHOR BIO among the various JRE classes is long as we pass in the text “Hello bcel/ Norman Richardssun.Applet.Main, the main program for World!” as the first argument to the Java • Engel, J. (1999). Programming for the works at Commercethe Java applet viewer application. program, as we were doing earlier, we’re Java Virtual Machine. Addison- One Labs, theApplet viewer requires a command all set. Since there are longer methods Wesley. research division of Commerce One.input argument, but we can pass in the with bytecode associated with the class, class file name “Code.class” as a com- the text “Code” is no longer available as [email protected]

48 JULY 2002 JULY 2002 49

Java COM Java COM As a child I owned one of these machines, and because of it I am, happily, a computer scientist. Although the Spectrum is no longer produced, my nostalgia for this machine never quite disappeared. Recently, I embarked on a project to write an “emulator” (in Java) that could run some favorites from the prolific library of Spectrum software. This article is about the chal- lenges encountered and my accomplishments during this adventure. The source code can be downloaded from www.sys-con/java/sourcec.cfm. What Is an Emulator? According to Merriam-Webster an emulator is “hardware or software that permits programs written for one computer to be run on another usually newer computer.” Emulators are in relatively common use today, although they are invisible – J2SE a powerful testimonial to the fact that they do their job well. The Java programming language is popular in large part because it can run on many different computers. This is achieved via an emulator (a “virtual machine”) that allows Java programs to be executed on different platforms. Emulators are particularly satisfying to write. Building an emulator is challenging, since it requires an intimate under- standing of both the emulated machine and the host machine in order to bridge them together. Emulators are hard to get right since they require extensive attention to detail: every single facility of the emulated environment, whether it’s a CPU instruction or interactions between two components, Spectrum EmulatorEmu in Java must work as per spec, or the program running on the emula- tor will likely fail. Once an emulator is completed, it’s possible to revive old programs in such a way that they’re completely

Home J2EE J2ME oblivious to their new surroundings. It’s almost like traveling ZX back in time. Emulation in Java RISING TO THE CHALLECHALLENGE Java has matured tremendously in the years since I first cu came into contact with it. Since writing emulators has been an on-and-off hobby of mine, I thought it would be an interest- ing experiment to see what it would take to implement one in Java. The first two challenges I had to think about before start- ing down this path were performance and timing. Performance is critical to the success of an emulator since Sir Clive Sinclair had a dream: everyone should no matter how accurate, if an emulator runs programs sig- nificantly slower than the original hardware, no one would own a computer. In the early ’80s, this was quite want to use it. The Java HotSpot engine has recently advanced the performance of Java programs by leaps and an ambitious, almost foolhardy thing to say, bounds, yet the risk still remains: for every instruction of an

written by Razvan Surdulescu original program, the emulator may have to execute tens or given that the cost of computing machin- hundreds of instructions. Timing is also critical since Java does not (yet) have facilities for running programs in real time. Most notably, garbage collection may well interfere ery was well beyond the grasp with the proper execution of the emulated program and cause significant pauses, making the programs appear jerky of individuals. Despite the hurdles, onscreen. On the flip side, Java provides an excellent environment for Sinclair Research Ltd. produced one writing code since it has a powerful and expressive API. The emulator I’ll be describing is loosely based on an open-source emulator (implemented in C) that I worked on with a few of the most popular personal computers other people a number of years ago. The Java source is an order of magnitude more compact and more elegant than the in Great Britain and, later on, in Europe: original C source. The Java AWT API significantly reduced the burden of implementing the screen emulation (one of the the Sinclair ZX Spectrum. harder aspects of the original emulator). Last, but not least, the emulator can run on any Java Virtual Machine.

50 JULY 2002 JULY 2002 51

JJavaava COMCOM JJavaava COMCOM The Sinclair ZX Spectrum other sibling. This simulates the “bus” of the original machine. The machine I wrote the emulator for is the Sinclair ZX For example, whenever a byte is written into the video RAM, Spectrum: one of the first personal computers. For a bit of his- the BaseMemory object can retrieve its BaseSpectrum parent tory on the machines and the man behind them, visit from which it can retrieve the appropriate BaseScreen object www.nvg.ntnu.no/sinclair/. and subsequently update the current screen frame. The Java emulator, called “JZX”, is loosely based on a Linux The BaseComponent class also imposes the contract for native emulator called “XZX” that I worked on a number of the major “lifetime events” of the emulator: startup, reset, years ago (www.zx-spectrum.net/xzx/). shutdown, and load. The Spectrum is a remarkably simple machine by today’s • init(): Initializes the component with the parent and the standards. logger object (used for logging error and debug messages) • CPU (Z80 @ 3.5MHz), I/O controller (ULA) • terminate(): Terminates the component and indicates that • 16K ROM (BASIC), 48K RAM all its state should be discarded • Integrated keyboard, TV decoder, loudspeaker • reset(): Notifies the component to reset all of its state and be • IN/OUT ports (microphone and headphone), expansion ready to start fresh slot • load(): Participates with BaseLoader in a simplified Visitor pattern used for loading relevant state into the object (the J2SE Despite its simplicity, the Spectrum was fully capable of Accept() and Operation() methods are merged into load() running sophisticated software such as games, Pascal and C since the Visitor is merely a passive data container) compilers, databases, and word processors. When the top-level BaseSpectrum object is created, it calls Architecture Overview init() on itself and all its children, followed by reset(). When The Spectrum is assembled as in Figure 1 and operates as the emulator is shut down, it calls terminate() in the same follows: way. • The CPU fetches instructions and executes them. –It passes I/O instructions to the ULA. Emulation Challenges –It handles interrupts from the ULA via interrupt routines. Main Loop • The ULA handles the interaction with the outside. The main loop of the emulator resides in the –It scans the video RAM to produce the TV frame. BaseSpectrum class (see Listing 2). –It interrupts the CPU at the end of a TV frame. Every instruction executed by the Z80 CPU takes a certain –It decodes the I/O ports to read/write the peripherals. amount of time, which is a multiple of one “state” (also known as “T-state”). The ULA renders one line of the screen every 224 CPU

Home J2EEThe software architecture resembles J2ME Figure 1, but is differ- states (STATES-PER-LINE), so it’s essential to keep track of how ent in a few key aspects (see Figure 2). many states pass every time the CPU decodes and executes one The emulator emulates two distinct machines: the original instruction. For efficiency purposes, the screen is not updated 48K Spectrum model and the subsequent 128K one. Since the every time a new line becomes available, but rather every 50 (TV- Dice machines are similar, 95% of the emulator code base is shared. LINES) lines, which means one frame every 20 milliseconds. www.dice.com “Building an emulator is challenging, since it requires an intimate understanding of both the emulated machine and the host machine in order to bridge them together”

Not all peripherals from the original Spectrum are emulated: The CPU interrupts are simulated by means of wait()ing on the I/O ports and the speaker are missing. The I/O ports are an external Thread object, which simply sets a public field to not present since the original hardware needed them for load- “true” and calls notifyAll() every 20ms, at which point the ing and saving software onto magnetic tape, while the emula- main emulator loop notifies the CPU of the interrupt. The rea- tor uses files instead. The speaker is not present since it would son for wait()ing on the interrupt is that the CPU emulation be almost impossible to emulate it correctly in Java: the sound runs at the speed of the host machine; no attempt is made to in the original Spectrum was produced by turning the speak- slow it down in order to run at the original Spectrum speed, er on and off rapidly to create the appropriate frequency. except whenever a screen frame is rendered. This turns out to Every Java class that represents a Spectrum component is be entirely appropriate and makes the emulation both fast derived from BaseComponent (see Listing 1). BaseComponent and believable. Note that it’s possible for the main emulation and BaseSpectrum form a (extended) Composite pattern, loop to “skip” one interrupt (if, for example, refreshing the where BaseSpectrum is the Composite and every screen takes too long). This is a measurably low risk that BaseComponent has a reference to its parent. Any would take place only on slower machines and would not be BaseComponent can access its parent and from there, any readily visible.

52 JULY 2002 JULY 2002 53

Java COM Java COM Memory Emulation The emulated CPU reads and writes data by indexing into The Z80 is a 16-bit CPU, meaning it can index up to 64K of the “m_frame” array. memory. This works naturally for the 48K Spectrum (16K ROM The BaseMemory object allows the CPU to select the “visible” and 48K RAM.) The 128K Spectrum, on the other hand, has pages via the method “public void pageIn(int frame, int page)”. It 12x16K pages (4xROM + 8xRAM); the software can select any also allows direct access to the page data via “public byte[] four to be “seen” by the CPU. The BaseMemory implementa- getBytes(int page)” (useful for the screen emulation, for instance). tion uses pages for the emulation in both models to achieve All memory operations must convert “virtual” addresses to maximum reuse. physical ones. The frame number is simply the first 2 bits of The BaseMemory object keeps track of two arrays to repre- the “virtual” address; the frame offset is the remaining 14 bits sent the memory: (see Listing 3).

Performance is critical to the

J2SE “success of an emulator since no matter how accurate, if an emulator runs programs significantly slower than the original hardware, no one would want to use it”

byte[][] m_page; Signed and Unsigned Data Types byte[][] m_frame; You may be wondering about the return types of the meth- odes in Listing 3; they both return an integer (32 bits) despite • The “m_page” array represents the full set of memory pages. the fact that they should perhaps return a “byte” (8 bits) and, There are 12 pages, each 16K long. respectively, a “char” (16 bits). • The “m_frame” array represents the four pages currently The Z80 CPU can operate on 8-bit or 16-bit values, either

Home J2EEbeing “seen” by the CPU. For example, J2ME the following code directly or via its registers. Although Java natively supports eNGENUITY makes the CPU “see” pages 0, 4, 6, and 9: data types that are 8- and 16-bits wide, the emulator is imple- mented almost exclusively in terms of integer types. The rea- m_frame[0] = m_page[0]; son for this is that the Java byte is a signed type, while the Java m_frame[1] = m_page[4]; char is an unsigned type. m_frame[2] = m_page[6]; Consider the following (fictitious) Z80 instruction that m_frame[3] = m_page[9]; adds the contents of the A register (8 bits) to the contents of Technologies the HL register (16 bits) and stores the results in the HL regis- ter:

Input: www.jloox.com A = 10000000 (=0x80), HL = 00000000 00000001 (=0x0001) Result HL = HL + A: HL = 00000000 10000001 (=0x0081)

The same thing in Java would look like this:

Input: byte a = (byte) 0x80; char b = (char) 0x0001; Result b = b + a: b = (char) (b + a); (=0xFF81)

Surprised? The Java language specification (paragraph 5.6.2) mandates that all binary operations where the operands are of type integer (or smaller) should be promoted to integer first. In our case, the (byte) value 0x80 and the (char) value 0x0001 are first promoted to integer before they’re added. Since the byte is a signed type, the integer promotion yields the value 0xFFFFFF80. Since the char is an unsigned type, the integer promotion yields the value 0x00000001. When the two integer values are added, the end result is 0xFFFFFF81, which is then truncated to a char, yielding the value 0xFF81. The only way to avoid this behavior is to explicitly prevent the sign extension in the widening conversion. The new code would FIGURE 1 The Spectrum look something like this:

54 JULY 2002 JULY 2002 55

Java COM Java COM b = (char) (b + (a & 0xFF)); input arguments are correct and need no further modifica- tions, while all return values need to be correctly truncated The “&” will mask all bits but the last 8, yielding (the inte- before being returned. ger) 0x80, which is then added to “b”, producing the correct result. CPU Emulation Although this solution solves the problem, it’s only a par- In addition to the signed/unsigned challenges described tial solution for the CPU emulation as a whole. The reason has earlier, the CPU poses additional problems in the area of to do with the CPU flags that indicate whether overflow instruction decoding. The decoder is implemented as a large occurred during a particular operation. Java has no mecha- “switch()” statement, which switches on the first byte of the nism for indicating overflow, so I must always use a Java data current instruction. Naturally, the code is very large and rather

I was pleasantly surprised to see that it was not only J2SE “possible to implement a Java emulator for the Spectrum, but that it also ran fast”

type that’s larger than the resulting value. The emulator would unwieldy to read and modify. One possible solution for deal- explicitly test for overflow and truncate appropriately. In the ing with such a large piece of contiguous code would be to end, the only feasible solution is to use integer types every- have an array of IRunnable objects (that can decode a partic- where, and explicitly deal with issues of truncation and over- ular instruction in the “run()” method) indexed on the flow. instruction code. To keep the code readable, I adopted a naming convention This approach would allow the code to be structured that exposes the size of the data types involved. The size in bits more elegantly, but it would proliferate the number of

Home J2EEof the return value and each argument J2ME of a function is classes and impose significant runtime overhead. The InstallShield appended to its name. For example, “int read8(int val16)” “switch()” approach, while difficult to write and maintain, means that the function returns 8 bits of data, and receives as is extremely fast since the JVM implements it internally as a an argument 16 bits of data, all embedded in an integer as the jump table, thereby exhibiting the same architectural less significant bits. Furthermore, the convention is that all approach as the object array, without the performance penalty of invoking an interface method for every instruc- tion. Software Screen Emulation Each pixel on the Spectrum screen can be either on or off. This is represented by the appropriate bit value in a byte (the www.installshield.com state of 8 adjacent pixels is governed by the byte value at a par- ticular memory address in video RAM). Color information is represented by another byte. To draw pixels on the screen, the BaseScreen object extends java.awt.Canvas and implements the drawing logic in the paint() method. A nice side effect of this is that the emulator can be “embedded” into any AWT or Swing container that can render Canvas objects. This allows the emulator to run seamlessly as a standard application or an applet. The BaseScreen object uses an offscreen image to render the screen contents, after which the image is drawn directly onto the screen via java.awt.Graphics.- drawImage() (this common technique prevents flicker- ing). Every time the CPU writes into the screen memory area, the BaseScreen object is notified. For maximum efficiency, the only action taken at this time is to toggle a Boolean value in an array that indicates that the particular screen byte has changed. When paint() is called, a for loop iterates through the Boolean array and, for every “true” value, it draws the corre- sponding byte into the offscreen image. The mechanism for fast updates to the offscreen image is the challenging part. The naïve technique is simply to use FIGURE 2 Software architecture java.awt.Graphics.fillRect() to render every pixel into the

56 JULY 2002 JULY 2002 57

Java COM Java COM image. While this works, it’s very slow due to the overhead of .drawImage() to render that piece of the video RAM on the calling the fillRect() method and running it many times for 1x1 screen (see Figure 3.) rectangles. The new performance numbers are in Table 2. A better technique is to create the offscreen image as a dec- As you can see, the performance improvements are dra- orator for a java.awt.image.MemoryImageSource object. The matic for Java1 (>90%); for Java2, however, the performance MemoryImageSource is created, in turn, containing a byte is far worse (a slowdown or more than 1,000%!). The reason array in RGB format with the pixel data. The rendering code for the bad Java2 performance lies in the performance of updates the byte array and then calls MemoryImage- java.awt.Graphics.drawImage(). This discussion is beyond Source.newPixels() to notify the object that the data has been the scope of this article, but you can read more about it on updated (see Listing 4). the Java Developer Connection Web site (http:// Table 1 provides the timing results, in milliseconds, for developer.java.sun.com/developer/) in the BugParade sec- rendering 200 consecutive frames of the (same) Spectrum tion (http://developer.java.sun.com/developer/bugParade/ game (the hardware/software configuration is Windows 2000 bugs/4276423.html). Professional, Pentium III 650, 192MB RAM). To resolve the performance problems in Java2, I use a These timings are barely adequate: as you recall, each different (and more conventional) technique that’s similar Spectrum frame is refreshed every 20ms. If rendering the to the MemoryImageSource technique described earlier. In J2SE frame takes longer than 20ms, the emulation will look Java2, the offscreen image object is a superclass of choppy (it will skip frames and slow down the machine java.awt.Image, namely a java.awt.image.BufferedImage. overall). This class has a method called setRGB() that allows you to To improve performance, I made a key observation set an RGB pixel array directly into the Image object, with- about the way color is encoded in the Spectrum. As out the performance penalties of MemoryImageSource. described earlier, every byte in video RAM is paired with newPixels(). another byte that describes its color: the first byte simply The final performance numbers are in Table 3. shows whether the pixels are “on” or “off” (the “pixel” byte) Note that prerendering all possible 256 * 256 (= 65536) Java and the second byte shows what color the pixels are (the image objects will take a toll on the memory footprint of the “color” byte). This means there are a total of 256 * 256 dif- emulator. If I want a fixed-size cache of these images, I run the ferent ways that a location in video RAM could appear on risk of “thrashing” in the cache. Discarding entries when the the emulated screen (256 values for the “pixel” byte and 256 cache is full means the garbage collection will have more values for the “color” byte). I can prerender some (fixed) work, slowing down the emulation. It’s possible to reuse number of these “pixel/color” byte combinations as Java entries in the cache (instead of discarding them), but this will image objects and then simply use java.awt.Graphics bring us back to the original performance problems with Home J2EE J2ME Borland www.borland.com/new/jb7/5068.html

FIGURE 3 Prerendered Java image

TECHNIQUE SUN JAVA 1.1.8_03 MICROSOFT JVIEW 5.00.3802 SUN JAVA 1.3.1 MemoryImageSource 23.93526824 24.0485756 20.20600913

TABLE 1: Timing results

TECHNIQUE SUN JAVA 1.1.8_03 MICROSOFT JVIEW 5.00.3802 SUN JAVA 1.3.1 MemoryImageSource 23.93526824 24.0485756 20.20600913 Prerendered Java 0.989330465 0.939373495 N/A Images

TABLE 2: New performance numbers

TECHNIQUE SUN JAVA 1.1.8_03 MICROSOFT JVIEW 5.00.3802 SUN JAVA 1.3.1 MemoryImageSource 23.93526824 24.0485756 20.20600913 Prerendered Java 0.989330465 0.939373495 N/A Images BufferedImage N/A N/A 5.995489495

TABLE 3: Final performance numbers

58 JULY 2002 JULY 2002 59

Java COM Java COM Listing 1 Graphics.drawRect() or MemoryImageSource.newPixels(). A public abstract class BaseComponent better idea is to use only half the “pixel” byte (a nibble) to pre- { render Java images. This means that any “pixel” byte will be protected BaseSpectrum m_spectrum; drawn by concatenating two prerendered Java images. The public BaseSpectrum getSpectrum() { total number of prerendered nibbles is far more manageable: return m_spectrum; 16 * 256 (=4096.) The tradeoff is that I now need to make twice } as many calls to java.awt.Graphics.drawImage(), but that turns public void init(BaseSpectrum spectrum) { out to be inconsequential. m_spectrum = spectrum; } Debugging Techniques public void terminate() { Debugging the emulator is very challenging. The hardest m_spectrum = null; part to debug is the CPU emulation, primarily due to its } sheer size and complexity. The CPU emulation code is bigger public abstract void reset(); and more complicated than the rest of the emulator. Although the Z80 CPU is simple by today’s standards, it has a public abstract void load(BaseLoader loader); } great many flags, registers, and instructions that manipulate J2SE these flags. For example, any addition will modify the sign flag, parity flag, carry flag, half-carry flag, and add-subtract while (true) { flag. The Spectrum software uses all these flags, and any mis- Listingstates 2 = current CPU state count take most often translates into a “hard reset” of the emulated if (states >= STATES-PER-LINE) { states = (states - STATES-PER-LINE) Spectrum. Furthermore, determining exactly where the emulated increment line count software crashed is not as easy as watching for the equiva- if (lines == TV-LINES) { lines = 0 lent of an illegal memory access or page fault. (There’s no refresh screen such thing on the Spectrum.) An incorrectly decoded instruction will most often translate to a Spectrum “hard wait for the next clock interrupt interrupt the CPU reset” or “hang” thousands of instructions down the stream } from it. } The easiest way to debug the emulator is to use another execute next CPU instruction emulator (that’s known to be correct) and compare the CPU } traces for executing the same program. In this case, I modified

Home J2EE J2ME the original Linux native emulator to output CPU traces (a CPU trace is the state of all registers and flags after executing public int read8(int addr16) { every instruction). This has the advantage of pinpointing the int data = m_frame[(addr16 >> 14)][(addr16 & 0x3FFF)]; precise spot where the Java emulator diverges from the native Interland return (data & 0xff); emulator and thus dramatically reduces the time required for Listing} 3 debugging. public int read16(int addr16) { int high = (read8((addr16 + 1) & 0xFFFF) << 8); int low = read8(addr16); Performance Considerations www.interland.com return (high | low); I was pleasantly surprised to see that it was not only possi- } ble to implement a Java emulator for the Spectrum, but that it also ran fast. The CPU emulation is on par with the native emulation; the screen emulation, while slightly slower and a private int[] m_data; private MemoryImageSource m_memoryImageSource; bit more awkward, is well within the limits of realistic emula- tion for what I would consider “average” hardware. // RGB data Surprisingly, and most probably due to screen emulation, m_data = new int[SCREEN_WIDTH * SCREEN_HEIGHT]; m_memoryImageSourceListing 4 = new MemoryImageSource(SCREEN_WIDTH, Java2 didn’t fare dramatically better than Java1, which puts SCREEN_HEIGHT, m_data, 0, SCREEN_WIDTH); Java1 on the map as a reasonable contender for this type of m_memoryImageSource.setAnimated(true); work. public void paint(Graphics g) { for every ‘address’ in Video RAM { Conclusion let ‘pixels’ be the byte at that address for every ‘bit’ in ‘pixels’ { As a platform for emulation, Java is a very strong player. let ‘(x, y)’ be the Cartesian coordinates of ‘bit’ Although the Sinclair Spectrum is not a terribly complex let ‘color’ be the RGB color of ‘bit’ machine by today’s standards, it poses significant challenges m_data[‘(x, y)’] = ‘color’ } in its implementation, and requires strong support both in } terms of language features and overall performance. Java’s ele- gant and expressive language rises to the challenge and over- m_memoryImageSource.newPixels(); g.drawImage(m_offscreenImage, 0, 0, this); comes it easily with code that’s more readable, more modular, } and far more concise. Java’s performance, the wild card in the equation, also meets expectations.

AUTHOR BIO Razvan Surdulescu is a software developer at Trilogy in Austin,TX, where he writes e-business software in Java.

[email protected]

60 JULY 2002 JULY 2002 61

JJavaava COMCOM Java COM J2ME EDITORIALOR J2ME INDEX

Books and Chewing Gum

J2ME According to a Palm press JASON R.BRIGGS J2ME EDITOR release, 5,000 Palms are to be pur- chased as part of a three-year grant program for several New York State J school associations. I wonder 62 whether Java is in the equation for Books and Chewing Gum any application suites being devel- oped (if they are) as part of that sys- recent press release from Palm got don’t also like browsing online, but the tra- tem roll out.And if not, why not? me thinking about their PDAs, as ditional retail book-buying experience defi- by Jason R. Briggs Awell as why Palm (in the UK) never nitely still has its allure. I’m not sure if I’m returned my e-mails...but that’s another mat- exactly representative of society as a whole, A Smart Card’s Place in a ter (and half a world away now). In any case, but I guess there’s a good percentage of peo- Security Architecture according to the release, 5,000 Palms are to ple out there who feel the same. A smart card is, in essence, a be purchased as part of a three-year grant Stick with me here – I’m going off on a computer that can be carried program for several New York State school tangent. around in your back pocket. “But 64 associations. Apart from wishing I was the I recently read on CNET that Sony is what does it do?” you might ask. As salesperson who got the commission on that endeavoring to make their memory stick a de with most computers, the answer 2ME particular contract, I wonder whether Java is facto standard. I’m sure you’ve come across to this question is, “What do you in the equation for any application suites these odd little storage cards before, but in want it to do?” being developed (if they are) as part of that case you haven’t – imagine a stick of Wrigley’s by Ken Greenwood system roll out. And if not, why not? chewing gum and you’re halfway there. If Java is not being considered, a col- Whether or not they succeed in becoming Java Card 2.2

Homeleague of J2EEmine thought of a reason. J2SE Polish. the market standard, I have to say I quite like Specifications Overview No, not people from Poland – the other the memory stick. They seem a lot more con- Ever since the Java Card 1.0 meaning/pronunciation (i.e., to remove venient to lug around in larger numbers (and was introduced in 1996 it has flaws from; to perfect or complete). To para- how is that pickpocket supposed to know been gradually maturing and QUALCOMM Inc phrase his words – the JVM for the Palm suf- that the pack of chewing gum in my pocket recently celebrated its fifth fers from a certain lack of polish compared isn’t actually chewing gum...unless of course anniversary. American Express, 66 to other applications available for the OS. they like chewing gum...?). Visa, and now the Department of Personally, I think the Palm JVM has So here’s the crazy idea for the month. Defense have all deployed solu- http://brew.qualcomm.com/ZJD4 really improved since I first looked at it, The old “walk-in-and-browse” bookshops tions that utilize the Java Card and it’s definitely better than VMs I’ve seen remain the way they are, but with a slight specifications. This rather large running on Windows CE, in terms of inte- difference. Rather than stocking books, movement proves that Java gration with the device, for example. they stock something like a pamphlet – a Card technology is a great sys- Java has a history of this “lack of polish” on standard book jacket (with cover and sum- tem for data security and data the client side. Compare the hiccup that is an mary on the back) plus a few excerpted mobility. applet starting up in your browser with the pages inside. It would work in a similar by Joseph Smith smoothness of Macromedia’s Flash and you’ll fashion to the way music stores do now – know what I mean. However, in comparison you take the cover up to the counter and Optimizing Java with desktop Java, I don’t think the Palm VM is they pull a CD out of a cupboard – except Performance in Heritage really that bad, so I hope that whoever is in this case, they pull a memory stick out of Designs advising the associations is giving the idea the cupboard with the book loaded on it. It’s become clear that the some serious thought. Those who want to browse in a shop can potential marketplace for embedded One of the killer applications for the still do so – those who want to browse Java devices is vast, but that some Palm seems to be electronic books. online can still do their purchasing on the of these markets are not yet mature. 70 Considering the price of a number of eBook Net. People like me, who enjoy doing both, This article discusses the introduc- “readers” I’ve seen, PDAs, like the Palm, are are happy as well. And the humble PDA tion of Java into multilanguage her- a cost-effective alternative – so it’s hardly (Palms, Handsprings, Cliés, and the like) itage designs, focusing on the surprising that eBooks are doing relatively will make an admirable reader until the advantages and disadvantages of well. However, the major problem I see with various companies inventing electronic deploying each solution. the whole concept of downloading books is paper (or whatever they’re calling it) bring by Carl Barratt that I quite like wandering down to a book- the technology to market. store, picking a title off the shelf, and read- Now to make sure that the infrastruc- ing a few pages to see if I like it. Not that I ture for all this is implemented in Java…

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

62 JULY 2002 JULY 2002 63

Java COM Java COM INDUSTRY COMMENTARY

A Smart Card’s Placein a Security Architecture PUBLISHER,PRESIDENT,AND CEO FUAT A. KIRCAALI [email protected] CHIEF OPERATING OFFICER WRITTEN BY KEN GREENWOOD MARK HARABEDIAN [email protected] VICE PRESIDENT,BUSINESS DEVELOPMENT

J2ME t the recent JavaOne conference in Public Key Infrastructures (PKIs) are GRISHA DAVIDA [email protected] San Francisco, SchlumbergerSema becoming more common. They rely on a ADVERTISING demonstrated the benefits of a pair of secure keys that make up a person’s SENIOR VICE PRESIDENT,SALES AND MARKETING A CARMEN GONZALEZ [email protected] Java-based smart card. “A Java what?” was a digital identity. One of these keys is the VICE PRESIDENT,SALES AND MARKETING common response by visitors. A brief “public key,” which can be seen and used MILES SILVERMAN [email protected] explanation showed that anyone with a by anyone to check the authenticity of a ADVERTISING SALES DIRECTOR GSM mobile phone, and many with a cred- document signed using the corresponding ROBYN FORMA [email protected] ADVERTISING ACCOUNT MANAGER it card, carry one of these around all the “private key.” As the name suggests, the pri- MEGAN RING [email protected] time. In an age when processor speeds are vate key must be kept secret at all times. A ASSOCIATE SALES MANAGERS measured in gigahertz, it’s often difficult to smart card offers the ability to securely cre- CARRIE GEBERT [email protected] think on a slightly smaller scale. ate the two keys onboard the card itself, KRISTIN KUHNLE [email protected] ALISA CATALANO [email protected] A smart card is, in essence, a computer ensuring that the private key is never visi- LEAH HITTMAN [email protected] that can be carried around in your pocket. It ble to the outside world. The use of this key EDITORIAL has input/output and power – via a set of to sign or decrypt a message is, again, EXECUTIVE EDITOR metallic contacts – a microprocessor (32 always done on the card. NANCY VALENTINE [email protected] EDITOR bits will soon be common), ROM, EEPROM While it’s possible to do these opera- M’LOU PINKHAM [email protected] (64K in recent models), and an operating tions using a computer’s hard drive, there MANAGING EDITOR system (OS). For a Java-based card the OS, are too many worms and viruses to make CHERYL VAN SISE [email protected] as defined by Java Card 2.1 standards, is a this a secure alternative. In addition, the ASSOCIATE EDITORS JAMIE MATUSOW [email protected] slimmed-down version of the OS found on common practice of writing down pass- GAIL SCHULTZ [email protected] a larger computer. The flexibility, security, words or making them easy to remember is JEAN CASSIDY [email protected] ease-of-use, and rapid development cycle a serious flaw in any security architecture. ASSISTANT EDITOR of Java technology has made it the leading By using a well-defined structure and com- JENNIFER STILLEY [email protected] ONLINE EDITOR

Homeopen standard J2EE for the smart card J2SE industry. munication within the card, it’s possible to LIN GOETZ [email protected] “But what does it do?” you might ask. As make certain that there’s no access to the PRODUCTION with most computers, the answer to this secret memory without the correct author- VICE PRESIDENT,PRODUCTION AND DESIGN question is, “What do you want it to do?” ization. A multifactor authentication JIM MORGAN [email protected] Sprint PCS LEAD DESIGNER Smart cards have been in use for over 20 years, ensures that, to use the card (and therefore LOUIS F. CUFFARI [email protected] although only fairly recently have they been the private key), it’s necessary to have the ART DIRECTOR able to run an actual operating system. card with you and know the password. A ALEX BOTERO [email protected] ASSOCIATE ART DIRECTORS Because smart cards are embedded with a third factor can even allow authentication CATHRYN BURAK [email protected] http://developer.sprintpcs.com microprocessor, they can store large amounts using a biometric application, such as a RICHARD SILVERBERG [email protected] of data and carry out their own card func- fingerprint or face recognition. AARATHI VENKATARAMAN [email protected] tions, such as encryption of digital signatures. Futurists once predicted we would ASSISTANT ART DIRECTOR TAMI BEATTY [email protected] A smart card communicates with a host carry computers in our pockets – with WEB SERVICES computer through a card reader, which can smart cards, we already do. Security has WEBMASTER generally be connected to a USB, RS232, or become paramount in the global con- ROBERT DIAMOND [email protected] WEB DESIGNERS PCMCIA port. sciousness, and Java-based smart cards STEPHEN KILMURRAY [email protected] Although widely used in GSM mobile offer a secure, mobile, practical, and CHRISTOPHER CROCE [email protected] phones, the Java Card is a relative newcom- affordable means of providing physical and CATALIN STANCESCU [email protected] er to the network security field. Despite the information security. A CCOUNTING CHIEF FINANCIAL OFFICER many advantages of smart card technology, More information about smart cards can be BRUCE KANNER [email protected] the cost of the reader has been a restraining found at www.smartcards.net. ASSISTANT CONTROLLER factor. There are significant advantages, JUDITH CALNAN [email protected] however, and with the cost of readers going References ACCOUNTS RECEIVABLE JAN BRAIDECH [email protected] down and the introduction of direct-to- • Smart Card Developer's Kit: www. ACCOUNTS PAYABLE USB port technology, the strong value of scdk.com. JOAN LAROSE [email protected] smart cards as an easy-to-use, portable, • Guthery, S. and Cronin, M. (2001). ACCOUNTING CLERK BETTY WHITE [email protected] and very secure means of logical identifica- Mobile Application Development with SYS-CON EVENTS tion is beginning to be better understood SMS and the SIM Toolkit. McGraw-Hill. VICE PRESIDENT,SYS-CON EVENTS by those outside the immediate industry. • Anderson, R.J. (2001). Security Engine- CATHY WALTERS [email protected] With the need for security – both physical ering: A Guide to Building Dependable CONFERENCE MANAGER MICHAEL LYNCH [email protected] and network – becoming ever more critical, Distributed Systems. John Wiley & Sons. SALES EXECUTIVES,EXHIBITS it’s clear that a portable device with a MICHAEL PESICK [email protected] secure memory is a good investment. AUTHOR BIO RICHARD ANDERSON [email protected] C USTO MER RELATIONS/JDJ STORE Recent laws in many countries have Ken Greenwood is the business marketing manager for MANAGER,CUSTOMER RELATIONS/JDJ STORE SchlumbergerSema Cards and Transactions. made electronic signatures a reality and ANTHONY D. SPITZER [email protected] CUSTOMER SERVICE REPRESENTATIVE [email protected] MARGIE DOWNS [email protected]

64 JULY 2002 JULY 2002 65

Java COM Java COM DATA SECURITY & MOBILITY

J2ME Java Card 2.2Specifications Overview

Java Card engineering with RMI specifications

Ever since the Java Card 1.0 was introduced in 1996 it has been gradually maturing, and recently celebrated its fifth anniver- WRITTEN BY sary.American Express,Visa, and now the Department of Defense JOSEPH SMITH have all deployed solutions that utilize the Java Card specifications.

This rather large movement proves applets with J2SE applets. Applets refer javacard.framework.JCSystem. that Java Card technology is a great sys- to applications that reside on the Java • Persistence and transience behavior tem for data security and data mobility. Card.) Another deterrent is that you are different from Java. At last count, American Express claimed have to deal with bytes! When was the • Only single-dimensional arrays are over 4 million deployed cards and Visa last time you had to think in bytes and allowed.

Home J2EEestimated over 7 J2SE million at the end of byte arrays? • Security management policy is last year. implied in the JCVM and not an Since September 11, 2001, there has Java vs Java Card explicit class. been a lot of interest regarding Java- The Java Card contains a virtual • The JCVM is a 16-bit system. Motorola based smart cards combined with bio- machine that’s tailored for it, the Java metrics (verifying the identity of a per- Card VM. Because of the limitations, the With that said, there are some useful son through some physical characteris- JCVM has some unsupported features supported features such as: tic). This has driven the Java Card speci- such as: • Packages www.motorola.com/developers/wireless fications to the forefront, and more and • Dynamic class loading • Virtual methods more engineers (and managers) are • Garbage collection • Interfaces, abstract classes, and scrambling to implement them. • Threads exception handling Currently, Java Card implementers • Cloning • Polymorphism use Java Card 2.1.x. Soon you’ll be seeing • Default visibility override • The root class is of class Object Java Card 2.2 deployed into the market- • Package visible interface can’t be place. Those who have started to use the extended to public visibility Other limitations that should be Java Card 2.1.x API are realizing that it’s • Int, double, float, and long are not mentioned include: quite a hassle to do some basic things. supported • A maximum of 256 instance fields per For example, you can’t utilize strings or • Static instantiated classes aren’t class other common primitive types found in allowed • Array size is limited to 32K Java because the Java Card processor • Memory space is limited to 32K per has extremely limited resources. Most The JCVM differs from standard package cards offer a little less than 32K of mem- JVMs in several ways: ory for applets. (Note: Don’t confuse • There’s only one system class, the To communicate with a card, use a Card Acceptance Device (CAD). This is usually a card reader but can also refer to an ATM or point-of-sale terminal. Your communication isn’t really to the With the new Java Card card itself – it’s actually to the CAD, which then sends commands to your specification, existing applet. “ To make engineering more complex, features become the structure of the applet code appears a bit backward: you use a large switch more powerful case block to process the commands you want. However, Java Card 2.2 makes all this a bit easier.

66 JULY 2002 JULY 2002 67 ” Java COM Java COM DATA SECURITY & MOBILITY

Java Card Remote Method Invocation More Algorithms can now query the amount of memory One thing that will make engi- For the implementation of security available to the applet, which wasn’t avail- neering easier is the use of Remote algorithms we must rely on the individ- able in 2.1.x. Method Invocation. An engineer ual vendors. Some vendors implement JCSystem.getAvailableMemory is a will no longer have to spend a lot of cards that contain just DES and Triple nicer way to query if memory is avail- time learning various APDU com- DES, while others implement DES, able before you allocate it. In 2.1.x, you mands. Triple DES, and RSA. For the implemen- cross your fingers and hope that the

J2ME Currently, you have to issue com- tation of RSA it’s common to also memory is available when you allocate mands in the following format: include a crypto-coprocessor in the it, otherwise you’ll receive an excep- smart card chip to help speed up the tion. CLA INS P1 P2 LC CData calculations. In Java Card 2.2, AES and elliptic Logical Channels • CLA: A class byte that can be an ISO curves are added. New key lengths are In Java Card 2.1.x your commands 7816-4 such as 80, 84, or user- also available with these new algo- are processed by the currently selected defined rithms. Of course, this can be a applet. Java Card 2.2 allows up to four • INS: An instruction byte that states headache involving export restrictions, sessions to be open, one session per which instruction to perform so check with your vendor to see what’s logical channel. Now applet instances AUTHOR BIO • P1/P2: Parameter 1/2 that subdivides actually implemented and what key can be selected on different logical Joseph Smith is a a command lengths they support. channels. The applet can take advan- senior software • LC: Length of data to be transmit- You can still perform digital signa- tage of multisession functionality and engineer with over ted ture and random number generation on can be concurrently selected with 13 years of experience. In the • CDATA: The data to be transmitted the card as you did with Java Card 2.1.x. another applet on a different logical last two years, his • LE: Length of data to be returned channel. The applet can even be select- area of expertise from the applet Applet/Package Deletion ed multiple times. There is a basic logi- has been in Java Applet/package deletion has been a cal channel, logical channel 0, that is Card and biometric-based Depending on the applet, it would hot topic since the first release of the activated upon a card reset. A card reset solutions. He can have to switch case on each individual Java Card. This feature of 2.2 will be up can occur when the card has been pow- frequently be found CLA, INS, and P1/P2 to process the nec- to individual vendors to support, utiliz- ered down via card removal or electrical answering questions essary command. This method of trans- ing their own implementation. But failure. on Sun’s Java Card Developer Forum. mitting data can be a tedious job and a nonetheless, it’s sure to be available Applets that are capable of being

Home J2EEmaintenance nightmare. J2SE The Java Card since engineers and others will be selected on multiple logical channels at Actuate RMI makes it easier to perform a com- requesting the functionality. Applets the same time are called multiselectable mand. created using the Applet.register() applets. These will have the same securi- methods exist until deleted by ty constraints as in Java Card 2.1.x with the applet deletion manager. regard to active contexts. To forward This manager can be an APDU commands to a logical channel, applet provided by the vendor the command will contain encoding in Corporation and is selectable by providing the header CLA byte to denote which an application identifier, AID. channel. For example, CLA byte 0x02 Sun wanted to leave the could denote logical channel 2, and 0x00 implementation of the applet could denote logical channel 0. The log- www.actuate.com/info/jdjad.asp deletion manager up to the ical channel is of key importance for vendors and, because of that, wireless support involving 3GPP, WAP, the AID won’t be standardized and ETSI. but it must be SELECTable. As long as the vendors provide a Conclusion SELECTable behavior to the Java Card 2.2 includes support for Northwoods outside world, they can contactless smart cards. These cards implement the applet dele- don’t have the visible chip on them, but tion manager any way they can be read if the card is simply waved see fit for their Java Cards. within a certain proximity of a contact- Software less CAD. There has been movement to Memory Resource Management include some form of biometry in the The JCSystem class offers Java Card API, and this technology will two new methods: isGarbage- no doubt be appearing on the market www.nwoods.com/go/ CollectionSupported and re- soon. questGarbageCollection. With the new Java Card specification, These offer limited garbage existing features, such as transaction collection support to query if a processing (much like commit/rollback vendor has implemented in a database), become more powerful. garbage collection functionali- Personally, I’m excited about the RMI ty and to request that the specification and memory management action be carried out. Garbage features that will make complex Java collection isn’t a requirement, Card engineering a lot friendlier. and once again it’s up to the implementers. However, you [email protected]

68 JULY 2002 JULY 2002 69

Java COM Java COM J2ME

Home J2EE J2SE HiT Software

ava, in its J2ME guise, has all the attributes Java Bytecode Executionin an Embedded Environment of a first-rate platform for embedded sys- Obviously, some platforms will be more proficient than www.hitsw.com tem design. More specifically, its platform others at executing Java code. The issue is clouded by hype, independence, code portability, and but, fundamentally, Java bytecode can be executed in one of robust operation render it particularly three ways: software translation, hardware translation, or suited to such applications. The extensive direct execution. use of embedded Java-based devices in the future is secure due to the proliferation of Translation in Software:The Java Virtual Machine standards based on it, and, moreover, the Bytecode can be executed using a software Java Virtual endorsement of major OEMs committed Machine (JVM) or, more specifically, a KVM designed particu- to its use in their designs. larly for embedded devices. Java code can be executed on any It’s become clear that the potential such virtual machine. A JVM takes the precompiled Java marketplace for embedded Java devices is source code (bytecode) and translates it into the native vast, but that some of these markets are not machine code of the processing platform in question preced- yet mature. Successful manufacturers in the ing its execution. Indeed, this process of interpretation is cen- immediate market for embedded devices, tral to the Java concept of platform independence. such as wireless handsets and set-top boxes, possess a huge investment in legacy code that they, Translation in Hardware: Bytecode Accelerators not unreasonably, wish to retain. Along with the problem A bytecode accelerator is a hardware solution that uses the of generating acceptable performance in resource-con- resources of an existing host processor. Accelerator solutions strained environments, the migration to Java-enabled don’t execute Java bytecode directly; instead, they convert the devices in markets that are already established and based on bytecode (in hardware) into the native instructions of the host other technologies is the most significant barrier to the processor prior to execution. Invariably, such solutions also widespread adoption of Java as the de facto standard in the utilize a software-based JVM, modified by the replacement of embedded space. the main interpreter loop and execution unit with the byte- Of the emerging solutions, both hardware- and software- code accelerator. based, none can claim to be a panacea. This article discusses the introduction of Java into multilanguage heritage designs, Native Java Processors focusing on the advantages and disadvantages of deploying Native Java processors are microprocessors designed to each solution. execute bytecode directly as their native instruction set. They

70 JULY 2002 JULY 2002 71

Java COM Java COM can be deployed as a coprocessor to a host processor in a mul- the Java bytecode into one or more native instructions, by tilingual, multiprocessor system, or as a standalone solution either a hardware or software interpretation process, will exe- in a dedicated embedded Java design. cute code much more slowly than solutions that are able to execute the bytecode directly. Native Java processors can exe- Embedded MultiprocessorJava Solutions cute bytecode directly for the vast majority of bytecode. More While there’s a clear desire for Java capabilities to be intro- complex instruction types can be microcoded (i.e., they follow duced into many embedded applications, it’s a prerequisite a number of internally coded steps), or else, when this is not that Java bytecode is executable in parallel with existing her- practical, a jump to a predefined software routine is invoked

J2ME itage code, rather than in place of it. Primary examples of such (see Figure 1). applications would be a mobile phone running a C-coded Register-rich hardware solutions (e.g., bytecode accelerators communications stack, or a set-top box currently evolving to or, similarly, those native processors based on RISC cores) will support interactive or Internet-based content. Understanding suffer a further performance impact resulting from the need to the fundamental design issues is vital when designing high- preserve the state of the registers during the frequent context quality embedded devices for Java-based applications. switches that are a feature of a threaded language like Java. Characteristics that influence the selection of components for JVMs are available for most processors and are the most any embedded system include: expedient way to enable Java capability on an existing plat- nderstanding the fundamental “Udesign issues is vital when designing high-quality embedded devices for Java-based applications”

• Resources form. However, this approach is wholly inefficient and not in • Performance any way aligned with the J2ME paradigm, as the performance • Ease of integration versus resources trade-off in this case is difficult to justify for

Home J2EE J2SE • Cost embedded devices. Bytecode accelerators are specifically InetSoft designed to operate juxtaposed with a host processor and are First, JVMs are inherently resource hungry. This is a corol- relatively easy to integrate. Furthermore, they’re able to exe- lary of the software interpretation layer, which abstracts the cute Java bytecode more rapidly than the pure software JVM code, and the processor upon which that code is executed. A solutions they replace. However, this is still at the expense of a JVM will typically map a single Java bytecode into several reduction in the available bandwidth of the host processor for native processor instructions prior to execution; therefore, to other functions (e.g., communications for an interactive Corporation sustain acceptable Java performance, a very fast processor is application) as a result of the extra processing burden placed required. Relatively speaking, the rise in silicon cost and on it. power consumption intrinsic in the use of such powerful Native Java processors can execute Java bytecode at opti- processors is huge. Additional memory resources, occupied by mal speeds and do not place any extra burden on the host www.inetsoft.com/jdj the JVM itself, present a further burden for embedded appli- processor if deployed as a coprocessor, since they can operate cations. concurrently. Taking everything into consideration, there’s a Bytecode accelerators also use a JVM and so require the clear migration path (probably time-line dependent) from same additional memory resources as software-only JVM “easy-to-integrate” JVM solutions through bytecode accelera- solutions. Typical bytecode accelerators are efficient in terms tors to the ultimate performance offered by native Java of silicon cost when added to an existing host processor; how- processors. ever, if a second dedicated processor is used, the gate count of How simple is it to integrate a native Java processor with an this additional processor must also be taken into account. existing host core? The answer, of course, depends on the Native Java processors vary drastically in size. Those that are design of the processor. The final part of this article explains stack-based, and thus accurately match the Java execution such a design in more detail. model, have a very low silicon cost, whereas those based on a Finally, though licensing costs are somewhat tangential to standard RISC processor are less than optimal. this discussion, they’re worth a mention since it’s an impor- Since there are still no dependable metrics available to tant concern for devices that are produced in high volume. evaluate the performance of embedded Java solutions, code While cost is very much a vendor-specific issue, it’s worth execution speed remains an emotive issue. When applied pru- pointing out that solutions that utilize both a JVM and hard- dently, benchmarks are an invaluable asset. However, they’re ware intellectual property will incur license fees for both not the sole criteria for evaluation and must be regarded with resources. caution since ultimately the crucial point is how fast the plat- form can execute the end application code. CaffeineMark fig- Integrating a Native Java Processorinto a Multiprocessor System ures are widely quoted but are not representative of real appli- The integration of a Java processor as a loosely coupled cations. It’s hoped that the imminent arrival of EEMBC indus- coprocessor can be simplified by the addition of a few extra try-standard benchmarks will clarify the issue as discussed in features, including: my previous article “J2ME Benchmarking: A Review” (JDJ, Vol. • An industry-standard bus interface 7, issue 1). • Relocation support for the core memory map Generally speaking, solutions that rely on the translation of • Host processor communication support

72 JULY 2002 JULY 2002 73

Java COM Java COM Externally, the Java processor must present an industry-stan- achieved using two mailbox registers: one for communication dard bus interface (e.g., AMBA, AHB, MLB) to simplify integration from the Java processor to the host, the other for communica- of the processor with the host CPU (see Figure 2). In a coprocessor tion in the reverse direction. A command packet passed from scenario, both processors are declared bus masters. Since they’re the sending processor to its mailbox then generates an inter- able to process data concurrently and are completely independent rupt to inform the recipient processor that a new value has of each other, conflicts may occur when both processors request been written. Subsequently, a further interrupt would be gen- bus access simultaneously. Ultimately, in such circumstances, the erated to inform the sending processor that the recipient has decision of which processor takes priority lies with the bus arbiter read the value. It follows that the recipient processor is then

J2ME and is defined by the systems integrator at design-time. Code able to extract the format of the request by inspecting the mail- caches are an important feature of any coprocessor implementa- box, which could be a method call, data transfer, or reference tion. Their importance lies in the fact that not only do they reduce to a multimedia object. Java coprocessor solutions that are code access times, but they also limit system bus access and so currently market-ready use one of two approaches to imple- reduce bus contention. ment data transfer. This depends on whether the processor By default, and upon reset, a standalone processor would requires dedicated memory resources or is able to support sensibly execute code from the first location in memory. shared access to system memory. Ideally, system memory can However, in a multiprocessor system, it must be possible to double up as a communications area using an independent relocate the program counter to allow the host to redirect the memory location that’s accessible to both processors to trans- vectors for external instructions to an appropriate location in fer data. Otherwise, where the processor does not support the physical address map. This could be achieved, for example, shared memory, a FIFO buffer can be used to provide a data by reconfiguration of an index register. transfer path, though this increases the complexity of the Low-level support must also be provided for interprocessor design. communications. In the example described here, this is Ultimately, a J2ME application programmer shouldn’t need to care about the hardware resources and, indeed, from an abstract point of view, there will be little or no difference between Java code developed for single or multiprocessor solutions. As an example, let’s assume that the Java code wish- es to make use of a set-top box resource supported by the host processor, such as the tuner. This resource would be accessi- ble only via a Tuning API, such as the one specified in the DVB Multimedia Home Platform standards. In this scenario, a standard Java method could trigger a request (passed via

Home J2EE J2SE mailbox registers) to the host, passing arguments to indicate Fiorano which channel is required. Once the operation had been car- ried out, the host would signal to the Java processor, again via a mailbox register, that the request had been successfully completed (or otherwise), and that the selected channel was available. Similarly, the process of debugging Java application code is Software as simple on a multiprocessor platform as it is on a single processor. This can be accomplished using standard protocols, such as the KVM Debug Wire Protocol (KDWP) to interface the Java processor directly to a development and debug environ- www.fiorano.com/tifosi/freedownload.htm ment such as Forte. In this instance, a JTAG port would be used to enable arbitrary locations in memory to be written to (i.e., to send command packets) or read from (i.e., to receive reply packets). Alternatively, debug can be accomplished via the FIGURE 1 Instruction execution model for a native Java processor host processor, using mailbox registers to enable communica- tion between the two processors, as described earlier. Summary This article discussed issues that pertain to the selection of a Java solution for devices with a significant investment in her- itage code. Moreover, following a clear migration path from virtual machines to embedded hardware solutions, the article also discussed the practical implementation of a dedicated hardware coprocessor solution. It’s probable that all the solu- tions described, from the easiest to integrate to those offering the ultimate performance, will be deployed in multilingual, multiprocessor systems long before single-language devices are upon us.

AUTHOR BIO Dr. Carl Barratt works in the applications department of Vulcan Machines Ltd. He has over eight years of experience in various hardware and software design roles. Carl holds a degree in electronic engineering and a doctorate from the University of Nottingham, UK.

FIGURE 2 Coprocessor deployment [email protected]

74 JULY 2002 JULY 2002 75

Java COM Java COM PRODUCT REVIEW JDJ Labs

o fully appreciate the power behind facility contains everything you need to verify Workshop, you need to know a bit and diagnose your Web service. The overview Tabout Java Web Services (JWS), an tab in the harness contains various links to the ? up-and-coming standard in the J2EE world. WSDL for the service, client source code, a Just as you can embed Java code in a JSP file description of the service, and some other use- and have it compile on the application ful links. The console tab takes you to the server, Java code in a JWS file is compiled WebLogic console, where you can monitor the automatically into a Web service. various components that make up your ser- JWS allows you to take standard vice. The Test form and Test XML tabs provide method calls in a Java class and, by adding you with the ability to run the Web service and one or more Javadoc-based annotations, monitor the request and response messages. instruct the Web application server to The harness automatically comes up when expose the method as a SOAP-based Web you build your Web service, and is essentially J2SE service. Workshop allows you to map an testing a fully deployed Web service. XML element in the SOAP message to a BEA specific method parameter. This allows First Impressions the service to maintain its public con- The GUI design is clean and visually tract (the underlying SOAP interface) appealing; the service controls and adapters while changing the implementation. are well laid out and easy to read. The com- plete development cycle is quick and seam- Features less; you can easily run through a complete J2EEWebLogic J2ME The Design View, an integrated test cycle in under a minute. development environment, contains a One particular aspect of the Design View I visual representation of a Web service found unique is the instant code checking fea- and a runtime environment where you ture. If there’s a problem in your code, it’ll can code, compile, deploy, and test a Web immediately be underlined with a wavy red service under development. The beta line. Move the mouse focus on top of the error version I used came bundled with a pre- condition and a description appears. The auto-

Labs Workshop by BEA Systems,Inc. release version of WebLogic Application fill feature in the editor worked equally well, Server 7.0 and WebLogic Builder. and listed the various methods available on a Rational User Home particular instantiation of a class. REVIEWED BY JOSEPH A.MITCHKO [email protected] Design View The Design View is made up of several Web Service Debugging info BEA Systems, Inc. window panes showing various aspects of The IDE provides several of the standard 2315 North First Street the Web service under development (see debugging features you would expect in a Java Figure 1). The left side contains both a project development tool. I ran one of the Web ser- Conference San Jose, CA 95131 and a structure pane, the right a property vice examples in debug mode and set a break- Phone: 800 817-4232 panel where you can modify the characteris- point or two. It worked as you would expect it Web: www.bea.com tics of the Web service. A visual representation to when invoking the service through the test E-mail: [email protected] of the service is provided in the center pane. harness. This is definitely an added bonus. www.rational.com/ruc When you click the source view tab, it switches to an editor containing Java source code. Limitations Testing Environment BEA WebLogic Workshop is not a Java IDE OS: Windows-XP Building a Web Service in the traditional sense. It simplifies J2EE Hardware: Dell Inspiron 8000 Workshop provides developers with the development for developers who don’t know ability to create and deploy Web services just J2EE APIs. While you don’t build EJBs directly by creating and configuring objects in a in WebLogic Workshop, the runtime creates “painter”-like interface. Within the Design EJBs to implement the Web service. Also, View, you can set up one or more public inter- although the builder can easily set up a JMS faces for the Web service and attach the con- queue for an operation, Workshop does not trol interfaces of the EJB components, data- assist in setting up JMS publish and subscribe base objects, etc., to the service. The underly- message interfaces. You’ll need to set them up ing Java code that you write for the service manually or use a utility that comes with the integrates the various control interfaces into a messaging server. Also, the product does not functioning Web service. contain an embedded workflow engine, so all Building and deploying your Web service is workflow activity needs to be managed within extremely easy and seamless. Initiate the the Java code. build, and you’re only a few seconds away from testing the interface in the test harness. Conclusion If all goes well compiling the JWS file, the Workshop has the potential to be a powerful process of building and deploying (no syntax tool in the development and deployment of large errors) works each and every time. and complex Web services, where you can literal- FIGURE 1 WebLogic Workshop visual development environment ly see how it all fits together and works. Combined Test Harness with the latest version of BEA WebLogic Server, it Workshop’s browser-based test harness becomes a very impressive platform.

76 JULY 2002 JULY 2002 77

Java COM Java COM Exclusive: Excerpts from JavaDevelopersJournal.com THE INTERNATIONAL JAVA COMMUNITY AGAIN ASKS THE MULTIBILLION DOLLAR QUESTION: ‘IS IT TIME SUN RELINQUISHED CONTROL OF JAVA?’

by JDJ News Desk ‘The Java Platform Has Everything You Need…’ WHEN MAINSTREAM NEWSPAPERS far from Silicon Valley, Phipps doesn’t see such a jump as being at all necessary. “And such as The New York Times, start referring to you as “troubled,” as of today,” he maintained firmly, “the Java platform has every- even a giant like Sun Microsystems has to pause and take stock. thing you need to manipulate XML and to process Web services. While on the subject of stock, Sun’s has now dropped 90% That’s why in the Giga survey at the beginning of this year 75% from a split-adjusted high just 20 months ago of $64.32 (on of developers said they would choose J2EE as their platform for 9/1/00)…so what’s going on in Santa Clara, and what effect Web services.” J2SE might it have on Java? IBM’s Sutor, who is used to sparring with Phipps, nonetheless reminded JDJ News Desk that the open-source This latter question is one that Java Developer’s Journal edi- model is “a model that gets a tremendous amount of input tor-in-chief Alan Williamson was asked on behalf of the world- from the community and produces high-quality code.” In wide Java community. other words, Sun might want to seriously consider relin- “I absolutely do not wish Sun to go down,” Williamson quishing control of Java. told JDJ News Desk, as he left the UK for a developer confer- “Sun owns Java,” Sutor underlined, “they can decide if they ence in Toronto, “but I do want them to get out of the court- want to bring it to an open-standards group or if they want to J2EEroom and back into the J2ME boardroom. Like many other Java open source it. [But] open source is a model that works, and I developers, I want Sun to start talking strategy as opposed to think it would work for Java as well.” lawsuits.” Alan Williamson wondered to what extent Sun’s current “Scott McNealy,” Williamson said, “has taken his eye off the predicament, with its COO Ed Zander leaving on July 1 and sev- ball and for some reason is dabbling in the world of law far more eral other executive departures all coming at the same time, than he should. If he were to channel the energy he is putting stems from an ambivalence at the very heart of Sun into court battles and lawsuits with Microsoft into making Sun Microsystems…as to whether Sun is in reality a hardware com- Exclusive back into the mighty corporate giant it once was, then I think pany or a software company, or both. Javaland wouldn’t even be discussing – as it is at present – the “To be honest, it doesn’t come as any great surprise that Sun Pramati Home possibility that IBM, for example, might somehow try and buy is in trouble,” Williamson said, “de facto Sun is a hardware/soft- Java from Sun.” ware company. But some of the diehard engineers would maybe argue that Sun is a hardware company at heart and their sally IBM Favors Open Sourcing into the world of software has been mismanaged. I guess histo- Or buy Sun from Sun. This last suggestion was one that JDJ ry will judge this.” News Desk put to IBM’s director of e-business standards strate- What does Williamson think is triggering Sun’s problems? Technologies gy, Robert S. Sutor, in an exclusive interview. “Well, it would be easy to point the finger at Microsoft,” replied “Well, that’s pretty hypothetical,” Sutor replied, laughing, Williamson. “Right or wrong, that’s the simplest thing to do, and adding: “I’m certainly not someone they would ask. I have no certainly doing so will get the most passionate response from idea. I deal with standards; I’m not anywhere near that.” the Java development community. However, strictly speaking, is www.pramati.com Of course, IBM wouldn’t necessarily have to own Sun that the case? Microsystems to have greater influence over Java. The same “Well, in a way it is,” he continued, referring again to what he would apply if Java were open sourced. On this point, Bob Sutor sees as the drain of focus and resources that goes with Sun’s was much more forthcoming. excursions into the judicial system with MS as its target. “Let’s “IBM is very much in favor of open sourcing these types of look at the amount of money Sun has spent on lawyers over the technologies,” Sutor explains. “It’s the basis of Linux; it’s the last few years,” Williamson noted, adding: “I suspect it would basis of the Apache Web Server, for example. We think it’s a keep a lot of Sun marketing folks and Java developers in work for model that works. I moderated a panel with my old colleague a long time.” Simon Phipps [Sun’s chief technology evangelist] well over a year ago, where he basically said something along the lines that The Ultimate Outcome Sun was moving toward open sourcing Java.” What if the worst happened? Williamson has no way of sec- What did Phipps, in turn, say? As reported in an exclusive ond-guessing IBM, which may or may not have designs on the interview with Web Services Journal News Desk (www.sys- Santa Clara company or its wonder language/platform. But on con.com/webservices/article.cfm?id=230), he said, “The major- one point he is clear: “I do not wish Sun to go down.” ity of players in the marketplace are using Java today,” and But what if? Williamson remains defiant that Java is now big- added: “The Java platform is a technology platform that is used ger than Sun and would continue its success story. “If such a throughout the computing industry, with 500 members of the thing were to happen, I don’t think Java will suffer. There are Java Community Process helping to standardize that Java plat- plenty of people in the wings who can more than cope with tak- form.” ing the Java mantle.” Hardly, in other words, a platform in “trouble.” Unless you What about you? Do you think Java would be safe in any think of Microsoft Corp’s .NET strategy, which is meant to other hands than Sun’s? Is Bob Sutor right that Java should now undermine Sun’s dominance of the enterprise-computing be open sourced? Is Alan Williamson right that Java will survive space by tempting developers into using C#, not Java, in order and thrive, come what may? to more easily jump aboard the “XML-Web services” bandwag- To respond to this article, go to www.sys-con.com/java/arti- on. cle.cfm?id=1443.

78 JULY 2002 JULY 2002 79

Java COM Java COM LETTERS TO THE EDITOR

Thank You Alan! can really rock – where it can ? ’d like to thank Alan Williamson for make a huge difference. Iremembering our issues and concerns Java is a beautiful language at JavaOne. I just read the April issue and will be around for a long (Vol. 7, issue 4) and time. I want to make sure that we saw that my ques- build and sing its strengths and tions were posed to accept its weaknesses. the JDK 1.4 product We have a duty to care for our manager. One thing: language; to that end, I hear Java scary response success stories all the time and this regarding the dou- brings a lot of pleasure to me. But J2SE ble and float per- in JDJ we don’t want to focus formance question, always on the good stuff, we have something to the to shed some light on some of the effect, “we don’t things that maybe aren’t so great. specifically isolate a If Java is to survive and not test for this.” You become just another legacy lan- would think numer- guage, we mustn’t let our confi- ical calc perform- dence be our down- J2EEance would be reviewed J2ME upon each new fall. release. We have to learn from SmallTalk and [email protected] C++ and not add Java to that list. Alan Should Stop Being a Pessimist! matter except as a means to an et on with it, Alan! In March (Vol. 7, Alan Williamson end: satisfying real require- Letters Gissue 3) .NET could kill Java. In May [email protected] ments. A lot of very good (Vol. 7, issue 5) J2ME may die. I’m get- developers found that out to TogetherSoft Home ting sick of all this nonsense from the Incorrect Impression their dismay during the editor-in-chief. n Scot Silverman’s Internet bubble. Ireview of Frankie RequisitePro (Vol. 7, Phillip Gordon [email protected] issue 4) the conclu- [email protected] sion gives the impression that a third- Corporation party database engine is mandatory. This CLR vs JVM is incorrect; RequisitePro installs out of LR, Microsoft’s virtual machine, has the box with MS Access DB drivers so it Cto be lightweight [“There May Be doesn’t even require MS Access software Trouble Ahead” (Vol. 7, issue 4)]. The www.togethersoft.com/challenge/1 to be installed (not mentioned on the JVM has gone through and continues to Rational site, www.rational.com/prod- go through many changes; the one lan- ucts/reqpro/prodinfo.jsp#more). guage it supports is Java. Now imagine the CLR supporting multiple languages. Tom Servaes How laughable to think that it can be all [email protected] things to all languages. A Means to an End Mark Allred an Pilone wrote a very good article [email protected] D(“Pervasive Computing,” Vol. 7, issue 4), but he said one thing that I’d like to contradict. “Now the question is: How can a developer lever- age the available tools Frankie, my editorials are written to make an applica- from a positive not a pessimistic angle. tion that’s useful for I sing the praises of Java at every the consumer?” opportunity, but I’m not afraid to learn The question some of its weaknesses. Java isn’t the should be (always): answer to everything, and if as a commu- “What kind of appli- nity we can learn to accept this, surely cation does the con- this will allow us to devote our energies sumer want?” Tech- to pushing Java into the areas in which it nology and tools don’t

80 JULY 2002 JULY 2002 81

Java COM Java COM JAVANEWS>

4 Macromedia Releases JRun 4 These diagrams help devel- (San Francisco) – Macromedia, Inc., has opers understand the announced the immediate availability of application generated by SUN UNVEILS SUN ONE JRun 4, the latest release of its Java OptimalJ, enabling them > PORTAL SERVER 6 application server. The new version to quickly navigate includes the latest standards compatibil- through its components. (Santa Clara, CA) – Sun Microsystems, Inc., has ity, simplified deployment, innovative www.compuware.com announced the Sun ONE Portal Server 6, a portal clustering technology, and Web services server solution that includes fully integrated, secure integration. Download from 4 PointBase Server 4.3 and identity management capabilities. www.macromedia.com/store/. Embedded 4.3 Available The Sun ONE Portal Server 6 (formerly iPlanet J2SE with JDBC 3.0 Compliancy Portal Server) also offers Web single sign-on, policy 4 Borland Expands Development (Mountain View, CA) – and access control, service provisioning, and unified Solution for Java PointBase, Inc., has user management – via the embedded Sun ONE (Scotts Valley, CA) – Borland Software announced the availabili- Identity Server – and provides all the development Corporation has announced its expand- ty of PointBase Server 4.3 tools and portlet ISV support required to quickly ed development solution for Java with and PointBase Embedded and efficiently deploy employee, customer, and the introduction of JBuilder 7, Borland 4.3. New features include business partner portals. Enterprise Studio 4 for Java, and JDBC 3.0 compliancy, http://sun.com/software/products/portal_srvr/ J2EEOptimizeit Suite 4.2. J2ME greater transactional per- home_portal6.html Borland’s new products support the formance, enriched func- latest standards for Java, Web services, tionality, improved database and wireless development. console, and enhanced documenta- 4 The Middleware Company Announces www.borland.com tion. J2EE Patterns Training www.pointbase.com (Austin, TX) – The Middleware Company’s 4 Sitraka JProbe 4.0 Now Shipping new J2EE Patterns training course is avail- News (Toronto) – Sitraka is shipping version 4 4 New Release of CocoBase from able to developers worldwide. of its comprehensive performance tun- THOUGHT Inc. J2EE Patterns is a one-week training Home ing toolkit with new investigative fea- (San Francisco) – THOUGHT Inc. has course for hard-core J2EE developers tures such as heap snapshot differenc- announced the release of CocoBase who already have experience with J2EE ing, new application server and IDE Enterprise O/R, version 4.0, service technologies and want to take their integration tools, and enhanced plat- release 2.0. knowledge to the next level. Students form and environment support. This release includes new distributed will learn best practices, design patterns, TOPICS HAVE INCLUDED: www.sitraka.com caching features with examples, a new antipatterns, and idioms. The course is Developing SOAP Web Services shared source transparent persistence vendor-neutral, and the concepts Architecting J2EE Web Services 4 Compuware Releases OptimalJ 2.1 facade interface with open APIs, updat- learned can be applied to any J2EE pro- (Farmington Hills, MI) – Compuware ed inheritance and cartesian manage- gramming environment with any mod- Corporation has announced the com- ment, and updates to the Sun ONE ern J2EE application server. …COMING TO A CITY NEAR YOU mercial availability of OptimalJ 2.1, a Development Environment (Forte for www.middleware-company.com 2002 Java development environment that’s at Java) integration including new user NEW YORK AT WEBSERVICES EDGE 2002 ...... EAST JUNE 27 the forefront of pattern editing function- documentation. 4 Parasoft Signs Global Software BOSTON...... JULY 10 ality. For a free 30-day copy of CocoBase Agreement with IBM SAN FRANCISCO ...... AUGUST 6 OptimalJ 2.1 includes three new dia- Enterprise O/R go to (Monrovia, CA) – Parasoft has announced Take Your Take Your SEATTLE ...... AUGUST 27 grams at the application model level – www.thoughtinc.com/cber_info.html. an agreement with IBM to provide Java AUSTIN...... SEPTEMBER 10 the DBMS Relational, the EJB application development testing, support, Career to the LOS ANGELES...... SEPTEMBER 19 4 Career to the Component, and the Web Component. eNGENUITY Technologies Announces and service for IBM software products. SAN JOSE AT WEBSERVICES EDGE 2002 ...... WEST OCTOBER 3 JLOOXTelecom 2.0 Under the terms of the licensing agree- CHICAGO ...... OCTOBER 17 (Montreal) – eNGENUITY Technologies ment, Parasoft will provide global use of NextNext Level!Level! ATLANTA...... OCTOBER 29 ROCOCO RELEASES BLUETOOTH Inc. has announced the release of its product as well as in-person and MINNEAPOLIS ...... NOVEMBER 7 SIMULATOR WITH J2ME SUPPORT JLOOXTelecom 2.0, a ready-to-use devel- Web-based training for IBM developers, LearnLearn HowHow toto Create,Create, Test Test andand NEW YORK ...... NOVEMBER 18 > opment framework for creating distrib- including IBM Global Services (IGS). SAN FRANCISCO ...... DECEMBER 3 uted Java-based network/element man- www.parasoft.com DeployDeploy Enterprise-ClassEnterprise-Class (Dublin, Ireland) – Rococo Software is shipping agement systems and network planning Web Services Applications 2003 Impronto Simulator 1.1, a Bluetooth application applications. 4 QNX Momentics Simplifies Embedded Web Services Applications CHARLOTTE ...... JANUARY 7 development tool that runs Java applications in a Among the new features is support of Programming REGISTRATION FOR EACH CITY CLOSES THREE BUSINESS DAYS BEFORE EACH MIAMI...... JANUARY 14 simulated Bluetooth environment. several new protocols for client/server (Ottawa, Canada) – QNX Software Systems is TUTORIAL DATE. DON’T DELAY. SEATING IS LIMITED. DALLAS...... FEBRUARY 4 Impronto Simulator 1.1 now includes J2ME and communication. JLOOXTelecom 2.0 also shipping QNX Momentics development NON-SUBSCRIBERS: REGISTER FOR $245 AND RECEIVE THREE FREE ONE-YEAR BALTIMORE ...... FEBRUARY 20 J2SE support, security control through the uses Lightweight Directory Access suite, an integrated toolset for embedded SUBSCRIPTIONS TO WEB SERVICES JOURNAL, JAVA DEVELOPER’S JOURNAL, AND BOSTON ...... MARCH 11 XML-JOURNAL, PLUS YOUR CHOICE OF BEA WEBLOGIC DEVELOPER’S JOURNAL Bluetooth Control Center, and an industry-leading Protocol (LDAP) to facilitate user development, that’s available in two editions: REGISTER WITH A COLLEAGUE AND SAVE 15% OFF THE LOWEST REGISTRATION FEE. JVM. It’s 100% Java and simulates a complete Java authentication and control access to Professional and Standard. The Professional OR WEBSPHERE DEVELOPER’S JOURNAL, A $345 VALUE! APIs for Bluetooth Wireless Technology (JABWT) specialized server- and client-side busi- Edition includes C, C++, Embedded C++, and environment without Bluetooth hardware or stacks. ness logic. Java code developer tools. www.rococosoft.com www.engenuitytech.com www.qnx.com TO REGISTER: www.sys-con.com or Call 201 802-3069

82 JULY 2002

Java COM CAREER OPPORTUNITIES ADVERTISERINDEX ADVERTISER URL PHONE PAGE What’s in the next

AccelTree www.acceltree.com 25 Actuate Corporation www.actuate.com/info/jdjad.asp 800-884-8665 69 Altova www.altova.com 49 issue of JDJ ? Altoweb www.altoweb.com 27 ‘Should I Stayor Should I Go?’ BEA Systems www.bea.com/download 4 Borland www.borland.com/new/jb7/5068.html 800-252-5547 59 JDJ VISITS MICROSOFT Canoo Engineering AG www.canoo.com/ulc/ 41 61 228 94 44 39 Switching careers midstream Compuware Corporation www.compuware.com/products/optimalj 19 Dice www.dice.com 53 WHAT ARE J2SE eNGENUITY Technologies www.jloox.com 800-684-5669 55 THE VIRTUES ESRI www.esri.com/mapobjectsjava 888-332-2320 37 OF .NET? Fiorano Software www.fiorano.com/tifosi/freedownload.htm 75 HiT Software www.hitsw.com 408-345-4001 71 IBM www.ibm.com/websphere/winning 32-33 Alan Williamson reports WRITTEN BY IBM www.ibm.com/db2/rocks 34-35 on his visit to Microsoft’s

J2EE J2ME Improv Technologies www.improv-tech.com/jdj/download 29 BILL BALOGLU & e were recently looking for a skilled Swing engineer for one of our clients. headquarters BILLY PALMIERI W InetSoft Corporation www.inetsoft.com/jdj 888-216-2353 73 Three people who had been referred to us looked like good candidates for the job. Infragistics, Inc www.infragistics.com 800-231-8588 14-15 One of them was happily employed. back on the job market. Still nada. left the corporate rat race to make a dif- InstallShield Software www.installshield.com 57 The other two had left the business – And then it occurs to you: Do I really ference in the nonprofit world. INT, Inc www.int.com 713-975-7434 30 one is now an aspiring rock star, the want to go back? He’s now managing director of COMBATING THE ‘OBJECT CRISIS’ other, a monk. Global Catalyst, a private foundation Interland www.interland.com 877-501-6055 61 In the wake of historically massive “A third of the people in my network that initiates and grants funding for Jinfonet Software www.jinfonet.com/JDJ7.htm 31 Why you should invest in object training before Java layoffs at technology companies, many ultimately saw their layoff as more of a projects that bring technology, software, training Macromedia www.macromedia.com/go/jrun4jdj 45 Home tech professionals have reconsidered blessing than a nightmare,” says Kim and Web access to underserved commu- FPO what they want to do with their lives. Mason, former design director at nities, including third-world countries. Metrowerks www.wireless-studio/com 9 For many people, this process of E*TRADE. “I saw it as a chance to “I went from a large corporate Mongoose Technology www.portalstudio.com 87 THE ANATOMY AND PHYSIOLOGY OF reconsidering career goals has followed change my whole paradigm.” atmosphere to the smaller, nonprofit Motorola www.motorola.com/developers/wireless 67 EJB 2.0 PRIMARY KEYS a familiar pattern. A common scenario Mason had led multiple groups environment,” says Chertok, “and it How primary keys are mapped when using container- /n software inc. www.nsoftware.com 47 for those who were laid off goes some- responsible for E*TRADE’s brand identi- works better for me. This is what I managed persistence in EJB 2.0. Why are they useful? thing like this: ty and product positioning in the U.S. always wanted. But today there’s a lot New Atlanta Communications www.newatlanta.com 42-43 AUTHOR BIOS 1. Within the first few weeks comes the and eight international markets. more caution on the part of nonprofits Northwoods Software www.nwoods.com/go/ 800-434-9820 68 Bill Baloglu is a disorientation and shock of losing After doing contract work and in hiring people with private sector WHY CREATE A CUSTOM LAUNCHER? Oracle Corporation www.oracle.com/ad 800-633-1072 21 principal at that daily routine and sense of accepting invitations to lecture and lead experience.” A custom launcher makes startup as simple as point ObjectFocus responsibility and self-esteem that short-term workshops, Mason went into “Nonprofits typically operate with a Parasoft www.parasoft.com/jdj7 888-305-0041 41 and click (www. ObjectFocus .com), a Java staffing goes along with an important posi- secondary schools, mentoring students consensus management style, while pri- Pramati Technologies www.pramati.com 79 firm in Silicon Valley. tion. in media design. vate companies use a top-down man- Precise Software www.precise.com/jdj 800-310-4777 23 Bill has extensive OO2. Still in fast-forward mode, your fran- Her recent move to Oakland, agement style,” says Chertok. PERFORMANCE TUNING IN JAVA QUALCOMM Inc http://brew.qualcomm.com/ZJD4 63 experience and has tic networking gene kicks in to “get California, coincided with Mayor Jerry “A lot of the people who’ve left are Simple techniques to make your code run faster held software Rational Software www.rational.com/offer/javacd2 6 development and you back in the game” as soon as pos- Brown’s plan to revitalize city schools making life decisions versus career deci- senior technical sible. with charter conservatory schools, sions,” says Anthony Ha, whose titles have Rational User Conference www.rational.com/ruc 888-889-0074 77 management 3. Everyone in your network is glad to including the Oakland School for the included director of application develop- SilverStream Software www.silverstream.com/coals 888-823-9700 17 IS THE CONSUMER MARKET positions at several hear from you and sympathetic, but Arts. Mason will be head of media arts ment and director of Web technology. READY FOR J2ME? Silicon Valley firms. Sitraka www.sitraka.com/jclass/jdj 800-663-4723 13 they’ve been laid off too – and no one for the new school, which opens in Currently working on a long-term Will J2ME make the huge impact that Sun (and the Billy Palmieri is a is hiring. September. contract at Sun Microsystems, Ha sees Sitraka www.sitraka.com/performance/jdj 800-663-4723 88 developer community) hopes for? seasoned staffing 4. You decide to use some of that over- “It’s been a 180 for me,” says Mason, plenty of opportunities on the horizon Sonic Software www.sonicsoftware.com/jdj 2 industry executive and time you earned pulling all those pre- who is herself a graduate of the Duke for engineers who are open to exploring a principal at Sprint PCS 65 ObjectFocus. His prior release all-nighters and take some Ellington School of Arts in Washington, new technologies. WHOLE HOUSE AUDIO IN THE PALM OF position was at time off to do a little traveling. D.C. “Education is one of those careers – “Most people I know are still in the Sun Microsystems www.sun.com/forte 11 YOUR HAND - PART 2 Renaissance5. That trip to Hawaii, South America, you either choose it or it chooses you.” industry, but they might be moving into TogetherSoft Corporation www.togethersoft.com/challenge/1 81 Getting and setting listening preferences Worldwide, where he Europe, or Australia reminds you that Many tech professionals have been newer technologies like wireless or Web held several senior Web Services Edge World Tour www.sys-con.com 201-802-3069 83 there are places in the world where trying to make the transition from the services,” says Ha. PLUS THE INSIDE SCOOP ON: management positions Zero G www.zerog.com 415-512-7771 3 in the firm’s Silicon time moves slower than in the hotbed private to the public sector, applying “If people really love technology, • Java jobs General Conditions: The Publisher reserves the right to refuse any advertising not meeting the standards that are set to protect the high edi- Valley operations. of high tech. their technical and management skills they’ll find a way to stay and do what torial quality of Java Developer’s Journal. All advertising is subject to approval by the Publisher. The Publisher assumes no liability for any • Reusable components 6. You relax, unwind, and realize that toward the goals of nonprofit organiza- they love, even if it’s for less money. And 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 • Java design or damages in excess of the cost of the advertisement as a result of a mistake in the advertisement or for any other reason. The Advertiser is fully there may be more important things tions. they’ll always be able to find jobs doing responsible for all financial liability and terms of the contract executed by the agents or agencies who are acting on behalf of the Advertiser. • Polymorphic EJBs in life than coding, debugging, and After five years as a manager at one it.” 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 beating the competition to market. of Silicon Valley’s largest educational of their advertisements printed in Java Developer’s Journal. Advertisements are to be printed at the discretion of the Publisher. This discretion 7. Two or three months go by. You check software companies, Michael Chertok [email protected] 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.

84 JULY 2002

Java COM CUBIST THREADS The Beautyof Java

This is the thirteenth installment of Cubist Threads, but iron- ically I’m feeling pretty darned lucky to be writing it.Who would WRITTEN BY have thought this blatantly self-aggrandizing auto-theoretica BLAIRWYMAN would survive a whole year?

Not me, though I must admit that Of course, part of me worries that FCMP to my heart’s nascent content. My time has really flown by. Every month, having a garbage collector makes me a “improved” iterator ran in just one-third J2SE Alan’s thoughtful e-mail reminder “namby-pamby” programmer. It just isn’t the time taken by the high-level lan- catches me a little off guard. hard enough to implement convoluted guage algorithm (even fully optimized), I’ve already used up most of my program logic when you know you have a and I was in programming Nirvana. “brushes with greatness” stories, so I find good GC behind you, right? How can I Of course, the real world reasserted its myself at a bit of a loss as to just what to maintain my illusion of guru-ery if I don’t cantankerous nature when the next release write about this month. For the life of have to malloc() and free()? Shouldn’t I of the compiler up and changed the ASM me, I can’t seem to get into “flowery ver- mask the occasional sign bit, grok the linkage. Suddenly, parameters were no biage mode” today, so please bear with double floating point format, or XOR longer getting pushed directly into the 8087 J2EEme as I try to adopt J2ME a less formal tone. repeatedly and recursively? “Proper” pro- registers, so I had to rework the linkage, los- (After all, we’ve been through a lot gramming simply can’t be simplified too ing a good bit of my hard-won perform- together this past year, dear reader, so much, or else it turns into some abom- ance improvement. perhaps I should start addressing you inable exercise in visual button-pushing, One true beauty of programming in less as an abstract audience of strangers, doesn’t it? I mean, you can’t let just any- Java, in my not-so-humble opinion, is and more as the amalgamated “friend” body be a programmer, can you? Egad! that we get to think about bigger pic- you’ve become.) Yeah, right…hogwash. Program- tures, without getting caught up in rel- I’ve been very busy at work lately. ming is about taming unruly slivers of ative trivialities. Instead of ensuring Schedules have a way of creeping up on etched silicon, using whatever best correct argument alignment, chasing Mongoose Home me, and the project I’m currently working practices are available (at the current pointer bugs, and forgetting to delete on is no exception. Compared to recent state of the art) to get the job done. our temporary structures, we can projects, the nice thing about this one is When I started programming, one of spend our time changing the world. that it is absolutely thick with Java code. The the first things I really sank my teeth into Okay, I’ve obviously swung my par- not-so-nice thing, as usual, is the looming was chaos and fractal visualizations. It adigm pendulum too far. I have a ton of deadline. There’s something about the seemed like my (4.77MHz 8088-based) respect and admiration for the bit- Technology word deadline that really twiddles my bits. hardware was never even close to fast twiddlers and storage managers in the As I’ve told you before, my links to enough – especially for Mandelbrot set programming world. Frankly, it is on Java began tenuously. My work has renderings – so I remember taking great their vast shoulders that we stand, mostly been about writing bits and pains (can you say ASM?) to implement boldly new-ing where no programmer www.portalstudio.com pieces of the C++ “underpinnings” of our an M-set iterator directly in the 8087 has new-ed before, and we must never wonderful iSeries JVM, but lately I’ve math coprocessor chip’s fabulously forget that. Java’s decidedly credible been studying (and writing) a lot of Java expansive 8-register onboard stack. beauty of form is the result of incredi- code – good and bad – and have never The interface between Turbo Pascal ble intellectual effort and the culmina- been happier. Oh sure, writing C and 3.x and ASM was as clean as could be tion-du-jour of programming practice. AUTHOR BIO C++ code is fun and all, but the relative hoped for: the compiler pushed floating What’s next? “Computer, please cue Blair Wyman is a softwaredrudgery of worrying about structure point arguments to my little assembler up some Blue Oyster Cult and brew me engineer working for IBMalignment and storage management routine (creatively named “iter”) direct- a stout ale, will ya?” Cool. in Rochester, Minnesota,really makes me appreciate the beauty of ly into the 8087 stack. All my ASM code home of the IBM iSeries. a garbage-collected language like Java. had to do was merrily FDUP, FMUL, and [email protected] Java Dudes

94 JULY 2002 JULY 2002 87

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

88 JULY 2002

Java COM