WEBLOGIC SERVER 6.0 REVIEW INSIDE PAGE 30

TM

The World’s Leading Resource Java COM June 2001 Volume:6 Issue:6 FREE! PRODUCT Sept 23–26, 2001 New York, NY PAGE 16 SHOWCASE CD! INSIDE!

SHOW PROGRAM 183

From the Editor by Alan Williamson pg. 7

Industry Commentaries by Richard Green pg. 8 by Bruce Scott pg. 146 EXCLUSIVE: INTERVIEW WITH KEYNOTER...SCOTT DIETZEN Product Reviews Sun Blade pg. 20 WebLogic 6.0 pg. 30 JDJJ2EE: The Challenges and Pitfalls of J2EE Chris Kampmeier 36 ServletExec pg. 54 iPlanet pg. 62 2.0J2EE: Growing JSP and Servlet Sites Patrick Sean Neville 44 J2EE Editorial SPECIAL FOCUS by Ajit Sagar pg. 22 ON J2EE, J2SEJ2EE: & J2ME WebSphere Column Brady Flowers 56 Interview J2EE: The Impact of EJB 2.0 Tyler Jewell 64 Larry Freeman, Manager J2EE Blueprints Team pg. 26 J2SE: Building a Telephone/Voice Portal Klinner & Walker 78 First Look Optimal J pg. 140 J2SE: Making a Mountain out of an Anthill Neal Ford 86 J2ME Editorial J2SE: JNI Programming in C/C+ Blair Wyman 96 by Jason Briggs pg. 144 J2SE: Evolving Functionality Satya Komatineni 104 $AVE BIG J2SE: Optimization and Java Irvin J. Lustig 110 J2SE: Using JavaBeans in Dreamweaver Barbarelli & Deming 118 J2SE: Deployment of JavaServer Pages John Goodson 126 J2SE: Java Quirks – Dates and Calendars Roedy Green 134 ONE-TIME OFFER! J2ME: The Incredibly Shrinking Platform Jason Briggs 148 Stop by our booth for special pricing J2ME: A UI Framework for the MIDP API Glen Cordrey 154 J2ME: Java Thick Clients with J2ME Glenn Coates 164 Sonic Software www.sonicsoftware.com

2 JUNE 2001

Java COM Zero G www.zerog.com/installs

JUNE 2001 3

Java COM BEA www.developer.bea.com

4 JUNE 2001

Java COM BEA www.developer.bea.com

JUNE 2001 5

Java COM TogetherSoft www.togethersoft.com/jdjspecial.html

6 JUNE 2001

Java COM FROM THE EDITOR ALANWILLIAMSON, EDITOR-IN-CHIEF The rational The Dawn alternative of Content

Version 4.5 t has been one hell of a journey to get where here at JDJ are looking forward to working with we are today. What you’re holding in your him. Introductory Offer Ihands is the first of the new breed of Java At the time of writing we haven’t made a Developer’s Journal. On behalf of the team firm decision on our J2SE editor. Choosing an $2995 here, allow me to introduce JDJ 2.0. editor is something we don’t take lightly; for Teamwork Server This has been the accumulation of however, I am interviewing a number four months’ preparation, and we of people at JavaOne, so I’ll let you hope you like the new look and feel know next month. of your beloved JDJ. We aren’t In addition to bringing you quite settled in yet, as this issue is J2EE richer content, we’re going to be All 9 UML diagrams the crowning glory of the year, running a series of beginner’s fea- Additional Features: with JavaOne, and it kind of throws tures to ease the learning curve that • Performs Java, C++ or CORBA IDL out the normal rules of engagement. many of you experience when starting code round-trip engineering (code One of the first changes you’ll notice out on the Java road. We’re looking to generation and reverse engineering); is the three major sections of the magazine that make the transition easier for our beginners and recognizes JavaDoc comments. This feature allows you to write code, reverse reflect the three editions of Java 2. We’ll be to help nurture them into world-class develop- engineer, make changes to the model focusing on each edition with equal journalis- ers. We’ve lined up some great writers for this and re-generate the code without losing tic flair. There’s a lot going on in the Java series and I look forward to introducing this any implementation specific information. space and we want to bring you the feature to you next month. • Supports UML 1.3 notation. best of the best each and every As editor-in-chief I have a • Saves diagrams as bitmap PNG/JPG and month. responsibility to set the tone of the scalable WMF/SVG/EPS/DXF formats. As you know, the Java spec- magazine and ensure continuity • Provides XML interoperability — native trum is simply too wide for one J2SE each month. Those of you familiar model files are stored in XMI format. single person to effectively report with my writings know I’m pas- • Integrated with Forte for Java (FFJ) IDE the latest goings-on. To that end we sionate about a number of areas of versions 1.0 and 2.0. have invited people who are Java and that I’m not scared to whip renowned in their respective fields to up a debate about any of the subjects. Standard Edition: ...... $249 become section editors. These editors are However, there is one area that I wish to cham- Professional Edition: . . . . $499 responsible for editing and sourcing the con- pion – the overall quality of the skill base of our tent for each section. You would think it makes new recruits to the Java community. With the Visit us at Java One my job easier, but sadly it doesn’t seem to work help of our section editors and Advisory Panel out quite like that. If anyone can figure we’ll be delivering articles for all skill lev- that out, let me know! els, from beginner right up to top- Floating License . . $100 additional Ajit Sagar has kindly accepted notch developer. the role of J2EE editor and, if his As I pack my kilt in preparation Upgrade for a $69 annual fee! work for this issue is anything to for JavaOne, I hope I get to meet go by, our J2EE section is in great J2ME and talk to a lot of you while I’m hands. I look forward to working out there. If you see a strange-look- with Ajit in subsequent issues as we ing bugger in a skirt, be sure to stop C bring you cutting-edge, J2EE-focused him; chances are it’s me! If it’s not, I articles. please apologize and quickly move on. I’m ✦ G ✦ ▲✦ For our J2ME section I feel fortunate in more than happy to talk to you about what M snagging a great writer and authority on this we’re up to here at JDJ and welcome your feed- No Magic... new emerging field. Jason Briggs joins us in back. Just Technology That Works earnest in the next issue, and I know that we I look forward to serving you in the future… Download fully functional demo at:

[email protected] www.magicdraw.com AUTHOR BIO contact us at Alan Williamson is editor-in-chief of Java Developer’s Journal. In his spare time he holds the reins at n-ary (consulting) Ltd, one of the first [email protected] companies in the UK to specialize in Java at the server side. Reach him at [email protected] (www.n-ary.com) and rumor has it he welcomes all suggestions and comments! 100% Pure Java Application

JUNE 2001 7

Java COM INDUSTRY COMMENTARY WRITTEN BY RICHARD GREEN Train Once,Write Anywhere

ince its introduction in 1995 Java technology has been worry less about memory size and more about page size. J2SE known for its “cross-platform” compatibility. This ability They’re game, map-application, and e-commerce shopping Sto run applications on multiple platforms made Java big page developers, or online newspaper editors, but I think they and presented developers with a new and unique appli- do what the traditional developer did at the highest level: pro- cation development platform. In the beginning cross-platform vide people with information they need to get their job done meant that Java applications could run on several distinct or their life arranged. workstation-system platforms such as Windows, Macintosh, Developers need to understand that the network has not and UNIX. only changed the paradigm for building and running applica- In 1999, we announced that the Java platform would tions, it’s changing the developer paradigm too. In the world of J2EEextend itself upward J2ME into the enterprise server with the Java there are many implications. Who is a developer today? Is Enterprise Edition, and downward into the client-device space it only someone who can craft an EJB, or does it include a with the Micro Edition. With the release of J2EE in December servlet developer or even a JSP developer who’s “developing” a 1999, cross-platform began to get a new, vertical meaning Web page that’s fundamentally content? since compatibility extended now from the desktop to the For years developers built on the platform they targeted. server. This compatibility has formed the basis for J2EE’s Today, as the IT industry crosses the great divide from address- incredible success as the standard for networked-enterprise ing just traditional computers to addressing consumer elec- application development, especially in the application server tronics devices, it becomes impossible to develop to a single space. hardware platform. The consumer space makes the desktop Home Today, we’re starting to see yet another manifestation of look like the height of homogeneity. In the consumer electron- cross-platform as J2ME-enabled consumer electronics devices ics world there are dozens, if not hundreds, of different system come to market. Now Java spans vertically from the server to types and many of them are completely proprietary. With Java the desktop to the modern client. However, we also introduce supporting applications and services horizontally on all the a new meaning to cross-platform because J2ME spans hori- different client-device types, as well as vertically from the zontally across all the new client devices such as cell phones, client to the server, developers can build services that will pagers, PDAs, TV set-top boxes, automotive systems, home reach millions of devices in the near term, and billions in the gateways, games, and even smartcards. You might call this long term if the analysts are correct. That’s a lot of sophisticat- “cross-client” compatibility. ed, increasingly intelligent applications and services that will When you think about it, this is an awesome shift and has be developed and targeted at a massive number of users. real impact on the meaning of the term developer. For the Ultimately, consumers will have a wide variety of devices to industry, putting Java into cell phones, like those introduced in access their services and will use the one most convenient at late January by NTT DoCoMo in Japan or the Motorola phones any given time. At work they might use a desktop computer; at for the Nextel network that debuted in April, means the digital home, a PC or television set-top box; while traveling, they can convergence we’ve been talking about for the last decade is use an automotive system; and in between, their cell phone. really happening. For developers it means the addressable This means developers will have to keep in mind the needs of market for their work has increased dramatically since indus- all these devices when developing networked applications and try analysts predict that billions of devices will log on to the services. Internet and other networks like DoCoMo’s and Nextel’s. We, of course, feel that Java is the only development and When JDJ’s editor-in-chief, Alan Williamson, visited me this deployment environment that can scale vertically and hori- spring, we had an interesting discussion about just what a devel- zontally. This capability is crucial for the fast-emerging era of oper is. Alan posited that the new devices that run Java would smart networked services, but it also provides a huge benefit appeal to the veteran developers, you know, the guys who write for developers because once they know the Java programming close to the silicon and can keep track of memory allocation and language and have experience with how the Java platform the other complexities that come with writing programs for a con- deals with different system types, the reach and range of their strained environment like a 640KB cell phone. skills becomes almost unlimited. I call this TOWA: train once, I countered that now there are, in effect, two categories of write anywhere. Java developers – regardless of whether developers: the traditional that Alan described and a new kind they’re hard-core application developers or the new breed of who are more focused on content than logic. The latter, of content developers – can take their skills almost anywhere in course, is not as technical as the traditional developer. They the digital domain they care to go.

[email protected] AUTHOR BIO Richard Green is vice president of Java Software Development for , Inc. He drives the strategy, product development, support, and compliance technologies for all of Sun's Java/Jini/XML platforms. Richard holds a BA/MA from the State University of New York at Albany.

8 JUNE 2001

Java COM FuegoTech www.fuegotech.com/d

JUNE 2001 9

Java COM JAVA FAQ What is Java? Is it a product? When Java first appeared on the public radar in 1995, it was heralded as the second com- ing. To that end the message conveyed by the marketers was at times mixed, and more often than not, wrong. Java was not the answer to everything, it was merely a new computer lan- Qguage that attempted to address some of the problems that previous languages failed to answer or found difficult to solve. It was not a product. It was not something you could buy from your local computer retailer. Java was not the solution, merely a tool. Never before in the history of languages has one language captured the imagination of the press the way Java has. The reason for this is a little unclear but, as a result, more confusion has built up around Java than any other language. Before long board rooms wanted “a Java solution” before really understanding what it was. When Java first came out, it was previewed J2SE within the Netscape (and then IE) browser. It became known as the “little gray rectangle” and, due to early implementations, had to fight the backlash that it was apparently slow. Since

JAVA A 1995, Java has been doing a lot of growing up and this early criticism of speed is no longer applicable. Who invented Java and why? What was wrong with the other

J2EE J2ME languages available? You could write a book about the history of Java, but the short-short version is as follows. QAround 1990, , , and Mike Sheridan got together to work on a project – to come up with an alternative to C++ that would address some of the issues associ- ated with this language. At that time all three were working at Sun and, after an initial demon- stration of their project to Bill Joy and Scott McNealy, it was decided to spin off a separate company to see if this “Oak” language could be successful in providing Time-Warner with a set-top box operating system. Fortunately, as history dictates, it failed. The project was brought back under the wing of Sun, where after a weekend of legendary coding by Naughton Home and later additional development by Jonathon Payne, HotJava was born, the first Java-based WebA browser. From there on in the popularity of Java simply grew, capturing the imagination of the development community. The main reason it was an instant hit was its “WORA” claim – Write Once, Run Anywhere. This allowed a developer to develop a single application once and deploy it to many platforms without recompiling/redeveloping a single line of code. What is this “JVM”acronym I keep seeing around? Following the answer from the previous question, Java’s ability to run anywhere is a result of the way it’s designed. When you develop a program in Java, you don’t compile to the native platform but to a virtual computer. This virtual computer is where your program will run. QWhen you compile your Java program it’s converted to bytecode. It’s this bytecode that you can run within the virtual computer. The virtual computer, of course, is so called because it doesn’t physically exist. Therefore, a piece of software plays the role of the virtual computer, FAQ‘s SPECIAL SECTION: which is more commonly known as the (JVM). The JVM is a native, spe- cific piece of software that runs on top of a given platform. The Java code then runs on top of DJ recognizes that not all our that. For example, the JVM for a Solaris machine is different than the JVM for the MS-Windows readers are world-class develop- architecture, but the functionality they provide is the same. This is the key to providing a WORA environment. Jers, in fact many of you don’t A even develop. To this end we’d like to Does JavaScript have anything to do with Java? introduce a regular column for those No. JavaScript is a language developed by Netscape. Originally it was designed to have a of you that are either just starting out closer relationship; this never materialized but the name stuck. It has created no end of con- fusion and headaches for all those who don’t know the difference. or simply want to get a feel for what’s Q happening out there in Java land. If What’s all the fuss about with respect to Microsoft and Sun? your question isn’t answered here, feel ’Tis a complicated story, but in layman’s terms: when Sun licensed the Java source code to free to ask any of our editors and we’ll Microsoft to allow them to build a JVM for the Windows platform, Microsoft modified it a lit- tle to have greater access to some of the Windows-specific components. This modification see if we can help you out. broke the WORA philosophy and to that end, Sun felt it was no longer Java and wanted Microsoft to restore their JVM to be 100% compliant. Microsoft didn’t feel the same. Hence the courtA case.

10 JUNE 2001

Java COM Talarian www.talarian.com/jms

JUNE 2001 11

Java COM Intenational Advisory Board www.sys-con.com

12 JUNE 2001

Java COM Merant www.merant.com

JUNE 2001 13

Java COM Infragisti www.infrag

14 JUNE 2001

Java COM c Spread gistics.com

JUNE 2001 15

Java COM JDJ: For the benefit of our readers, could you briefly describe your role in BEA?

Dietzen: I’m the chief technology officer for the

BEA e-commerce server division. As CTO I look after the technical strategy for BEA’s application server products, including the WebLogic Server,

WebLogic Enterprise, and Tuxedo. So I get to spend a lot of time on newer technology initia- tives, such as Web Services, wireless, and J2EE- based integration. Also, I represent BEA on the

Java Executive Council, which helps shape the future of Java via the .

Finally, I drive relationships with BEA’s high-level partners, OEMs, and blue-chip customers.

JDJ: BEA seems to be every- We’ve substantially upgraded market the same way J2EE Dietzen: Of course, competition where on the application JMS performance and are now transformed application is good for the industry and server map. Can you tell us supporting IP multicasting. servers. good for BEA. Longer term, the some of the plans you have But e-business platforms We’re also growing biggest advantage that the Java for expansion in the next cou- are more than application WebLogic up toward the line community offers over Microsoft ple of years? servers. I’m most excited right of business with .NET may be the breadth of Dietzen: Application servers now about the impact Java Personalization, Portal, innovation happening on our are growing up into what BEA and Web Services standards Commerce, and Campaign platform. Our second rule is that has been calling an e-business are having on integration. To Manager. These products most competition is really “coo- platform. Much of this new date, the EAI market has failed empower business users to pitition.” Sun remains one of our functionality is being pack- to deliver on its promise, aggregate and tailor informa- most strategic partners even aged directly within the appli- because (1) the frameworks tion services to better meet though we compete with cation server, such as support have been built on proprietary the needs of their customers iPlanet. And while WebSphere for multichannel applications – middleware platforms with no and business partners. remains our primary competitor, INTERVIEWED BY a unifying architecture for standard data model, and (2) BEA complements more than delivering information servic- adapters to the legacy systems JDJ: I attended your BEA 99% of IBM’s business. Even AJIT SAGAR es across Web, wireless, need to be “one off’ed” for User’s Group Conference ATG is becoming complementa- voice, and Web Services. each EAI solution. So (1) is about a month ago. It seems ry. I was excited to hear that With WebLogic Server 6.1, now being addressed by J2EE, that you’re close to complet- ATG was following the direction [email protected] we’re also automating the XML, and Web Services, ing the story on a true e-busi- of BroadVision and Vignette in generation of Web Services while (2) is being taken care ness platform. How do you replacing their proprietary mid- bindings for existing J2EE of by the J2EE Connector plan to distinguish yourself dleware with a J2EE application applications by generating Architecture (JCA). BEA from other leading vendors server. So how is BEA maintain- SOAP and WSDL from EJB believes this one–two punch like iPlanet, WebSphere, and ing the #1 position against session beans and vice versa. will transform the integration ATG? strong competition?

16 JUNE 2001

Java COM • Reference customers: We’re integrated e-business. The platform JDJ: This year it seems that the ent interaction models? We’ve got leading the J2EE market in pro- includes the market-leading application server vendors are some very large wireless deploy- duction deployment. WebLogic application servers plus continuing their move toward ments under our belt, but no one • Alliances: BEA has over 1,600 commerce, personalization, and being “one-stop-shops” for all has yet made wireless as easy as value-added partners, including portal components for rapidly B2B2C frameworks. BEA seems to the Web is today. almost all of the enterprise soft- developing e-commerce applica- be on the same bandwagon. What Overall, while I remain well ware vendors (PeopleSoft, tions to win and retain customers. would you say is unique about satisfied with BEA’s ability to com- BroadVision, Vignette, Ariba, and It also includes newly updated what your company offers? pete, we also must continue to so on), and virtually all of the integration capabilities that sup- Dietzen: In addition to what I men- aggressively improve our platform leading systems integrators port new ways of automating busi- tioned earlier about key differentia- to keep our lead – J2EE-based (Accenture, CSC, KPMG, and so ness processes, and linking and tors for BEA, I would say our plat- application integration; business on). This is the most critical lit- interacting with suppliers, part- form is unique in how it offers a Web services for complex, multi- mus test for a platform: How ners, and existing deployed appli- comprehensive e-business platform party, transactional applications; many other vendors are standing cations. for building and deploying e-busi- broadly distributed caching and on top of you? ness applications, spanning the full replication; opening up J2EE appli- • Technology leadership: JDJ: One of the things I took spectrum from personalized e-com- cations to the line of business man- WebLogic’s initial claim to fame away from the conference was merce and customer relationship ager for access to real-time opera- came out of getting new Java that although you have a broad management on the front end to tional data; and working with our technologies to market as early range of offerings, there’s still total e-business integration on the partners on higher-level tools for as possible. We’re continuing some integration work to be back end, including integration J2EE application development. that trend with EJB 2.0, JCA, and done. For example, most of the across the enterprise and outside These are all areas that we’re transparency for Web Services. products run on WebLogic 5.1 the enterprise to the supply chain investing in aggressively. • Independence: The final point I instead of 6.0. How will you and other business partners. We’re would cite is BEA’s independ- bridge the gap? able to provide all of this on the JDJ: With consolidations and ence. Unlike our larger competi- Dietzen: Well, the good news is industry’s only fully integrated plat- mergers, where do you think the tors, we don’t have a vested that all of our WebLogic products form based completely on open application server market is going? interest in hardware, operating now run on WebLogic Server 6.0. industry standards, such as XML, Where does BEA stand in that mar- systems, databases, or profes- The time frame you refer to was Web Services, and J2EE. ket? sional services. That means ISVs several months ago, shortly after Dietzen: We believe the J2EE appli- and end users can partner with WebLogic Server 6.0 was intro- JDJ: In which areas do you think cation server represents the pre- BEA knowing that their applica- duced. The only alternative to this WebLogic needs more enhance- dominant platform for e-business tions can be deployed on gap would be our holding up the ments to compete in the market? applications. For BEA to do well, Solaris, Linux, Windows, HP-UX, release of WebLogic Server until For example, I think you need Java and J2EE must continue to do AIX, AS/400, and even OS/390, our value-added e-commerce and more work on the presentation well. At present, the only emerging and deployed with Oracle, DB2, integration products were certified end. alternative appears to be MS SQL Server, Informix, on the new platform. Given the Dietzen: I’d agree with you if the Microsoft’s .NET. As .NET continues Sybase, and so on. continuing demand for new appli- point regards multichannel presen- to flesh out over the coming year, I cation server technology, we felt tation services. BEA’s current offer- expect to see increasing and JDJ: Whom do you consider your this was the wrong thing to do. ing around the Web is very power- healthy competition between the strongest competition? ful, incorporating graphical tools Java and Microsoft stacks. We all Dietzen: IBM is the only competi- JDJ: Who are some of your biggest and content management solutions need to help educate the market tor we see on a regular basis. In customers? from our strategic partners that the real game is Java and EJB our most recent earnings report, Dietzen: Some of the big names Macromedia, WebGain, versus C# and COM+, while Web you’ll see the latest evidence that are FedEx, J.P. Morgan Chase, Documentum, Interwoven, and Services and XML are features of we’re growing our WebLogic busi- Charles Schwab, Nokia, DHL, Vignette. However, the multichan- both platforms. Indeed, the adop- ness faster than IBM WebSphere is United, Delta, British Airways, nel problem is more difficult. tion of the common Web Services growing, and we’re growing from a General Electric, Verizon, Amazon, While there’s a lot of marketing stack – SOAP, WSDL, UDDI – substantially larger base. and NTT DoCoMo. All told, we around wireless technology solu- offers the Java community the have over 9,400 corporate cus- tions, the industry hasn’t yet solved promise of “out-of-the-box” inter- JDJ: Could you broadly categorize tomers, including 100% of the all of the challenges. For example, operability with Microsoft. your product line? Fortune Global 500 financial serv- how can I automatically rerender Much as Microsoft and Oracle Dietzen: Our product line makes ices companies, telcos, my content for the diversity of emerged as the predominant plat- up the WebLogic E-Business computer/office equipment manu- wireless devices – different screen form for the client/server genera- Platform that provides the essen- facturers, pharmaceuticals, airlines, sizes, different browsers and tion, BEA aspires to offer the server- tial infrastructure for building an and delivery services. markup languages, and even differ- side platform for “networked” appli- “ We believe the J2EE application

server represents the predominant platform for e-business applications“

JUNE 2001 17

Java COM cations or “Web apps.” This is a JDJ: When do you plan to integrate products in the process manage- Dietzen: We think we’ve done a large and growing market, but con- WebLogic Server with Tuxedo? Can ment space. BEA has entered this unique and good job of this solidation is going to continue. The you briefly outline for our readers space with WebLogic Process already. You might say it’s BEA’s rai- costs associated with delivering a the advantages of such an enter- Integrator and Collaborate. Do son d’etre. BEA software is now comprehensive e- business platform prise environment? you think that with these environ- running sites with more than have doubled over the past couple Dietzen: We have very tight inte- ments, the way business applica- 10,000 transactions per second. of years as more and more func- gration between WebLogic and tions are designed will change? We’ve scaled a single Java applica- tions – personalization, clustering, Tuxedo today, but don’t look for Dietzen: We believe integration tion to run across a 60-server/240 integration, Web Services, wireless, these to become a single product needs to be designed in from the processor cluster. We’re offering and more – have become built in. that runs in one address space. The beginning. Adding these capabili- Web and EJB session protection The industry will seek to amortize things that make Tuxedo the ties to the WebLogic platform, that doesn’t rely on a single process these costs by standardizing on the world’s best application server for along with the Web Services, JCA, pair (scaling bottleneck) or writing platforms that are the richest and C and C++, don’t work well with JMS and other integration enablers, updates to a DBMS (far too expen- most ubiquitous. I believe that to Java. BEA is offering our enterprise will enable our customers to build sive). Count on BEA to do our best date BEA is benefiting most from customers the marriage of the two “integration-ready” applications. to maintain our competitive advan- this consolidation. market leaders – WebLogic Server tage here. is the leading Java/Web container, JDJ: How well do you integrate JDJ: Does BEA plan to get into while Tuxedo is the market’s lead- with back-end systems? Besides JDJ: How far have you advanced in actual application design; that is, ing container for C/C++ (Tux even JCA, do you have any partners that the wireless and mobile market? do you plan to step into industry supports COBOL). you integrate with directly? For Where do you think this market is verticals or do you plan to always Far more important than merg- example, WebMethods or even going? be application enablers? Do you ing WebLogic and Tuxedo is tight BizTalk? Dietzen: We’re providing cus- plan to continue expansion in hori- interoperability between the two. Dietzen: I think that’s already hap- tomers with a single platform that zontal technology offerings? The most recent release of Tuxedo pening. For quite some time people they can use for multichannel Dietzen: We’ll stay focused on e- allows direct invocation from have been talking about workflow applications – wireless and wire- business infrastructure. BEA doesn’t Tuxedo to WebLogic EJBs (via automation tools, but still hand line, as well as voice and Web have the expertise to compete in IIOP). Of course, we go in the coding such tasks. But by building Services. We expect the wireless vertical applications. More impor- opposite direction as well, allowing applications on J2EE, you’re already application market will be very tant, to do so would alienate our Java applications to easily invoke building in the integration points large in a couple of years. Today, most critical allies – the independ- CORBA objects or Tuxedo services. (EJB, JMS) that a Java-based work- the growth is uneven. Northern ent software vendors. All with security and transaction flow solution plugs into. The same Europe, Japan, and some other For application design, we do sharing between the containers. thing is true for integration – by Asian marketplaces are well ahead offer professional services to our building on WebLogic you inherit of the U.S. While I’d argue that this strategic customers, but that’s most JDJ: WebLogic 6.0 is a big release an integration platform for tapping market is not quite mainstream yet, often used to validate their use of for BEA. Would you like to into legacy systems. That allows we have many customers that have BEA technologies. We couldn’t describe the main enhancements our ISVs to offer products that are deployed first-generation wireless possibly hope to grow our own as compared to Release 5.1? How “built to integrate” without having applications already. professional services organization many of your current customers to invest in the integration technol- as fast as the demand. Leveraging have made the switch? ogy. JDJ: How does XML fit into your our system-integration partners is Dietzen: WebLogic Server 6.0 is the overall technology blueprint? the only scalable approach. platform of choice for nearly all our JDJ: Do you plan to enhance sup- Dietzen: XML has become a funda- customers’ new applications. In 6.0 port for Microsoft environments in mental part of the application serv- JDJ: With Commerce Server and we introduced a powerful new man- the future, or do you plan to con- er, and we’ve been supporting XML Collaborate, aren’t you stepping agement framework built on JMX tinue in a pure Java arena? for quite some time. XML clearly into the same space as some of the with a Web-based console, a new Dietzen: Both. We’ve been com- plays a big role in Web Services, as B2B solution providers? For exam- scalable, high performance messag- mitted to integration with the well as the other integration servic- ple, the companies who build elec- ing (JMS) engine, major transaction Microsoft platform all along and es we have built into the overall tronic marketplaces? Is this inten- manager enhancements built in Java will continue to do so going for- WebLogic platform. tional? by the Tuxedo team, along with ward. We’ve been providing native Dietzen: Actually, I don’t quite buy numerous improvements in installa- integration with IIS (MS Web JDJ: For Java developers who are this. For customers looking for an tion, ease of use, and in XML. Server), COM, SQL Server, and the not familiar with BEA products, “out-of-the-box” B2B solution, they Now we’ve gone one better NT registry for several years, and what would be a good place to should absolutely continue to go to with WebLogic Server 6.1, avail- with Web Services we have the start incorporating them into their our ISV partners. However, other able at JavaOne. 6.1 adds Web promise of “out-of-the-box” inter- existing applications? companies are looking to differenti- Services automation, J2EE updates operation with the Microsoft envi- Dietzen: Certainly, anyone building ate via home-built B2B solutions. (EJB 2.0, JCA, JSP 1.2, Servlet 2.3), ronment. However, we have no or planning to build Web, wireless, So this generally comes down to a and support for caching and repli- plans to embrace application or Web Services applications in Java buy versus build analysis. Provided cating “read mostly” entity beans development in C#. Instead, BEA should look at WebLogic as well as the underlying platform is J2EE and efficiently across a large cluster. Of will continue to ensure that our our competitors. The sooner the bet- WebLogic, both approaches offer course, we also have a substantial Java/J2EE-based products work well ter, since I’m convinced that virtual- superior scalability, reliability, inte- deployed base of 4.5 and 5.1 users on the Microsoft platform. ly all server-side Java applications gration, and investment protection. that we’ll continue to look after. are going to be deployed on appli- So getting the customer to choose a JDJ: How do you plan to address cation servers for ease of develop- WebLogic and J2EE foundation is JDJ: It seems that all the applica- enterprise-level concerns like scal- ment, manageability, security, quali- BEA’s goal. tion server vendors are offering ability, robustness, and security? ty of service, and so on.

18 JUNE 2001

Java COM Propel www.propel.com/RAS

JUNE 2001 19

Java COM PRODUCT REVIEW

hen Sun Microsystems rings you up My only issue with this aspect of the system is that and asks whether or not you’d be the communication between the virtual Windows Winterested in playing with a new desk- machine and the Blade could have been made a lot top system they’ve just announced that’s aimed easier. Ironically, you can copy and paste text at Java developers, amongst many, what can between the two with the clipboard, but you can’t you do but nod affirmatively. After much easily access files. The Blade system’s file space is dis- paperwork to allow the machine to leave the tinct and not directly accessible from the virtual shores of the U.S., it arrived here in Scotland Windows machine. I was informed you can FTP or where it was immediately unpacked and fired even set up an SMB/NFS channel between the two, Sun up. That was two months ago. but this isn’t set up from the start. You literally have So how did I get on? Well, let me take two different machines sharing a keyboard/mouse you through the trials and tribulations of and monitor, but sharing nothing else. You even need working with a Sun desktop machine, as to put in an extra network connection as the ability to opposed to a Windows-based system, to share the same network connection doesn’t exist. J2SE develop Java applications. I believe this to be more of a selling point than an The first thing I noticed about the actual practical feature. I couldn’t get DVDs or even physical box is that it’s undeniably drop- audio CDs to work, so my initial excitement to get dead gorgeous. Traditionally Apple com- WinAmp up and running was muted very quickly. puters have always triumphed in this Now I’m sure much of this is due to configuration Blade area over and above the dull, lifeless PC and, if this is the case, I hope the final version of Blade boxes. Sit an Apple beside a PC and each is all sorted and ready to run without customers hav- time the Apple beckons you closer. Sit an ing to dash to the online Web sites for help. J2EE J2ME Apple beside the Blade system and sud- So how did I get on with Java? Well, I copied over by Sun Microsystems denly the Apple has serious competition one of our internal product sources, totaling around on its hands in the looks department. 32,000 lines of code, which I thought would be a Increasingly, hardware manufacturers good starting point. After firing up Forte and creat- are moving away from “plain-Jane” ing the necessary projects, I was happily compiling. boxes to the more eye-pleasing sexier No immediate problems. Couldn’t really complain. Is it that sharp? packaging. So hurrah on that score. After a week of this I decided to install a number of I asked to have the Forte development application servers on the machine and start testing it tools preinstalled on the machine so I from a server’s point of view. It’s fair to say that Sun was Home could start building as soon as it was horrified when they heard of this, as the machine was- REVIEWED BY ALANWILLIAMSON powered up. As you can see from the n’t designed as a server but as a desktop. Not too sure pullout, the specification of the machine where the fire was as it performed admirably, and we [email protected] is very impressive. Sun’s biggest selling put the machine under a lot of stress testing; the com- point with this machine is the 64-bit pro- bination of Solaris 8 with an UltraSparc 500MHz CPU cessing power for under $999 and, with- made light work of our tests. out question, you do get a lot of machine I took the machine into this world on purpose. for that price. But does a Java developer Many Linux servers are installed on ex-desktop really need or care about 64-bit process- machines, giving them a whole new lease on life. ing? I was about to find out now that I was Seeing the price of the basic Blade system, this brings set to begin the trial period. it into the world of low-end server budgets, and I Now it’s fair to say from the outset that as wanted to see how well it would perform in this much as I enjoy the Linux/Solaris world for world. The results were good and we would happily Sun Microsystems servers, Windows NT is still my preferred take a Blade system to run in a server environment. 901 San Antonio Rd desktop choice. So to be forced to use the Should you decide to purchase a Sun Blade, a Palo Alto,California 94303 standard Solaris desktop was indeed a bit- word of warning. When visiting the main Web site, tersweet pill to swallow, and a pill that was www.sun.com/desktop/sunblade100/, don’t be Web:www.sun.com/desktop/sunblade100/ indeed swallowed. I did put up with it, and fooled into thinking you’ll be getting a flat-screen any criticisms I may pose here are not panel. It’s not part of the standard package, but you Sun Blade 100 Workstation: indicative of the desktop software. I appreci- have to do a lot of digging on the Web site to discov- • 500MHz UltraSPARC-IIe Processor,256-KB L2 Cache ate that you can download and install alter- er this. Don’t worry too much about the lack of a flat- • 128MB memory (1x128MB DIMM) native Windows managers, but I simply didn’t screen; I wasn’t that impressed with it and LCD tech- have the time to go through this procedure. nology has a long way to go to meet the crispness • Sun PGX64 On-Board Graphics Accelerator However, the pill did indeed have a sugar and sharpness of traditional CRT monitors. • 15GB 7200 RPM EIDE disk coating in the form of the preinstalled SunPCi On the whole I liked the machine. I don’t • 48x CD-ROM drive coprocessor card, which at the time of the think the benefit of 64-bit processing is going to • 1.44MB floppy review was a 600MHz Celeron processor. This be much of a gain for the average Java develop- was a complete Windows machine within a er. I also don’t believe you’re going to get many • Smart Card Reader window and it worked wonderfully. Sun is ship- developers to give up their Windows machine • Solaris 8 Installed (RTU) ping this dual-computing feature with the Blade for a Sun Blade system. If you’re a developer who • 3 PCI I/O slots to ease the transition for people like myself that requires a reliable server platform running in • 2 EIDE disk bays are hell-bent on staying with the Windows world, the background and doesn’t have the budget for • 10/100M-bit Ethernet but would like to have the 64-bit processing power a separate machine, the Sun Blade is for you. and all the other benefits the Blade system can That said, it’s a fine-looking machine when • 4 USB,2 IEEE 1394,1 serial and 1 parallel port offer. all’s said and done.

20 JUNE 2001

Java COM HostPro www.hostpro.com

JUNE 2001 21

Java COM J2EE EDITORIAL WRITTEN BY AJIT SAGAR J2EEJ2EE J2ME Welcome toJ2EE ROADMAPROADMAP

s Alan Williamson, JDJ’s editor-in- ible. We have an interview with one of the chief, mentioned earlier in this market leaders, BEA Systems, in this issue. J2SE Aissue, JDJ 2.0 is a total redesign of We’ll continue to provide you with the latest JDJ; our intention is to reflect the develop- news from the leading players in the J2EE ments in the Java platform as closely as we app server market in subsequent issues. can. Some of you may be familiar with my One thing that has definitely helped the role in JDJ – I wrote a column, E-Java, and J2EE market is the coherence that’s now was one of the editors. I’m honored to wear available in the documentation. Sun has The Java2 Platform, Enterprise the hat of the J2EE editor for JDJ 2.0. Alan published the J2EE framework in a concise Edition defines the APIs for and I have worked together in the past and set of blueprints. The types of applications building enterprise-level I’m sure that the synergy between us will built on J2EE frameworks now include e- applications. J2EE take JDJ 2.0 to new heights – all focused on marketplace applications such as auctions your needs. and storefronts. This is in contrast to the J2SE...... v. 1.2 So, without further ado, Welcome to examples on simple airline sites that were J2EE. This section is dedicated to the Java 2 available last year. It’s now much easier to Enterprise JavaBeans API Enterprise Edition and focuses on the find information on when to use JSPs ...... v. 1.1 application of the Java platform in the instead of Servlets, how CMP compares development of enterprise solutions. Last with BMP, and more. Java Servlets...... v. 2.2

Home year at JavaOne, Sun announced the three I’m very excited about this issue. It Java platform editions. And let me tell you marks a new era for JDJ and for our J2EE JavaServer Pages technology ...... v. 1.1 folks, after several years of confusing the coverage. In subsequent issues you’ll see community with complicated messages, I an assortment of: JDBC Standard Extension think they finally got it right. This past year • Case studies ...... v. 2.0 has been a testimony to the success of this • Information from the source (Sun) decision. J2EE has matured and come of • Interviews Java Naming and Directory age. •FAQs Interface API...... v. 1.2 The past year has also proven to be an • Programmer tips and tricks eye-opener for those of us developing • Design guidelines RMI/IIOP...... v. 1.0 applications using the J2EE APIs. This stuff • Book and product reviews actually fits together. For folks developing • A wealth of information that’s available Java Transaction API ...... v. 1.0 distributed enterprise applications, it’s only from SYS-CON also easier to focus on the n-tier architec- JavaMail API...... v. 1.1 ture principles evangelized by the J2EE As you know, we’ve also expanded the Blueprints to build world-class applica- venues for sharing information with all of Java Messaging Service tions. you. Check out our Web site at www.sys- ...... v. 1.0 The J2EE APIs have also made it easier con.com/java and the conferences we’re for application server vendors to publish hosting at www.sys-con.com/javaedge. clearer guidelines for building applications The only way we can address your spe- Useful URLs: using their products. The last year has seen cific issues, your requirements, your prob- Java 2 Platform Enterprise Edition a shakeout in the app server industry. In lems is if we hear back from you regarding http://www.java.sun.com/j2ee/ 1999, app server vendors were popping up what we’re doing wrong and what we’re J2EE Blueprints all around the market. With the rude awak- doing right. Your input is what differenti- http://www.java.sun.com/j2ee/ ening in the B2B market in the latter half of ates us from the rest. Our sole purpose is to blueprints last year and the beginning of this one, sev- serve your needs. So please write to us and eral consolidations and mergers have taken tell us what you think, what you need, and J2EE Technology Center place. For example, Bluestone is no longer a how you’d like us to help you achieve your http://developer.java.sun.com/de stand-alone app server vendor; HP now goals. Feel free to e-mail me at ajit@sys- veloper/products/j2ee/ owns it. The dust is still settling, but the con.com, or any of the other contributors ones who will remain standing are now vis- in this issue, with your feedback. J2EE Tutorial http://java.sun.com/j2ee/ [email protected] tutorial/ AUTHOR BIO Ajit Sagar is the J2EE editor of JDJ, and the founding editor and editor-in-chief of XML-Journal. A senior solutions architect with VerticalNet Solutions, based in San Francisco, he’s well versed in Java,Web, and XML technologies. ROAD MAP

22 JUNE 2001

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

JUNE 2001 23

Java COM J2EE FAQ

J2ME What is J2EE and how does it relate to EJBs? J2EE is a standard architecture to define and support an n-tier application programming model for building enterprise applications. It’s based on standard design practices and pat- Qterns that simplify the application development by decoupling the components between the different tiers of an application. The three main tiers that are defined are the thin client, the business logic layer, and the data source layer. J2EE also encompasses security, performance, and integration issues with external (non-Java) environments. Enterprise JavaBeans define the server-side component model used by J2EE to implement J2SE business logic and are the crux of the J2EE Platform. EJB design defines how to write distrib- uted Java components that run in a J2EE-compliant application server. EJBs simplify devel- opment of middleware components by enabling them to be transactional, scalable, and portable.A EJB components run only in the context of a J2EE application server, which acts as the “operating system” of the enterprise by handling such mundane tasks as EJB instantiation and destruction, transactions, persistence and recovery, and component deployment. J2EE

J2EE What are the J2EE Blueprints? Last year Sun came out with a new set of design guidelines for building enterprise appli- cations using enterprise Java APIs. These are collectively available as a set of documents called the J2EE Blueprints. These documents include architectural design guidelines for developing Qenterprise applications using the Java 2 Enterprise Edition APIs. The following quote from Sun’s Web site describes the rationale behind the J2EE Blueprints: The J2EE Blueprints provide an integrated set of documentation and examples that describe

Home and illustrate “best practices” for developing and deploying component-based enterprise appli- cations using the J2EE platform. The J2EE Blueprints are intended to help developers of e-com- merce applications in the areas of component design and optimization, division of develop- ment labor, and allocation of technology resources. The Blueprints are a great source of information and guidance for developers who are try- ingA to get their arms around J2EE development. They run the gamut of APIs that comprise the J2EE platform. The Blueprints may be viewed in the same light as blueprints that are used to build a house. This set of guidelines outlines the tools at your disposal and the framework that can be used to build applications based on the J2EE APIs. More information about the Blueprints can be obtained from the following sources: Overview: http://java.sun.com/j2ee/articles/blueprints.html Download: http://java.sun.com/j2ee/download.html#blueprints Book: Kassem, N., and the Enterprise Team. (2000). Designing Enterprise Applications with the Java Platform, Enterprise Edition, Addison-Wesley. What is the Pet Store Demo and how can it help me understand J2EE application development? The Pet Store Demo is an example application built based on the guidelines and design SPECIAL SECTION: Qpatterns that comprise the J2EE Blueprints. In other words, the Pet Store Application is akin to a model house built using the J2EE Blueprints. The Pet Store is a complete end-to-end e-commerce application built using J2EE. However, it is a sample application. The demo acts as a great tutorial for understanding how to build Web-based e-commerce applications using J2EE. However, to build a real-world application, you will have to deal with issues including security, scalability, and performance, using the demo as a base. Some of the Java application server vendors have implemented the Pet Store Demo as a sample application built using their respective application server fea- tures.A More information on the Pet Store can be obtained from the following sources: FAQ‘s Architecture Overview: http://java.sun.com/j2ee/blueprints/jps11/archoverview.html Book: Kassem, N., and the Enterprise Team. (2000). Designing Enterprise Applications with the Java Platform, Enterprise Edition, Addison-Wesley. Application Servers: BEA Systems offers a tutorial using the Pet Store Demo as a base. The demo is documented in their standard documentation sets.

24 JUNE 2001

Java COM isavvix www.java.isavvix.com

JUNE 2001 25

Java COM The important idea is that products/jsp/taglibraries.html. an online store is one of many It’s our hope that the Pet Store application scenarios that can and other Blueprints demo Interview with be built using the design applications will aid the guidelines presented by the developer and architect in Blueprints team. building J2EE applications that

J2ME take advantage of key fea- Larry Freeman JDJ: Could you broadly tures. describe how the Pet Store application can be used to JDJ: What is Sun’s relationship Manager,J2EE Blueprints Team build and deploy real-world with J2EE application server applications? vendors with respect to the INTERVIEWED BY AJIT SAGAR Freeman: I think the key here reference implementation? is the design guidelines and Freeman: The reference imple- J2SE patterns that are presented on mentation is not an industrial- the Blueprint Web site, strength J2EE implementation. s readers of JDJ know, future, J2EE Blueprints will http://java.sun.com/j2ee/blue It’s meant as a way for the J2EE is a standard plat- include other demo applica- prints. The goal is to help developer community to try Aform for developing tions besides the Pet Store. developers and architects out J2EE and write applica- enterprise applications using The Pet Store is currently make design decisions when tions on it before purchasing reusable components, standard being used in the writing a J2EE application. a professional J2EE platform. APIs, and popular software Deployathon, an event in Implicit in the Java Pet For example, there’s an early design patterns. The J2EE which a J2EE application is Store is a set of components access reference implementa- J2EE Blueprints is a Sun initiative deployed and run on multi- that can be reused in other tion currently available that that’s meant to aid developers ple application servers to contexts. For example, the enables developers to try out trying to get their arms around demonstrate J2EE portability. Java Pet Store includes a J2EE 1.3 (http://developer. the wide gamut of J2EE tech- shopping cart, a mailer, and java.sun.com/developer/early nologies and APIs, and the Pet JDJ: Could you briefly inventory components. It’s our access/j2ee). The reference Store Demo is a part of this ini- describe what role you’ve intention that this reference implementation is also used tiative. They provide a combi- had in the design and “dis- application can be used as a by J2EE application server

Home nation of J2EE design guide- bursement” of the Pet Store framework for building real- vendors as a standard for lines and a sample application Demo application? world applications. In addi- comparing their own imple- for building distributed appli- Freeman: I’m the manager of tion, recommendations about mentations. cations on the Java platform. the J2EE Blueprints team, and typical design decisions need This month JDJ brings you an my team designed and wrote to be made, such as JSP ver- JDJ: How many application exclusive interview with the code for the Java Pet sus servlets, stateful versus server vendors have imple- Lawrence Freeman, the manag- Store. As J2EE’s Application stateless session beans, and mented the Pet Store as a refer- er of the J2EE Blueprints team. Programming Model group, container- versus bean-man- ence application that’s distrib- we’re responsible for making aged persistence. uted as part of their product? JDJ: The last year has seen best-practice recommenda- Freeman: I assume you’re some major developments in tions to application develop- JDJ: The Pet Store serves as a referring to the J2EE the J2EE Platform. Were there ers. The Java Pet Store was good reference implementa- Deployathon. Last year at the any targets Sun wanted to designed to illustrate these tion. However, in the real Deployathon an earlier ver- achieve in this time? guidelines. The J2EE world do you expect the sion of the Pet Store was run Freeman: There are four deliver- Blueprints team will be speak- application writers to imple- on numerous J2EE application ables for J2EE: the specification, ing at this year’s JavaOne. ment all the pieces of the servers to demonstrate J2EE the reference implementation application or do you expect portability – it was tested on (RI), the Compatibility Test Suite JDJ: The Pet Store demo is an part of the framework to be eight different platforms. (CTS), and the reference applica- unusual application. How did built by third-party vendors Detailed information about tion, that is, the J2EE Blueprints. it emerge? such as application server last year’s Deployathon can Freeman: The application providers? be found at http://developer. JDJ: What is the Pet Store began as part of an effort to Freeman: It’s our belief that java.sun.com/developer/techni Demo? write a book on the J2EE these decisions are best left to calArticles/J2EE/deployathon2. Freeman: The Pet Store Demo application programming the market. I think there are In this year’s Deployathon is the reference application model. A sample application many fascinating frameworks we expect to have a larger for J2EE that showcases the was needed to go with the out there. For example, in the number of participants using main features of the J2EE book. recently released J2EE Tutorial Java Pet Store 1.1.2. We’ll platform. It’s part of the The original application (http://java.sun.com/j2ee/ have full details at JavaOne. Blueprints program that seeks was a wine store; however, the tutorial), there are some At present, I’m not sure to provide best practice images that represented the examples of the Struts tag about the exact number of guidelines for J2EE applica- different wine bottles all library (http://jakarta.apache. application server vendors tion development. J2EE looked the same. Two mem- org/struts) that can help devel- who are distributing the Pet Blueprints includes a Web bers of our team who are pet opers speed up the imple- Store as part of their product, site, a best-selling book, lovers thought a pet store with mentation of their applica- however, it’s available for design patterns, and refer- its variety of animals would tions. Other tag libraries can download at our Web site. For ence applications. In the make a more interesting demo. be found at http://java.sun.com/ the latest information on J2EE-

26 JUNE 2001

Java COM Compuware www.compuware.com/numega

JUNE 2001 27

Java COM “ The J2EE reference implementation

is an excellent way to try out J2EE. J2ME Best of all, it’s free. “

compatible application facto test; the CTS is the offi- tions do you think offer the Pet Store is to take advantage servers, check out cial test. However, none of best examples? of the Blueprints book avail- J2SE http://java.sun.com/j2ee/com this is required by the J2EE Freeman: This is not the inten- able at http://java.sun.com/ patibility.html. Blueprints. tion of the Pet Store. The goal j2ee/blueprints/apmtoc.html. of the Blueprints program is to JDJ : What exactly is the JDJ: Have you received any help developers take advan- JDJ: What other resources are Deployathon and how is it feedback from the vendors? tage of the key features of available for learning J2EE used? Freeman: We’ve received a J2EE. Our target audience is application development? Freeman: The Deployathon is large amount from vendors developers. Freeman: At present J2EE is an exercise run by Sun to and developers. As the J2EE putting together a Developer’s demonstrate J2EE’s “write best practice group, we’re JDJ: Are there any other ref- Corner that should be avail- J2EE once, run anywhere” mes- constantly thinking and erence applications in the able before JavaOne; check sage. It takes the Blueprints rethinking the best way to offing? Do you think the Pet for this at http://java.sun.com/ reference application and implement the different J2EE Store covers it all? j2ee. As I mentioned before, deploys and runs it on differ- technologies in applications. Freeman: There are other ref- there’s a new J2EE tutorial ent J2EE app servers. Last For example, we’ve updated erence applications currently available at year’s Deployathon is avail- our book with more recent being planned. I’m very excit- http://java.sun.com/ able online at http://develop design recommendations ed about what’s coming up. j2ee/tutorial. Another useful

Home er.java.sun.com/developer/ based on this feedback, which I’d encourage developers to resource is the document technicalArticles/J2EE/deploy can be found at continually check bundle that comes with the athon2. http://java.sun.com/j2ee/blue http://java.sun.com and reference implementation. prints/qanda.html. http://java.sun.com/j2ee to Included in this bundle is the JDJ: Does Sun provide stan- find out the latest. In addition, J2EE Developer’s Guide, dard guidelines for vendors JDJ: How useful do you think developers can sign up for which helps developers take to implement the Pet Store? such a reference application our mailing list at advantage of the Deploytool, Freeman: I’m not sure what is for the Java community? http://archives.java.sun.com/ar a GUI-based tool that comes you mean by “implement.” Does it benefit only the J2EE chives/j2ee-interest for the lat- with the reference implemen- Java Pet Store is designed to platform developers or can it est information. tation. The Java Developer be deployable and runnable be used by all factions of the No, I don’t think the Pet Connection has resources for on all J2EE-compatible Java community? Store covers it all. That’s not learning more about J2EE, for servers. We provide both the Freeman: My team is focused its goal. Its goal is to cover all example, http://developer. source code and the binary on the J2EE so their recom- the major features of the latest java.sun.com/developers/tech form of the Java Pet Store on mendations focus on it too. release of J2EE. When J2EE nicalArticles/J2EE. For devel- our Web site. Any developer 1.3 is released, a reference opers looking for an IDE, on any J2EE-compatible appli- JDJ: Does the Pet Store Demo application will also be there’s an early-access release cation server can run the ref- contribute to any type of cer- released that showcases its of the J2EE IDE Toolkit at erence application on their tification or measuring stick major features. http://developer.java.sun.com/ platform. for Sun to evaluate applica- developer/earlyAccess/j2eeid tion server vendors? JDJ: How can our readers e-toolkit. JDJ: What types of problems Freeman: It’s not a measuring familiarize themselves with have vendors faced getting stick for Sun. I’d say it’s more the Pet Store? What if they JDJ: Are there other their application server prod- of a tool used by the applica- don’t have access to an “Blueprints” under develop- ucts to comply with the J2EE tion server vendors them- industry-strength application ment for the Java platform? Blueprints that are used to selves. As mentioned earlier, server? Does Sun plan to provide implement the reference it’s a useful test after a vendor Freeman: I’m glad you asked other implementations of application? has passed the CTS. It’s a this question. The J2EE refer- them? Freeman: J2EE Blueprints is a standard way for them to try ence implementation is an Freeman: Yes, there are other set of design guidelines used their J2EE platform out. Sun’s excellent way to try out other implementations. by application developers. It’s official test is the CTS. J2EE. Best of all, it’s free. It’s Hopefully, we’ll be able to routine that after an applica- one of the many platforms make some announcements at tion server has passed the JDJ: Of the vendors who have that make up the JavaOne. In the meantime, CTS, the next step is to verify leveraged the Pet Store to Deployathon. keep checking our Web site at that the Java Pet Store can run provide tutorials for their Another way to become http://java.sun.com/j2ee/blue- on the platform. This is a de products, which implementa- more familiar with the Java prints.

28 JUNE 2001

Java COM CustomWare www.customware.com

JUNE 2001 29

Java COM PRODUCT REVIEW

ill Coleman, Edward Scott, and Alfred with the administration panels. The issue is just Chuang must be looking at their how complex and sophisticated these enterprise- BSeptember 1998 acquisition of class application servers are fast becoming. BEA is WebLogic WebLogic as the best money they ever spent. supporting a wealth of functionality within the WebLogic’s Tengah product was a little- WLS 6.0 product, and there’s just no getting around

J2ME known, Java-based application server when the fact that it’s a lot of product to get your arms BEA made the decision to buy their way into around. WLS 6.0 is not a product that you can the growing market for Java application expect to master overnight. BEA continues to forge Server 6.0 servers way back when. Since those early ahead in the J2EE realm and WLS 6.0 supports a days the J2EE specification has matured wealth of new and enhanced Java features such as and BEA has made great strides with the EJB 2.0, JMS, XML, and native JDBC drivers for by BEA WebLogic product line. Their most recent most of the popular RDBMS engines. However, the effort is WebLogic Server 6.0 – a product new release also offers improved functionality in J2SE REVIEWED BY JIM MILBERY that was touted with much fanfare at several other critical areas of the product. We’ve BEA’s eWorld conference in Dallas, Texas. already mentioned the updated Web administra- Fresh from my indoctrination at tion interface (based on Sun’s Java Management eWorld, JDJ turned me loose on a copy of Extension: JMX), which is substantially better than WebLogic Server 6.0 to give it a test drive. previous releases. BEA now provides support for In my opinion, the market is starting to HTTP 1.1 directly within WebLogic, so there’s no see a division between the enterprise-class need to install or configure a separate Web server. application servers (IBM, Oracle, iPlanet, While this is not a critical feature for production and BEA) and other Java-based applica- sites (that may have already standardized on J2EE tion servers. The enterprise J2EE servers Apache/iPlanet or Microsoft IIS), it makes life a lot are stocked chock-full with lots of bells easier for developers to work with WebLogic. This AUTHOR BIO and whistles, while the remaining prod- release also includes a number of security Jim Milbery is a software consultant based in Easton, ucts tend to offer “best-of-breed” solu- enhancements such as ACL improvements, audit Pennsylvania, with Kuromaku Partners LLC. He has over 17 tions for specific application needs – such trails, and JAAS login support. years of experience in application development and relational as JMS, servlets and JavaServer Pages. During the user conference I got the impres- databases. He is the applications editor of Wireless Business BEA’s WebLogic 6.0 is clearly an enter- sion that WLS (rather than WLE) is quickly becom-

Home & Technology, the product review editor of Java Developer’s prise-class product, and it continues to ing the key product for BEA. However, underneath Journal and the author of Making the Technical Sale. take the lead in all things related to Java as the covers BEA is clearly drawing from their far as application servers are concerned. Tuxedo expertise to flesh out the WLS platform. [email protected] I’ve tested numerous versions of Updated transaction-processing features, such as WebLogic in the past, and I’ve always distributed transaction management, are just one found the product to be easy to install and example of this effort. BEA was an early proponent configure. Each version of WLS offers new of advanced scalability features for the application features, which in turn makes the software server platform (another result of their Tuxedo her- more complicated to install, manage, and itage). WLS 6.0 extends its support for servlet repli- maintain. This is not to say that BEA has cation to include replication for session EJBs. This not made incremental improvements in new release can even perform in-memory replica- the management tools for WLS. Clearly, tion of stateful session EJBs, which provide failover the new management console, shown in for business logic. In the long haul, BEA is staking Figure 1, is well organized and robust. out the high ground as regards scalability and fault Test Environment: In fact, all of the panels in the manage- tolerance. The customers that I spoke with have Dell 4300 PowerEdge 2CPUs (397MHz),Windows NT Server 4.0 ment interface are hyperlinked to the not necessarily taken advantage of these high-end SP5 1 GB RAM online documentation, so it’s easy to work features in previous releases. (In fact, I have sat through several of Dean Jacob’s highly regarded user group sessions – and Dean’s advice is always BEA Systems,Inc. the same. If you want scalability, design your appli- 2315 North First Street cations to be stateless.) With the release of WLS 6.0, San Jose,CA 95131 the scalability features appear to be more fully 800 817-4BEA baked in, and I would venture a guess that devel- opers will begin to leverage these features more www.beasys.com fully in their applications. Servlet failover and EJBs tend to be the two big features that I hear develop- ers talk about when they mention WLS 6.0. Summary BEA’s WebLogic Server 6.0 continues to break new ground in the J2EE application serv- er market. If you’re looking for a high-end application server with extensive transaction processing capabilities, WLS 6.0 is worth a long look. You can download a free 30-day trial from FIGURE 1 WebLogic server console BEA’s Web site.

30 JUNE 2001

Java COM Pointbase www.poinbase.com

JUNE 2001 31

Java COM IBM Spread www.ibm.com/db2/freethinkers

32 JUNE 2001

Java COM IBM Spread www.ibm.com/db2/freethinkers

JUNE 2001 33

Java COM IBM Spread www.ibm.com/websphere/speed

34 JUNE 2001

Java COM IBM Spread www.ibm.com/websphere/speed

JUNE 2001 35

Java COM J2ME J2SE J2EE

Home SOMESOME PRACTICALPRACTICAL TIPSTIPS FORFOR LARGE-SCALE DEPLOYMENT

2EE applications WRITTEN BY

are becoming the norm rather CHRIS KAMPMEIER Jthan the exception in today’s distributed computing environment. But organizations are still facing

the same issues with this technology set that they did with

application models of yesteryear – how to ensure that they can scale

quickly, respond dynamically, and maintain flexibility as their business

environment changes.

These challenges have never been more Web applications designed to support thousands pressing than they are in today’s environment, of concurrent users. Areas covered include the where business models are changing rapidly as importance and impact of up-front architectural organizations cope with the realities of a cyclical decisions, development steps to help ensure economy. smooth deployments, performance tuning, and This article focuses on some of the applica- production deployment planning and design. tion characteristics of large-scale J2EE applica- tions and is prescriptive in terms of what we have Considering Architectural Approaches seen work and not work with large-scale Web Because of the popularity of both Java and applications. In particular, this article considers J2EE, organizations have an unprecedented vari-

36 JUNE 2001

Java COM Tom Sawyer www.tomsawyer.com

JUNE 2001 37

Java COM ety of portable software to draw on in the formation of their requirements with respect to RDBMS integration. This architectural standards. Since J2EE currently focuses more on should be done even before testing the various approach- application portability and less on the underlying implemen- es. Since approaches can run the gamut from lightweight, tation and operational characteristics of an application server, local-access DAO-style classes to heavier-weight, it’s important for organizations to look beyond the J2EE pro- remotable CMP-based entity beans, there are huge design gramming model and concentrate on how key decisions will and implementation ramifications to adopting one impact the operational characteristics of the deployed sys- approach over another. For example, using entity beans

J2ME tems. Apart from decisions related to the underlying hardware enables developers to rely on the underlying EJB contain- and operating systems, the following architectural considera- er to manage complex aspects such as transactions, secu- tions will weigh most heavily on the performance of the oper- rity, and remote communication. However, the container’s ational environment. role comes with the price of additional processing over- • Select application server: To an extent not seen with other head. Many organizations fail to realize the downstream Web and enterprise component platforms, the J2EE plat- impact of their RDBMS integration approach on system form enables an organization to base the bulk of its devel- performance until well into the deployment phase of an opment investment on the portable base platform and lay- application. J2SE ered frameworks rather than on vendor-specific APIs and • Decide on enterprise connectivity solutions: From the features. The adoption of J2EE has allowed organizations to standpoints of both development efficiency and runtime worry less about comparing application development envi- performance, it’s generally preferable to employ prebuilt ronments, but they still need to perform a comprehensive back-end connectors to shield developers of the Web pres- evaluation of the available J2EE-compliant application entation layer and new EJB-based business components server products to ensure that the products meet the orga- from the detailed interface semantics of existing systems. nization’s operational requirements. Switching application Much like the RDBMS integration, back-end connectivity to servers midway through development of a J2EE-based enterprise systems can be a major source of headaches dur- application effort will moderately impact the delivery ing deployment if the proper evaluation and testing of solu- J2EE schedule. However, given the investment necessary to train tions is not performed in advance of development. operational teams on the product-specific processes and Although the emerging Java Connector Architecture (JCA) is features, switching application server products near or dur- gaining adoption as a standards-based approach to enter- ing the deployment phase will result in significant addition- prise connectors, many of the higher-end application al costs and extended deployment delays. servers already support some degree of prebuilt, albeit pro- • Examine Web presentation layer frameworks: Almost any prietary, connectors. A few of those vendors offer SDKs to Web application will benefit greatly from the use of a pre- enable organizations to quickly build their own connectors

Home built Web presentation layer framework. For example, the for back-end systems not addressed by the prebuilt connec- Apache Jakarta project’s Cocoon and Struts Web presenta- tors. Compared to relying on individual developers or tion layer frameworks have become very popular with development projects to implement efficient and secure many J2EE developers. Although some teams will be hesi- access to back-end systems from their J2EE applications, tant to build the Web presentation layer on a third-party the connector approach enables an organization to ensure framework, most organizations end up developing a gener- consistent performance and security characteristics across ic infrastructure that sits between the base J2EE Web con- applications. tainer services and business presentation logic – whether or not they call it a framework. In addition to the time savings For J2EE-based applications, these are several of the most they generate, such frameworks are portable across almost prominent architectural considerations. In each case, up- any J2EE Web container implementation. Although the front investigation and testing will help ensure a solid base for popular frameworks evolved with JSPs and servlets prior to development and deployment. the formal J2EE specification, the relative newness of the frameworks warrants caution when considering them for Designing and Developing Production-Ready Applications production use. It’s advisable to thoroughly test any adopt- The source of perhaps the largest impact on the viability of ed framework in a production-like environment to ensure a J2EE application in production is the initial detailed design that stability and performance requirements are met. of the application. Even though many development teams are • Survey prebuilt components: As the architecture team iden- new to J2EE features, we often encounter cases in which the tifies enterprise components that will be useful to many of team performs very little, if any, performance testing of indi- their organization’s business applications, the architects vidual application components, let alone the complete appli- should first review the prebuilt Java and EJB components. cation, prior to the production deployment phase. In truth, This is true whether they’re available through their applica- there’s nothing magic about J2EE that would permit a devel- tion server vendor or through the several component mar- opment team to skip important steps in the basic develop- ketplaces on the Web. As in the case of prebuilt frameworks, ment process. Key steps worth highlighting are: third-party components, even if customized, gain greatly • Engage experts: For your first J2EE development effort, from speed development efforts. The Flashline.com site ref- engage experts that have already implemented production erences a wide variety of both EJB and Java com- J2EE-based systems. Since momentum behind J2EE has ponents. As part of any component evaluation built rapidly and the standard has had approximately a year effort, each component should be thoroughly of exposure, there are now many more experienced profes- reviewed and tested for its performance and secu- sionals available to lead new teams through develop- rity characteristics. ment and deployment of applications than there were • Make hard decisions on RDBMS integration: One even nine months ago. of the most contentious aspects of J2EE and EJBs is • Leverage proven design patterns: Become familiar RDBMS access. It’s worthwhile for an architecture with the popular design patterns that apply to your team to invest a great deal of time with key application application problems. Proven patterns have typi- design team members to determine the organization’s cally evolved to the point of becoming the most

38 JUNE 2001

Java COM Macromedia JRun www.allaire.com/download

JUNE 2001 39

Java COM efficient yet maintainable means of addressing a particular to simulate moderate loads against a portion of your appli- problem. A set of patterns applied to J2EE-based systems cation. Use the application server monitoring tools to gain was recently published on java.sun.com at http://develop- insight into resource utilization prior to formal system and er.java.sun.com/developer/technicalArticles/J2EE/pat- integration testing. terns/. • Perform code analysis and profiling: One of the biggest • Consider impact of session size on performance: If you’re issues arising during the deployment of new J2EE-based considering the use of session-replication features provided applications is the lack of expected performance. Often,

J2ME by the application server, consult the session-size guide- such performance problems can be readily identified in lines provided by the application server vendor. These advance through the use of mature code profiling tools guidelines are important when determining how much such as JProbe and OptimizeIt!. Although these products information to store in the HttpSession of the Web applica- predate J2EE, they are able to hook into the leading appli- tion and/or instance variables of stateful session beans. cation servers to provide a comprehensive view of code effi- Although management of large amounts of session data ciency. may yield acceptable performance when an application is deployed to a single application server instance, the per- Understanding Operational Requirements J2SE formance characteristics may vary dramatically as session As the application development activity ramps up and you replication is configured at deployment time. This is often have begun to tune simple deployments of the application, done in an effort to ensure availability of session data across the implementation team can establish the general layout of system outages. the operational environment based on the requirements of • Perform code walkthroughs: It’s critical that development the application server product and the business application. teams review source code to ensure that resources are prop- This general layout will show the relative position of the sys- erly managed by the application. The J2EE environment tem’s external interfaces. Before the general layout can be provides many opportunities for sloppy housekeeping. transformed into a more concrete design, implementers need Code reviews are an early and, therefore, relatively low-cost to factor in the following operational requirements of the new J2EE means of avoiding the following common mistakes: system: –Failure to close JDBC result sets, statements, and connections • Security –Failure to remove unused stateful session beans • Availability –Failure to invalidate HttpSession • Performance Although the JVM will handle the garbage collection of unused object instances, the application server product Mature organizations are well schooled in these facets of and JDBC drivers implement their own strategies for clean- an operational environment. One of the key differences

Home ing up unused resources. To minimize the overhead between J2EE-based application servers and older middle- imposed by such housekeeping tasks, it’s important for the ware is that high-end application servers provide many application to clean up after itself. If code deployment configuration options that drastically impact all reviews are not performed, then the next oppor- of these areas without affecting the application implementa- tunity for catching resource issues is during tion. either code profiling or initial tuning efforts. • Security: Is there a requirement to encrypt the browser • Performance test various options: In your devel- to Web server communications for all or part of the opment environment, establish small-scale test application? Will the Web-server tier exist in a demilita- harnesses to evaluate the relative performance of rized zone (DMZ) separate from the application-serv- different configurations. For example, experiment er tier and back-end enterprise systems? Is encryp- with both Type 2 and Type 4 JDBC drivers to assess not tion required between the Web servers and applica- only their compatibility with your application, but also the tion servers? If so, is the encryption necessary for all performance of each driver type. Use any of the commonly interactions with the application? These are ques- available load-generation tools in the development phase tions you have to consider.

put your Java™ applications in motion.

kada systems. mobilizing e-business

40 JUNE 2001

Java COM • Availability: Availability issues are also critical. What are the Understanding Factors Affecting Sizing availability requirements of the application? Is the loss of The main factors affecting sizing are: service acceptable when a machine becomes unavailable? • User load: The larger the load that’s applied to a system, the Can the loss of a user’s session information be tolerated? greater the amount of hardware needed to satisfy that load. What are the possible weak links with respect to the manner • Application design/implementation: An application that in which the application interacts with other aspects of the performs very little work will be able to handle many users environment? Can these weak links be reasonably for a given amount of hardware. In a relative sense, this kind enhanced or are they constants? Many shops view a CPU of application often scales poorly as it spends a large per- busy rate of 80% as a high-water mark. What is your shop’s centage of its time waiting for shared resources (network, standard? database, other enterprise systems, etc.). Conversely, appli- • Performance: Performance requirements pose challenges cations that perform a great number of computations tend as well and must be addressed. What, for example, are the to require much more hardware per user, though these required response times experienced by the end users for applications typically scale much better than those per- various interactions with the application? What are the forming a small number of computations. perceived steady state and peak user loads? What is the • Hardware platform: Raw processor performance is critical average and peak amount of data transferred per Web for reducing the amount of hardware needed. Generally, request? What is the expected growth in user load over the Web applications do not include floating-point-intensive next 12 months? computation, which means integer performance is usually the most important factor. Even with high-speed proces- For peak user loads, you must focus on the number of sors, a server can scale poorly if shared resources cause sig- concurrent sessions being managed by the application nificant contention. Usually, cache design and memory server. We often find that organizations view peak user bandwidth play a big role in determining how much extra load as the number of possible users rather than the aver- performance is achieved, as processors are added to a serv- age number of concurrent users. Given this more realistic er. view of user loads, you’ll often find the number of peak • Safety margins: Additional capacity is normally designed users drops dramatically on paper from hundreds of thou- into a solution. One reason for this is that user loads tend to sands or even millions to tens of thousands of concurrent increase over time. Another reason is that most businesses users. expect to keep their Web-based services available during Defining these operational requirements will help move planned and unplanned outages. Proper sizing and capaci- you to the next stage in understanding the deployment envi- ty planning is typically able to compensate both for the ronment. For the purposes of this article, let’s assume that increase of loads as businesses grow and for partial system the operational security and availability requirements are outages. Planned outages of a portion of the system may such that multiple Web and app server instances, separated also be required as this permits an application system to be by a set of firewalls, will form the basis of the environment. upgraded to a new version. To do this, a portion of the sys- In other words, you’ll need separate tiers of tem is taken offline, while user requests are still handled on machines to support the division between the the active portion of the system. DMZ and the secure, back-end business systems. You’ll also need to plan on multiple instances of Predicting Performance machines in each tier to enhance the availability of Given the factors affecting the sizing process and the the application. Proceeding from these assump- general layout of the operational environment, how do tions, the layout of the operational environment is fur- you predict either the capacity of a given combination ther refined, though it does not yet address the exact of hardware or the minimal hardware required to number or size of machines required by the system. The next sustain a specified capacity? The best way to answer step is to develop a basic understanding of how to size a sys- these questions is to take the data gathered above tem. and plug it into the sizing calculator offered by your

introducing Kada Mobile™ VM–small, fast, complete.

In the world of mobile business applications, size matters, speed thrills and completeness is essential. Now there is a new platform for deploying Java™ applications designed specifically to address your mobile business needs. With Kada Mobile VM, applications designed with your favorite Java tool can be deployed to any handheld device. And Kada enables your applications to operate with a wireless connection or locally with a database to later synchronize with your enterprise systems, making your applications “always available”.

When it comes to mobilizing e-business, Kada delivers the platform you have been searching for– small, fast, complete and available today at www.kadasystems.com.

visit our booth at Java One www.kadasystems.com Kada Systems and Kada Mobile VM are trademarks of Kada Systems, Inc. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries. JUNE 2001 41

Java COM 2. Determine vertical scalability: You need to know how much additional perform- ance is gained when you add processors. That is, you’re indirectly measuring the amount of shared-resource contention that occurs on the server for this workflow. You either obtain this information based

J2ME on additional load testing of the applica- tion on a multiprocessor system or lever- age existing information from a similar application that has already been load tested. Running a series of performance tests on one to four CPUs generally pro- vides a decent sense of the vertical scala- bility characteristics of the system. On J2SE Solaris, for example, it’s easy to disable/enable processors. Based on your sizing estimates, it’s important to exercise the application under load on systems of the target configuration. While determining the vertical scalabil- ity, ensure that availability requirements are factored into the configuration. For example, to guarantee that the failure of a J2EE single JVM does not result in a loss of all sessions, perform the vertical scalability tests with at least two JVMs and configure session replication between the JVMs. FIGURE 1 Application server sizing tool 3. Determine horizontal scalability: You application server vendor. For example, iPlanet provides cus- need to know how much additional performance is gained

Home tomers with two calculators to help size applications deployed when you add servers. Again, benchmarking a cluster of to the iPlanet Application Server. The first calculator computes application server systems is required if information on a sim- the size of a system (i.e., the number of CPUs and the number ilar application is not already available. Ensure that you take of machines in each tier) based on the factors described above. into consideration high-availability requirements and the The second calculator computes the maximum capacity of a attendant session-replication configuration as you lay out given hardware configuration (see Figure 1). your horizontal scalability test environment. In this case, ses- iPlanet built these calculators based on a combination of sion replication occurs across application server instances tests, including those for popular application workflows, and deployed to multiple machines, in addition to session replica- drew upon publicly available benchmark results for RDBMSs tion across JVMs within each application server instance. and processors. Both calculators assume a fully tuned system. If your application server vendor does not make a calcula- Running this suite of tests will provide you with a solid under- tor available, or the application workflows do not match those standing of the performance of the application server. Using this of your application, then you’ll need to develop your own information, you can develop your own custom-sizing equations. understanding of sizing based on the following steps: Summary 1. Determine performance on a single CPU: You must deter- The increased programming flexibility and the great num- mine the largest load that can be sustained with a known ber of deployment time configuration options offered by J2EE amount of processing power. You can obtain that figure by and advanced application servers can cut the time it takes to measuring the performance of the application on a develop and deploy highly available business services. Before uniprocessor machine. You can either leverage the per- these benefits can be realized, however, mature development formance numbers of an existing application with similar and deployment practices must be established. In short, J2EE processing characteristics or, ideally, use the results of basic provides a powerful development paradigm, but one that performance testing done during development. Based on requires careful operational planning to ensure success. their experience with large-scale J2EE implementations and internal validation of their products, vendors of high- end application servers can usually provide base perform- AUTHOR BIO ance numbers for Web applications imple- Chris Kampmeier is group manager for technical evangelism within the application services menting a basic workflow. group at iPlanet E-Commerce Solutions. He leads the team responsible for creating development While determining performance on a single and deployment content for the J2EE developer community including sample applications, coding CPU, it’s imperative that you begin to tune the tips, sizing and tuning guides as well as documentation for the application server family. basic environment. As with any performance Additionally, Chris is heavily involved in defining future product strategy. Prior to iPlanet, he test, you must ensure that none of the outlying spent more than two years at Sun Microsystems supporting field systems systems (driver machines, Web servers, database engineers, and seven years developing EFT switching systems at MasterCard International. machines, etc.) throttle the test. Otherwise, your He holds a BS in computer science from Northern Illinois University. performance numbers may be artificially low and will [email protected] adversely impact the follow-on sizing numbers.

42 JUNE 2001

Java COM Sybase www.sybase.com/eas

JUNE 2001 43

Java COM J2ME J2SE J2EE

Written by Patrick Sean Neville

J However, there are ava Servlets and clear guidelines for evolv-

Home ing the JSP and custom code JavaServer Pages (JSP) approach into a more flexi- ble EJB-based architec- threaten to collapse out ture. Once convinced that the endeavor is there in the mud houses of server both worthwhile and feasible, developers can land. Developers succumb to the temptation to take steps to pare down servlets and JSPs to simple MVC-compliant muddle their pages with complex business logic, and to fill presentation layer elements that elegantly access hard-core logic in the form of decoupled behemoth proprietary libraries with data and subsystem access and refactored EJBs. This is the practice of growing a JSP site into a full-blown J2EE application. routines. We find stronger solutions in EJB-based architectures JSP Anti-Patterns than in fattened JSPs, but molding existing sites into EJB-cen- In designing software, most of us will agree that mixing presentation logic and business logic is a naughty thing to do. tric designs strikes most of us as a daunting and expensive task. In practice, however, JSPs do not naturally lend themselves to a decoupling of these layers, often leading us to compromise our design aesthetics in favor of implementation conven- The possibilities ience. After all, we’re not HTML designers. We know Java, and we don’t mind plopping Java routines right in the middle of our pages. It’s quick and dirty. Eventually, as the business logic are powerful when in the pages grows more complex and touches more external subsystems (databases, mail servers, custom proprietary servers), our cool apps coalesce into great balls of mud. Figure the design and 1 illustrates such a scenario, in which the client event handlers perform business logic that includes enterprise-level resource implementation are usage. It’s not that a pattern has become obscured in such cases; it’s that an anti-pattern has emerged. Anti-patterns begin as atomically compelling solutions that result in the eventual amplification of the problems they address. In particular, many JSP and servlet sites follow the BLOB and Stovepipe anti-patterns, in which originally compelling code spirals out of control and elegant sprouts numerous tightly coupled subsystems. Designers,

44 JUNE 2001

Java COM Parasoft www.parasoft.com/jdj6

JUNE 2001 45

Java COM connectivity in addition to the applica- tion logic. This approach not only exac- Presentation Layer Application Layer Data Layer erbates the issue by spreading the prob- lems out among a larger code base; it also implies instant legacy code – costly Browser Databaseatabas and confusing to maintain, not portable, JSP/SP Servlets proprietary and interoperable with

J2ME ERP nothing beyond its own boundaries. In anti-pattern terms, the Stovepipe sys- Browser tems and BLOBs are eventually covered Subsystem Layers by unmaintainable lava flow. Tag libraries, or taglibs, are a terrific SMTP solution for many problems caused by typical JSP usage, but when taglibs con- File System Swing App tain hard-core business logic – requiring J2SE Messaging transactions and concurrent processing, for instance – they suffer the same prob- lems associated with all proprietary FIGURE 1 A typical first-generation JSP/servlet Web application code libraries. Taglibs are excellent pres- entation layer elements that cleanly broker communications to portable remote business logic components, but Presentation Layer Application Layer Data Layer they should not contain business logic and resource connector code. Your tag- J2EE loving Web designers will be much hap- Browser Databaseatabas pier with a handful of powerful tags that JSP/Servlets can access business components rather ERP than hundreds of overly specialized tags that perform the business logic them- Browser Proprietary selves. Subsystem Layers Library When masterfully employed, servlets

Home and JSPs conform to event-based rather SMTP than component-based patterns. Servlets are event processors; in comes a Swing UI File System request, out goes a response. They thrive Messaging in pipe-and-filter designs, in which the request and response types and the sequence of pipes through which they FIGURE 2 The enterprise logic is refactored into proprietary libraries flow define the system functionality. Therefore they thrive as the transformers developers, and engineers step on one another’s toes to turn of client/server communications. simple systems into sophisticated ones. The Web apps devel- Enterprise business logic, however, is well suited to com- oped in this manner are akin to a house in which cleaning the ponent-based design and its implicit decoupling of system windows inexplicably causes the roof to leak. The situation and application functionality. System functionality, including grows even uglier when new teams take charge of maintaining security, transaction and life-cycle issues, are managed inde- the code. Justifying the code BLOB under the “Controller” pendently of business logic invocations. EJB components MVC label doesn’t resolve the practical problem, even if it don’t rely on request and response types or stacks of user- sounds promising in high-level architectural discussions. crafted filters to define their environmental functionality; Lengthy procedural code is more difficult to test than instead, they rely on their container for such things, and the object-oriented code, and dropping business logic into JSPs business logic remains separate. and servlets eventually results in just this sort of procedural Either one of these models alone won’t fit the bill. In a code. Unit and regression testing is a snap when a specific complex enterprise application, we require connected subsys- function is isolated in layered component architectures, but tems that follow both models. In most real-world cases this QA balks at tightly coupled systems that do not readily expose means pulling logic out of JSP/servlets and out of any depend- functionality to clean test cases. ent proprietary libraries they may rely upon. To resolve these problems, many developers take the pre- EJB route of moving complex business logic out of a few JSPs EJB Design Best Practices and into chained servlets and separately included JSPs, and Once convinced your application would benefit from EJB eventually into proprietary libraries and utilities that their usage, how do you go about making the change? Refactoring, pages invoke. Proprietary libraries typically consist of or methodically improving the design of existing code, is scores of classes linked in complex inheritance the recommended approach, and EJB design principles schemes that grow increasingly convoluted over the provide the engineering ammunition. library’s lifetime. These libraries in turn may grow to There are several emerging strategies for EJB call upon bandied-together O/R tools, or transac- design, covering topics from the granularity of data tion engines. Figure 2 illustrates this scheme, in access to inheritance to caching. At a high level, which proprietary libraries assume the burden of refer to the following design principles and EJB security, transactability, persistence, and resource best practices:

46 JUNE 2001

Java COM Segue www.segue.com

JUNE 2001 47

Java COM Principles • Consider the network and your hosting facilities while architecting • Session EJBs are extensions of the client into the server, and your particular software. If you have one large database host but only should be used for any logic that the JSP/servlet application a small Web and middleware host, consider moving much of your previously executed. logic into stored procedures and calling them via JDBC in session • Entity EJBs are representations of data that exists in an beans. If your database host is weak or unknown, or you require underlying datastore, and should be used to encapsulate greater portability, keep the data calculations in entity beans. logical groups of data (such as a customer, a company, etc.) • Most J2EE server vendors provide optimization parameters

J2ME as well as any logic inherent in that data collection. For for improving the overhead of EJB loading and storing. Use example, include logic that returns different values depend- them. At minimum, these optimizations should follow the ing on whether a specific customer entity is a regular cus- three commit options described in the EJB specification. tomer or special customer. • Consider using a single stateless session bean to provide • Resource factories provide a portable means for accessing access to other EJBs (this is a façade pattern). All of your EJB subsystems such as mail, messaging, and the like. Use clients request operations through this session bean rather resource factories through JNDI rather than directly access- than making calls and obtaining references to multiple ing a resource through explicit delegation or hard-coded EJBs. This not only satisfies aesthetics, it also optimizes J2SE references. multiple EJB references and calls by keeping them in • JavaBeans, whether exposed in JSP pages or encapsulated process, useful for local beans in particular. in taglibs or GUI elements, provide excellent places to store • Merely porting a large body of code into a few EJBs won’t client-side references to remote EJBs. resolve anti-pattern problems (EJB is not a silver bullet). • Client interaction with application logic and resources You should still segment business logic into sublayers, exists in a fluid, contextual data structure that may be trans- where each sublayer is composed of EJBs with different formed either explicitly or implicitly into EJB value objects, functions; for example, consider an access layer to present JavaBeans, files, or database tables. Even when not explicit- a public API, an invocation layer to handle references and ly architected, this context exists in some form across all lookups, a logic layer to handle application algorithms and J2EE layers in an enterprise application. an entity layer for data representation.

In“ designing software, most of us will

Home agree that mixing presentation logic and business logic is a naughty thing to do“

Best Practices • Monitor pattern sources, such as the J2EE Blueprints and • Entity EJBs should be coarse-grained, with one entity repre- the Server Side, for specific best practices, designs, and case senting a large type of data grouping rather than a number studies applicable to your projects. of smaller types. For example, craft one customer entity rather than separate entities for each type of customer. Refactoring Strategies • Entity EJBs should contain aggregate get/set methods that There are two general approaches to the actual JSP-to-EJB return chunks of data rather than fine-grained get/set refactoring, and each is equally viable. The top-down methods for individual attributes. For example, instead of approach involves starting with the presentation layer, while creating getStreet()/setStreet() methods along with the bottom-up approach involves first sorting out the data getCity()/setCity() methods, create a single getAddress() access layer and its collections. The choice of strategy is large- method. This eliminates frivolous database, transactional, ly a function of your personal engineering approach and the and network communication overhead. nature of the project at hand. • Decouple EJB access from your pages and servlets. At a mini- The top-down approach is common to Web-heavy applica- mum, use a tag in a taglib to call an EJB and execute its meth- tions and to developers employing an Extreme Programming ods; also consider relying on a JavaBean decoupled from your methodology. This strategy asks you to start with your users taglib, where that JavaBean contains all the EJB access code. and the presentation elements they see. Take a look at all the • Avoid stateful session beans in large public enterprise Java code in your JSPs. Pull that code out and group related applications (as opposed to intranet or small-distribution functions into methods. Stash these methods in tag libraries. applications). Stateful session beans are resource-heavy, If you are using a proprietary code library, identify the presen- since one instance is maintained for each client. In tation-related methods in your library’s classes and refac- Web-based applications, JavaBeans scoped to the tor them into a taglib. Replace the Java code in your JSP user session or taglibs often provide reasonable pages with these tags. lightweight alternatives to stateful session EJBs. Next, identify the heavier business logic that is in • Under heavy loads, entity beans should do more your taglib and/or proprietary library, and move it than merely represent a table in a database. If you into session EJBs. The easiest way to do this is to are merely retrieving and updating data values, find the relevant methods and simply cut-and- consider using JDBC within session beans instead. paste them into a session bean implementation.

48 JUNE 2001

Java COM Valtech www.valtech.com

JUNE 2001 49

Java COM Regardless of whether you pursue a top-down or bottom-up strategy, the Presentation Layer Application Layer Data Layer most time-consuming element of this process will likely be refactoring your JSP/ data access and data manipulation Servlets JJavaBeanavaBea code into entity EJBs. In general, it’s Browser Databaseatabas advisable to use Container Managed Taglib EntityE J2ME Persistence (CMP) entities rather than EJBB the Bean Managed Persistence (BMP) alternative. But again, you have legacy Browser code; don’t be afraid to work against Sesssionsion Subsystem Layers the grain of standard practices. If you already have JDBC code in Swing UI EJJJB Resource SMTP Factory your servlets, taglibs or session beans, Session File System first create a BMP entity. Work first Palm J2SE C/C++ Resource CORBA AdapterAd Factory with the bean implementation, skip- Palmm OSS EJB Resource Messaging ping the remote and home interface Client Clientent Factory creation for now. This approach means essentially cutting-and-pasting the FIGURE 3 Refactored EJB version of the application JDBC code into the appropriate entity life-cycle methods. After you have the implementation, then write the inter- faces (the reverse of the normal proce- Presentation Layer Application Layer Data Layer dure). Creating a BMP entity EJB from J2EE existing JDBC code in this manner is UserService.ear DataSourceDataSourc extremely quick, and after you’ve fash- JSP EJBB RDBMS ioned such a BMP entity, you can fur- ther refine it to make use of CMP, Taglib JaaavvaBeanvaBeav Connector JSP which typically provides better per- JSP EJBB ERP formance (due to data caching) in addition to its obvious portability.

Home Another advantage CMP offers is Subsystem Layers PublishingService.ear that the EJB is independent of any par- ticular database and datastore type. It Resource SMTP JSP Factory Taglib may rely on a relational database, but JSP File System it may just as easily rely on SAP or EJB Resource Factory some other ERP system with no Resource Messaging changes to the bean code. The EJB Factory need not specifically worry about such things, and is therefore portable (a FIGURE 4 EJB-based service view of the application, encapsulated in portable EAR format very attractive feature of EJBs). EJB QL, the datastore-agnostic query language Don’t worry about writing the bean’s remote interface first. for CMP entities, standardizes this abstraction syntactically Since you have existing legacy code, you are refactoring rather under the EJB 2.0 specification. In most vendor implemen- than writing an EJB from scratch. After you’ve moved the tations today, regardless of whether they support EJB QL, business logic into session bean methods, write the bean’s transforming a BMP entity into a CMP entity means moving remote and home interfaces to abstract those methods. the SQL code out of the JDBC routines and into some Finally, identify the core-data components and pull them out object-relational mapping facility, such as a vendor-specific of the session EJBs and into entity EJBs. More on those in a XML file. moment. Refactoring isn’t complete without a repackaging of The bottom-up approach sets the Web site aside while first your application according to its functional units. delving into the core-data requirements. The strategy for top- Enterprise applications consist of JSP, servlet, and taglib down refactoring applies in reverse. Pull the data access and files collected into Web archives (WARs) and EJBs collected collection code out of JSPs and taglibs and move them into in Java archives (JARs). The format for this collected appli- entity EJBs. Got a Hashtable called customer? Sounds like an cation is the Enterprise Archive (EAR). Think of an EAR as a entity EJB to me. Then move the entity EJB accessor code (that molecule, where the JARs and the WARs are the molecule’s is, the client code) out of the JSPs and their taglibs and into atoms. The metaphor extends further to compare the EJB’s session beans. Finally, build any new tag libraries that you internal pieces to subatomic particles. This is no mistake – require for presentation layer transformations. The idea is that J2EE apps follow a deliberate component-centric design JSPs use taglibs or servlets to call session beans (or that mirrors beauty in nature. Components consist of MessageDriven beans for asynchronous functionality) components. and session beans may call other session beans or You can mirror this in your packaging. Instead of entity beans in order to execute logic for the tags. merely deploying the layers of your application Figure 3 illustrates this scenario, in which the com- individually (a Stovepipe process), package them ponents contain only segmented application logic. as a logical organic service (as shown in Figure The components delegate system logic to their 4), which can be deployed on any certifiably containers. compliant J2EE server.

50 JUNE 2001

Java COM Rational www.rational.com/jdj

JUNE 2001 51

Java COM tation constructs. Through method invo- cations, the Controller transforms the Model Controller View Pattern Model and returns the Model to the Controller. Whether the Model is best StStateful t f l Components Entity Stateless Session represented as an entity bean, collection, { EJB Session EJB EJB or value object is a complicated design decision that’s dependent upon the size

J2ME of the data structure, the transactional attributes associated with it, and the Possible Collection JavaBeaJavaBean number of method calls necessary to Implementations { manipulate it. Multiple invocations on Other remote objects such as entity beans EJB'EJB's result in high network usage, but large Data Custom data objects are much bulkier to send Object Tags across the wire than entity EJB stubs. Let J2SE your project analysis determine the cor- rect implementation. Content Model Publishing Engine Page of Articles In the end, users view pages, which are Product E-Commerce Engine Shopping Cart Game Piece Game Engine Game Board created by designer-crafted JSPs and Examples Movie Movie Controller Movie Menu Account ATM Banking Menu their developer-crafted custom tag Server Host Sys Admin Utils Network Console libraries. As users navigate through con- { Bug Report Bug Tracker Bug Menu tent, the taglibs send messages to the developer-crafted Controller code. This FIGURE 5 MVC view of enterprise applications Controller translates the user’s actions J2EE into requests for application logic; the Applying MVC to Enterprise Services Controller executes the logic by calling various developer- Three basic categories exist in the software patterns com- crafted EJBs. In this scenario, all of the EJBs are part of the munity: architectural patterns that define high-level frame- Controller. In a long-lived session, the Model isn’t re-created works (such as the layer pattern used throughout this article’s but continuously transformed by the Controller EJBs and illustrations), design patterns that outline system and subsys- remembered between calls by the View. The Controller sends tem strategies, and idioms that describe language-specific pieces of this Model (or even the entire Model) back to the

Home tactics. Among architectural patterns, few have garnered as taglibs for translation into presentable elements on a JSP page. much attention as the MVC pattern, which originated in Smalltalk user-interface design. The idea is that the presenta- The Future of EJB-Based Services tion View is cleanly separated from the data Model that it pres- Once JSP-based applications are refactored into independ- ents, and that both data and presentation are refereed by a ent but connected services, the app is prepared for swift evo- Controller containing business logic. Figure 5 presents some lution. As vendors create new resource adapters, developers examples of MVC implementations, in which a Controller EJB add entirely new subsystems to apps without interfering with sends requests for logic to other EJBs in order to create or any existing functionality; obsolete logic is removed without transform the Model, which represents the data. The interfering with the Web presentation; new EJB components Controller returns relevant pieces of that data to the View, are purchased, removed, and added to existing services; entire which prepares it for client-specific display. applications are tied together and ported across unrelated The Controller fits snugly into the application logic layer of enterprises; legacy data in mainframe systems filter effortless- our enterprise service. The central Controller object does not ly into existing services. The possibilities are powerful when necessarily execute the business logic itself, but it’s at least the the design and implementation are atomically elegant. entry point into the business logic. A stateless session bean is a good fit, as it scales well and can efficiently pass off requests for Resources heavy logic to other EJBs. This Controller session bean could be The definitive guide to refactoring strategies, complete accessed directly by tags in a tag library, or by a servlet. with a catalog of refactoring patterns and idioms, is Martin The Controller is the common BLOB culprit in failed MVC Fowler’s Refactoring: Improving the Design of Existing Code implementations. Often when logic is removed from the pres- (Addison-Wesley, 1999). Strong EJB books are difficult to come entation tier, the Controller grows fat and convoluted as a by, but Ed Roman’s Mastering Enterprise JavaBeans is a good result. To avoid this, follow the aforementioned best practices, resource, and its latest incarnation is available for public and segment the Controller into sublayers. Then apply proven review at www.theserverside.com. That site and www.javasuc- design patterns to each of these segments. cess.com are both good online sources for advanced EJB-spe- The WAR component of an application, which includes the cific design and patterns. JSPs and taglibs, is the View of a Web-based service. If you find business logic winding its way into these elements, then AUTHOR BIO you’re flirting with violating strict MVC. Patrick Sean Neville is principal engineer at Macromedia, where he is the architect of JRun’s The Controller updates the Model in accordance with EJB server, core-service infrastructure, and other enterprise components. Prior to joining messages received from the JSP-based View. The Model Allaire/Macromedia, he designed and implemented distributed applications for may be a heavyweight entity EJB, or value object, or a companies ranging from media agencies and Web start-ups to banks and lightweight data collection that the Controller sends financial institutions across the country. He is the creator of the Code Studio as a parameter to EJB method invocations. Often (www.codestudio.com), a supporter of open-source endeavors, and a frequent the Model is all of these things at different periods author and speaker on J2EE topics. of its life cycle; as the Model passes through layers it [email protected] may be transformed into any number of implemen-

52 JUNE 2001

Java COM Intranet www.intranetsolutions.com

JUNE 2001 53

Java COM PRODUCT REVIEW

n a recent editorial meeting with the JDJ tion server category. The panels were easy to staff I broached the subject of open follow and the installation didn’t wipe out any Isource software with editor-in-chief, Alan of my preexisting Apache settings (as some Williamson. I freely admit that I was baiting other products have done). The postinstalla- him – but Alan was favorable towards it. It’s tion process is also a breeze. ServletExec’s man- J2ME ServletExec a touchy subject for any technical person, agement console (as shown in Figure 1) pro- sort of a motherhood and apple-pie thing. vides access to all the various capabilities of the Well, here it is folks, I’ve spent much of server. You can control the depth and content Web Application Server my technical career working for software of server logs, change the JVM, and configure vendors and I’m not so foolish as to bite Web applications (WARs) directly from the the hand that has fed me in the past. The browser interface. by New Atlanta old adage that you get what you pay for is I was able to create a couple of quick JSP as true as it ever was. Before you start pages, package them into a WAR file, and create J2SE flaming me, let me just say that I’m not an my own Web application in a matter of min- “Open Source Luddite” and I freely admit utes. Experienced Java Servlet developers will to using the occasional open source find that they can control lots of detailed set- WRITTEN BY JIM MILBERY product (Web browser, e-mail client, and tings within the ServletExec environment, HTTP server). In general, I prefer to use including servlet chains, servlet aliases, and the commercial grade products for every- ability to define multiple logical “servers” with- thing else. Thus, I was more than happy in a single server instance. You can create sepa- to dump my copy of Tomcat into the vir- rate ServletExec instances and tie them to dif- tual shredder and try out New Atlanta’s ferent applications – even on the same J2EE much-vaunted ServletExec 3.1 Appli- machine. Thus, it’s a simple process to host cation Server. applications for multiple audiences on the New Atlanta makes the ServletExec same set of hardware. product available for download from You have complete control over the session- their Web site. It comes packaged in a tracking environment, including the ability to 3MB InstallShield download kit for control session persistence across server AUTHOR BIO Windows (and shell scripts for UNIX). restarts. New Atlanta also provides lots of sam-

Home Jim Milbery is a software consultant based in Easton, ServletExec can be installed as both a ple servlets. My only real complaint is that Pennsylvania, with Kuromaku Partners LLC. He has over 17 years separate application server (Apache, ServletExec doesn’t provide any direct support of experience in application development and relational Microsoft IIS, iPlanet Enterprise Web for JDBC. If you want connection pooling or databases. He is the applications editor of Wireless Business Server), or as an in-process Servlet JDBC drivers, you’ll have to use some addition- & Technology, the product review editor of Java Developer’s engine (IIS/iPlanet). The installation al third-party solutions. (ServletExec 4.0 will Journal, and the author of Making the Technical Sale. Jim can be expects you to have a JDK preinstalled provide support for managing JDBC reached via the company Web site at http://www.kuromaku.com. on the server, but otherwise it’s a resources.) breeze. The ServletExec developers jumped on the Servlets bandwagon way Summary [email protected] back in 1997, and their technical acu- ServletExec 3.1 is a compelling product for men shines through in the product. those organizations that want to build dynamic I chose to install ServletExec as an Web sites and applications – without the cost application server and connect it to my and overhead of an enterprise-class application Apache Server. New Atlanta didn’t sup- server. Keep a sharp eye on New Atlanta. They port the Apache release that I was using, recently cancelled plans to merge with Unify so I dropped back to 1.3.14 in order to Corporation, and it’s my guess that the compa- proceed with my tests. Once I had the ny will be hitting the market with renewed vigor correct version of Apache running, the as a result of this change in strategy. ServletExec install went like clockwork. It correctly config- ured ServletExec to service Servlets and JSPs on behalf of New Atlanta Communications,LLC my Apache Server. In fact, you 1041-D Cambridge Square can even run the installer on an ongoing basis to move Web Alpharetta,Georgia 30004-1871 application definitions from Web:www.newatlanta.com the ServletExec configuration e-mail:[email protected] over to the Web server’s config- Phone:678 366-3211 uration files. I’d like to see this clever little configuration pro- gram uncoupled from the instal- Test Environment lation program and offered as a Dell 1400 PowerEdge 1 CPU (795MHz), separate utility. Windows 2000 Server SP1 256MB RAM I’d have to say that ServletExec was one of the easiest products to install and configure in the applica- FIGURE 1 ServletExec administration interface

54 JUNE 2001

Java COM ServletExec www.servletExec.com

JUNE 2001 55

Java COM WEBSPHERE COLUMN

J2ME Using the VisualAge for Java Enterprise Access Builder for Transactions J2SE Last month in JDJ (Vol. 6, issue 5) we looked at the Java 2 Platform, Enterprise Edition (J2EE) connector architecture (JCA) and its common client interface (CCI).To recap, JCA is the part of the J2EE 1.3 specification that facilitates the integration of Java applications with Enterprise Information Systems (EISs).The term WRITTEN BY EIS refers to a number of systems such as ERP,legacy databases, BRADY FLOWERS or transaction processing systems. J2EE As we saw in the last issue, integrating The ADDER Example 01 DFHCOMMAREA. these systems into a modern e-business To illustrate EAB we’ll use it to devel- 02 op1 PIC S99999 DISPLAY. architecture is complicated, to say the op a set of classes in VisualAge for Java. 02 op2 PIC S99999 DISPLAY. least. The APIs that these systems pro- These classes will encapsulate a single 02 res PIC S99999 DISPLAY. vide, if they provide one at all, are in gen- back-end transaction. For simplicity, 02 keyNum PIC X(5) DISPLAY. eral proprietary and require the develop- we’ll use a sample CICS transaction that er to reinvent the process for each and comes bundled with VisualAge for Java. To make sure that the required fea-

Home every system that needs integration. JCA If you have a CICS host available, you tures are installed into your workspace, is Sun’s proposed solution to this prob- can actually compile and link the trans- start VisualAge for Java and press F2 to lem. It should do for EIS integration what action into the CICS subsystem to try it open the Quick Start dialog. Select JDBC did for relational database access. out. “Features->Add Feature” and then select The name of the CICS program is “IBM Enterprise Access Builder Library” EAB and CCF ADDER. It accepts two integer values for and “CICS Connector.” If you don’t see As the vendor of CICS, MQSeries, input and returns their sum. The one or both of these, the feature is Encina, IMS, and Host on-Demand, IBM COBOL source, located in the file already installed and you can move to has a vested interest in EISs. Since 1998 \eab\samples\com\ibm\ the next step. If you’re using a different they’ve delivered a framework for access- ivj\examples\eab\adder\adder.ccp, example, make sure you install the con- ing them (and SAP R/3) in VisualAge for defines this record structure: nector for your EIS. Java. That product’s Enterprise Access Builder for Transactions (EAB) feature and the common connector framework (CCF) bear a striking resemblance to JCA and CCI and it’s easy to see why; IBM is a member of the expert group conferring with Sun on JCA. Both JCA and CCF define abstract objects for connections, interactions, transaction management, and input and output structures. They both assist the application server to better manage resources, such as connection pools for the EIS connections. At present there’s one big difference. JCA isn’t formally released yet and it’s not implemented by any application server or tool vendor. EAB and CCF are avail- able now, robust and mature. If you need to integrate any of the EAB-supported EISs, you can leverage the power of this framework now. Of course, since JCA is still a draft specification, you may need to make some changes to your applica- tions when the architecture is finalized. FIGURE 1 Import a COBOL file into EAB

56 JUNE 2001

Java COM IONA www.iona.com/inyourdreams

JUNE 2001 57

Java COM WEBSPHERE COLUMN

AdderRecord finished”, and click Finish. This creates Next we specify the input and out- Create a project and package for the the command class and immediately put beans. Right-click on “Input” and generated code. I called my package starts the Command Editor as shown in select “Add Input Bean”. Make sure jdj.june01.eab. From the package’s pop- Figure 2. “Implements IByteBuffer” is selected up menu select “Tools->Enterprise We must specify connection informa- and use the “Browse” button to select Access Builder->Import COBOL to tion. Right-click on “Connector” and AdderRecord. IByteBuffer is a special

J2ME Record Type.” Figure 1 shows a page select “Add ConnectionSpec”. Use the superclass that knows how to parse from this dialog. Use the Browse button Browse button to list all available connec- COBOL COMMAREAs and other byte- to navigate to the adder.ccp file. On the tion specs for the connectors you’ve buffer types of data records. Specify an last page of the dialog make sure that installed. Select “CICSConnectionSpec”. AdderRecord for “Output” as well. “Create record from record type” is When you highlight CICSConnectionSpec Now, select the input bean from the selected, name the output class “Adder- in the top-right window, its properties upper-right pane so its properties RecordType”, and click Finish. This will appear in the bottom window. In the URL appear in the bottom pane. Right-click generate your AdderRecordType and field, enter the name of the gateway used the “op1” property and select “Pro- J2SE AdderRecord. to connect to the server. In the CICSServer mote property”. This causes the code field enter the name of the CICS server. generator to create getOp1() and AdderCommand To specify the interaction right-click setOp1() methods, which delegate to To create the command bean, select on “Connector” and select “Add Inter- the input bean methods. Likewise pro- “Tools->Enterprise Access Builder- actionSpec”. This time select “ECIInter- mote the “op2” property of the input >Create Command”. Name the class actionSpec” and, in its properties, enter bean and the “res” property of the out- EABAdderCommand, select “Edit when “ADDER” for the programName property. put bean. Test the EAB Command J2EE Normally we’d have to write a class to test our code. The Enterprise Access Builder relieves us of this task, not to mention the chore of debugging the test code. It has a built-in test client that we can execute from the Command Editor or from the Enterprise Access Builder

Home menu. After launching the test client, select “Command->Create new instance” to get a list of all classes in our work- space that inherit from com.ibm.ivj.- eab.command.CommunicationComma nd. Pick EABAdderCommand from the list. The test client instantiates the class and displays the dialog you see in Figure 3. From here you can inspect and adjust any of the properties of EABAd- derCommand. Set the inputs op1 and op2 to some values and invoke the com- mand from the “Selected” menu. Assuming all goes well and you have FIGURE 2 EAB Command Editor your CICS gateway set up correctly, you should see the results in “res”. After only a few minutes of work and with no handwritten code, we now have a command object that can be used from client Java code with just a couple lines of setup:

EABAdderCommand cmd = new EABAdderCommand(); cmd.getCeConnectionSpec().set... // set any required properties cmd.getCeInteractionSpec().set... // set any required properties cmd.setOp1(2); cmd.setOp2(3); try { cmd.execute(); System.out.println("Result = " + cmd.getRes()); } FIGURE 3 Built-in Test Client catch (Exception e) {}

58 JUNE 2001

Java COM CapeClear www.capeclear.com

JUNE 2001 59

Java COM WEBSPHERE COLUMN

3. The vendor or another party will pro- command interface. It contains an EAB Is Not JCA vide a cleaner, more robust JCA EABAdderCommand to do the work and What can we do now to leverage the implementation for us sooner or later. “promotes” the relevant properties of power of EAB and still be able to migrate 4. Did I mention it’s a lot of work and the input and output records, making to a JCA implementation later? In addi- hard to do? them accessible to the client code, and tion to different class and package implements the execute() method and

J2ME names, we have architectural and philo- One solution would be to reuse the exception handling. We’ve included a sophical differences that are nontrivial: notion of command. The command pat- main() method for testing; all you need • JCA connections are created by a tern characterizes any activity by wrap- to do is fill in the server properties for ConnectionFactory that was obtained ping it in a straightforward interface. We your system and execute it. via a JNDI lookup, while EAB handles have “setters” for input values to the connections via the com.ibm.connec- command, an execute() method, and Conclusion tor.Communication class. “getters” for resulting values. When it’s time to make our sample • The JCA interaction behaves like a In the example code (listings are work with a JCA infrastructure, we need J2SE combination of the EAB interaction located on the JDJ Web site) we’ve to create only an AdderCommand that and the EAB command. defined a command interface and an uses JCA. The client code won’t have to • In JCA, local transactions are accessed associated CommandException class in change. In the package jdj.june01jca and controlled through a LocalTrans- its own package. The command inter- there’s an AdderCommand that shows action object obtained from the connec- face is intended to be generic, to serve as what this would look like. tion; in EAB the RuntimeContext handles a front end for both our EAB-generated transactional boundaries and scope. classes and any future JCA-based imple- Resources • Unlike EAB, JCA has the notion of mentations. We’ll address only those 1. The JCA specification and information AUTHOR BIO result sets. features we need right now: the ability to on CCI: http://java.sun.com/j2ee/ J2EE Brady Flowers is a set input parameters, to execute the EIS connector/ software IT architect Reprising a Command Performance transaction, to read output results, and 2. IBM documentation for the Enterprise with IBM’s We could write all the code to imple- to handle exceptions if they occur. Our Access Builder for Transactions: WebSpeed team ment the CCI classes with the EAB code design is generic so we can add other www7.software.ibm.com/vad.nsf/Da specializing in providing the “plumbing.” We could, but JCA features when we need them. ta/Document3852 WebSphere, Java, we won’t because: The command interface and 3. Gamma, E., Helm, R., Johnson, R., and and the rest of 1. It’s a lot of work and hard to do, not to CommandException are located in the Vlissides, J. (1995). Design Patterns.

Home IBM’s suite of mention hard to do correctly. jdj.june01.command package in the Addison-Wesley. e-business 2. JCA isn’t finalized; our code may code listings. We’ve written jdj.jun01.- applications. become obsolete at any moment. eab.AdderCommand to implement the [email protected]

INT www.int.com

60 JUNE 2001

Java COM Softwired www.softwired-inc.com

JUNE 2001 61

Java COM PRODUCT REVIEW

Planet recently announced some updates to quires. Advanced servlet/JSP applications can their family of Web and application server be built with the Standard Edition, which iproducts that help consolidate the overall includes native support for Oracle, IBM DB2, product line. The new product positioning Sybase, and Informix. The Enterprise Edition won’t surprise iPlanet enthusiasts as it positions adds support for EJB deployment (including J2ME iPlanet iPlanet as a superior solution for a broader EJB failover capabilities), providing developers range of the application server marketplace. with the full power of the J2EE platform. The core of these announcements is a new Should you need to add process management release of the Web server software and new and application-to-application integration to the New Web and packaging for the application server lineup: mix, iPlanet offers the Enterprise Pro Edition. The • iPlanet Web Server, Enterprise Edition 6.0 upgrade path between the various versions is • iPlanet Application Server, Standard almost transparent, so it’s a simple matter to start Application Server Family Edition 6.0 small and add to your applications as needed. J2SE • iPlanet Application Server, Enterprise The Forte for Java development environment Edition 6.0 works with all three editions of the Application • iPlanet Application Server, Enterprise Server lineup – so your developers can work with WRITTEN BY JIM MILBERY Pro Edition 6.0 all three versions using a single IDE. In fact, iPlanet has launched an aggressive Although iPlanet is separate to some campaign to woo developers to the iPlanet degree from Sun Microsystems, the two platform. In the past, developers had to join companies are very closely aligned. The their developer program and pay a $995 regis- new product lineup reflects this part- tration fee to gain access to the application J2EE nership in several ways. First, the new server product line. However, you can now product line is an essential component download trial versions of the Enterprise of the Sun Open Net Environment Edition from the iPlanet Web site free of charge. (ONE), which is Sun’s initiative in the Should you wish to develop an application on Web Services arena. The product suite the iPlanet Server, iPlanet has put together an has always shared a common infra- aggressive developer package in the form of the AUTHOR BIO structure, and the new product family iPlanet Developer Pack. The iPlanet Developer

Home Jim Milbery is a software consultant based in Easton, has been designed to improve on this Pack, Enterprise Edition 6.0, improves developer Pennsylvania, with Kuromaku Partners LLC. He has over 17 integration. The updated product suite productivity by combining a development license years of experience in application development and relational is targeted toward a diverse audience: of the iPlanet Application Server, Forte for Java databases. He is the applications editor of Wireless • Service providers and enterprises Internet Edition 2.0 trial software, and WebGain Business & Technology, the product reviews editor of Java looking to create dynamic content Studio 4.1 trial software – all for $1,295 per devel- Developer’s Journal, and the author of Making the • Customers looking for an entry-level oper. The developer pack includes access to over Technical Sale. Jim can be reached via the company Web site Java 2, Enterprise Edition (J2EE) 120 prebuilt EJB components from a variety of at www.kuromaku.com. platform iPlanet partners, including ComponentSource, • Core J2EE customers who want to Compoze Software, Diamelle Technologies, Ever- [email protected] leverage the full power of the J2EE green Internet, Flashline, and Omix. platform Many of the organizations that I talk with are • Customers needing to tie legacy developing portal strategies for both internal and applications together to automate a external access. iPlanet now offers the iPlanet business process Portal Server, which is built on the iPlanet Application Server platform. This Portal Server The iPlanet Web Server has long had a addresses all the critical portal requirements, strong presence in the corporate market- including single sign-on, personalization, appli- place. Although the Apache HTTP Server cation integration, and knowledge management. rates the most Internet hits according to Most organizations start their portal efforts with Netcraft, the iPlanet Web Server has a much simple e-mail and calendar access and this is stronger following within the enterprise where iPlanet really shines, with its integration market. iPlanet’s new packaging reflects this with both the Messaging and the Calendar Server. enthusiasm within the corporate environ- iPlanet’s product suites are easy to install ment and provides their customers with an and maintain, but Sun and iPlanet have also integrated stack of products that follow a announced a set of preconfigured hardware/ iPlanet E-Commerce Solutions simplified growth path. The iPlanet Web software packages to make the entire process World Headquarters Server Enterprise Edition 6.0 supports both even easier. Each solution features the iPlanet 901 San Antonio Road servlets and JavaServer Pages, allowing cus- Web Server, the J2EE-certified iPlanet App- Palo Alto,CA 94303 tomers to deliver dynamic Web content along- lication Server, and the Solaris Operating side existing static HTML pages using a single Environment 8.0 combined with various con- Phone:650 960-1300 server. When it comes time to add support for figurations of Sun server hardware built around Web: www.iPlanet.com advanced EJB capabilities, you can easily add the 64-bit SPARC microprocessor architecture. E-mail:see Web site the iPlanet Application Server to the mix. These recent announcements and product The iPlanet Application Server comes in upgrades make a compelling story and have three versions, so you only need to pay for the “upped the ante” in the hotly contested Java specific features that your organization re- application server market.

62 JUNE 2001

Java COM Borland www.borland.com

JUNE 2001 63

Java COM E J B 2 . 0

J2ME The Impact of EJB 2.0

J2SE An introduction to many of the issues that developers will face immediately

Last summer, Sun Microsystems released the first public draft of the EJB 2.0 specification with a lot of fanfare. Since then, it’s been J2EE through a whirlwind of discussion, controversy, and modifications.Yes, WRITTEN BY modifications. The latest release of the EJB specification is Public TYLER JEWELL Final Draft 2, which was released at the end of April.

The latest incarnation of the EJB application will be able to query the that’s undergoing community review at specification has a variety of features magazine component for magazines theserverside.com. Once the chapter that developers should become familiar and articles. Additionally, the client has completed community review and is

Home with: application will be able to register a sub- published, it will be made available for • The introduction of message-driven scriber to a magazine by sending a JMS download in a PDF format. beans message to a queue that has a registra- Writing a message-driven bean is • The creation of a new entity EJB con- tion message-driven bean consumer. straightforward. Message-driven beans tainer-managed persistence model The registration message-driven bean do not have client-visible home or com- • A model for creating container-man- will simulate registering the subscriber ponent interfaces since they’re decou- aged relationships between entity and sending an e-mail message to con- pled from message producers. Thus, a EJBs firm the information. message-driven bean’s implementation • The creation of a standard query lan- The examples provided with this is a class that: guage, EJB-QL, for querying EJBs and article are configured to run on BEA • Implements the javax.ejb.Message- their properties WebLogic Server 6.0, Service Pack 1. The DrivenBean interface (ejbRemove() • The introduction of local interfaces for examples are based on the EJB 2.0 spec- and setMessageDrivenContext(…)) session and entity beans ification, Public Draft 1 (PD1). The • Implements the javax.jms.Message- • The renaming of remote interfaces to examples do not support PD2 semantics Listener interface (onMessage(…)) component interfaces since a vendor implementation sup- • Provides an ejbCreate() implementa- • The introduction of home methods porting PD2 did not exist at the time this tion • The introduction of ejbSelect methods article was written. PD2 introduces that allow an entity EJB to internally requirements around the use of local Listing 1 shows the implementation query for properties using a deploy- interfaces for entity EJBs participating in of a registration bean. (All listings appear ment descriptor–defined EJB-QL a CMR relationship, a modified EJB-QL on the JDJ Web site.) It contains com- query language, and a different DTD for the ments explaining the bean developer’s EJB deployment descriptor. responsibility for each message-driven This article provides a rapid-fire bean method implementation. In the implementation primer to the new fea- Message-Driven Beans registration bean, the onMessage(…) tures of the EJB 2.0 specification for Message-driven beans are a new method expects to consume a message developers with prior EJB experience. component type in the EJB 2.0 specifica- of type MapMessage. The MapMessage The examples in this article are tion that allows developers to meld JMS will have two string instances contained based on the simple UML diagram pre- with a component model. A message- within it: one with the name of the mag- sented in Figure 1. Our mini e-business driven bean is an EJB component that’s azine that should be subscribed to and system will model components that a JMS consumer. Message-driven beans another with the e-mail address of the might be used by a magazine publisher. have all of the benefits of decoupled, individual that wants the subscription. Our magazine component will be a asynchronous message-based models. The examples provided in this article CMP-entity EJB that can have zero or For a good description of the benefits of contain a client test application, more article CMP-entity EJB compo- using asynchronous invocations, check Client.java (not listed). This application nents in a one-to-many container-man- out the “Message-Driven Beans” chapter tests all aspects of the EJBs deployed for aged relationship (CMR). The client in the upcoming Mastering EJB II book this article. In particular, for the registra-

64 JUNE 2001

Java COM Pingtel www.pingetel.com/javachallenge

JUNE 2001 65

Java COM E J B 2 . 0

tion bean, the client application creates messages of interest. This is declared ambiguous now since developers a transacted QueueSender instance, fills with the tag. need only to provide a pair of a MapMessage with the appropriate val- • An optional JavaBean-like accessor methods in the ues, and sends the message to the tag that tells a container using bean- implementation class. SampleQueue deployed in the applica- managed transactions the semantics • Declare the implementation class to tion server. The registration bean’s that should be used to determine be abstract. The application-server deployment descriptor contains the when a consumed message should be vendor will provide the concrete bean

J2ME name of the JMS destination that the acknowledged to the JMS server. The implementation class during contain- bean subscribes to. valid acknowledgment values are er generation. The container genera- Creating a deployment descriptor for AUTO_ACKNOWLEDGE and tion utility will extend this abstract a message-driven bean is equally sim- DUPS_OK_ACKNOWLEDGE and class with an implementation of its ple. The DTD for EJBs has been extend- have the same semantic behavior as own that provides a concrete imple- ed to include a tag listed in the JMS 1.0.2 specification. mentation for all of the abstract prop- that a bean developer adds when the erty accessor methods. The actual bean is first built. A message-driven Note: For message-driven beans that persistence logic for the EJB will be J2SE bean is required to declare: use container-managed transactions, located in the concrete implementa- • The recommended JMS destination the valid transaction attributes are tion created by the container genera- type for this bean. The recommended Required and NotSupported. If the mes- tor. destination type can be sage-driven bean container is config- • For each property declared with an javax.jms.Queue or javax.jms.Topic. ured to use the Required attribute, mes- abstract accessor method in the These are recommendations made by sage acknowledgment will be performed implementation class,the bean devel- the bean developer to the deployer when the user transaction commits or oper must provide a matching declaration in the deployment bean should consume messages sage-driven bean container is config- descriptor. The value of the tag must start with a lowercase nation-type> tag. Note: the actual des- message acknowledgment is undefined letter and match the text following the tination that a message-driven bean in the specification but will likely hap- get/set accessor methods in the binds to is not listed in the ejb-jar.xml pen after the completion of the implementation class. For example, if file. The destination that a message- onMessage(…) method. you declare age, the bean implementation class server–dependent and included in a of the EJBs in this article. The

Home vendor implementation deployment driven> tag declares the registration setAge(…) methods. descriptor. bean. • The primary key must be a CMP field • If the recommended JMS destination in the bean implementation class type for a bean is javax.jms.Topic, the New CMP Model with an appropriate bean developer can configure the The EJB 2.0 specification introduces declaration in the deployment message-driven bean to be a durable a new format for handling container- descriptor. Additionally, the subscriber of messages. This allows a managed persistence. It is commonly tag must be used to message-driven bean container to agreed that this new format is more flex- declare which value is crash and later consume any missed ible and easier to develop with than the the primary key value for the EJB. messages. This is declared with the EJB 1.1 model. Complex primary keys are still sup- tag. The specification provides a formal ported and have a slightly different • An optional message selector to be mechanism for declaring properties that semantic associated with them. used by the JMS consumer to filter out should have their persistence managed • The ejbCreate(…) method must by the container. This return null. The concrete implemen- involves the bean developer tation will create an appropriate altering his or her approach return value that will be handled by to developing an entity the container. bean that will be managed through container-man- Listings 3–5 contain the implemen- aged persistence. In partic- tation of a simple CMP entity EJB. The ular, bean developers must EJB has three CMP properties: articleID now: (primary key), text, and author. The • Declare each property implementation class declares each of through a series of get/set these properties using the appropriate accessor methods that are abstract accessor methods. Additionally, declared abstract. The data the class is declared to be abstract. type of the property can be It’s extremely important to under- determined by a container stand that the container callback meth- generation utility by using ods and the business logic implementa- introspection on the return tion methods must use the abstract type of the getXXX() method accessor methods to read or write any of and the input parameter of the CMP properties. This is demonstrat- the setXXX(…) method. ed in the ejbCreate(…) method where Declaring CMP properties the properties of the bean are initialized FIGURE 1 UML model for examples in the bean class is less using the appropriate set methods. Also

66 JUNE 2001

Java COM Thought Inc www.thoughtinc.com

JUNE 2001 67

Java COM E J B 2 . 0

• WHERE mb.name IS NOT NULL: This “ clarifies the query. The dot ‘.’ syntax is Container-managed relationships (CMR) used to navigate to any CMP field or container-managed relationship. are easy to define using the new EJB 2.0 mb.name refers to the value of the name CMP field of the mb EJB J2ME model. CMRs can be one-to-one, instance. The dot ‘.’ syntax can go many levels deep, but can not be used to navigate to a field or a relationship one-to-many,or many-to-many that references a collection of fields. A different syntax must be used.

note that the ejbCreate(…) method findByPrimaryKey()’s query is automat-’’ This example will return references returns null as defined by the specifica- ed by the container. Queries are to all magazine EJBs whose name CMP J2SE tion. declared in the ejb-jar.xml deployment field is not null. Listing 2 contains the deployment descriptor as part of the tag. descriptor for the article EJB. The decla- The tag declares the method New Container-Managed Relationship Model ration of the and tags are done for the article EJB as itself. (CMR) are easy to define using the new described by the rules listed above. You EJB-QL queries can also be applied EJB 2.0 model. CMRs can be one-to- might be wondering what the intent of to ejbSelect() methods, which are new in one, one-to-many, or many-to-many. the tag is. The the EJB 2.0 specification. ejbSelect() Additionally, CMRs can be unidirection- value of this tag will be used in any EJB- methods are private methods declared al or bidirectional. The bean developer J2EE QL queries that are defined for your EJB. in an implementation class, and used by is responsible for defining the relation- Its value acts as a symbolic data type other implementation methods to ships between beans in the implemen- that references this particular EJB in the access fields and collections of fields tation classes and the deployment query. Since multiple EJBs can be that are accessible from a particular EJB. descriptor. declared in a single deployment descrip- This includes fields that are accessible The bean developer has to perform tor, it’s required that each EJB has a through a container-managed relation- the following activities to define a CMR: unique value. ship. Even though we do not provide an • Provide abstract accessor methods

Home Because of the innovative approach ejbSelect() implementation in our that indicate directionality and multi- taken to declaring CMP properties of an example, the definition of the EJB-QL plicity in the implementation class. entity EJB, application server vendors query is similar to those for finder meth- Similar to CMP field declaration, can provide a whole series of enhance- ods. every CMR field must have a get/set ments to increase performance of entity EJB-QL queries have three clauses: method that references the other EJB EJBs: SELECT, FROM, and WHERE. The in the relationship. • Lazy loading of fields when they’re SELECT clause is needed for ejbSelect() • If the target of the relationship has a accessed: The container can deter- method queries but can be dropped for multiplicity of one, then the get/set mine when a get method is invoked finder queries. For example, Listing 6 methods must reference the remote and load fields at the time of the invo- contains the home interface for the interface of the other EJB in the rela- cation instead of pre-fetching values. magazine entity EJB that uses CMP for tionship. Note: In PD2, the specifica- • Group loading of fields: An applica- its name and editor fields and partici- tion requires accessor methods to ref- tion server vendor can provide a way pates in a container-managed unidirec- erence only the local interface of the to declare groups of fields so that tional, one-to-many relationship with other EJB in the relationship. when one field is accessed, all of the article. Listing 2 contains an EJB-QL • For relationships where the target of fields for the group will be loaded as query for the findAllMagazines() the relationship has a many multiplici- part of a single query. method declared in the home interface. ty, the get/set accessor methods repre- • Optimized writes to a database: Since We want this method to return refer- senting the relationship must use col- the container can monitor all get- ences to any magazine that exists in the lection or set as their data type. Listings and-set method invocations made, persistent store. 6–8 contain a one-to-many, unidirec- the container can optimize any write Let’s break down the value, tional relationship to the article EJB. queries to write out only those fields : class declares Collection getArticles() • The creation of read-only and read- • : This construct is and setArticles(Collection) since the write distributed data caches: These used to escape any SGML tags that target of the relationship is a many can be done at the container level in a may appear within the query. The multiplicity. much more automated way since body of this declaration is the query. • The absence of get/set accessor properties can be monitored for alter- • FROM MagazineBean mb: This methods in an implementation class ations. declares a query variable, mb, of type indicates lack of directionality for that MagazineBean. MagazineBean comes particular EJB. As a result, the article New EJB Query Language from the EJB implementation (Listing 5) does Because of the declaration of CMP declaration of the EJB as mentioned not have the get/set accessor meth- fields in a deployment descriptor, it’s above. The mb variable can be used to ods to the magazine since this rela- now possible to create queries in the reference an instance of that particu- tionship is unidirectional. deployment descriptor for any finder lar EJB type in the WHERE clause of • The source EJB, target EJB, direction- method other than findByPrimaryKey(). the query. ality, and multiplicity of the CMR are

68 JUNE 2001

Java COM ILOG www.ilog.com/jdj

JUNE 2001 69

Java COM E J B 2 . 0

also defined in the deployment many relationship in a relational that refers to a single instance of the descriptor via a tag model is to have a foreign key in one collection of article references that are that appears after all EJB declarations, table pointing to a primary key in associated with this magazine but before the . The tag defines a in the table representing the “many” articles. single relationship between two EJBs. multiplicity of the relationship and • Since the article variable refers to a An tag has two

J2ME relationship-role> tags that define table representing the “one” multiplic- cle can be used in the WHERE clause each end of the relationship. Each ity. This abstract-to-concrete persist- to reference CMP fields of the article tag defines ence mapping is not defined in the EJB EJB. the for this role, the EJB specification and is left up to each EJB • ?1 is EJB-QL syntax for referencing the that is the of this role, container vendor to supply. For BEA first input parameter of the finder and a that indicates WebLogic Server, this is done in the method. ?2 would represent the value whether or not this EJB contains weblogic-ejb-jar.xml and weblogic- of the second input parameter, etc. get/set accessor methods that imple- cmp-rdbms-jar.xml files. • The syntax for this example is based J2SE ment directionality for this source. As a final note, it should be under- on PD1 and has changed slightly in stood that EJB-QL is robust enough to be PD2. Listing 2 contains the tag for the magazine-article magazine EJB home–interface defined a Conclusion Tyler Jewell is a principal CMR. Notice that only the MagazineEJB findMagazinesWithArticlesBy(String) Whew! What a mouthful! As you can technology source has a declared since method that requires an EJB-QL query see, the EJB 2.0 specification made evangelist for BEA we’re creating a unidirectional relation- that navigates magazine and article. many modifications that impact EJB Systems, and an expert ship. Additionally, the value of the Since the dot ‘.’ syntax can not be used to developers. This rapid-fire article educator, mentor, and must match the text navigate relationships with a multiplicity attempted to provide a quick introduc- J2EE lecturer on enterprise appearing after get/set in the accessor of many, a special syntax has been creat- tion to many of the issues that develop- technologies. He is a method. ed to support this. The query provided is ers will face immediately. Now, it’s time coauthor of Mastering It’s important to understand that FROM MagazineBean mb, article IN to go have some fun and implement the EJB 2.0 (Wiley) and a the actual persistent mapping of the mb.articles WHERE article.author = ?1. biggest and brightest e-business sys- contributor to Pure EJB relationship is not defined anywhere Some points about this query include: tems using your newfound EJB knowl- (SAMS). He is also a in the standard deployment descrip- • The IN clause defines a loop variable edge! member of the O’Reilly tor; it is completely vendor-depend- that refers to a single instance defined

Home Network’s ONJava.com ent. For example, the most common in a collection. article IN mb.articles [email protected] editorial advisory panel. technique used to represent a one-to- declares a local loop variable, article,

Jess www.herzberg.ca.sandia.gov/jess

70 JUNE 2001

Java COM Jinfonet www.jinfonet.com

JUNE 2001 71

Java COM Elipsus www.ellipsus.com

72 JUNE 2001

Java COM Elipsus www.ellipsus.com

JUNE 2001 73

Java COM J2SE EDITORIAL WRITTEN BY JEREMY GEELAN Welcome to the J2SEJ2SE Heart of Java ROADMAPROADMAP

s Rich Green, vice president of Java too, for an up-to-the-minute roadmap and software development at Sun and a for the J2SE FAQ, since JDJ is well aware of contributor to this historic JavaOne its duty to entrants to the Java space. J2SE A issue of JDJ once said, J2SE technology “is We’ll print plenty of source code, plenty the heart and soul of the Java 2 platform.” of tips and tricks...and of course want plen- In other words, it allows software devel- ty of feedback. opers to build network-centric software Java programmers of every stripe should that’s compatible across all major platforms, feel free to become involved with the JDJ Web helping to protect their customers’ IT invest- site, www.sys-con.com/java, and should con- ments. The J2SE runtime environment sup- sider subscribing to JDJList, too, where Java The Java2 Platform, Standard ports the architecture of the J2EE platform, information, insights, and viewpoints are Edition defines the APIs for the providing it – and the applications deployed exchanged on a daily, and often an hourly, basis. on it – with all the standard Java facilities. Last but not least, as no reader of this issue core language. So for JDJ, even in its new “2.0” incarnation, could possibly be unaware – short of having to be published without a section devoted to read the issue through the wrong end of a tel- the Java 2 Standard Edition would be a little like escope...or in the dark maybe – SYS-CON J2SE the New York Times being published without Media’s conference arm, SYS-CON Events, is its Op-Ed page, or a Ford Explorer being sent producing and presenting in September what

Homeout of the factory J2EE without its wheels. is simply J2ME the largest Java developer conference Javabeans Accordingly, this month’s selection of and expo ever held on the East Coast. So if you articles is plentiful and varied, ranging are able to get to New York anytime between JavaSound from John Goodson on Java database con- September 24 and 26, make a firm note in your nectivity and Irvin Lustig on optimization calendar to attend. Further details are also on to Blair Wyman on JNI programming in our Web site; you can’t miss them. Java Native Interface C/C++ and Michael Barbarelli’s piece on Java Developer’s Journal undergirds the using JavaBeans in Dreamweaver. conference in much the same way that J2SE RMI-IIOP If you’re reading this issue at Sun’s undergirds the Java 2 Platform. The new JavaOne show, perhaps you’ve been saturat- section editors will all be there, along with ed with the myriad possibilities of J2ME or the head honcho himself, editor-in-chief Swing maybe emboldened by the transformational Alan Williamson, and a good many of JDJ’s powers of J2EE for e-commerce. There may stalwarts like product review editor Jim Java2D not be too many sessions devoted to J2SE, Milbery, plus an assortment of editorial any more than there are technical books panel members and regular contributors. with “J2SE” in the title available through What’s more, if you want to listen to the Java Accessibility API Amazon.com (there aren’t, not a one). likes of the coinventor of Java, the legendary But J2SE isn’t the “poor relation” of the James Gosling, or to the man who helped Java Naming and Directory Java industry any more than, say, paper is orchestrate the growth and adoption of the Interface (JNDI) considered second fiddle when it comes to Java platform from its infancy to its present sta- the publishing industry. Accordingly the tus as a robust platform that supports mission- J2SE Section will always give houseroom to critical applications in almost 80% of Fortune Java Foundation Classes good technical writing that explores the 1000 companies – which is what conference development of apps using the J2SE APIs. keynote speaker Dr. Alan Baratz did in his for- There will always be, just as there is this mer life as president of the software products Useful URLs: time, at least one book review (this time and platforms division at Sun – then you we’ve selected Debugging Java by Will D. should attend. Java 2 Platform Standard Edition Mitchell; next month we’ll look at 3D User We look forward to seeing you there in http://java.sun.com/j2se/1.3/ Interfaces with by Jon Barrilleaux). September. Just as we look forward to There will always be reviews of products meeting you here, in the J2SE Section of the Features: and apps, and there will always be room, new-look JDJ, next month. http://java.sun.com/j2se/1.3/doc [email protected] s/relnotes/features.html AUTHOR BIO Jeremy Geelan, editorial director of SYS-CON Media, speaks, writes, and broadcasts about the future of Internet technology and about the business strategies appropriate to the convergence of business, i-tech, and the future. ROAD MAP

74 JUNE 2001

Java COM Tidestone www.tidestone.com

JUNE 2001 75

Java COM J2SE FAQ

QWhat’s new in J2SE? J2SE has focused on adding new libraries. Some new features include the javax package, Swing, Java Collections API, JavaBean enhancements, and Java 2D. It also introduced a com- pletely new security architecture and Java Hotspot. At the same time J2SE was brought into existence, two other versions were split off – J2EE and J2ME.

J2SE A What is Swing technology? Swing is a set of GUI components with a “pluggable look and feel” based on the JDK 1.1 Lightweight UI Framework. The pluggable look and feel allows developers to implement an operating system–specific look and feel (Motif, Microsoft Windows, MacOS). Swing components include both 100% Pure Java versions of the 1.1 AWT component set,

J2SE plus a rich set of higher-level components. The complete set contains borders, buttons, checkboxes, combo boxes, icons, labels, lists, list boxes, menus, menubars, menu items, pop- up menus, radio buttons, progress bars, scroll panes and viewports, scrollbars, tabbed panes, Qtables, text areas, text components, text fields, trees, and HTML viewers. What security enhancements are in J2SE? J2SE introduces the concepts of permission and policy. When code is loaded, it’s assigned

Home J2EEpermissions J2ME based on the security policy currently in effect. These new concepts of permission and policy enable the to offer fine-grained, highly configurable, flexible, and extensible access control. Now such access control can not only be specified for applets, but also for all code written in the Java pro- grammingA language, including applications and beans. What is Java 2D? The Java 2D API is a set of classes for advanced 2D graphics and imaging. It encompasses line art, text, and images in a single comprehensive model. The API provides extensive sup- port for image compositing and alpha-channel images, a set of classes to provide accurate color-space definition and conversion, and a rich set of display-oriented imaging operators. These classes are provided as additions to the java.awt and java.awt.image packages (rather than as a separate package). What about Java Collections API? Collections Framework is a unified framework for representing and manipulating collec- tions, thus allowing them to be manipulated independently of the details of their representa-

SPECIAL SECTION: tion. It reduces programming effort, increases performance, allows for interoperability among Qunrelated APIs, reduces effort to design and learn new APIs, and fosters software reuse. The framework includes interfaces, implementations, and algorithms. How have JavaBeans been improved? Interaction with Applet Semantics eases the development of objects that implement applet as well as JavaBeans architecture behavior. ABetter design-time support adds infrastructure during the JavaBeans component architec-

FAQ‘s ture design time to enable a more sophisticated builder environment. Runtime containment and services protocol (BeanContext) adds additional context to the execution lifetime of JavaBeans architecture including, but not limited to AppletContext and the ability to parent into an AWT presentation hierarchy.

76 JUNE 2001

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

JUNE 2001 77

Java COM a Telephone/Voice Portal Building g with Java Phonelets

ast month we introduced the phonelet

architecture and developer API for creat-

ing lightweight telephone/voice services in J2SE L Java. This article expands the automated answering

machine with caller ID, basic voice processing capa-

bilities, and, just for fun, a simple appliance control

function using an inexpensive X10 power line mod-

ule. We’ll also introduce voice recognition and Home J2EE J2ME speech synthesis and provide recommendations for

further exploration. A how-to for both the newbie and the pro A how-to for both the newbie and pro A how-to for both the newbie and pro

Part 2 Written by Kent V. Klinner III & Dale B. Walker

Caller ID Makes Simple Phonelets More Useful Caller ID, recently made available by most U.S. telephone companies, identifies the tele- phone number and sometimes the name associated with a particular telephone line. The information is transmitted between the first and second ring using Frequency Shift Keyed (FSK) modem tones. Most modems can be set to provide this information if it’s on the tele- phone line. Two formats are used for CID: • Single Data Message Format (SDMF), which provides date, time, and calling number • Multiple Data Message Format (MDMF), the more common format, which additionally provides the name associated with that number

Both formats, when provided by a modem, take the form of an ASCII hex string, where the first byte of the string indicates the message type.

78 JUNE 2001

Java COM Loox www.loox.com

JUNE 2001 79

Java COM An MDMF string might look like this: extend GenericVoiceModem to develop a device handler for a "80200108303332343039303207084A4F484E20444F45020A383030 specific modem should specify at least one common audio 353535313231327D" format. Modem documentation can be difficult to obtain, but This would decode to: one of the most accessible sources of modem information is 80: MDMF available in the INF files distributed with Microsoft Windows. 20: 32 bytes of data Each modem manufacturer provides an INF file as part of the 01 08 3033323430393032: date and time (length 8) 03/24 Windows installation package to specify the modem’s operat- 09:02 ing capabilities and command sets. A description of modem 07 08 4A4F484E20444F45: name (length 8) JOHN DOE INF files is beyond the scope of this article, but if you’re famil- 02 0A 38303035353531323132: number (length 10) 800 555 iar with AT command sets you won’t have much trouble 1212 culling useful information for your model. • VoiceModem.getAudioFormat() returns the currently active The CallerId Class takes such a string and decodes it into audio format. useful information. • VoiceModem.setAudioFormat() sets the current audio for- Caller ID can transform a useless phonelet like HelloCaller mat for the modem. into a useful application. The following code demonstrates • VoiceModem.getPreferredAudioFormat() returns the pre- J2SE the service method of a phonelet that never answers the ferred audio format for the modem. phone, but always announces the phone number of the call- ing party. The definition of preferred is up to the device handler developer. For example, some modems based on public void service (PhoneCall call) throws Rockwell/Conexant chips support a PCM 8-bit encoding at IOException { 11,025 Hz, but won’t report DTMF events or silence intervals CallerId cid = call.getCallerID(); at that rate. At a lower sample rate of 8kHz the same modem String callerPhoneNumber = null; will detect and report DTMF events as well as intervals of if (cid != null) callerPhoneNumber = silence. Clearly, the higher rate would not be preferred for any cid.getPhoneNumber(); application that needed to detect touchtones while playing a Talker.talk("Incoming call from message for the user. "+formatForReadback(callerPhoneNumber)); } How to Play Audio In the HelloCaller example we demonstrated how to play a AnnounceCaller simply reads the phone number of the wav file to a caller. We’ll now discuss the Phone.play() method

Home J2EEcalling party to the PC user. The caller J2ME ID packet is available in more detail. only on telephone lines that subscribe to the caller ID service GenericVoiceModem doesn’t provide on-the-fly audio for- of their local telephone company. If the packet is unavailable, mat conversion. Developers must make sure that the audio the phonelet simply announces the caller as “unknown.” The format of the file, stream, or data buffer they intend to trans- details of the announcement are implemented in the method mit with the Phone.play() method matches the currently formatForReadback(). The Talker.talk method assumes the active format of the phone. If you try to play an 8-bit/8kHz/u- presence of a text-to-speech package like IBM’s ViaVoice. (See law wav file through a phone set to 16-bit/7.2kHz/PCM, the section “How to Handle Speech” for more detail.) result will be unintelligible. The following code illustrates the One of the most frustrating aspects of developing audio correct way to play a wav file. If the audio format of the wav applications is wrestling with the wide variety of audio file for- file isn’t supported by the phone’s underlying modem, a mats, encoding schemes, sample rates, and resolutions. The ModemException is thrown. narrow bandwidth and serial speed limits of voice modems narrow the selections for phonelet programmers, but there is try { still room for confusion. Table 1 illustrates the range of choic- AudioFormat audioFormat = es for some Lucent and Rockwell/Conexant chip sets. AudioSystem.getAudioFileFormat(waveFile).getAudioFormat The phonelets’ framework uses javax.sound.sampled, and (); therefore supports wav file format and the encoding schemes phone.setAudioFormat(audioFormat); defined for AudioFormat in Java v1.3 (PCM, u-law and a-law). phone.play(waveFile); Three methods defined in the VoiceModem interface will } help developers choose an appropriate audio format for play- catch (PhoneException e) ing or recording sound. { VoiceModem.getAudioFormats() returns an enumeration // thrown if audioFormat is not supported of audio formats supported by the modem. Developers who }

The Phone.play() method allows callers ENCODING BITS/SAMPLE SAMPLES/SECOND CHIPS to interrupt a message with a simple PCM 8 7200 Lucent, Rockwell touchtone. This interrupt feature is espe- PCM 8 8000 Lucent cially useful when your phonelet is PCM 8 11025 Lucent, Rockwell prompting the user for touchtone input PCM 16 720 Lucent and you want an instructional message A-Law 8 8000 Lucent to stop playing immediately upon detec- U-Law 8 8000 Lucent tion of a specific touchtone key. In the ADPCM 2 7200 Rockwell following example we play a sequence of APCM 4 7200 Rockwell wav files, aborting the play if a certain key is pressed. TABLE 1 The range of choices for certain Lucent and Rockwell/Conexant chipsets.

80 JUNE 2001

Java COM RSA www.rsasecurity.com/go/paint

JUNE 2001 81

Java COM public void service (PhoneCall call) throws phonelet might do something with the message file before IOException { exiting, like e-mail it to the owner or copy it to a specific fold- Phone phone = call.answer(this); er. if (phone == null) return; phone.play("welcomeToCinemaPhone.wav"); How to Place an Outgoing Call phone.play("pressPoundToEndThisMessage.wav"); Placing an outgoing voice call can be quite complicated for a modem. Data modems and fax machines answer with spe- phone.play("theFeaturePresentationToday.wav",pressPound cific tones to signal their functions, but humans and answer- KeyToAbort); ing machines aren’t so predictable. Determining when a call phone.play("thankYouForCallingCinemaPhone.wav"); has been answered has been a challenge for modem and phone.hangup(this); telephony board manufacturers. The most common scheme } among modem manufacturers is to set a timer that expires when the ring signal goes away. This method is crude and isn’t How to Record Audio always reliable. The service routine in Listing 1 demonstrates how Manufacturers have also had some difficulty determining to record a message from an incoming caller. In this precisely when a call has been terminated by the distant party. J2SE example all instructional messages and prompts are Some modems and telephony boards use silence detectors played from wave files. (All listings can be found on but, again, these methods may not work reliably, especially if www.JavaDevelopersJournal.com.) the line is noisy. Other schemes have been developed but A reasonable message recorder application should be tolerant require a much more detailed discussion of telephony sys- of slow callers and resilient to premature hang-ups. Before a mes- tems and audio signal processing. sage is recorded, instructions should be repeated a reasonable The phonelet framework allows developers to place outgo- number of times. If the caller doesn’t respond with an appropriate ing calls with the Phone.call() method. It also allows develop- touchtone or verbal response within a reasonable time frame, the ers to redirect audio to a specific OutputStream. We challenge phonelet should hang up. When recording commences, the pru- readers to develop an audio stream processor that can accu- dent developer will make allowances for callers who hang up or rately and reliably detect a spoken (or recorded) greeting. We are disconnected. Reasonable applications may also allow the also challenge you to develop a reliable adaptive silence caller to terminate the recording phase with a touchtone. detector. Phone.record() allows developers to limit recordings to a maximum time and terminate them when the device detects Control Your World a defined period of silence or with a touchtone. The API docu- A personal phone/voice portal can provide access to home

Home J2EEments the specific methods. J2ME and office appliances. Remote control can be easy with an Not all modems will support silence detection. As men- inexpensive X10 serial line power control module. If you have tioned previously, some Rockwell/Conexant chips won’t a DSL modem in your home or office, you’ve probably experi- report silence intervals or detect touchtones when the sam- enced the kind of failure that requires you to cycle the power pling rate is 11,025 Hz. on the modem to reestablish your Internet connection. This

Voice“ recognition technologies have advanced rapidly in the last

decade, although speaker-independent voice recognition with large vocabularies remains the industry’s holy grail“

One of the design goals of the phonelets framework was to kind of failure can be very inconvenient when you’re away insulate the developer from the complexities of audio stream from your office and your Web server is stranded behind a handling. The wide variety of hardware has made it almost stalled DSL connection. impossible to hide all the details. Developers need to under- With an inexpensive X10 serial port transmitter and a wire- stand the basic capabilities of their hardware and, above all, less power line control module, you can command a restart be very paranoid. remotely with a telephone touchtone. You can purchase X10 The Phone.play() method accepts the touchtone string appliance control modules at most electronics stores, but “one” as an interrupt argument. If the caller presses the “1” make sure you don’t connect a sensitive electronic device like key while the instructions are playing, the phonelet interrupts a DSL modem, a VCR, or a PC to a lamp dimmer module. Use the message and starts recording it. the appropriate appliance module. The Phone.record() method accepts a maxTime argument The Phonelet framework includes the X10Transmitter and a maxSilence argument that stops the recording after a class to simplify the transmission of the control commands specified number of seconds or after a specified interval of through an available serial port. A detailed explanation of silence has been detected (the caller may have hung up). X10 is beyond the scope of this article, but Listing 2 shows Finally, the phonelet plays a goodbye message to indicate how simple it is to turn appliances on and off with touch- that it is about to terminate the call. Of course, a really useful tones.

82 JUNE 2001

Java COM Brokat www.brokat.com/wp/jdj

JUNE 2001 83

Java COM conclusion of audio output. Talker is able to wrap the synthe- How to Handle Speech sizer and treat it as a shared resource. Voice recognition technologies have advanced rapidly in the last decade, although speaker-independent voice recogni- VoiceXML tion with large vocabularies remains the industry’s holy grail. VXML is emerging as the standard for scripting All of the commercial voice portals employ speech recogni- phone/voice service applications. Based on XML and sup- tion. The limited vocabulary of the navigation commands ported by a consortium of telephony vendors including IBM, simplifies the speech recognition problem and results in a Nuance, and Lucent Technologies, VXML looks promising as a much more accurate, although not yet perfect, dialogue cross-platform scripting system. between caller and service. At least one service employs new If your voice service can be implemented as a relatively hardware that accelerates the voice recognition algorithms straightforward dialogue between caller and server, and if it with chips that cost as little as $2. Nevertheless, speech-driven requires relatively simple error handling and little or no access navigation can be cumbersome and vulnerable to background to native platform capabilities or local resources, then VXML and line noise. may be the most cost-effective development approach. If your Voice recognition is beyond the scope of this article, but service requires sophisticated or special speech processing the phonelets framework can be extended to support a third- capabilities, you might consider a hybrid approach using J2SE party voice engine. VXML and a third-party voice component framework like Text-to-speech systems have also improved dramatically Nuance’s SpeechObjects and Voice Channel technologies. in recent years. The robotic monotone of earlier engines is giv- VXML is a young standard, and portable implementations ing way to a much more natural elocution. Lernout and may be expensive and complicated. You can get started with Hauspie, in particular, have produced a text-to-speech system VXML by visiting TellMe Networks. Nuance also provides a lot that closely approximates the natural rhythms of the human of helpful information for developers. voice. Nuance also provides a sophisticated and Java-compat- ible framework for text to speech. Speech synthesis is likely to Relevant Packages and Standards for Java Developers be a much more useful addition to a lightweight voice portal The Java Telephony API and the Java Speech API promise than speech recognition as it’ll allow callers to access infor- to simplify the development of telephone/voice systems and mation from home, office, and Web databases that would oth- applications…eventually. erwise be available only via PC, wireless PDA, or Web-enabled cell phone. JTAPI The Java Speech API attempts to standardize the interface JTAPI must be implemented by telephony device vendors between applications and third-party speech products, but and will offer systems developers a comprehensive software

Home J2EEsevere limitations in the current API will J2ME force service devel- platform for telephone devices, call centers, and PBX/CBX opers to use vendor-specific interfaces. Specifically, JSAPI pro- systems. Many of its functions go beyond what is necessary for vides no mechanism for the developer to redirect the output voice/phone application developers. of the synthesizer from the speakers to a file or to an output stream. JSAPI is a prime example of emerging standards that JSAPI are still incomplete and often poorly implemented by third- Application developers can look forward to a unified inter- party vendors. face to commercial speech synthesis and recognition engines, The Talker class included in the “Resources” section but significant oversights in the API render it practically use- demonstrates a quick-and-dirty workaround for JSAPI limita- less for service developers. Notably, JSAPI assumes that all tions. Specifically, it demonstrates how to wrap the speech speech synthesis will be delivered through the default audio synthesis function of a JSAPI-compliant engine for easier output device of the user’s PC and that all audio input will be access. The talker was developed and tested for IBM ViaVoice delivered through the user’s microphone. Audio systems con- Millennium Edition and will require IBM’s ViaVoice SDK Java trols for redirecting output to a stream or file are lacking as are Technology Edition, available to developers on the Web at controls for specifying an audio input stream. Service devel- www-4.ibm.com/software/speech/dev/sdk_java.html. opers must look to third-party Java interfaces for comprehen- sive packages. Warning: The Talker workaround is provided for informa- tional purposes only. Consider it experimental and only a VoiceXML temporary patch for the current limitations of the JSAPI. Developers will find a lot of useful VXML information on Talker attempts to bypass the limitations of the JSAPI by the Web from IBM, Nuance, and TellMe Networks. Visit the implementing an audio loopback function that will capture www.vxml.org Web site for a complete specification. synthetic speech through the audio input port as the synthe- sizer is playing the audio (we warned you that this was for Building Automation Java API (JSR-000060) experimenters only). You’’ll need a full duplex audio card Environmental control of office buildings is emerging as a capable of playing and recording audio simultaneously. You’ll ripe opportunity for cross-platform software. Commercial real also need an audio patch cable appropriate for your sound estate management companies will automate their control card. Some sound cards will require an attenuating cable and management functions with standards that work across a between the audio output port and the microphone or audio broad field of properties. input port. The safest way to loop the audio output back into the audio input may be to route the audio through an ampli- Open Services Gateway Specification fier or mixer with an appropriate audio line out or micro- The home of the future has been a favorite subject of phone out port. You’ll also have to adjust volume levels man- World’s Fair prognosticators for decades. The OSG consortium ually. (www.osgi.org) may actually get it right. When broadband This workaround is viable only because of the ViaVoice opens the big double-wide doorway into homes and offices, speech synthesizer’s ability to queue text-to-speech requests, the possibility for services will emerge and the demand for operate asynchronously, and accurately report the start and applications will follow. Java developers will be influential in

84 JUNE 2001

Java COM specifying how these services are developed and delivered. If • CommonVoiceModemCommands.txt you want to turn on the lights and set the thermostat from your cell phone, watch this specification for the nuts and Recommended Reading bolts. • Lindley, C.A. Digital Audio with Java. Prentice Hall. • McClellan, J.H., et al. DSP First: A Multimedia Approach. Resources Prentice Hall. • AnnouncePhonelet.java: Demonstrates how to process • Pierce, J.R., and Noll, A.M. Signals. Scientific American caller ID packets. Announces an incoming call and the Library. identity of the caller if the phone number (as delivered by • Rorabaugh, C.B. DSP Primer. McGraw-Hill. caller ID) is contained in a contacts database. • MessagePhonelet.java: Source code demonstrating how to Web Links record and play voice messages, how to generate synthetic • A brief history of TouchTone: www.att.com/technology/his- speech from text, and how to use touchtones to control pro- tory/chronolog/64touch.htm gram flow. • VoiceXML forum: www.vxml.org/ • Talker.java: Source code for a wrapper to simplify use of a • IBM speech technologies: www- JSAPI speech synthesis engine. Has been tested with IBM’s 4.ibm.com/software/speech/ Via Voice and Speech for Java SDK. • Caller ID FAQ: www.ainslie.org.uk/callerid.htm • CallerID.java: Source code for a caller ID object that parses • JTAPI: www.javasoft.com/products/jtapi/ unformatted caller ID packets. • JSAPI: www.javasoft.com/products/java-media/speech/, • PhoneServerLite: A multithreaded phonelet host with load- able device handlers and phonelets. Includes javadoc doc- umentation for phonelet framework. • SpeedSerialWin32.dll: Win 95/98/NT native library for AUTHOR BIOS high-speed serial access. JavaSoft’s javax.comm package Kent V. Klinner III, chief technology officer at TransPhonic, Inc., develops platforms and provides adequate support for serial data transfers at low components for portable and wireless devices. An electrical engineer who still likes to get speeds, but fails at the relatively high speeds necessary to close to the hardware, he’s been developing Java since 1995. record and play digitized voice with an external voice- enabled modem. The javax.comm package is unnecessarily Dale B.Walker is principal engineer at TransPhonic, where she develops applications for complicated by an attempt to wrap the parallel and serial mobile and wireless devices. Dale is an electrical engineer with 20 years of broad ports into a single package. SpeedSerialWin32 simplifies the experience. programmer’s view of the serial port and provides reliable [email protected] / [email protected] high-speed serial transfers.

sun www.sun.com/service/suned/java

JUNE 2001 85

Java COM J2SE

One of the not-so-old and not- cutables are defined as properties. In completely-forgotten programmer the last part of the make file, each line utilities of the past is the make utili- defines a transform for how to convert ty. I’m not suggesting that make isn’t one file into another file. Thus, to con- still used (especially in the UNIX vert a .cpp file to an .obj file, you use the world), but the percentage of pro- compiler command (with the flags) list- grammers who know what a make util- ed in the make file. You’ll also notice that

Home J2EEity is and what it does is pretty J2ME small. the dependencies are implied. In other Yet the need for its functionality has words, you can’t make the .EXE file until never been greater, particularly for the .OBJ files have been created. large-scale Java projects. I hope this arti- Even though this is a simple concept, cle will return it to the forefront where it make files can perform a great service. They belongs. exist to handle repetitive, multistep process- First, for the unenlightened, a little back- es that change in content (source files) but ground on what a make utility does. Then not in tasks (how to compile, deploy, etc.). I’ll discuss the best thing to happen to Java Make utilities exist for all different platforms. since cream and sugar – Ant. In fact, most versions of UNIX have a make utility built into the operating system. Make Utilities Traditional make utilities are a little ornery, Back in the dark ages of software develop- however. The make file syntax must be in an ment (about 10 years ago), most code was writ- exact format, and the format is specific to the ten in a good editor (back when the editor was version of the make utility. Different implementa- the IDE). To make sure it was all compiled and tions of make utilities require slightly different linked correctly, a make utility was used. A make syntax. As you can see, the syntax of the make file utility is a command line utility that uses a text file is somewhat daunting – it’s like learning an entire- that contains a bunch of rules to transform one ly new development language. The make file also thing into another thing. For example, the make file defines special wildcards (like the “@&&!” wildcard would define the relationship between a “.c” source in Listing 1). file and the “.OBJ” file generated by the compiler. The bigger concern is that make utilities aren’t The make file would then follow the rules (i.e., how to well optimized for Java. For example, Java has very invoke the compiler) to make the transformation special requirements for package and directory struc- happen. You could also define dependencies to con- tures. Make utilities don’t natively understand this rela- trol the order in which artifacts were created. For tionship. This isn’t to say they haven’t been used quite example, you must compile the source files before you successfully for Java development. However, what was deploy them. Make files don’t flow from the top of the really needed was a new make utility that understands file to the bottom. You tell the make file what the ultimate Java. That’s where Ant enters the picture. target is and it executes the necessary steps (in the correct order) to fulfill the target. Ant An example is in order. Listing 1 shows a simple make file Ant, a make utility written in Java for Java, is part of the for a C++ project (all code listings can be found at impressive Jakarta project at Apache. In fact, it’s one of the JavaDevelopersJournal.com). The top of the make file Jakarta subprojects. The Apache developers needed to be defines what files make up the project. Next, compiler flags able to automate the build process and they couldn’t do it are listed as properties of the make file, and the compiler exe- gracefully with traditional make files, so they wrote their own.

86 JUNE 2001

Java COM JRockit www.jrockit.com

JUNE 2001 87

Java COM It turned out to be so useful that they released it as its own source files into it. The build utility can then work on the subproject. And because it’s from Apache, it’s open source – source code in the new make directory while you make the source code is freely available. You can find Ant in both changes to the mainline code. binary and source form at http://jakarta.apache.org/ant. To Notice how Ant handles directory structures. Because Ant install ant, you unzip it into some directory structure and take was written for Java, it understands how Java packages and the following three steps: directories are related to one another. Ant defines a special 1. Set the ANT_HOME environment variable to point to the file-based wildcard: “**”. This is like the normal wildcard “*”, installation directory. which matches anything in the current directory. However, 2. Add the ant/bin directory to your system path (Ant is start- the “**” wildcard matches everything in this directory and all ed with a bat file in the /ant/bin directory, so you’ll proba- its subdirectories. So if you tell Ant to copy /src/**/*.java, it bly want to put that directory on your path for easy access). will copy all the Java source files in all the subdirectories of the 3. Set the JAVA_HOME environment variable to point to your /src directory. In addition, when Ant copies source files, it JDK installation directory. leaves the directory structure in tact. The next target in the build file is the Java compiler invoca- Ant differs in several ways from traditional make utilities. tion. It will compile all the source files and place them in the First, the make file itself isn’t in a proprietary file format but is destination directory defined by a property above. This task J2SE an XML document called build.xml by default. Within this also shows how you can specify classpath information for tasks document you specify a series of targets. Each target encapsu- that need a classpath. You can define the classpath attribute in lates some task or set of tasks that you need to perform. Ant two ways. You can use a semicolon-delimited list, much like also defines a set of built-in tasks to handle everything from the classpath environment variable is defined. But that creates copying files and directories to e-mailing someone. For a short an attribute that’s hard to read. The alternative, shown here, is partial list of the built-in tasks see Table 1. A full list of the tasks to use a nested property. In this case the classpath is defined as is included with the docs that come with Ant (as of the current a special attribute, which has its own attributes, making it version, there are 47 predefined tasks). Moreover, because it’s much easier to see what’s on the classpath and make changes. written in Java, you can create your own Ant tasks by sub- A Javadoc task is defined next. You probably don’t want the classing built-in tasks. Javadoc process to run every time you build your project. You’d probably rather run Javadoc only at certain stages in the project. To invoke ANT TASK DESCRIPTION Ant for a particular target, you can pass copy Copies a file, a series of files, or an entire directory structure the name of the target on the command cvs Checks files into or out of the CVS version control package. You can specify the line. Ant will then try to fulfill that target. labels and other CVS specific information for the checkout Home J2EE J2ME However, each target may have a exec Executes an external command (i.e., shells out to the operating system to call any “depend” attribute. Ant will ensure that command) every dependent target is run success- javac Invokes the javac compiler. This task allows you to set the classpath, targets, fully before executing the next target. output location, and a host of other properties Notice that the “compile” target lists java Launch another Java application from within the Ant process “prepare-src” as the target it’s dependent javadoc Invokes the javadoc compiler on. So, like traditional make files, the mail Sends an e-mail to a specific address (to notify of build completed successfully, flow of execution doesn’t necessarily go the results of automated unit testing, etc.) from the top of the document to the bot- replace Replaces the contents of one string with another string in a text file tom. The dependencies between the tar- jar Generates a JAR file gets determine the order of execution. unjar Unpacks a JAR file You can also define a default target at the war Generates a Web Archive format file top of the file – this is the target that will sql Executes an arbitrary set of SQL commands against a database be fulfilled if no specific target is passed on the command line. Thus the Javadoc TABLE 1 Summary of a few predefined Ant tasks target will be executed only when you specify that you want Javadoc. Generally, you define a build.xml file as a series of targets, The last target is the “clean” target. It goes through and each consisting of one or more tasks. Listing 2 shows a simple cleans up all the working directories created by Ant. build file for Ant. Notice that the top of the file starts with an When you run Ant, you can pass it an XML document and “init” task. This is typical in that it allows you to define prop- a target. If you’ve named your build file “build.xml” and it’s in erties that can be used throughout the build document. You the directory where you start Ant, you don’t have to specify the can think of these as global variables that can be used any- build file name. Moreover, if you’re building the default target, where within the build document. This is typically where you don’t have to specify a target either. Most of the time, directories, compiler settings, and flags are set up. By defining therefore, you’ll just invoke Ant on the command line. Ant will them at the top of the file, you can make changes to the values show each target that it executes in turn, printing status mes- that flow throughout the entire document. The next target, sages for individual tasks. Figure 1 is an example of a typical named usage, allows the developer to invoke the Ant make file successful build. However, if any task can’t complete success- and find out what targets are available. This is help for this fully, the entire build process is aborted. Figure 2 shows an particular make file. The third target is called prepare; the example of a build that failed. fourth, prepare-src. Because Ant is written in Java, it can be extended using Automated builds can sometimes take a long time for Java. If you have a particular tool that you need to sup- large projects. It would be convenient if you could contin- port in Ant, you can build an Ant task to handle it. Some ue working on the project while the build is proceeding. of these custom tasks have already been written and are Thus one of the early tasks typical in a build file is a task available from the Ant Web site. For example, many to create a build working directory and copy all the developers use Visual SourceSafe as their version

88 JUNE 2001

Java COM Component Source www.componentsource.com/java

JUNE 2001 89

Java COM J2SE

FIGURE 1 Ant shows the status of each task and whether or not the build succeeded. Home J2EE J2ME

FIGURE 2 When a build fails, Ant stops on the task that fails.

control package. Ant has support for CVS built in, but there’s label="Release1" no support for VSS. However, if you download the optional.jar login="me,mypassword" file from the Ant site, you’ll discover that someone has already vsspath="/source/aProject" written the integration for VSS for Ant. The optional JAR file writable="true"/> contains several tasks that were written and contributed to the Ant project that aren’t mainstream enough to become built-in Details on both the optional tasks and how to build your tasks but are still useful. To use one of the optional tasks (or own tasks are included in the Ant documentation. one of your custom tasks), you have to make Ant aware of what class to use to define the task. This can be done with a Enterprise Deployment taskdef task, generally placed in the init section of the build As you can see, Ant makes it very easy to consolidate all file. A sample task registration is shown below: project construction information in a single location. You can define classpaths and other build artifacts once and reuse one shown above, however, most modern IDEs handle some of these chores (although none that I have seen handle it as You can use the MyVeryOwnTask as if it were a built-in well as Ant). Ant really begins to shine when you look at more task. If you want to register a new task with Ant more perma- complex applications that have more complex dependencies nently, you can add the task to the default.properties file in the or complicated distribution requirements. org.apache.tools.ant.taskdefs package. To use the optional A major headache in building Web applications in Java VSS task, add a taskdef line to your build file and use the fol- concerns the deployment of the required files to all their lowing syntax to invoke it: appropriate locations. For example, in most Web proj- ects you have a mixture of HTML, JSPs, JavaBeans, and

90 JUNE 2001

Java COM Cloudscape www.cloudscape.com/FreeDev

JUNE 2001 91

Java COM “ Ant’s ability to guarantee consistent builds and

correct deployment, and its automatic unit testing make for a powerful tool indeed “

definitions of where these files belong. Although this has got- unjarred in the appropriate place so the client has access to ten better since Sun introduced the concept of a WAR file and stub code. This is obviously a job for Ant! In fact, there is a rel- the ensuing directory structure, the deployment headache still atively new set of Ant tasks defined especially for EJB tasks. J2SE exists. If you forget to copy even one of these files when you Currently, the tasks defined for EJBs support only WebLogic deploy your project, the magic just doesn’t work. This sort of 4.5.1 and 5.1, although I’m sure other tasks will appear as tedious task is exactly why tools were built. Obviously, you can needed. If you don’t use WebLogic, here’s your chance to add build an Ant build file that can handle not only the compila- to the open source movement! Of course, as long as your tion chores for each Web project, but these annoying deploy- application server supports command line tools, you can use ment chores as well. the exec task in Ant to invoke the tools for your application One of the nice characteristics of Ant is that it does the min- server. In fact, before there were specific tasks for EJBs, I wrote imum amount of work necessary. So, if a file already exists in the an Ant task to execute WebLogic’s ejbc compiler to generate all target location and it has the same timestamp, Ant won’t both- the necessary code for deployment. Just like WebLogic, most er copying it. This is contrary to the solution that many devel- vendors give you Java versions of their deployment tools, all of opers currently use, the lowly batch or script file. The disadvan- which are easy to launch from within Ant. One advantage this tage of batch and script files is that they generally do the most has over batch files is that Ant can spawn the VM in a new amount of work necessary rather than the least. Some scripting thread rather than in a new process. Thus the start-up over- languages allow you to build in more intelligence, but you must head is much less when Ant launches a Java application versus remember to add it. Ant does the smart thing automatically. when a batch file launches the same application. In an organ-

Home J2EEIf you look at the build and deployment J2ME process for multi- ization that used batch files to check out, build, and deploy a ple Web projects, it looks as though they do basically the same large number of EJBs, I wrote an Ant build file that reduced the things, just for different sources and destinations. Rather than amount of time required from 47 minutes to 15 minutes! The build a separate Ant build file for every Web project, it seems entire time savings were realized by doing the minimum as though you could build one Ant build file and change just a amount of work rather than the maximum and by spawning few characteristics to make it work for almost all Web projects. threads instead of processes. This generic build file for Web projects (see Listing 3) makes a The last supported task type in Ant that I’ll mention is inte- couple of assumptions about the way you have your project gration with the open-source testing framework JUnit. In a defined. First, it assumes that there is a source directory nutshell, JUnit defines a framework to automate unit testing (named /src, but this detail is easy to change) that consists of for your Java classes. It includes both a command line and a a directory/package structure containing your Java source graphical test environment. The JUnit task is defined in the files. It also assumes that the JSPs and HTML are defined in optional JAR file and can invoke JUnit tests as part of the build the /src directory without being inside the package hierarchy. process. The typical scenario involves building classes and Last, it assumes that the JavaBeans used as library classes by defining tests, and making sure they’re run each time the proj- your servlets are not in the same directory or directories as ect is built. If subtle bugs appear during subsequent develop- your servlets. You may want to alter the build.xml file to ment, the unit test fails and can optionally fail the entire build change some of these assumptions. process. Alternatively, you can define a task to e-mail the build A nice Ant feature demonstrated in Listing 3 is the ability to manager whenever a class fails its regression test. define Ant properties outside the Ant build file and import Ant’s ability to guarantee consistent builds and correct them. Listing 4 shows the properties for a specific Web project. deployment, and its automatic unit testing make for a power- Ant uses standard java.util.Properties files and a special prop- ful tool indeed. It automates part of the development process erty attribute to import properties. To import the properties file that should be automatic. Developers are too busy with more in Listing 4, the following task line is defined in the init target: important jobs than making sure that files are copied correct- ly. Ant is powerful, extensible, convenient. And the source is included and the price is right!

This imports the properties in the named file, which become indistinguishable from properties defined directly in AUTHOR BIO the Ant build file. This mechanism makes it easy to define Neal Ford is vice president of technology, DSW Group, Atlanta, Georgia, He is also the generic build files that can be customized without even edit- designer and developer of applications, instructional materials, magazine articles, and video ing the build.xml file. presentations, and author of the books Developing with Delphi: Object-Oriented Techniques The other monstrous build and deployment task typical- and JBuilder 3 Unleashed. Neal has been the featured speaker for the Borland ly found in enterprise Java development involves Delphi/C++Builder/JBuilder World Tours, and has spoken extensively at annual Enterprise JavaBeans. They must be developed, jarred, Borland Developers Conferences worldwide. handed to a deployer tool for the application server, [email protected] copied to a deployment location, and optionally

92 JUNE 2001

Java COM Host Centric www.hostcentric.com/jdj

JUNE 2001 93

Java COM HP WebGain www.webgain.com/javaone_hp.html

94 JUNE 2001

Java COM HP WebGain www.webgain.com/javaone_hp.html

JUNE 2001 95

Java COM JAVA NATIVE INTERFACE JNI Programming in C/C+

J2SE Additional challenges of using the IBM e(logo)Server iSeries

If you’re familiar with the Java Native Interface (JNI), as this arti- cle presumes, you know that it’s tailored primarily for C and C++ programmers. Compile-time support for JNI in these languages WRITTEN BY comes straight from the Sun specification, and is frankly a work of BLAIRWYMAN art.

The architects of the JNI had a terri- The heritage of today’s iSeries Sharing a single address space

Home J2EEfying three-part task: to tame the hydra J2ME machine dates back quite far, by mod- across the entire machine? How can of platform-specific issues inherent in ern standards. You probably recognize there be any hope of security between so-called “native” code, provide a way to the most recent progenitor of the iSeries processes and users? The answer is in use native code in Java, and to do so in platform, the IBM AS/400 System the notion of the pointer being as “portable” a fashion as possible. The announced in 1988, but it’s actually the “tagged.” If a pointer operation is per- ubiquity and standardization of C and IBM System/38 that deserves the credit formed by the machine, then the C++ made them the natural choices for for being the seminal implementation of pointer is tagged (i.e., made valid). If preferred native languages, and their this truly unique computer architecture. any sort of operation, other than a affinity to Java is apparent to anyone The unique features of the iSeries pointer operation, changes the storage, who has programmed to the JNI. architecture are too numerous to the tag is cleared and the pointer is If you’re familiar with IBM’s recount here, but a couple of salient invalidated. e(logo)Server iSeries machine, you know points will motivate the discussion that As you can imagine, pointers of this it supports a wide range of program- follows. size are...um...“unusual,” even in today’s ming languages, including: The original architects of the iSeries diverse mix of systems. It’s the very size • C (in several incarnations) chose not to differentiate between of our 16-byte pointer that’s probably • C++ (quite recently) “working storage” and “disk storage”; it’s the most cantankerous issue when port- • RPG (Report Program Generator) logically just one big pool of something ing Java native method code to the • COBOL colloquially known as Single Level Store iSeries machine, as we’ll see. • CL (Command Language, the iSeries’ (SLS). One advantage of this scheme in a So, how could this unusual memory workhorse) database-centric system is clear: architecture even hope to support • qsh (POSIX-based scripting language) process-specific data movement is all something as modern as Java? • MI (Machine Interface assembler lan- but eliminated. Data can be shared Especially, how could it support Java guage) among processes, without the overhead well enough to allow the iSeries (then • Perl of ensuring that process-specific virtual AS/400) JVM to capture the top spot in address images of the data are seen in a four separate industry-standard Java In contrast to most UNIX-based consistent form. benchmarks last summer? One part of machines, however, the C language has Obviously, to accomodate for future the answer is simple, yet profound: Java never been at the foundation of the iSeries growth, this SLS scheme requires a very doesn’t know about “pointers” and machine’s operating system; in fact, C is a large address space since everything on “addresses.” Hallelujah. With the intro- relative newcomer to the platform at the the machine is in one big “addressable duction and increasing popularity of applications level. The internal develop- universe.” To satisfy this requirement, Java, the iSeries is on level ground from ment language has varied over the years, the designers of the System/38 specified a programming standpoint. but if any language deserves the founda- a 16-byte (that’s byte, not bit) pointer. However, as soon as we start talking tion role on iSeries, from an applications- Well, that was over 20 years ago, and the about JNI and native code, we’re talking development standpoint, it’s Report 16-byte pointer has so far stood the test mainly about C and C++; pointers and Program Generator (RPG). of time. addresses are back in the spotlight. And,

96 JUNE 2001

Java COM Corda www.corda.com

JUNE 2001 97

Java COM JAVA NATIVE INTERFACE

#pragma convert(819) “ /* starting now, all literal JNI programming on the IBM strings are ASCII (819) */ /* NOTE: ASCII is NOT exactly the iSeries system poses some extra same as UTF-8! */ void main(int argc, char **argv) { int i, rc; challenges to the programmer, for (i=0;ijString object into a } but Java and the JNI prefer UCS-2 or jBooleanArray variable /* Formats MUST be */ J2SE UTF-8 character encodings. Most without an error message. When the ref- machines run the JVM at a sort of erences are integers, this type-confor- /* in EBCDIC ONLY */ “application-level,” while the iSeries mance checking is lost. A minor impact #pragma convert(0) effectively embeds the JVM into the is that the null reference becomes the char *backInEbcdic = "I am EBCDIC, operating system. integer zero, instead of a null pointer hear me roar"; There are five basic issues to consid- value. er when porting native method code to Since JNI requires UTF-8 input, it the iSeries machine: 2. Codepage considerations would naturally be wonderful if we could 1. JNI reference types (e.g., jobject, The iSeries is an EBCDIC machine, just specify some value nnn in our #prag- jclass, jstring, etc.) are implemented and Java’s Unicode heritage is ASCII- ma convert statements that would magi- as 32-bit signed integers, instead of based, so there’s a sort of conflict cally transmogrify the literals into a UTF- pointers. between Java’s native side and the 8 encoding. Unfortunately, although the 2. In C and C++ source code, literal iSeries. This conflict is mostly avoided iSeries supports UTF-8 for dynamic string strings and character values are when you stick to Java, but once you conversions (as we’ll see in a moment), it encoded in EBCDIC, by default. start writing native method code, Java’s does not yet support the use of UTF-8 in

Home J2EE3. The JNI jlong data type is implement- J2ME wonderful platform-neutrality is neces- the #pragma convert statement. ed on the iSeries using a C struct of sarily reduced. Instead, a value of nnn that most two integers, instead of a true 8-byte The JNI expects all character data to closely fits the bill is codepage 819, integer. be provided either in Unicode (the which is ISO 8859-1 Latin. The low-order 4. The simple pointer type in C and C++ jchar type), or in the 128 characters of this codepage are is 128 bits, as discussed earlier. modified UTF-8 representation of identically UTF-8. 5. Direct addressability into the garbage- Unicode (where the NUL character is We have to be careful, though, to collected heap is never permitted. represented using the two-byte encod- make sure that all literal strings contain ing of 0xc080). only invariant ASCII – any use of an 8-bit Let’s examine each of these in turn: UTF-8 has the interesting property of character whose most-significant bit is being, itself, composed partly of the 128 set requires that the character be repre- 1. Object references are integers characters of the ISO 8859-1 Latin char- sented in its two-byte UTF-8 form. This is a nice place to begin, since it’s acter codepage. That is, all ASCII charac- Fortunately, most uses of ASCII for JNI only a minor factor in the porting effort, ter arrays are already UTF-8 – a quality parameters such as class and method but brings up some fundamental iSeries that simplifies coding native methods names are already likely to be UTF-8. issues right away. on ASCII platforms. Literals containing character values The iSeries pointer in C and C++ is a This issue is really twofold, depend- greater than decimal 128 can be repre- different sort of animal, as we saw earli- ing on whether the character data is lit- sented using escapes in the source er, and this functionality comes with a eral or dynamic. string, as this example shows: price: manipulating pointers is inher- ently expensive on the iSeries. Literal Strings /* \u00EB is 'ë' -- the ISO When the JNI specification came Using the ILE C and C++ compilers 8859-1 Latin 1 code for (e-diare- out, all the object references were imple- for the iSeries system, the default sis) mented by Sun as pointer types. encoding for literal character data is * The UTF-8 value for this However, Sun’s object reference pointers EBCDIC. However, this compiler default character is the two-byte sequence are “opaque” – there was no “layout” can be overridden using a #pragma 0xC3AB defined at the end. Since these pointers statement in the source code. */ are truly just handles, we asked Sun for p = "Zo\xc3\xab"; /* UTF-8 for permission to implement our object ref- #include Zoë */ erences as integers instead of pointers. #include The main impact of this change /* literal strings here are still occurs only when compiling C++ native EBCDIC */ Dynamic Strings method code. The JNI specification for char *fmt = "%d:%s\n"; /* EBCDIC In contrast to literal strings, the value C++ uses a class hierarchy to allow some */ of dynamic strings is not known until type-conformance checking to occur at char *message = "Return code non- runtime. These strings may become compile time. For instance, in C++ you zero!\n"; /* EBCDIC */ parameters to the JNI, and therefore

98 JUNE 2001

Java COM Compoze www.compoze.com

JUNE 2001 99

Java COM JAVA NATIVE INTERFACE

might have to be converted to “modified support to use the 8-byte integer form, >GetFieldID(env,clazz,"intField","I UTF-8.” The standard API for the pur- we would be sacrificing forward-com- "); pose of codepage conversion on the patibility in existing native method (*env)- iSeries is iconv(). libraries. The iSeries team is loathe to >SetStaticIntField(obj,clazz,fid,(i The iconv() API accepts two code- introduce incompatibilities that break nt)somePointer); page numbers – one for the “from” code- existing code. Therefore, despite the fact page, and one for the “to” – and supports that the ILE C and C++ compilers have As we discovered earlier, the iSeries both UCS-2 and UTF-8 codepages. supported 8-byte integers for a couple of pointer is 16 bytes in length, so it simply However, be forewarned. In the (admit- releases, the JNI is stuck with the struct doesn’t fit. And even if it did, the modifi- tedly unusual) case where your C string form of jlong. cation of the pointer as an integer would might contain an embedded NUL char- The impact of this fact on the porting clear the tag, rendering the pointer acter, the UTF-8 conversion of iconv() effort can be widespread but generally invalid. So we see there’s a problem. preserves it. Remember, JNI takes “mod- straightforward. For example, consider There are two types of solutions – ified UTF-8,” where the NUL is a two- this C native method code: one that’s robust and expensive, and byte character. one that’s lighter in weight yet more J2SE JNIEXPORT jlong JNICALL complicated to get right. 3. The jlong data type Java_TestJava_getlong The robust, heavyweight solution The jlong data type is (JNIEnv *env, jobject obj) relies on two key facts: the JNI equivalent of the Java { 1. The iSeries defines a special class, long, an 8-byte integer long y; com.ibm.as400.system.MiPtr, which value. At least it’s supposed to be. somefunc(&y); /* pass y by ref- can be used to hold 16-byte pointers, When the JNI was first being imple- erence to some routine */ 2. Object references on the iSeries are mented on the AS/400 system, the C lan- return y; /* Uh-oh! y is integers. guage did not have an 8-byte integer value not compatible with jlong */ (although COBOL did, ironically). So, the } The scheme is simple. Each time the only alternative for our implementation native code stores a pointer into a Java int was to define the jlong as The “fixed” version of this code looks or long field, change the code to create a a structure, with two 4-byte integers. like: com.ibm.as400.system.MiPtr object, Now, when the 8-byte integer came to store the pointer into the object, take a the C compiler on the AS/400, we had JNIEXPORT jlong JNICALL global reference to the object, and store

Home J2EEalready shipped a release of JNI using the J2ME Java_TestJava_getlong that reference into the int or long field. structure form of jlong, (JNIEnv *env, jobject obj) In order to use this scheme, you have and we realized that if we changed our { to bind your native method library code jlong x; /* here with the QJVAJNI service program, is our compatible return which exports two functions called value */ “GetPointer” and “SetPointer”. Here are long y; the before and after pictures: somefunc(&y); /* pass y by reference to some rou- • Before: tine */ void *ptr; /* pointer we JavaI2L(y,x); /* con- want to store in the int field venience macro from */ jni_md.h */ jclass otherClz; /* class con- /* sign- taining static int field extends if necessary */ */ jfieldID otherFid; /* fieldID of return x; /* OK */ the static int field in otherClz */ } /* DO NOT try the following at home Microedge */ (*env)- 4. “Pointer hiding” in Java >SetStaticIntField(env,otherClz,oth objects erFid,(int)ptr); /* UGH */ One of the most difficult issues with porting native www.slickedit.com/jdj601 methods to the iSeries is the • After: issue of “pointer hiding.” An void *ptr; /* pointer we all-too-common idiom in want to store in the int field native methods is to take the */ address of some native storage jclass otherClz; /* class con- and to store that address in a taining static int field int or */ long field of a Java jfieldID otherFid; /* fieldID of object using JNI. the static int field in otherClz */ jclass pClz; /* class ref to someObj *somePointer; com.ibm.as400.system.MiPtr */ fid = (*env)- jobject pObj; /* object ref

100 JUNE 2001

Java COM Flashline www.flashline.com

JUNE 2001 101

Java COM JAVA NATIVE INTERFACE

to instance of MiPtr we create */ since the allocation of a “slot” in this ever, the JNI programmer is never provid- jmethodID pCtor; /* method ID of table of pointers must be performed ed with such direct addressability – these the MiPtr constructor */ atomically. Also, how do we know when JNI interfaces always return the address jobject gRef; /* global ref- the pointer should be cleared from the of a copy of the data. Even the so-called erence to new instance (why?) table? A deep understanding of the “critical” interfaces added to the JNI in */ application will be required to get this Java 2 – GetPrimitiveArrayCritical and right. GetStringCritical – return the address of a /* create instance of copy of the data. com.ibm.as400.system.MiPtr */ 5. Direct addressability to objects in This decision not to expose the pClz =(*env)- the garbage-collected heap garbage-collected heap to any user- >FindClass(env,"com/ibm/as400/sys- One aspect of the iSeries JVM imple- level addressing in the iSeries JVM was tem/MiPtr"); mentation is its integration with the not made lightly, but it is incontrovert- pCtor=(*env)- underlying platform. This integration is ible. If a JNI programmer could get the >GetMethodID(env,pClz,"","()V tight enough to allow Java-to-Java calls address of an object in the heap, it "); to be made very quickly using a would be possible for that code to acci- J2SE pObj =(*env)- “machine addressing” scheme that dentally walk over storage and corrupt >NewObject(env,pClz,pCtor); avoids the overhead of 16-byte pointers. the state of the JVM. This restriction is SetPointer(pObj,&ptr); However, as soon as native method code one clue to the robust nature of the /* NOTE: pass ADDRESS of ptr */ comes into the picture, so do the 16-byte iSeries JVM. gRef =(*env)- pointers. >NewGlobalRef(env,pObj); Selected JNI interfaces are designed Summary (*env)- to provide addressability to the elements JNI programming on the IBM iSeries >SetStaticIntField(env,otherClz,oth of a Java array, or to the characters of a system poses some extra challenges to erFid,(int)gRef); /* OK */ Java String object. For instance, the the programmer, but none that are GetArrayElemen insurmountable. If the programmer is The lightweight solution is more ts or GetStringChars lucky enough to be dealing with a well- AUTHOR BIO complicated to get right. Basically, you interfaces return an address to designed body of native method code, Blair Wyman is a just allocate an array of pointers in C the caller: an address that may or may code that avoids some of the pitfalls software engineer static storage, store the pointer into the not be directly addressing the actual we’ve discussed, the port to the iSeries is working for IBM in array, and then store the integer array object. a relative breeze.

HomeRochester, Minnesota, J2EEindex into the Java int or long field. J2ME On most platforms, these addresses home of the However, now we have the issue of actually point directly into the Java object [email protected] IBM iSeries. possibly synchronizing many threads, in the heap. On the iSeries system, how-

QuickStream www.quickstream.com

102 JUNE 2001

Java COM Elixir www.elixirtech.com

JUNE 2001 103

Java COM Using BACKWARD J2SE simple application-levelCOMPATIBILITY

++ brought into vogue the concept of interfaces, abstract-

ness, and implementations. Java went a step further and factory Cformalized them with proper keywords for each of the concepts. There are a substantial number of BACKWARD patterns in which services interfaces, abstract classes, and classes can be combined forCOMPATIBILITY var- ious purposes. You only have to look at the book Design

Home J2EE J2ME Patterns, by et al (Addison-Wesley), to realize the

Written by importance of recognizing these constructs. Satya Komatineni

104 JUNE 2001

Java COM Constructing a software program that you ILogFacility lf = new FileLogFacility(); expect to have a long life is an attempt to lf.log("log this message for me"); evolve its functionality over time, without abandoning older behavior for backward com- As you can see, irrespective of the nature of patibility. This is a lot more essential when the construction, an object of type ILogFacility you’re designing libraries and frameworks. The is used the same way. newer libraries should work with older sys- This brings us to an important observation tems that were designed for the older releases in OO programming – construction is different of a library. Here are some concrete examples from usage. In other words, the construction of why this is important and how to accom- interface of an object is different from its usage plish this in situations where every program- contract/interface. We can delegate the con- mer is encouraged to adapt the scheme owing struction of the ILogFacility to any number of to its simplicity. mechanisms, but the usage remains the same. Using this property let’s investigate a method What Is Evolving Functionality? where the programmer doesn’t have to do the To understand what evolving functionality following: is, let’s walk through the design of a very simple class in Java. Here’s the class: ILogFacility lf = new FileLogFacility();

class LogFacility This line of code is hard-coding the con- { struction of an implementation. In doing so we public log(final String message) create a compile-timeBACKWARD dependency with the { implementation. And we can’t substitute // implementation StdoutLogFacility for FileLogFacility because } that dependency is necessitated by the compil- } ing. So, in a general sense, you can’t really vary Top the implementation of a COMPATIBILITY given interface at run- LogFacility provides a mechanism to log time if we use the "new" option for construc- messages. Everyone on the team would use this tion. Also you’ll have to know the name of the functionality as follows: implementation class, which may not even exist at compile time. What to do? The solution LogFacility lf = new LogFacility(); lies in understanding the factory pattern. lf.log("log this message for me"); Here’s an example: Coder

As it’s simple and useful, it’s hard to argue class ObjectFactory against it. Now I take this utility and ship it to { two different teams. One team wants to log to a public static Object create(final String file and the other to stdout. I improvised and objectName, Object args ) came up with StdoutLogFacility and throws CreationException; www.top- FileLogFacility, and suggested that the pro- } grammer use the appropriate logging facility as follows: You can attempt the following:

StdoutLogFacility lf = new ILogFacility lf = ObjectFactory.create StdoutLogFacility(); (ILogFacility.NAME, null); lf.log("log this message for me"); if.log("log my message"): coder.com FileLogFacility lf = new As a programmer you’ve delegated the con- FileLogFacility(); struction of an interface named ILogFacility.- lf.log("log this message for me"); NAME to a factory. This factory could look up a system-wide properties file for a class that’s You’d quickly realize that irrespective of responsible for this interface and load it at run- what log facility is constructed, it gets used the time. Let’s look at one such properties-file same way. This is a cue to design an interface entry: for the usage of the log facility as follows: Objects.loggingObject.className=com.your_ public interface ILogFacility { public company.StdoutLogFacility; log(final String message); } Assuming ILogFacility.NAME is StdoutLogFacility and FileLogFacility "Objects.loggingObject", it is not difficult for would implement this interface. In this sce- the factory to do the following: nario the programmer would do the follow- ing: public static Object create(final String objectName, Object args ) ILogFacility lf = new { StdoutLogFacility(); Properties systemWidePropertiesFile; lf.log("log this message for me"); String className = systemWide

Java COM When“ you’re specifying target implementation objects via a prop-

erties file, it’s possible that anything might go wrong in the con- struction process, resulting in an exception. “

PropertiesFile.getValue "MyInterface"; (objectName); .. other public method signatures Object o = Class.forName(className); } return o; J2SE } Using a synonymBACKWARD like “interface.NAME” instead of a liter- al string, we reduce the risk of getting the name wrong. If Using this mechanism you can improvise every interface has the same publicCOMPATIBILITY synonym, it’s just that StdoutLogFacility gradually without impacting its users. For much easier for the programmer to instantiate an implemen- example, you’ve improved logging but don’t want to replace tation for it. the older implementation until it’s been field tested. You can cut and paste the source code of StdoutLogFacility to another Interface Definition for an Application-Wide Factory Service class called StdoutLogFacility1 and replace your properties Now we’ll discuss the factory object in more detail and file as follows: define some desirable characteristics. The idea is we’ll use this factory object to create all our implementations for the Objects.loggingObject.className=com.your_company.Stdout desired interfaces. By that I mean to choose interfaces that are LogFacility1 going to be instantiated by factories. Once decided, these interfaces can be instantiated by the same global object facto- This way the older clients can continue to use the older ry. The aim of this section is to define a simple interface for implementation while you migrate to the new one. You can such an application-wide factory service.

Home J2EEcontinue to evolve this functionality J2ME while incrementing the numbers. The same facility can provide a radically different Static vs Nonstatic Method implementation if necessary. For example: The method “create” of the ObjectFactory is declared static and public. It’s public for obvious reasons and static so Objects.loggingObject.className=com.your_company.Socket the programmer can invoke it without an object reference. LogFacility For example:

logs all your messages to a socket. ObjectFactory.create(..) This discussion isn’t limited to logging; any of your core modules can follow the same pattern, which allows them a instead of path for evolution while maintaining backward compatibility. To summarize the points so far, we’ve learned the following: ObjectFactory of = new ObjectFactory(); 1. Construction is different from usage of.create(..) 2. Use interfaces, not implementations for, key areas of func- tionality There are some exceptions to this rule for example, if you 3. Use factories to construct implementations, at runtime want to evolve the functionality of the factory itself. The 4. You can use properties files to associate implementations method also throws a suitable exception indicating any fail- with their interface names ures in the construction process. There are some interesting 5. Having an interface.NAME as a standard allows a program- consequences to the nature of this exception, which I’ll cover mer a simple reference to instantiate an interface at the end of this article.

Usage Pattern for an Evolving Implementation getObject vs createObject Let’s reexamine how we can utilize an interface. The At this point I’d like to change the name of the “create” emphasis here is that you get your implementations via a method of the ObjectFactory to “getObject”. create() implies global factory instead of "new"ing them explicitly. This allows that an object is being created every time the method is called. for runtime variations of the implementation. For example: This may not be true for a number of reasons. Certain objects you may want to create only once, others with each request, MyInterface i = (MyInterface)ObjectFactory.create and some as part of a pool. Because of this, getObject() suits (MyInterface.NAME,null); the semantics of this intention more accurately. i.useMethod(); Passing Arguments Let’s examine the MyInterface.NAME: Certain objects require construction arguments. How do you pass them? The argu- interface MyInterface ments are passed via the second parameter to { the function call. This could be any object, public static final String NAME = including a collection of objects that get passed

106 JUNE 2001

Java COM to the constructor of the target object. This in Web-based systems. It’s fairly trivial to do, can get sophisticated with EJBs when the but adds a great value to the overall functional- constructors are invoked through reflection ity. For example, using such a functionality you and the correct constructor called. But for can convert an incoming result set to a simplicity the classes can have default con- comma-separated string or sum the values into structors, with a well-known “init()” method a single entity. All this can be done without that accepts the passed parameter as an argu- recompiling the target code. This properties ment. file demonstrates how this can be accom- The implication is that programmers not plished: only need to know the interface name of the object that they want to instantiate, but also Objects.employee.className=com.comp.Employee the nature of its arguments. This I call the con- Objects.employee.filterName=SumSalary struction interface of the object. This needs to Objects.SumSalary.className=com.comp.Sum- be published and adhered to by all the imple- EmployeeSal mentations. And it’s the responsibility of the programmer to pass the correct set of argu- The Default Object ments. Otherwise an exception is thrown by When you’re specifying target implementa- the generic factory. tion objects via a properties file, it’s possible that anything might go wrong in the construc- Caching Strategy tion process, resulting in an exception. In this Once you start using this facility, it won’t be case you’d like a default implementation to be long before you start asking, “How can I limit available. For example: the number of object occurrences of a specific class?” For example, singleton. To facilitate this MyInterface myObj = null; a factory can use multiple strategies to cache try object instances. The factory can save the { Top instantiated objects in a hashtable keyed by myObj = ObjectFactory.getObject their interface names. So, when a repeated (MyInterface.NAME,null) request comes in for an interface, the factory } can return the previously constructed object. catch( FactoryException x) But how does the factory know to cache an { object? You can specify in the properties file x.printStackTrace(): that a certain interface needs to be cached, myObj = new MyDefaultObject; Coder which is how it’s done in EJBs at deployment } time. Specifying the number of object instances at deployment time is more generic. Doing this everywhere discourages the pro- But for systems of medium complexity, you grammer from using the facility. The following may want to define an ISingleThreaded inter- code alleviates the problem: face and implement that interface to force www.top- multiple instances of the object. This avoids MyInterface myObj = ObjectFactory.get the errors that might occur due to lack of Object (MyInterface.NAME, args, new knowledge at deployment time, or you could MyDefaultObject(); provide both facilities. This method doesn’t throw any exceptions, Name-Based Caching May Not Be Sufficient instead it returns the MyDefaultObject on any Interface name-based caching sounds good kind of internal exception, ensuring the default coder.com until you consider the fact that a given imple- functionality of the application. mentation can support multiple interfaces. In this case you’ll have two such objects cached A Well-Defined Factory Interface to when one would have been sufficient and even Fulfill the Factory Service wrong at times. I believe the right approach is With that discussion we’re able to define an to use caching based on class names instead. interface for our factory object:

Pooling Support interface IFactory I think a factory shouldn’t provide pooling; { it should be implemented on top of factory. Object getObject(final String Otherwise the simple factory interface also interfaceName, Object args) throws needs to deal with synchronization and return FactoryException; to pool semantics. Object getObject(final String interfaceName, Object args, Object Support for Object Filters defaultObject); When a factory instantiates an object, it can } also pass the object to an object An interface definition tells filter and return the output of the you only the contract of the facto- filter instead. This allows for the ry and doesn’t specify its intended chaining of objects, which is simi- behavior. For that reason I’m sum- lar to the servlet chaining popular marizing here the desired charac-

JUNE 2001 107

Java COM “ Using a simple application-level factory service, it’s

possible to effectively employ interfaces and implementations to write code that provides backward compatibility “

teristics of a typical factory implementation: With this you’d be able to do: 1. Provides a static façade for easier calling semantics 2. Uses getObject, not createObject, semantics String value = Config.getValue("key","default value"); 3. Requires a default constructor for the objects to be con- J2SE structed Why go to such lengths when properties is such a simple 4. Arguments are passed to the init method for initialization interface; why not use it? Frequently you would want the 5. Caching is based on the class name of the object IConfig implementation to exhibit the following characteris- 6. Caching is also based on the IsingleThreaded tagging inter- tics: face 1. Case-insensitive keys so you don’t have to constantly 7. Supports object filters remember capitalizations BACKWARD 8. Supports default objects 2. Ability to include multiple-properties file inside the main 9. Uses an application-wide configuration interface for class configuration file definitions 3. Ability to provide substitutionsCOMPATIBILITY based on keys that were defined at the beginning of the properties file ObjectFactory Implementation Although we’ve defined an interface for a factory, we All these can be provided gradually by the evolving imple- need a convenient set of static methods that would make mentations of IConfig. In this case, one of the facilities of the use of the above interface internally. Such a facility pro- framework evolves using the same principles. vides the best of both worlds. On one side it obviates the

Home J2EEneed to instantiate a factory interface J2ME and on the other it Evolving an Interface adheres to a nonstatic factory interface definition. Here’s So far I’ve discussed where the implementations are chang- one such implementation. Obviously many variations are ing. What if the interface itself has migrated to the next level? possible, but the idea is to give the programmer the sim- Although less common, this will happen eventually, even in the plest way to accomplish the characteristics stated above best of designed interfaces. For instance, with the logging (see Listing 1). interface defined above, I’d like to extend the interface by pro- viding a logging mechanism for exceptions. One approach is to Role of an Application-Wide Configuration Service extend the base interface instead of modifying it: So far all the object definitions are stored in a properties file. It’s not that difficult for the factory implementation to interface ILogFacility_1 extends instantiate a properties object and read in the properties file. ILogFacility What if in the future you’d like to move the entries from a { properties file to a database, an LDAP, or an XML configura- public void log(Throwable t); tion file? } For this reason the factory implementation accesses the object definitions through a common configuration interface. If there’s an implementation that supports the ILogFacility_1 interface, it automatically supports the Interface Iconfig ILogInterface and hence can be used in a backward-com- { patible manner. On the other hand, if an older implementa- public String getValue(final String key) tion that supports only ILogInterface is used in a newer throws ConfigException; environment that’s expecting ILogFacility_1, there are two public String getValue(final String key, alternatives: String defaultValue ); 1. Let the system throw a class-cast exception and correct the } mistake 2. Write the client code in such a way that this can be handled Again, for programmer simplicity, this interface is exposed gracefully: through a static Config class as follows: Object logFacility = Class Config ObjectFactory.getObject { (ILogFacility.NAME,null,new MyLogFacility); static public String getValue(final String if (logFacility instanceof ILogFacility_1) key) throws ConfigException; { static public String (ILogFacility_1)logFacility.log(x); getValue(final String } key, String defaultValue ); else (logFacility instanceof ILogFacility) } {

108 JUNE 2001

Java COM (ILogFacility)logFacility.log- such generic interfaces as the factory interface (x.getMessage()); I’ve shown here. When a factory tries to load a } class at runtime and fails, all the client sees is the factory exception. If you’re not careful, the Request-Based Factories root cause of the exception is never known. To As I’ve mentioned, factory plays a central deal with this scenario, interfaces should role in adapting this evolution-based approach define exceptions that can carry with them a to programming. The factory I’ve discussed so child exception, and the child exception can far is primarily creation-based because it carry another child exception. This way the instantiates the necessary class and calls the root exceptions are propagated all the way to well-known method to initialize it. A more the top. When the final exception is printed, sophisticated approach would be a request- you’ll see a complete hierarchy of exceptions, based factory in which the input symbolic which is extremely good for debugging purpos- name refers to a request rather than a class es. I call this the principle of Kangaroo excep- name. You can simulate the creation-based fac- tions, and it’s necessary for interface-based tory from a request-based factory. For example: programming. This is because interfaces are like firewalls and compile-time exceptions Object o = RequestBasedFactory.getObject can’t propagate through them without help. ("GET_OBJECT", null): This concept of Kangaroo exceptions hides the root exception in terms of the interface-specif- The request-based factory locates a class ic exception. name identified by “GET_OBJECT” in a proper- BACKWARD ties file. Instead of calling the init method to Conclusion initialize the object, the request factory calls Using a simple application-level factory the “executeRequest” method with the param- service, it’s possible to effectivelyCOMPATIBILITY employ inter- eters. Whatever the executeRequest method faces and implementations to write code that Top returns is then returned to the caller as the provides backward compatibility. Even when return object. you don’t need this compatibility, it enables When the executeRequest method returns you to try new bug fixes without affecting the the self-reference, we basically have the old behavior. This provides developers with RequestFactory behaving like a creation facto- some assurance that they won’t undo every- ry. RequestFactory has broader applications thing they’ve done before. than a simple CreationFactory. For example: Coder

RequestBasedFactory.getObject("GET_EMPLOYEE_ AUTHOR BIO ROWS","employee_name=John Doe") Satya Komatineni is president of Active Intellect, Inc., and the author of a Java-based RAD framework for developing J2EE-based HTML invokes a database request executor identified applications (www.activeintellect.com/aspire/). He holds an MS in by “GET_EMPLOYEE_ROWS” and returns the electrical engineering from the Indian Institute of Technology, New Delhi. www.top- result set back to the caller. Interfaces and Exceptions I’d like to cover one more detail since we’re dealing extensively with interfaces, particularly [email protected]

Listing 1 coder.com class ObjectFactory implements IFactory { private static m_self = new ObjectFactory(); public static Object getObject(final String interfaceName, Object args) throws FactoryException { return m_self.getObject(interfaceName, args); } public static Object getObject(final String interfaceName, Object args, Object defaultObject) { return m_self.getObject(interfaceName, args); } // private non static methods Object getObject(final String interfaceName, Object args) throws FactoryException { // implement as appropriate } Object getObject(final String interfaceName, Object args, Object defaultObject) { // Implement as appropriate } }

JUNE 2001 109

Java COM OptimizationOpt m zat on and J2SE

written by Irvin J. Lustig No longer mutually exclusive As Java continues to be used in a wider range of applications, for the Web. Java developers should come away from this article one measure of its progress is in its ability to take on more with a better understanding of optimization and how they might

Homerobust, J2EE high-performance computational J2ME applications. One of leverage this powerful and flexible technology in their own the most demanding areas within commercial software is opti- applications. mization. Best known as the driving technology for planning and scheduling inside supply chain management applications, Definition of Optimization optimization involves computational engines fueled by special- Modern-day optimization is defined by the application of ized algorithms that crunch through complex business prob- mathematical and constraint programming. However, the ideas lems to find quick answers that can save businesses enormous of optimization go back to Isaac Newton and calculus. Every cal- amounts of time and money. culus student learns how to find the minimum value of a func- Optimization applications have lived in a universe far distant tion of variables by taking the derivative and solving a set of from Java. They’ve largely been C-, C++-, and FORTRAN-based – equations for the answer. just what you would expect from such sophisticated, computa- Today, optimization methods represent a set of techniques tionally demanding software. However, rapid evolutionary for finding the best usage of limited resources. The best usage forces in both Java and the optimization sector, combined with could be minimum cost, maximum profit, highest level of the relentless need for higher levels of intelligence in commer- service, or quickest delivery time. The types of resources that cial software applications, are converging to the point where may be limited are people, vehicles, equipment, time, sup- Java and optimization are no longer mutually exclusive. plies, and money. Optimization is applied to manufacturing Until quite recently Java programmers who wanted to systems, telecommunication networks, asset allocation, and include optimization within their applications needed to write other business processes where it’s possible to come up with a their own Java wrappers around optimization code. Another mathematical model for the underlying business processes. limiting factor has been the lack of hands-on knowledge of high- The successful application of optimization has the following end optimization techniques among developers, who often features: aren’t skilled in model development and selecting the best-solv- • Represents decisions by using a set of decision variables in ing strategy. However, commercial Java Native Interface (JNI) which the possible values of the decision variables are known wrappers for optimization code are now emerging, with pure • States a set of constraints that the decision variables must sat- Java-based development solutions imminent. In addition, isfy recent ease-of-use breakthroughs in the form of tools for mod- • States an objective function of the decision variables eling and embedding optimization software are bringing this technology closer to the mainstream. Given this broad description, a variety of powerful algo- For Java developers, having access to optimization technolo- rithms have been developed that are able to determine solutions gy offers the potential for smarter applications that deliver to such problems. With the advent of improved computational greater efficiencies, not just in planning and scheduling – the hardware power combined with the improvements in the bedrock of optimization – but in emerging areas such as cus- underlying algorithms for solving optimization problems, it’s tomer-facing software for solutions such as Web self-service. now possible to solve problems in seconds on desktop comput- This article introduces optimization to the Java programming ers that only 10 years ago required weeks of computing time. community: what it is, what it isn’t, and how it can be an invalu- Because of this, the range of possible applications of optimiza- able tool for creating a wide range of applications, particularly tion has widened.

110 JUNE 2001

Java COM VM Gear www.vmgear.com

JUNE 2001 111

Java COM Optimization problems are inherently difficult to solve because the number of possible solutions to any particular Minimize problem is enormous. The most classic optimization problem is c=[c1 2 n] c1x1+c2x2+...+cnxn the traveling salesman problem: given a set of cities and starting Subject To 1, 2 n]

at a home city, determine the shortest path that would enable A11x1+A12x2+...+A1nxn= x=[x1, 2 n] the salesman to visit all the cities without visiting any city more b1 A=[A1 A2... An] A21x1+A22X2+...+A2nXm= than once, then returning home at the end of the tour. For a [A21 A22... A2n] problem with 1,000 cities, there are over 102,567 possible solu- tions to consider! Sophisticated opti- mization algorithms are able to effi- ciently solve similar practical problems, BusinessBusiness despite the large number of potential Product Model solutions. Extendedd Rules Builder

Optimization Examples BBusiness Config. T Some examples help illustrate the Languageanguage Minimize c x J2SE kinds of problems that can be solved XML Config. XML Subject To Ax= Design Rules & Product with optimization technology. For each PPreferencesreference Model DescriptorDescripto W eb S erv of these problems the concepts of “best Runtime er Web FIGURE 1 A linear program usage,” stated as an objective, and “lim- UI

ited resource,” reflected in constraints, Se ss JSP io will be described. n numerous companies solve opti- E Configuration J Open B • An airline has a schedule of flights Engine mization problems using both CCaCatalog Object and a fleet of different aircraft types. Model techniques. The organization needs to determine the assignment of the aircraft to the Web Mathematical Programming Connector different flights so as to maximize Many optimization problems profit, while making sure that aircraft can be stated using decision are scheduled for maintenance, have FIGURE 2 Java-based configuration tool variables that are real-valued, sufficient turnaround time between combined with objective func- flights, and anticipated demand is met. Here, the “best usage” tions that are linear and constraints that are linear inequali-

Home J2EEis the profit, as measured by the expected J2ME revenue obtained ties. Such problems are known as linear programs. Here the by assigning a particular aircraft type to a particular flight, word program refers to the original statement of the problem less the cost of purchasing and operating enough aircraft to by Dantzig as a programming problem, where the problems fly the entire schedule. The limited resources are the planes Dantzig studied involved finding the best activities program and the limits imposed by the airline’s schedule. Optimization for achieving a desired goal. If you restrict some or all of the technology is used to determine the best assignment. decision variables to be integer valued, the problem is then an • An automobile manufacturer needs to sequence cars through integer program. a paint shop. Each car is painted a certain color. Each time the Linear and integer programming are the foundations of the paint color is changed, an expensive paint purging operation field of mathematical programming and are taught in many must occur. The goal is to reduce costs and increase through- universities in operations research and industrial engineering put by reducing the number of purges. Here the limited departments, as well as in quantitative courses in many MBA resources are the paint shop and the space allocated for cars programs. A linear program can be represented using numerical waiting to be painted, and the objective is to find the best matrices and vectors. Figure 1 illustrates the algebraic and usage of the shop. Optimization is applied to find a sequence matrix-vector forms of a linear program. of cars that minimizes the number of times the paint system In general, mathematical programming technologies are must be purged by grouping cars of the same color together used for long-range planning applications. They’re one of the and respecting the availability of the limited size of the wait- keys behind the success and growth of supply chain manage- ing area. ment applications. Mathematical programming techniques are • A consumer desires to obtain a home equity loan. Each con- also used by all the major airlines for fleet assignment and crew sumer may have different objectives, such as minimizing pay- scheduling. Telecommunication companies use mathematical ments, reducing overall debt, or maximizing the cash avail- programming techniques to optimally design their networks. able from his or her home. At the same time, a bank has lim- The applications’ growth has been driven by the improvement its on the type of loan it’s willing to approve. Optimization in algorithms and hardware so that linear and integer programs allows the bank to offer the loan best tailored for the con- are solved by computationally intensive algorithms in a reason- sumer’s needs by searching among all the possible loan con- able amount of time. figurations. The underlying algorithms used to solve linear and integer programs require a substantial amount of floating point compu- Optimization Technologies tation. Efficient implementations take advantage of the underly- While the foundations of mathematical optimization are ing processor and cache architectures, as well as compilers that found in calculus, the age of modern optimization began with the can produce code that’s efficient for a particular class of hard- discovery of the simplex method for linear programming by ware. Near term, pure Java implementations of these algorithms George Dantzig in 1947, which led to the development of the won’t deliver the required performance for all kinds of optimiza- fields of operations research and mathematical programming. tion applications. As an initial remedy, it’s now possible to obtain Subsequently, developments in the artificial intelligence commu- JNI wrappers around the implementations of these algorithms, nity led to the emergence of constraint programming as a tech- which allows Java developers to develop in Java while achieving nique that could be used to solve optimization problems. Today, the performance delivered by the algorithms.

112 JUNE 2001

Java COM Premptive www.preemptive.com

JUNE 2001 113

Java COM Constraint Programming mize an objective function. Sophisticated constraint propaga- Constraint programming has its roots in the research of the tion and domain reduction algorithms are used to process each artificial intelligence community. Here, the word programming constraint type so as to make the overall search strategy effi- refers to a particular methodology for doing computer pro- cient. Listing 1 illustrates an example of a constraint program gramming. To apply constraint programming a specialized pro- for coloring a map in the optimization programming language gramming language is required, or special libraries built into a (OPL). The decision variables are represented by the array color, mainstream programming language can be used. Abstractly where for each country a specific color must be chosen. The speaking, a programmer lists variables of a computer program constraints indicate which countries can’t have the same color. along with their domains of allowable values. Then, constraints Recently, constraint programming has been successfully are listed that the variables must satisfy. As opposed to linear applied to optimization problems that appear in more opera- programming, they can be in any form that the underlying con- tional and tactical applications, where real-time answers to straint programming language allows. problems are required and mathematical programming tech- The final step in applying constraint programming is to niques are insufficient. Typically, these problems involve logical write a search strategy in the programming language indicating constraints on integer variables, which can be processed effi- how the variables should be modified in order to find values of ciently by a constraint programming engine. the variables that satisfy the constraints and, optionally, opti- Constraint programming has been successfully applied to J2SE scheduling, sequencing, and configuration problems. In supply chain management applications, it’s used to determine the schedule of how products should be manufactured on a limited number of machines. The auto paint shop application mentioned earlier is solved using constraint programming techniques. Finally, the loan configuration problem represents another successful application of constraint program- ming due to its ability to efficiently process the com- plex underwriting constraints that describe the loans in order to search for the best loan configuration for a customer.

Modeling Languages A model of the underlying processes must first be built

Home J2EE J2ME to successfully apply optimization techniques to solving business problems. In mathematical programming this Just has typically been done by writing software to generate the matrices representing linear and integer program- ming. More recently, specialized mathematical program- ming modeling languages have been developed that pro- vide the capability to succinctly represent a mathematical programming problem. The initial development of these languages created stand-alone tools that would allow Computer users to enter problems in the modeling language, inte- grate external data, and then solve the resulting program. Today, these languages are now provided in the form of libraries that allow easy integration of mathematical pro- gramming models into large-scale applications. Constraint programming development has occurred in two directions. One was the development of special Jobs purpose languages for applying constraint program- ming techniques. Like mathematical programming languages, the specialized constraint programming languages were created as stand-alone tools and are now available as object libraries. The second direction is the creation of specialized constraint programming libraries on top of existing programming languages www.justjavajobs.com such as C++ and Java. Java-constraint programming tools are still in a state of development. The next year should see the intro- duction of pure Java constraint programming engines. The optimization programming language is unique in that it provides a language that enables the use of both mathematical and constraint programming techniques. An example of a linear program written in OPL is shown in Listing 2. The data is represented by the sets Products and Resources, and the arrays product and capacity. The decision variables are the arrays inside and outside. The modeling language representation directly maps to the matrix/vector notation discussed earlier.

114 JUNE 2001

Java COM Unify eWave www.unifyewave.com

JUNE 2001 115

Java COM Java Tools for Optimization describe a configuration problem at design time, a business Optimization has been remote to the Java community main- product model and configuration language are used with a ly due to the lack of effective tools to utilize it. Affecting the builder, which generates an XML representation. This is then technology’s wider spread into the Java community has been used at runtime. the inherently slower performance of the Java platforms that Constraint programming is used inside the configuration made fully leveraging the technology difficult. But things are engine. Because the state of the current configuration must be changing. New technology advances and new features in opti- represented and updated quickly, using a non-Java engine will mization software mean easier access for Java programmers and be problematic. The performance improvements in the Java 2 better performance. Complementing these advances and mak- framework should allow this kind of application to execute effi- ing it relevant are the performance improvements to the Java ciently within a Web-based environment. platforms that help minimize the performance hit for optimiza- tion applications. Conclusion As mentioned above, traditional optimization as represented As more real-time decisions are required by businesses, opti- by mathematical programming applications have yet to be mization applications will appear on the Web and integration offered directly on the Java platform due to performance con- with Java will be a requirement. Java programmers are already siderations. Today, Java interfaces to existing engines are now creating JNI interfaces to existing optimization engines to allow J2SE available, providing the benefits of a Java interface to a high- access to Java programmers. Whether it’s by using JNI interfaces performance computational engine. If demand emerges for to high-performance engines or by using pure Java applications, pure Java versions of mathematical programming tools, it’s like- a growth of such applications should occur within the next cou- ly such solutions will be developed. Fortunately, the speed of the ple of years. Fueling this growth will be the improvements in underlying engines has improved to a point where “Java” opti- computer hardware and the underlying algorithms for opti- mization can be used in real-time applications. In particular, mization, allowing businesses to reduce costs and increase prof- marketplace auctions on the Web represent an excellent appli- its. The opportunities are unlimited. cation of this technology. An interesting development for both mathematical and con- AUTHOR BIO straint programming is the introduction of ILOG OPL Studio 3.5, Dr. Irvin Lustig is ILOG’s optimization evangelist responsible for education and marketing initia- which allows models represented in OPL to be embedded inside tives around optimization. He received his PhD in operations research from Stanford University Java programs. A Java developer assembles the required inputs and a ScB in applied mathematics/computer science from Brown University. He’s also the for an OPL model and passes the data and the model descrip- author of more than 30 scientific research papers. tion to the OPL component libraries, which are supplied with [email protected] JNI wrappers. The libraries then interpret the model and the

Homedata J2EE and solve the resulting optimization problem. J2ME The optimal values of the decision variables can then be obtained by query- ing methods in the OPL component libraries. Listing 1 The advantage of using JNI in this case is that the underlying enum Country {Belgium,Denmark,France, performance of the optimization engine on different hardware Germany,Netherlands,Luxembourg}; enum Colors {blue,red,yellow,gray}; platforms is preserved. Furthermore, the process of developing var Colors color[Country]; an optimization model, which requires expertise in understand- solve { color[France] <> color[Belgium]; ing the underlying business processes, is separated from the color[France] <> color[Luxembourg]; process of integrating the optimization model into a Java pro- color[France] <> color[Germany]; color[Luxembourg] <> color[Germany]; gram. color[Luxembourg] <> color[Belgium]; On the other hand, Java versions of constraint programming color[Belgium] <> color[Netherlands]; color[Belgium] <> color[Germany]; tools can be useful in a new class of Web-driven applications color[Germany] <> color[Netherlands]; that are based on solving configuration problems, such as the color[Germany] <> color[Denmark]; loan configuration problem described earlier. In fact, the first versions of these tools will be available later this year. To illus- Listing 2 enum Products ...; trate, let’s consider the problem of configuring an automobile enum Resources ...; that’s subject to the requirements of a consumer and the con- struct ProductData { straints determined by the automobile manufacturer. The con- float+ demand; sumer may want the lowest-priced car with specific features. float+ insideCost; float+ outsideCost; The manufacturer may have constraints that indicate the com- float+ consumption[Resources]; patibility of certain options. For example, certain models may }; not be available with a sunroof or a particular engine. ProductData product[Products] = ...; Constraint programming can be used to represent the possibil- float+ capacity[Resources] = ...; ity of different choices and the constraints on these choices. var float+ inside[Products]; On the Web a form can be used to represent the different var float+ outside[Products]; choices that are available to the consumer for configuring his or minimize her automobile. After the consumer makes a choice, the con- sum(p in Products) (product[p].insideCost*inside[p] + straint programming engine can then eliminate incompatible product[p].outsideCost*outside[p]) choices. Once a set of choices is made by the consumer, the subject to { forall(r in Resources) choices left open by the user can then be considered for opti- sum(p in Products) product[p].consumption[r] * mization by the constraint programming engine, and the low- inside[p] <= capacity[r]; est-priced car subject to the consumer’s choices and the manu- facturer’s constraints can be determined. forall(p in Products) inside[p] + outside[p] >= product[p].demand; For this application a Java-based constraint engine is }; required, and it can be easily integrated within the J2EE frame- work. Figure 2 illustrates the design of such an application. To

116 JUNE 2001

Java COM Pramati www.pramati.com

JUNE 2001 117

Java COM using javabeans in DREAMWEAVER ULTRADEV 4 J2SE Make your workflow process more productive and effective

written byyMICHAEL BARBARBARELLI anddDAVID DEMING

of APIs. The JavaBean API coupled with JSP helps users to develop Web applications by moving much of the server-side logic into the bean and focusing the JSP page on the presenta- tion layer. By developing JavaBeans to contain most of your

Home J2EEiven the publication this article J2ME is appearing in, I’m server-side logic, reusable classes can be defined, greatly G reducing future application maintenance requirements. This not going to spend much time trying to sell you on the benefits makes it possible to extend those classes and tailor them to different requirements. of the Java platform for Web application development. Let’s What this means to most Web development teams today is that a wide variety of skills are necessary to effectively deploy assume we’re all on the same page here. Java-based Web applications. You need Java programming experts to develop the JavaBeans, design and layout experts to I think we can also agree that developing Web applications create the front-end user interface (usually in HTML), and using JavaServer Pages (JSP) could be easier. The technology Web application programmers to glue the back-end logic and builds on the rich development architecture of the Java platform, data structure to the front-end user interface. Although, but there aren’t many programs that effectively mask the com- depending on the size of the team, some of these tasks might plexity of the language to simplify Web application development. be performed by the same people, getting all of them running Macromedia Dreamweaver UltraDev 4 simplifies visual together smoothly is a challenge. Web application authoring using JSP while taking advantage of I think most people involved in Web application develop- the unique capabilities of the Java platform. This includes data- ment can relate to the following scenario. A front-end designer base connectivity through JDBC, connecting to other back-end creates a static user interface; at this point the back-end system and legacy systems through JavaBeans, and supporting custom (database data business logic, etc.,) may not be designed, or it tag libraries. In this article we explore how UltraDev can help may not be accessible enough to integrate with the user inter- Web application development teams (or individuals) stream- face. Once it is ready, the Web application developer must then line the process of deploying applications. We’ll use JavaBeans go through an iterative process of plugging in the back-end as an example technology to illustrate this point. system to the user interface, uploading the result to a test serv- A little more marketing background and then I promise I’ll er, determining what works and what doesn’t, and asking the get technical and dig into how UltraDev makes it easier to designer to tweak the design to fit the data structure. Where incorporate JavaBeans into your Web development workflow. UltraDev really helps is in this test/tweak/redesign process. It’s built on the core architecture and shares all the features One of the most difficult aspects of this problem is that it’s available in Macromedia Dreamweaver, a visual Web author- hard to find a single person, let alone a single application, that ing environment for professional Web developers. The prod- can effectively tweak design elements and plug in server-side uct is fully customizable and scriptable using JavaScript, XML, logic and dynamic data. As an application development envi- and HTML. This means that with UltraDev you get an HTML ronment, UltraDev can help tremendously here. editor to help visualize your design. Let’s assume we’re responsible for the task I just described. Now that you have a basic background on UltraDev, let’s An enterprise Java developer has given us a JavaBean that look at how JavaBeans can be used with it. masks the complexity of a set of database functions that store As you know, the Java 2 Platform, Enterprise Edition customer information. We must now integrate the data from includes JSP. The Java platform allows access to a varied range that bean into an HTML user interface.

118 JUNE 2001

Java COM Parasoft www.parasoft.com/jdj_wk

JUNE 2001 119

Java COM Using JavaBeans in a Code-Only Environment When doing tasks like this by hand, the Web application developer needs to know a bit of JSP syntax to effectively incor- porate a JavaBean into the design. Assuming we have a bean called Customers available, our Web application developer would include a line in the HTML that looked something like this:

This creates an instance of the bean that’s then available on the rest of the Web page. The next step might be to set certain properties of the bean to ensure we’re accessing the proper cus- tomer. This is one of the beauties of JavaBeans – the application developer doesn’t need to know anything about the structure of the database that stores the information about the customer, J2SE just the unique ID that’s used to identify them.

"/> FIGURE 1 UltraDev 4’s split view

In this case things became even more complicated – the ID for the customer was stored in a form variable called ID that came across in the request. Once this property is set, the application developer can then plug in various customer properties at appropriate points in the design. Let’s assume the designer had earmarked a portion of the page to contain a personalized greeting. The application developer would wade through the HTML to locate the appro- priate area. A message welcoming the customer by name could then be inserted, for example: FIGURE 2 The UltraDev Bean initialization dialog Home J2EE J2ME Welcome to our site, to create a personalized greeting for each customer. The last, often overlooked, step in this workflow is for the appli- cation developer to upload this completed file to the application server and preview it in the browser. It’s usually at this point where things get difficult. Although it might work perfectly in this simple case, rarely in the real world will the initial design perfectly accom- modate all the dynamic elements needed on the page. This is where the dance of transferring files back and forth between the developer and the layout designer leads to delays and frustration in getting the design and dynamic elements just right. Designers get frustrated because they can’t see the dynamic data on the page as they’re tweaking the layout – they have to work with placeholders. They have to take the developers’ word for it – “That one table cell isn’t quite big enough. You’ll have to move that image somewhere else….” And application developers get frus- trated because designers often step all over their hand-developed JThreadKit code when tweaking the design. This back and forth can be a seri- ous headache, even when both tasks are performed by the same person! UltraDev can offer a compelling solution to this problem. Using JavaBeans in UltraDev’s Visual Development Environment Because hand coding is so important to most developers, it www.jthreadkit.com would be possible to implement the above scenario exactly as described using UltraDev. By operating only in code-view, the application developer could diligently type out each of the above lines of code in the appropriate places in the HTML lay- out. Of course, part of the power of UltraDev is making that process easier and more effective. One of the first things a traditional coder will notice about UltraDev is all the visual panels and inspectors that surround the target document to be edited. Assuming that the flat HTML file is open and ready to be modified with dynamic data, the user also has a choice in how to view it. There are three editing modes in UltraDev that can be used depending on the situation

120 JUNE 2001

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

JUNE 2001 121

Java COM and preference of the developer. Code view shows all the code ronment – it instantly lets you know what properties are avail- behind the page (HTML and Java) using syntax-coloring for able to set. This is where we could type in the ID property for the clarification. Design view shows a visual representation of customer, thus eliminating the need for a setProperty tag. what the page will look like when viewed in the browser, while Once all this is done, UltraDev automatically uses introspection split view allows both the code and visual representation of the to discover all the available setter and getter methods of the bean page to be viewed and edited at once (see Figure 1). and shows them in the data bindings inspector. To use these ele- Let’s assume we’ve chosen to work in design view. The first ments on the page, our application developer has to simply drag step with UltraDev is to set up the JavaBean as a data source. This and drop the various elements into place. In Figure 3 the designer process consists of browsing to the appropriate class file, typing notices the placeholder on the page and can easily replace it with in the initialization parameters, and giving the bean a name. You the dynamic bean element. UltraDev generates the necessary JSP can even visually set any of the available properties of the bean code behind the scenes, creating the dynamic welcome message at this point (see Figure 2). This is one benefit of the visual envi- that includes the individual customer name from the bean. Let’s go beyond our simple example for a moment and assume the app builder needs to build more complicated behavior into the page. For example, the developer wants to hide the entire greeting message if the user’s first name is not J2SE available, that is, it was never passed from the form on the pre- vious page. Since this is such a common task, entering the code by hand each time is laborious. Using the UltraDev serv- er behavior builder, the developer could automate this process by teaching UltraDev the code that should be used in this sit- uation and setting the appropriate variables to make it work. Then this behavior would be saved and used later, automating this task. Let’s work through this example: • The developer opens UltraDev’s server behavior builder and gives this new behavior a name, “Hide if null”. • The developer then defines the first code block to come before the area of the page that is to be hidden:

<% if (request.getParameter("@@Parameter@@") == null) { %> FIGURE 3 Integrating dynamic data Home J2EE J2ME The “@@” surrounding Parameter tells UltraDev that this is a variable name that should be entered by the user each time the server behavior is used. • The developer configures the first code block to come before the area of the page the user had selected. • The developer defines the second code block to come after the user’s selection:

<% } %>

• The developer determines how the user enters the parame- ter when using the behavior. In this case we’ll have the user enter it using plain text (see Figure 4).

Now that the developer has saved this behavior, it can be easily accessed again though the server-behavior menu. To have a certain area of the page hidden if a request variable is null, the developer needs to select the area on the page, click on the serv- er behavior, and type in the appropriate request parameter (see FIGURE 4 Creating reusable code blocks Figure 5). The developer can even share this with other users in the group to help them speed their development process. Instead of saving the file, uploading it, and then previewing it on the browser, the application developer can use UltraDev’s LiveData Mode to see instantly what this design is going to look like in the browser (see Figure 6). With this instant visual feedback the application builder can then see the effects that different text formatting will have on the design, and even make layout tweaks visually to accommodate the dynamic data (with the designer’s approval, of course!). If the file needed to be passed back to the designer for more complicated changes, that designer could work in UltraDev’s LiveData Mode to visually edit the HTML layout and instantly see how the design changes affect the page that incorporated the dynamic data. They can also instantly tell if their design change FIGURE 5 Applying a behavior from the server behavior menu has broken some aspect of the code because UltraDev will give

122 JUNE 2001

Java COM JRealTime www.systronix.com

JUNE 2001 123

Java COM them an error message in LiveData Mode. They can then use the unlimited undo feature to return the document to its previous state before things went awry. This saves developers and designers lots of heartache by eliminating the possibility that the designer could inadvertently break the code of the page during a design change. More enterprising designers can even use the code/design split view to see what code is generated by each of the dynamic elements on the page. This has been used as an effective learning tool for designers to become familiar with JSP style code and what it does. Anything that’s unclear can be instantly looked up in the Wrox JSP reference book that’s built right into the product (see Figure 7). The idea here is that the instant visual feedback UltraDev pro- FIGURE 6 Using UltraDev’s LiveData Mode vides makes this whole workflow process more productive and effec- tive. It cuts down on the amount of time that designers and develop- ers have to spend tweaking their work to accommodate what the other is doing. While UltraDev is certainly not a replacement for a J2SE Java development environment that’s used to create JavaBeans and other components without visual elements, it’s absolutely crucial for streamlining the process of combining a visual interface with back- end systems. Using UltraDev, teams of application development professionals can streamline their processes, allowing them to spend more time optimizing their design and code.

AUTHOR BIOS Michael Barbarelli, lead technician for Macromedia's UltraDev technical support group, is responsible for managing the product from the customer's viewpoint. He studied computer science at the University of California.

David Deming is the product manager for Dreamweaver UltraDev. He has a mcechanical engineering degree from UC–Berkeley.

[email protected] Home J2EE J2ME

FIGURE 7 The embedded Wrox JSP reference [email protected]

Quadbase www.quadbase.com

124 JUNE 2001

Java COM Breeze Factor www.breezefactor.com

JUNE 2001 125

Java COM JDBC APPS A Practical Solution for the Deployment of JavaServer Pages Download Web apps without J2SE

While Java databases have become essential for Web applica- compromising your security tions, developing performance-oriented Java Database Connectivity (JDBC) applications can be challenging. But by following tried-and- true approaches, it is possible to develop and fine-tune JDBC appli- WRITTEN BY cations to make them run faster, jump higher, and make fewer trips JOHN GOODSON to the database.

Below, we present practical guide- lems, always supply as many non-null GUIDELINE 2: lines for many of the common JDBC arguments as possible to result sets RETRIEVE DATA EFFICIENTLY applications. that generate database metadata meth- Too many calls from the application ods. to the driver can cause your application GUIDELINE 1: Moreover, because these methods to run more slowly. To improve perfor- USE METADATA WITH CARE are slow, applications should invoke mance, try to reduce the size of data that

Home J2EEThe first guideline is to be careful J2ME them efficiently. Many applications pass is returned. Also, avoid retrieving long about using metadata. Although it’s the minimum number of non-null argu- data unless it is absolutely necessary. almost impossible to write JDBC appli- ments required for the function to Retrieving long data across the network is cations without database metadata return a successful result set. slow and resource-intensive. Moreover, methods, you can improve system per- For example: most users don’t want to see long data. If formance by minimizing their use. a user does want to see these result items, ResultSet WSrs = WSc.getTables the application can query the database Cache Information to Limit Executions (null, null, "WSTable", null); again, specifying only the long columns To return all result-column informa- in the select list. This method allows the tion mandated by the JDBC specifica- should be: average user to retrieve the result set tion, a JDBC driver may have to perform without having to pay a performance multiple queries, joins, and subqueries ResultSet WSrs = WSc.getTables penalty of higher network traffic. in order to return the necessary result ("cat1", "johng", "WSTable", While it’s best to exclude long data set for a single call to a database meta- "TABLE"); from the select list whenever possible, data method. Applications should cache some applications do not formulate the information returned from result sets Unfortunately, sometimes you select list before sending the query to that generate database metadata meth- don’t know much about the object for the JDBC driver. (For example, some ods so that multiple executions are which you are requesting information. applications select * from

....) If the select list contains long Info once in the application and cache tion can send the driver when calling data, the driver must retrieve that data the elements of the result set that your database metadata methods can result at fetch time, even if the application application depends on. It is unlikely in improved performance and reliabil- doesn’t bind the long data in the result that an application will use all elements ity. set. In this scenario, whenever possible of the result set generated by a database use a method that does not retrieve all metadata method, so the cache of infor- Use Dummy Queries columns of the table. mation should not be difficult to main- Avoid using getColumns to deter- To allow the application to control tain. mine characteristics about a table. how long data is retrieved in the appli- Instead, use a dummy query with cation, designers use the getClob and Avoid Null Search Patterns getMetadata. getBlob methods. However, in many One thing to avoid with metadata is Consider an application that allows cases the JDBC driver emulates these the use of null arguments or search pat- the user to choose the columns. Should methods due to the lack of true loca- terns with database metadata methods the application use getColumns to tor support in the DBMS. In these because this generates time-consum- return information about the columns cases the driver must retrieve all of ing queries. In addition, network traffic to the user or prepare a dummy query the long data across the network can increase due to unnecessary result and call getMetadata? Look at Cases 1 before exposing the getClob and set information. To avoid these prob- and 2 on the next page for the answer. getBlob methods.

126 JUNE 2001

Java COM Fiorano www.fiorano.com

JUNE 2001 127

Java COM J D B C A P P S

Sometimes retrieving long data is database server must parse the state- CASE 1: GETCOLUMNS METHOD necessary. When this is the case, ment, validate the argument types, and remember that most users don’t want to convert the arguments into the correct ResultSet WSrc = WSc.getColumns see 100KB, or more, of text on the data types. (... "UnknownTable" ...); screen. // This call to getColumns will CallableStatement cstmt = generate a query to GUIDELINE 3: conn.prepareCall ("call getCustName // the system catalogs... possi- REDUCE THE SIZE OF (12345)"); bly a join DATA RETRIEVED ResultSet rs = cstmt.executeQuery // which must be prepared, exe- One option for reducing network (); cuted, and produce traffic and improving performance is to // a result set reduce the size of any data being . . . retrieved to some manageable limit. You Example 2 WSrc.next(); can do this by calling setMaxRows, Stored procedure can be optimized string Cname = getString(4); setMaxFieldSize, and the driver-specific to use a server-side RPC. The applica- . . . J2SE SetFetchSize. Another way to reduce the tion calls the procedure by name and // user must retrieve N rows from size of the data being retrieved is to the argument values are already encod- the server decrease the column size. If the driver ed, so the load on the database server is // N = # result columns of allows you to define the packet size, use less. UnknownTable the smallest size that will meet your // result column information has needs. CallableStatement cstmt Ð now been obtained conn.prepareCall ("Call getCustName GUIDELINE 4: (?)"); USE MARKERS TO CALL cstmt.setLong (1,12345); CASE 2: GETMETADATA METHOD STORED PROCEDURES ResultSet rs=cstmt.executeQuery(); One of the most complex tasks in // prepare dummy query JDBC programming is the handling of GUIDELINE 5: PreparedStatement WSps = stored procedure calls. OPTIMIZE JDBC PERFORMANCE WSc.prepareStatement JDBC drivers can call stored proce- THROUGH SMART DISK I/O (... "SELECT * from dures on the database server either by You can improve application per- UnknownTable WHERE 1 = 0" ...);

Home J2EEexecuting the procedure as any other J2ME formance by limiting the amount of // query is never executed on the SQL query or by optimizing the execu- input/output. Connections and transac- server - tion by invoking a Remote Procedure tions are a good place to start looking for // only prepared Call (RPC) directly into the database problems. ResultSetMetaData server. Instead of using literal argu- WSsmd=wsps.getMetaData(); ments, always use parameter markers Managing Connections int numcols = for the argument markers when calling Connection management has a WSrsmd.getColumnCount(); stored procedures. direct effect on application perfor- ... Executing the stored procedure as a mance. So design your application to int ctype = SQL query results in the database server connect once and use multiple state- WSrsmd.getColumnType(n) parsing the statement, validating the ment objects, instead of performing ... argument types, and converting the multiple connections. Also, avoid con- // result column information has arguments into the correct data types. necting to a data source after establish- now been obtained Remember that SQL is always sent to the ing an initial connection. // Note we also know the column database server as a character string. For Although it’s a good thing to gather ordering within the example, look at this command: “{call driver information at connect time, // table! This information can- getCustName (12345)}.” In this case, don’t minimize the effect by connecting not be even though you might assume that the twice. For example, some applications // assumed from the getColumns argument to getCustName is an integer, establish a connection and then call a example. the argument is actually passed inside a method in a separate component that character string to the server. The data- reattaches and gathers information In both cases, a query is sent to the base server would parse the SQL query, about the driver. Applications that are server. But, in Case 1 the query must isolate the single argument value 12345, designed as separate entities should be evaluated and return a result set to and then convert the string “12345” into pass the established connection object the client, so Case 2 delivers better an integer value. to the data collection routine instead of performance. By invoking an RPC inside the data- establishing a second connection. base server, you avoid the overhead of Besides connecting twice, another Pooling is another recommended using a SQL character string. Instead, bad practice is to connect and discon- practice for managing connections. You the procedure is called by name with the nect repeatedly throughout your appli- can improve performance significantly argument values already encoded into cation to perform SQL statements. this way, especially for applications that their native data types. Here are two Connection objects can have multiple connect over a network or through the examples: statement objects associated with them. Web. Connection pooling lets you reuse Statement objects, which are defined as connections; closing connections does Example 1 memory storage for information about not close the physical connection to the Stored procedure cannot be opti- SQL statements, can manage multiple database. When an application requests mized to use a server-side RPC. The SQL statements. a connection, an active connection is

128 JUNE 2001

Java COM Persistence www.persistence.com/go/jdj

JUNE 2001 129

Java COM J D B C A P P S

reused, thus avoiding the network I/O Leaving transactions active can reduce ... needed to create a new connection. throughput by holding locks on rows for WSs.executeQuery ("UPDATE EMP SET long times, preventing other users from ADDRESS = ? Managing Commits in Transactions accessing the rows. Commit transac- WHERE first_name = ? and last_name Committing transactions is extreme- tions in intervals that allow maximum = ? and ssn = ? ly slow and disk I/O-intensive. concurrency. and address = ? and city = ? Therefore, always turn Autocommit off and state = ? by setting WSConnection.setAuto- GUIDELINE 6: and zip = ?"); Commit(false). There are two reasons CHOOSE THE RIGHT // fairly complex query for this. TRANSACTION MODEL First, the database server must flush Many systems support distributed Applications should call getBestRow- AUTHOR BIO back to disk every data page that contains transactions, that is, transactions that Indentifier() to retrieve the most optimal John Goodson is the updated or new data. This is not a span multiple connections. But distrib- set of columns (possibly a pseudo-col- vice president of sequential write, but a searched write to uted transactions are at least four times umn) that identifies any given record. research and replace existing data in the table. By slower than normal transactions due to Many databases support special columns J2SE development for default, Autocommit is on when connect- the logging and network I/O necessary to that are not explicitly defined by the user MERANT ing to a data source, and Autocommit communicate among all the compo- in the table definition but are “hidden” DataDirect. For mode usually impairs performance nents involved in the distributed transac- columns of every table (for example, nearly ten years, John because of the significant amount of disk tion. So, unless distributed transactions ROWID and TID). These pseudo- has worked closely I/O needed to commit every operation. are required, avoid using them. Instead, columns generally provide the fastest with Sun and Second, some database servers do use local transactions whenever possible. access to the data because they are point- Microsoft not provide an Autocommit mode. For And for the best system perfor- ers to the exact location of the record. But on the development this server type, the JDBC driver must mance, design the application to run because pseudo-columns are not part of of database access explicitly issue a COMMIT statement under a single Connection object. the explicit table definition, they are not standards, and is an and a BEGIN TRANSACTION for every returned from getColumns. The only active member of operation sent to the server. So, in addi- GUIDELINE 7. method of determining if pseudo- the Expert Panel for tion to the large amount of disk I/O USE GETBESTROWINDENTIFIER() columns exist is to call getBestRow- the JDBC required to support Autocommit mode, FOR COLUMN UPDATES Indentifier(). specification a performance penalty is paid of up to Use getBestRowIndentifier() to deter- Consider the previous example evolution three network requests for every state- mine the optimal set of columns to use in again:

HomeJohn holds a BS J2EEin ment issued by an application. J2ME the Where clause for updating data. computer science Using transactions can help applica- Pseudo-columns often provide the ... from Virginia Tech. tion performance, but it’s not a panacea. fastest access to the data, and these ResultSet WSrowid = columns can be determined getBestRowIndentifier() only by using getBestRow- (.... "emp", ...); Indentifier(). ... Some applications cannot WSs.executeQuery ("UPDATE EMP SET be designed to take advantage ADDRESS = ? of positional updates and WHERE first_name = ? and last_name deletes. These applications = ? and ssn = ? typically update data by form- and address = ? and city = ? ing a Where clause consisting and state = ? of some subset of the column and zip = ?"); values returned in the result // fastest access to the data! set. Some applications might formulate the Where clause by If your data source does not contain using all searchable result special pseudo-columns, then the result columns in calling get- set of getBestRowIndentifier() consists of Metaphore PrimaryKeys(), or in calling the columns of the most optimal unique getIndexInfo() to find columns index on the specified table (if a unique that might be part of a unique index exists). Therefore, your applica- index. These methods typically tion does not need to call getIndexInfo to work, but might result in com- find the smallest unique index. plex queries. Consider the following Conclusion www.cyberons.com example: With thoughtful design and imple- mentation, you can improve the per- ResultSet WSrs = formance of your JDBC applications. By WSs.executeQuery following the suggested guidelines in this ("SELECT article, your applications can run more first_name, last_name, efficiently and generate less network traf- ssn, address, city, state, fic. Review your JDBC applications to zip find hidden treasure that will boost per- formance and reduce network traffic. FROM emp"); // fetchdata [email protected]

130 JUNE 2001

Java COM Softwired www.softwired-inc.com

JUNE 2001 131

Java COM BOOK REVIEW Debugging Java:Troubleshooting for Programmers Learn Debugging Skills

BY WILL DAVID MITCHELL REVIEWED BY JAMES MCGOVERN PUBLISHED BY OBBORNE/MCGRAW HILL J2SE

In my travels I’ve run across lots of bad Java code (some of I liked Chapters 6–8 the best. Chapter 6 covers the 80/20 which I’ve written myself). Usually it’s due to unrealistic proj- rule, which says that 80% of your bugs are most likely to ect deadlines, bad estimates for how long something will appear in 20% of your code. He notes additional tools for take, no architecture in place, and developers’ not really tracking down bugs that are syntactic in nature, and even understanding the subtleties of the language. suggests using LINT tools for finding them. For those who are Many people have learned Java by reading those 1,000- not familiar with LINT tools, they’re parsers that identify page books where you cut and paste code from the accompa- potential syntax errors in code that will compile but may lead nying CD. Usually this teaches you how to get simple things to problems. Its origin comes from the C/C++ world. For working but doesn’t help you learn Java. This book is the solu- instance, a LINT tool will flag the following code as a poten- tion to all these problems. tial error: String abc = "\0123"; it will say you may have tried The author, who has years of experience teaching com- to incorrectly specify an Octal value. Other checks would puter science, emphasizes the importance of learning debug- include whether a loop should start with 0 or 1, using = in ging skills. Industry research has shown that people who place of ==, memory leaks, thread conflicts, and Boolean

Homelearn J2EEthese skills first, master computer languages J2ME signifi- checks. cantly faster. For the beginning developer, this helps you Chapter 7 talks about best practices, which will further avoid picking up bad coding habits. help you develop good coding habits. Chapter 8 discusses The book is 13 chapters, 460 pages, and reasonably priced automated debugging and using debugging tools such as at $39.99 ($31.99 on Amazon). Unlike many of the other Java Sitraka Software’s JProbe. books on the market, even the appendix provides useful Chapter 9 covers what the author calls “Grand De- information and is not filler. The text contains useful tips and bugging Strategies,” which will give you insight on how to advanced troubleshooting techniques for tracking down avoid regression errors. Chapter 10 covers black box test- bugs. It also provides guidance on how to avoid scope creep ing. Black box testing checks a particular class’s function- and reduce deadline pressures by using proper estimation ality by determining if its public interface performs techniques. according to specification without regard to implementa- Chapter 1 begins with a profound statement: “No amount tion details. of testing finds all bugs.” There’s no such thing as perfect Chapter 11 is obligatory reading for anyone developing code. With this in mind, the author guides you to use prioriti- threaded applications. You’ll learn when and where to make zation for finding and fixing bugs. Chapter 2 explains why your methods synchronized to avoid corrupted state. bugs exist, which on the surface seems obvious (the other Synchronized methods carry a heavy performance penalty in developers aren’t always clueless). The author suggests that Java and usually execute at 25% of the speed relative to a non- developers write documentation before writing code. The synchronized method. You’ll learn how to make your applica- documentation will turn into a programming specification tions faster. that can be reviewed by the business community, which in The last two chapters are final thoughts about political turn will help relieve pressure and buy you more time to correctness as well as conducting other forms of testing, such develop properly. as stress and fault insertion. There’s plenty of humor in both Chapter 3 goes into actually practicing creating bugs so of these chapters as they even give you an idea on how to get you’ll be familiar with the outcomes such as exceptions or your users to think they did something wrong when hitting a “not a number.” Chapter 4 talks about risk factor analysis and bug in an application. provides great insight into figuring out how long something Overall, this is a high-quality, easy-to-read book that will take to develop. Chapter 5 discusses the usage of IDEs promotes learning. I recommend it for both beginning as and brings up some very good recommendations. You’ll learn well as advanced Java developers. In fact, I’d suggest every how to use macros to reduce defective code. The author even project manager buy a copy of this book for his or her team points out how to use Microsoft Word as your IDE and inte- members and make it mandatory reading. This book defi- grate spell checking and error correction facilities. nitely rates five stars.

[email protected] AUTHOR BIO James McGovern is an enterprise architect for Hartford Technology Services Company, L.L.C., an information technology consulting and services firm dedicated to helping businesses gain competitive advantage through the use of technology. He’s a coauthor of multiple books on Java and a member of several Internet advisory boards.

132 JUNE 2001

Java COM IAM www.iamx.com

JUNE 2001 133

Java COM JAVA QUIRKS

Dates and Calendars Dealing with pure dates using the BigDate class J2SE

WRITTEN BY Dealing with dates and times is probably the most confusing ROEDY GREEN aspect of Java for newbies.There are three reasons for this:

1. The date and time classes are the set): The number of millisecond cor- year in which most of its days lie. This most poorly designed of all the Sun rection to account for daylight saving means that week 1 of any year is the class libraries. time; 0 if daylight saving time is not in week that contains 4 January or, 2. The standard class libraries force you effect for the time stamp specified. If a equivalently, week 1 of any year is the to deal with time zone and time of one-hour daylight saving is in effect, week that contains the first Thursday day, even when they’re irrelevant to the offset will be 3,600,000. Add both in January. Most years have 52 weeks, your problem. the DST and the zone offsets to UTC but years that start on a Thursday and 3. The vocabulary used in the various to get local time. leap years that start on a Wednesday date classes is inconsistent. • ISO day of week: Day of the week 1 to 7 have 53 weeks. January 1 may well be for this date according to the ISO stan- in week 53 of the previous year!

Home J2EEVocabulary J2ME dard IS-8601. Monday=1...Sunday=7. • Month of year: January to December; • Day of month: The day of the month • ISO week number: Week number 1 to note that in GregorianCalendar, 1.31, sometimes called the date. 53 of the year that this date falls in, January is month 0. In contrast, in • Day of week: Day of the week for a according to the rules of the ISO stan- DateFormat, January is month 1. given date; for example, Sunday=1 dard IS-8601, section 5.5. A week that • Time stamp: An instant in cosmic ...Saturday=7. lies partly in one year and partly in time expressed in milliseconds since • DST offset (daylight saving time off- another is assigned a number in the January 1, 1970, 0:00 in UTC. It can be a positive or negative 64-bit-long CLASS PURPOSE number. These are sometimes called dates or times. java.text.DateFormat Used to convert a date to or from a String. Contains an associated • Offset: How many milliseconds differ- TimeZone. ence local time is from UTC. If you live in North America this will be a java.text.SimpleDateFormat Used to convert a date to or from a String when you want precise control negative number. It’s the sum of both over the format. Contains an associated TimeZone. the zone and DST offsets. You add the DST offset and the zone offset to UTC java.util.Calendar Abstract class that’s the mother of all Calendars such as to get local time. GregorianCalendar. It owns the dozens of magic date constants such as • UTC: For all practical purposes it’s just Calendar.JANUARY = 0; Calendar.SUNDAY = 1; and Calendar.YEAR = 1. standard time in Greenwich, England. The people in Greenwich use daylight java.util.Date Sun’s first attempt at a Date class. I refer to it as the lemon of Java. It’s now saving time, so the term GMT or almost completely deprecated. It’s now basically just a wrapper around a Greenwich time would be ambiguous. UTC date/timestamp long milliseconds since 1970. Unfortunately, it’s still • Week of year: There are many possi- not completely gone. ble definitions. The default GregorianCalendar definition de- java.util.GregorianCalendar Used to do date calculations. Each GregorianCalendar contains a UTC time- pends on whether you consider stamp and a TimeZone. Sunday or Monday as the first day of the week, setFirstDayOfWeek (the java.util.TimeZone Contains the name of a time zone and how many hours’ difference from UTC default is locale specific), and how that time zone is. It also contains the rules for when daylight saving begins many days you insist must be pres- and ends. Time zones are named after cities. They’re not the usual names. ent in the first week of the year, setMinimalDaysInFirstWeek cmp.business.BigDate A simple date class for pure date calculations when you don’t want the (default 1). The first week of the year complication of TimeZones and times. Not part of Sun’s libraries. You can is week 1. January 1 may sometimes download it from http://mindprod.com/products.html#BIGDATE be considered in week 53 of the pre- vious year. TABLE 1 Classes to solve problems involving dates

134 JUNE 2001

Java COM software ag www.softwareagusa.com

JUNE 2001 135

Java COM JAVA QUIRKS

• Zone offset: How many milliseconds Note: Specify the time stamp with gc = new GregorianCalendar(); difference local time is from UTC if GregorianCalendar.set in terms of east- gc.setLenient(false ); you ignore any daylight saving time ern standard time, not UTC. Internally /* Bug only manifests if lenient correction. If you live in North the time stamp is stored as UTC. set false */ America, this will be a negative num- • Don’t create the TimeZone object gc.set(2001 , 1, 1, 1, 0, 0); ber. You add both the DST and the with new. nYear = gc.get (Calendar.YEAR); zone offsets to UTC to get local time. • The getTime().getTime() is not an /* throws exception */ The bug dis- error. The first getTime retrieves a Date appears at 7AM on 2001/01/01 for The Cast object from GregorianCalendar, and the MST. You need to use quite a few different second retrieves a time stamp from the classes to solve even a simple problem Date object. GregorianCalendar is controlled by a involving dates (see Table 1). For details • Elapsed time in days is not simply giant pile of untyped int magic constants. on these classes download the Sun hours/24. It’s much more complicated This technique totally destroys any hope JavaDoc from http://java.sun.com/j2se/ than that. of compile-time error checking. For 1.3/#documentation. example, to get the month use Gregorian- J2SE How Long Until Christmas,Daddy? Calendar.get(Calendar.MONTH)). Displaying a Date This sounds like a simple problem. GregorianCalendar has the raw This program converts a date to a Programmers posted many different GregorianCalendar.get(Calendar.ZONE String for display using the default date solutions to the comp.lang.java.pro- _OFFSET) and the daylight saving format (see Listing 1). That format grammer newsgroup before the gurus GregorianCalendar.get(Calendar.DST_O depends on what the user has config- stopped finding holes in the logic. Part FFSET), but no way to get the actual ured as his or her preferred date format of the problem is that the question can time zone offset being used. You must in the OS. have many answers. I show eight plausi- get these two separately and add them Note: You must tell the Simple- ble solutions in Listing 5. together. DateFormat your GregorianDate twice, GregorianCalendar.set(year, month, once to get the time zone and once to Gotchas day, hour, minute) doesn’t set the sec- get the time stamp. java.util.GregorianCalendar has far onds to 0. fewer bugs and gotchas than the old DateFormat and GregorianCalendar Displaying a Date with Precise Control java.util.Date class, but it’s still no pic- don’t mesh properly. You must specify If you want to control how your date nic. the Calendar twice, once indirectly as a

Home J2EElooks, use a mask like the one in Listing J2ME 2. Had there been programmers when Date. Note: You must tell the Simple- daylight saving time was first proposed, If the user hasn’t configured the time DateFormat your GregorianDate twice, they would have vetoed it as insane and zone correctly, it’ll default quietly to once to get the time zone and once to intractable. With daylight saving there’s either PST or GMT. get the time stamp. a fundamental ambiguity. In the fall In GregorianCalendar, months are when you set your clocks back one hour numbered starting at January=0, rather Parsing a Date at 2 a.m., there are two different instants than 1 as everyone else on the planet does. To convert a date from a String to an in time both called 1:30 a.m. local time. Yet days start at 1, as do days of the week internal format is quite a production. You can tell them apart only if you with Sunday=1, Monday=2...Saturday=7. Listing 3 shows one way of doing it. record whether you intended daylight However, DateFormat.parse behaves in Note: Be very careful with time zones. saving or standard time with the read- the traditional way with January=1. If you don’t specify one, your date will be ing. Unfortunately, there’s no way to tell AUTHOR BIO interpreted using the the local default GregorianCalendar which one you Learning More Roedy Green maintains time zone. If the user hasn’t configured it intended. You must resort to telling it The calendar classes are full of sur- the Java glossary of correctly in his or her OS, you may get the local time with the dummy UTC prises. To learn more about them see Canadian Mind Products Pacific standard time or GMT without time zone to avoid the ambiguity. http://mindprod.com/gotchas.html#D (http://mindprod.com). He warning. Programmers usually close their eyes to ATE. spends most of his time this problem and just hope nobody does Dealing with pure dates is much sim- in the comp.lang.java.* Elapsed Time in Hours Between Two Time Stamps anything during this hour. pler using the BigDate class. Download newsgroups helping new- Look at the example program in Millennium bugs are still not out of it from http://mindprod.com/prod- bies and has been writing Listing 4 to calculate how many hours the calendar classes. Even in JDK 1.3 ucts.html#BIGDATE. custom computer until the next presidential inaugura- there’s a 2001 bug. Consider the follow- programs since 1963. tion. ing code: [email protected]

GregorianCalendar inauguration = new GregorianCalendar(est); Listing 1 inauguration.set(2005, Calendar.JANUARY, 20, 12, 0, 0); import java.text.DateFormat; import java.util.Calendar; // locale specific: e.g. Jan 20, 2005 import java.util.GregorianCalendar; DateFormat df = DateFormat.getDateInstance(); import java.util.TimeZone; // display inauguration day as a String // set timezone public class Inauguration1 df.setCalendar(inauguration); { static public void main(String [] args) // set timestamp { String dateString = df.format(inauguration.getTime()); // inauguration day is Thursday 2005 January 20 noon Eastern System.out.println (dateString); Standard Time. } TimeZone est = TimeZone.getTimeZone ("America/New_York"); }

136 JUNE 2001

Java COM epicdata www.epicdata.com/expresso

JUNE 2001 137

Java COM MILLIS_PER_HOUR; Listing 2 System.out.println (hours + " hours until the inauguration."); import java.text.SimpleDateFormat; } import java.util.Calendar; } import java.util.GregorianCalendar; import java.util.TimeZone; Listing 5 // display inauguration day as a String import cmp.business.BigDate; public class Inauguration2 import java.util.Calendar; { import java.util.GregorianCalendar; static public void main(String [] args) import java.util.TimeZone; { /** // inauguration day is Thursday 2005 January 20 noon Eastern * How Long until Christmas? Standard Time. */ TimeZone est = TimeZone.getTimeZone ("America/New_York"); public class Christmas GregorianCalendar inauguration = new GregorianCalendar(est); { inauguration.set(2005, Calendar.JANUARY, 20, 12, 0, 0); static final int MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; // mask for: Thursday 2005/01/20 12:00:00 PM EST Eastern Standard public static void main (String [] args) Time { SimpleDateFormat sdf = new SimpleDateFormat("EEEE yyyy/MM/dd // How long till Christmas? (Sun's way.) hh:mm:ss aa zz : zzzzzz"); // this code will give a negative number just after Christmas.

J2SE System.out.println ("Your child asks, how long is it until " // set timezone + "Christmas?"); sdf.setCalendar(inauguration); System.out.println ("Here are the possible answers you might give" + " to an American child:"); // set timestamp GregorianCalendar now = new GregorianCalendar(); String dateString = sdf.format(inauguration .getTime()); int thisYear = now.get(Calendar .YEAR); System.out.println (dateString); } // You may open presents at 7 AM December 25, local time } System.out.println ("You may open your presents at 7 AM Christmas" + " morning." ); GregorianCalendar christmas = new GregorianCalendar(thisYear, Listing 3 Calendar.DECEMBER, 25, 7, 0, 0); import java.text.ParseException; // millis since 1970 Jan 1 import java.text.SimpleDateFormat; long christmasTimeStamp = christmas.getTime( ).getTime( ); import java.util.Calendar; long nowTimeStamp = now.getTime() .getTime(); import java.util.Date; double dayUnitsDiff = (christmasTimeStamp - nowTimeStamp) / import java.util.GregorianCalendar; (double) MILLISECONDS_PER_DAY; import java.util.TimeZone; System.out.println ("1. It is " + dayUnitsDiff + " day units of // parse a date 24" public class Inauguration3 + " hours until you may open your presents."); { System.out.println ("2. It is " + Math.ceil(dayUnitsDiff) + " day" Home J2EE J2ME static public void main(String [] args) + " units of 24 hours rounded up until you may open your " { + "presents."); String dateString = "2005/01/20"; System.out.println ("3. It is " + Math.round(dayUnitsDiff) + // define the format of the date " day units of 24 hours rounded until you may open your " SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); + "presents."); // set timezone to use in interpreting the date System.out.println ("4. It is " + Math.floor(dayUnitsDiff) + TimeZone est = TimeZone.getTimeZone ("America/New_York"); " day units of 24 hours rounded down until you may open your" GregorianCalendar inauguration = new GregorianCalendar(est); + " presents."); sdf.setCalendar(inauguration); try int gmtChristmasOrdinal = (int) (christmasTimeStamp / { MILLISECONDS_PER_DAY); // set timestamp int gmtNowOrdinal = (int) (nowTimeStamp / MILLISECONDS_PER_DAY); Date date = sdf.parse (dateString); int gmtDiffInDays = gmtChristmasOrdinal - gmtNowOrdinal; inauguration.setTime(date); System.out.println ("5. Children in Greenwich have " + // inauguration is now ready with both timezone and timestamp gmtDiffInDays + " sleeps (midnight crossings) to go until\n" + } "you may open your presents.\n" + catch (ParseException e) "They may open theirs even sooner."); { System.out.println ("bad date"); // For children living in the USA, the timezone offset will be } negative. } int christmasZoneOffset = christmas.get(Calendar .ZONE_OFFSET) } now.get(Calendar .DST_OFFSET); int localChristmasOrdinal = (int) ((christmasTimeStamp + christmasZoneOffset) / MILLISECONDS_PER_DAY); Listing 4 int nowZoneOffset = now.get(Calendar .ZONE_OFFSET) + import java.util.Calendar; now.get(Calendar .DST_OFFSET); import java.util.GregorianCalendar; int localNowOrdinal = (int) ( (nowTimeStamp + nowZoneOffset) / import java.util.TimeZone; MILLISECONDS_PER_DAY); // Hours until the next presidential inauguration int localDiffInDays = localChristmasOrdinal - localNowOrdinal; public class Inauguration4 System.out.println ("6. You have " + localDiffInDays + { " sleeps (midnight crossings) to go."); static final int MILLIS_PER_HOUR = 60 * 60 * 1000; static public void main(String [] args) // how long till Christmas? ( with BigDate. ) { // this code will give a negative number just after Christmas. // inauguration day is Thursday 2005 January 20 noon Eastern BigDate today = BigDate .localToday(); Standard Time. BigDate nextChristmas = new BigDate(today.getYYYY( ), 12, 25); TimeZone est = TimeZone.getTimeZone ("America/New_York"); System.out.println ("7. Uncle Roedy's Bigdate says it is " + GregorianCalendar inauguration = new GregorianCalendar(est); (nextChristmas .getOrdinal() - today.getOrdinal()) + inauguration.set(2005, Calendar.JANUARY, 20, 12, 0, 0); " sleeps until Christmas."); // now is current time, using default timezone int [ ] age = BigDate .age( today, nextChristmas); GregorianCalendar now = new GregorianCalendar(); System.out.println ("8. Or put another way " + age[0 ] + // milliseconds since 1970 Jan 1 " years and " + age [1] + " months and " + age[2] + " days to" long epochInauguration = inauguration.getTime( ).getTime( ); + "go."); long epochNow = now.getTime().getTime(); } } double hours = (double) (epochInauguration - epochNow)/

138 JUNE 2001

Java COM Muska & Lipman www.makingthetechnicalsale.com

JUNE 2001 139

Java COM FIRST LOOK

reliable applications in a fraction of the time it sion EJB, and entity EJB technologies with only would take using current development tools. limited knowledge of the J2EE specs. So how does it do this? Let’s step through Compuware Corporation’s the features of OptimalJ. Active Synchronization of Models and Code OptimalJ provides live synchronization Rapid Enterprise Java Development between the application models and the Java Developers use OptimalJ to interact with a code. Developers can make changes to appli- visual model of the application that can either be cations during or after release using the visual imported from other modeling tools using the XMI model, and the affected code will be regenerat- or DTD interfaces or built from scratch with the ed automatically. The OptimalJ Source Editor Optimal J visual modeler. OptimalJ uses this model to gener- identifies managed source code, business rule ate the architectural submodels and even the code, and custom source code to accelerate WRITTEN BY BOB HENDRY working code needed to implement a complete understanding and enable you to make modifi- application. Simple graphical windows, editors, cations during development or after release of J2SE and wizards walk developers through each stage of the software. This feature really underlines one the design, generation, and deployment, reducing of the core benefits of OptimalJ, one that will the time spent on tedious implementation tasks. become more apparent as Java business appli- In addition to its model-based interfaces, the cations reach their second and third iterations. integrated development environment based on In most projects today the application the open-source IDE, NetBeans, provides a source model is not kept up to date and is discarded editor, class browser, form editor, and debugger to once the initial implementation is completed. enable developers to view, modify, and customize Developers who join projects late or have to the generated application. So-called “free-blocks” take the first cut and create new versions will in the generated code allow existing classes to be benefit from being able to make modifications AUTHOR BIO imported and called by the application, making directly at the model level, confident that Bob Hendry is a Java instructor at the Illinois Institute of use of work done outside of OptimalJ. OptimalJ has kept the implemented code fully Technology. He’s the author of Java as a First Language. Using this visual paradigm, developers are shield- synchronized with that model. ed from the complexity of coding to the distributed J2EE development. Less experienced Java developers Integrated Deployment Environment

Home [email protected] can quickly J2ME build or make modifications to business OptimalJ automatically deploys to many of the applications. Advanced developers are freed from leading J2EE production servers including the fully many of the repetitive coding tasks and can focus on integrated Compuware OptimalServer, offered as architecture refinements or customization. an option to OptimalJ. OptimalJ also includes an evelopment of enterprise applications open-source test environment that contains a Web using Java technologies is not for the faint- Dynamic Business Rules Implementation server and EJB container. The OptimalJ deploy- Dhearted. Writing to the J2EE specs is prov- Once the basic application structure has been ment packager automatically deploys to this local ing to be complex, difficult, and tedious – slowing defined in the model, application differentiation environment, allowing developers to directly test down advanced Java developers and creating a can be built-in using a flexible business rule edi- as they develop without worrying about the com- barrier to entry for many mainstream developers. tor. Simple scripting enables developers to add plexities of deployment. In the time it would nor- With advanced Java developers in short both static and dynamic business rules at the mally take to create the basic business design of an supply and even among them, experience with model level. The business rules editor can define application using a visual modeling tool, OptimalJ EJB development is rare, thus slowing time-to- referential data constraints, which ensure data can finish coding the entire application and deploy market for business applications and challeng- integrity and consistency, and event condition it. Developers can spend their time refining the ing application reliability and performance. rules that provide support for conditional pro- design and the advanced development staff can To solve this problem we’d ideally want to sim- cessing. Static rules are generated as Java code in concentrate on adding new patterns or customiz- plify Java development to allow developers of all lev- the application, and dynamic rules are stored in a ing the existing ones. els to build reliable, high-performance components rules database on the application server to allow and provide them with a framework for delivering for modification at runtime. By separating out Summary J2EE-compliant business applications. Compuware business rules as easily identifiable elements in OptimalJ represents a new paradigm in Java Corporation believes that it has built such a solution this way, many business requirement changes development, promising productivity gains simi- with OptimalJ, a new breed of development envi- can be quickly and easily implemented. lar to those experienced with the popular and ronment that enables the rapid design and devel- advanced proprietary 4GL products of yesteryear. opment of J2EE business applications. Pattern-Driven Application Generation It adheres to open standards such as J2EE, EJB, Using OptimalJ, developers can generate OptimalJ can generate all the application JSP, XML, and MOF, uses open source compo- complete working applications directly from a code required for running an application. To do nents and industry patterns, and is even IDE and visual model, bypassing many of the routine cod- this it first generates models for the Web (JSP), application-server independent. (It supports ing tasks associated with EJB development. business logic (EJB), and data tiers, which are NetBeans or Forte for Java as its IDE and the Design patterns implement best practices for then used to generate the actual Java code, busi- iPlanet Application Server, IBM WebSphere, or architecture and coding, and an active synchro- ness rules, and data implementation scripts. BEA WebLogic as application servers.) nization feature keeps the code and model in step The generated models and code are based on Compuware has made a clear investment in and up-to-date, allowing application changes at implementation templates called patterns, the J2EE development market and is aligning any stage of the development life cycle. which encapsulate knowledge and best prac- other products such as its DevPartner and The promise is that OptimalJ, by simplifying tices for coding to the J2EE specification and fol- QACenter testing suites alongside OptimalJ to the development of J2EE applications, will enable low OMG standards. Developers can quickly provide a Java tools platform to make develop- developers of all experience levels to produce generate full working applications using JSP, ses- ment of J2EE applications much easier.

140 JUNE 2001

Java COM Internet World www.internetworld.com/chicago2001

JUNE 2001 141

Java COM Silverstream www.silverstream.com/onlineseminars/jad

142 JUNE 2001

Java COM Silverstream www.silverstream.com/onlineseminars/jad

JUNE 2001 143

Java COM J2ME EDITORIAL WRITTEN BY JASON BRIGGS

WRITERS IN THIS ISSUE BILL BALOGLU, MICHAEL BARBARELLI, JASON BRIGGS, GLEN COATES, GLEN CORDREY, DAVID DEMING, BRADY FLOWERS, NEAL FORD, JEREMY GEELAN, JOHN GOODSON, RICHARD GREEN, ROEDY GREEN, BOB HENDRY, TYLER JEWELL, CHRIS KAMPMEIER, KENT V. KLINNER III, J2ME SATYA KOMATINENI, IRVIN J. LUSTIG, JAMES MCGOVERN, JIM MILBERY, PATRICK SEAN NEVILLE, BILLY PALMIERI, AJIT SAGAR, BRUCE SCOTT, Critical Mass DALE B. WALKER, ALAN WILLIAMSON, BLAIR WYMAN SUBSCRIPTIONS echnology seems at times to proceed some serious fun with it. FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, at a breakneck pace. The downside Also on my list is a Java-enabled PDA PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT Tto this expectation for a consistently from Sharp. Back in March a news item on SUBSCRIPTION HOTLINE:[email protected] high rate of technological improvement is Bloomberg declared that Sharp would be COVER PRICE: $4.99/ISSUE that at other times, progress comes at a using Java on its communications devices DOMESTIC: $69.99/YR. (12 ISSUES) more leisurely pace – analogous to watch- with PDAs slated to be first. Since then, it CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. ing paint dry or sloth racing. has been hard to find any further informa- (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. For example, announcements about tion on Sharp’s plans – so once again it’s a PUBLISHER,PRESIDENT,AND CEO: FUAT A. KIRCAALI chip-design developments and the associat- case of twiddling your thumbs until a prod- VICE PRESIDENT,PRODUCTION & DESIGN: JIM MORGAN ed higher CPU speeds seem to appear week- uct is officially released. SENIOR VICE PRESIDENT,SALES & MARKETING: CARMEN GONZALEZ ly. , IBM, AMD, (name your company), J2ME presents a unique opportunity for VICE PRESIDENT,SALES & MARKETING: MILES SILVERMAN are engaged in a constant competition to developers. Try as I might I can’t think of VICE PRESIDENT,SYS-CON EVENTS: CATHY WALTERS TRADE SHOW MANAGER: outdo the others as they increase speed, another time in computing history when a DONA VELTHAUS SALES EXECUTIVES,EXHIBITS: MICHAEL PESICK reduce power consumption, and introduce development environment was freely avail- RICHARD ANDERSON new manufacturing processes. However, able before most people had access to the ADVERTISING SALES DIRECTOR: ROBYN FORMA waiting for those advances to trickle down hardware. (Note: This can mean one of two ADVERTISING ACCOUNT MANAGER: MEGAN RING to consumer devices definitely rates as one things: either there hasn’t been another occa- ADVERTISING ASSISTANT: CHRISTINE RUSSELL of those “paint-drying” experiences. sion, or my knowledge of the history of the ASSOCIATE SALES MANAGER: CARRIE GEBERT SALES ASSISTANT: ALISA CATALANO

HomeAnother J2EE example is the recent J2SE announce- industry is embarrassingly lacking.) Whether CIRULATION MANAGER: CHERIE JOHNSON ment regarding organic LEDs (light emitting this is true or not, we as programmers have the ART DIRECTOR: ALEX BOTERO diodes) by Eastman Kodak and Sanyo. unusual chance to become completely famil- ASSISTANT ART DIRECTOR: CATHRYN BURAK Potentially, organic LEDs will be simpler (and iar with the platform very early on. Certainly GRAPHIC DESIGNERS: ABRAHAM ADDO therefore cheaper) to produce than current liq- you can imagine a critical mass of developers RICHARD SILVERBERG uid crystal displays; they’ll shine brighter than and applications building up in the near future AARATHI VENKATARAMAN WEBMASTER: ROBERT DIAMOND LCDs and consume less power. A number of and, as a consequence, even more Java- WEB DESIGNER: STEPHEN KILMURRAY large companies are racing to bring these dis- enabled devices appearing on the market as CAROL AUSLANDER plays to the mass market, and technology like manufacturers rush to take advantage of this. WEB DESIGNER INTERN: PURVA DAVE this will eventually have a direct effect on you In addition to bringing opportunities, JDJSTORE.COM: ANTHONY D. SPITZER as a J2ME developer. Forget those stock-ticker J2ME also brings its own novel collection of ASSISTANT CONTROLLER: JUDITH CALNAN CREDIT & COLLECTIONS: and mobile-commerce applications you’re challenges. The platform is targeted at such CYNTHIA OBIDZINSKI ACCOUNTS PAYABLE: JOAN LAROSE working on – it’s time for some truly vivid mul- a broad range of devices, from the most tiny timedia. Though, on reflection, it will no doubt to things like set-top boxes, which can be EDITORIAL OFFICES turn into a waiting game once again before close to a computer in size, there’s not much SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 consumers, or developers for that matter, real- chance we’ll get bored with the choices. TELEPHONE: 201 802-3000 FAX:201 782-9600 ly see the benefit. Might as well go back to that There’ll be new virtual machines to come to JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly stock ticker after all. grips with, new APIs, and new ways of doing (12 times a year) for $69.99 by SYS-CON Publications, Inc., 135 Chestnut Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at High on my wish list (to see in action), things. Micro Edition seems destined to sat- Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address after reading a recent press release from isfy the saying, “Variety is the spice of life.” changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., aJile Systems (www.ajile.com), is the It’s an exciting time for mobile and 135 Chestnut Ridge Road, Montvale, NJ 07645. JEMcore Java processor core, which uses embedded Java development. It’ll be very ©COPYRIGHT for its native instruction set. interesting to see what happens, both to Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. To quote directly from the release: “The the platform and within the industry over No part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopy or any information storage and aJile hardware, with 100% Java technology the next few years. retrieval system, without written permission. For promotional reprints, contact reprint coordi- software drivers, delivers a 320x240 pixel, This is my first foray as an editor for JDJ, nator. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its readers to use the articles submitted for publication. 18-bit, full-color display running at 15 and I’m looking forward to bringing you as frames per second.” When you consider much useful information about mobile W ORLDWIDE DISTRIBUTION BY that the minimum frame rate for smooth development and the embedded market as CURTIS CIRCULATION COMPANY animation is usually cited as 24 frames per can be squeezed into these pages. Perhaps 730 RIVER ROAD, NEW MILFORD NJ 07646-3048 PHONE: 201 634-7400

second, JEMcore is not quite there, but it’s a smaller font and a magnifying glass Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., definitely close enough so you can have would be helpful? 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, service marks or trademarks of their respective companies. [email protected] AUTHOR BIO Jason Briggs works as a Java analyst programmer in London. He’s been officially developing in Java for three years – unofficially for just over four.

144 JUNE 2001

Java COM Esmertec www.esmertec.com

JUNE 2001 145

Java COM INDUSTRY COMMENTARY WRITTEN BY BRUCE SCOTT

The New World of Mobile Computing EDITORIAL ADVISORY BOARD JEREMY ALLAIRE, TED COOMBS, ARTHUR VAN HOFF, JIM MILBERY, GEORGE PAOLINI, KIM POLESE, SEAN RHODY, RICK ROSS, AJIT SAGAR, By 2004, each corporate knowledge worker will have 3 to 4 different BRUCE SCOTT, RICHARD SOLEY, ALAN WILLIAMSON computing and information access devices that will be used to access FOUNDING EDITOR/CHIEF CORPORATE EDITOR: SEAN RHODY J2ME various applications. EDITORIAL DIRECTOR: JEREMY GEELAN —META Group EDITOR-IN-CHIEF: ALAN WILLIAMSON EXECUTIVE EDITOR: M’LOU PINKHAM ASSOCIATE ART DIRECTOR: LOUIS F. CUFFARI n the new world of mobile computing, ing information on everything, everywhere, and MANAGING EDITOR: CHERYL VAN SISE according to IDC, it’s estimated that by launching the mobile revolution. EDITORS: NANCY VALENTINE the year 2004 there will be 40 million Now, Java applications can extend data GAIL SCHULTZ I ASSOCIATE EDITOR: JAMIE MATUSOW active computing devices, up from 11 mil- beyond servers and onto smart mobile devices ASSISTANT EDITOR: GREGORY LUDWIG lion currently. The growth of other handheld such as notebooks and subnotebooks, providing EDITORIAL INTERN: NIKI PANAGOPOULOS TECHNICAL EDITOR: BAHADIR KARUV, PH.D. devices, like mobile phones, will grow from a strong foundation for the deployment of front- PRODUCT REVIEW EDITOR: JIM MILBERY 300 million devices to a billion by 2004. office, back-office, and e-business applications to INDUSTRY NEWS EDITOR: LEE PARSEGHIAN What is driving this anticipated growth? the mobile worker. Moving out and beyond J2EE EDITOR: AJIT SAGAR There are several factors: the increasing mobile enterprise applications, the unique fea- demand for information birthed with the tures of the small-footprint Java application data- SUBSCRIPTIONS FOR SUBSCRIPTIONS AND REQUESTS FOR BULK ORDERS, launch of the Internet, and the launch of vari- base allow sophisticated applications to be PLEASE SEND YOUR LETTERS TO SUBSCRIPTION DEPARTMENT ous technologies enabling the access of infor- deployed on PDAs, smart phones, and many SUBSCRIPTION HOTLINE:[email protected] mation anywhere, anytime, and on every- other Java-enabled consumer devices. COVER PRICE: $4.99/ISSUE thing. One of the primary technologies driving In the new world of mobile data, data is DOMESTIC: $69.99/YR. (12 ISSUES) this growth is Java and Java-enabled devices, more available and can fit in your pocket and CANADA/MEXICO: $79.99/YR. OVERSEAS: $99.99/YR. (U.S. BANKS OR MONEY ORDERS). BACK ISSUES: $10/EA., INTERNATIONAL $15/EA. and the development of Java-based business be accessed or updated on diverse mobile plat- PUBLISHER,PRESIDENT,AND CEO: applications that transform today’s gadgets forms. Java is the programming language of the FUAT A. KIRCAALI VICE PRESIDENT,PRODUCTION & DESIGN: JIM MORGAN into business tools. The power of Java-enabled new world. Java aligns with Internet pervasive- SENIOR VICE PRESIDENT,SALES & MARKETING: CARMEN GONZALEZ devices empowered with a business applica- ness. Java and Java APIs are owned by the devel- VICE PRESIDENT,SALES & MARKETING: MILES SILVERMAN VICE PRESIDENT,SYS-CON EVENTS: CATHY WALTERS tion using a Java database can always be avail- oper community, allowing Java to evolve TRADE SHOW MANAGER: DONA VELTHAUS

Homeable and act independently J2EE of a constant J2SE con- according to the needs of the community, SALES EXECUTIVES,EXHIBITS: MICHAEL PESICK nection to servers. The user can browse, rather than by an oligopoly of a few large tech- RICHARD ANDERSON ADVERTISING SALES DIRECTOR: ROBYN FORMA update offline, and synchronize data occa- nology companies. With Java, a win-win sce- ADVERTISING ACCOUNT MANAGER: MEGAN RING sionally or as required. nario is created. By supporting Java, platform ADVERTISING ASSISTANT: CHRISTINE RUSSELL Like electricity, information devices will vendors can attract millions of Java application ASSOCIATE SALES MANAGER: CARRIE GEBERT SALES ASSISTANT: ALISA CATALANO become ubiquitous through every aspect of developers. By using Java, application vendors CIRULATION MANAGER: CHERIE JOHNSON modern life, providing information where and can make their applications available to an ART DIRECTOR: ALEX BOTERO when it’s wanted. The demand for information unprecedented number of platforms. ASSISTANT ART DIRECTOR: CATHRYN BURAK GRAPHIC DESIGNERS: ABRAHAM ADDO will push technology to deliver data with low For applications on mobile devices to be RICHARD SILVERBERG cost of ownership and simplicity. Server-based available always, disconnected usage is the AARATHI VENKATARAMAN WEBMASTER: applications and server appliances will be key. Unreliable and costly wireless connec- ROBERT DIAMOND WEB DESIGNER: STEPHEN KILMURRAY developed to manage groups of small appli- tions, limited server capacity, and limited CAROL AUSLANDER ance-like devices. The Java application data- battery life make applications dependent on WEB DESIGNER INTERN: PURVA DAVE JDJSTORE.COM: ANTHONY D. SPITZER base will be key to making all of this happen. constant wireless access impractical and of ASSISTANT CONTROLLER: JUDITH CALNAN We’re leaving a world where informa- limited use. People want their mobile appli- CREDIT & COLLECTIONS: CYNTHIA OBIDZINSKI tion is stored in large, complex, and expen- cations to be available regardless of whether ACCOUNTS PAYABLE: JOAN LAROSE sive systems controlled by a few and mov- they themselves are on an airplane or train or EDITORIAL OFFICES ing to the new world where information is in an elevator shaft. Because of this, the best SYS-CON MEDIA 135 CHESTNUT RIDGE RD., MONTVALE, NJ 07645 stored everywhere and controlled by many. wireless applications are those that use the TELEPHONE: 201 802-3000 FAX:201 782-9600 JAVA DEVELOPER’S JOURNAL (ISSN#1087-6944) is published monthly Since digital data became available, the wireless connection the least. The wireless (12 times a year) for $69.99 by SYS-CON Publications, Inc., 135 Chestnut demand has been there to free the data from its connection is used only for periodic bursts of Ridge Road, Montvale, NJ 07645. Periodicals postage rates are paid at Montvale, NJ 07645 and additional mailing offices. POSTMASTER: Send address cumbersome hosts. Many remember that in synchronization activity, allowing for the changes to: JAVA DEVELOPER’S JOURNAL, SYS-CON Publications, Inc., the beginning data was hosted on expensive 24/7 access to the wireless application and 135 Chestnut Ridge Road, Montvale, NJ 07645. mainframes with limited access. Over time, the data that supports those applications. ©COPYRIGHT computing started to expand; with the intro- What does this mean? It means that knowl- Copyright © 2001 by SYS-CON Publications, Inc. All rights reserved. No part of this publication may be reproduced or transmitted in any form or by any duction of enterprise servers, desktops, and lap- edge workers will become a part of the most means, electronic or mechanical, including photocopy or any information storage and retrieval system, without written permission. For promotional reprints, contact reprint coordi- tops, data began to free itself more and more. significant technology transformation of the nator. SYS-CON Publications, Inc., reserves the right to revise, republish and authorize its readers to use the articles submitted for publication. Billions of small points of data are expanding to twenty-first century: mobile, pervasive com- the outside edge, finding a home within both puting. Java will be a core technology enabling W ORLDWIDE DISTRIBUTION BY fixed and mobile Internet appliances, mobiliz- the transformation to technology mobility. CURTIS CIRCULATION COMPANY 730 RIVER ROAD, NEW MILFORD NJ 07646-3048 PHONE: 201 634-7400 Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc., [email protected] 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, AUTHOR BIO service marks or trademarks of their respective companies. Bruce Scott, president, CEO, and founder of PointBase, is a leader in the area of enterprise and embedded database architecture and product development. A cofounder of Oracle in 1977, Bruce cofounded Gupta Technology in 1984, pioneering the notion of the small-footprint database server for Intel-based platforms.

146 JUNE 2001

Java COM Prosyst www.prosyst.com

JUNE 2001 147

Java COM J 2 M E The Incredibly Shrinking Platform

J2ME A look at Java for small devices (and other strange tales) n o ti al n da n so r Fou PDA MID Pe Profiles Okay. Let’s get one thing clear right away. I am not writing (or better yet, dictating) this on a Java-enabled Configurations PDA while sitting on the bus on my way to work – a fact CDC CLDC that I find somewhat disturbing, and more than a little CVM KVM ersonalJava ers

annoying. Perhaps not as disturbing as my fellow passen- Pers gers would find it if I was talking into a little box, but dis- WRITTEN BY turbing nonetheless. Instead, I’m balancing my notebook JASON BRIGGS on my lap, at a 45-degree angle, while lying on the sofa. FIGURE 1 Configuration and profile relationships

The other way would really be more section). It seems we are now coming full and the Connected Device Configuration convenient for those times when I’m circle and returning to the very devices it (CDC). The CLDC targets devices with just too lazy to sit properly. was originally intended for. However, 160–512KB of total memory, limited Why then, you may ask, is there no despite hardware technology advances, power, possibly intermittent network cute little coffee cup logo on the bottom you are unlikely to find a handheld connectivity, and limited or no user inter- right-hand corner of my screen? The device with the requisite storage space to face. The CDC targets devices with a 32- answer is that despite the fact that Java 2 handle the Standard Edition of Java (a bit processor, 2MB of total memory and, Micro Edition software has been out for runtime size of around 5Mb) plus the again, intermittent network connection

Home J2EEsome time, there J2SE are few devices out processor requirements to make the with limited or no UI. there for me to play with that have J2ME most out of it. Which is undoubtedly the Profiles sit on top of the configuration installed (out of the box). This is not to reason why PersonalJava emerged, in and specify all the other APIs required to say that there are no devices available, due course. provide a runtime environment for a par- but it’s not easy to walk into a consumer More recently Java was split into ticular type of device. The user interface electronics store and find something sit- three main platforms: Java 2 Standard also falls under the control of the profile. ting on the shelf, waiting for you. Edition, Enterprise Edition and, of par- Figure 1 shows the relationships between Impatience aside, it seems likely that ticular interest to us, Micro Edition. In configurations and profiles. relatively soon there will be plenty of the words of Sun, Micro Edition “specif- devices to choose from. A number of big ically addresses the vast consumer PersonalJava players in the device market have space, which covers the range of Most people already know what announced Java support in some form. extremely tiny commodities such as PersonalJava is, so there’s probably not Motorola jumps immediately to mind, smart cards or a pager all the way up to much point in going into detail about with their iDEN developer community – the set-top box...” (Java 2 Platform, the API. Suffice it to say that PersonalJava aimed at providing assistance to embed- Micro Edition, Sun Microsystems). was there before J2ME emerged as a con- ded Java developers. The expert group for This is a shrewd move on Sun’s part: cept and the specification describes a the MID Profile (more on that later) reads the Java space is fragmenting somewhat cut-down version of the Java Standard like a who’s who of big multinationals: because of these new platforms. Since Edition to fit into resource-constrained AOL, Ericsson, Fujitsu, Matsushita (Pan- an application written specifically for devices. PersonalJava, as it stands, does asonic), Mitsubishi, Motorola, NEC, Standard Edition may not necessarily not really fit into the concept of Nokia, NTT DoCoMo, Palm Computing, work unchanged on a Micro Edition “Configuration and Profile” and hence Sharp, , Sun Microsystems (obvi- device, it makes sense to have some there are two specifications currently in ously), and Symbian, among others, sit in form of delineation between the groups. development aimed at the same kinds of the group. (For the full list, see the MIDP It becomes even more necessary when target device – JSR-000075 PDA Profile FAQ listed in the References section at you look at the number of products that for J2ME and JSR-000062 J2ME Personal the end of this article.) fall beneath the J2ME umbrella. Profile. The latter is “...intended to pro- So what is Java 2 Micro Edition, and vide the next generation of Sun’s why is everyone so keen on it? Configurations and Profiles PersonalJava environment, and as such Before looking at actual products, it’s has the explicit requirement of providing The Electronic Coffee Cup worth taking a look at how a product is compatibility...” with previous versions Java (before it was even called Java) defined within J2ME. of the specification (see References). So was originally destined for consumer Configurations are the low-level APIs it looks like PersonalJava will eventually electronics devices. Obviously this focus and virtual machine used by a product. be absorbed fully into the framework. changed along the way, and the Java we There are currently two configurations PersonalJava, in its current incarnation, know today eventually emerged (for a defined as part of J2ME: the Connected is probably the most common version of full history lesson, see the References Limited Device Configuration (CLDC) Java you will find on small devices. The

148 JUNE 2001

Java COM CTIA Wireless www.wirelessit.com

JUNE 2001 149

Java COM J 2 M E

runtime environment from Sun is avail- where just outside, but are intended for and the market they’re selling to is even able for a number of WinCE machines, and the same market. larger. The manufacturer gains by hav- compatible software is also available from IBM has the J9 virtual machine, with ing more software available for their a number of other manufacturers. runtime support for a variety of architec- product, and the developer gains by the tures (Linux/ARM, Linux/PPC, Linux/x86, larger market. (I agree that this is an Mobile Information Device Profile QNX in various forms, the Palm OS, and oversimplification of the issues, I merely The Mobile Information Device Profile Windows CE). They also have CLDC and a hope to provide at least one reason why

J2ME (MIDP) is one of the newer sets of APIs, Personal Profile, currently in beta form. industry support is growing.) and targeted at smaller gadgets than Insignia has their Jeode EVM, Wind River PersonalJava. In fact, if you take a look at has Personal JWorks, Hewlett Packard has The Master of Many Disciplines the MIDP specification, devices are ChaiVM, Tao Group has Intent JTE. Most Hopefully, you now have a vague severely constrained. A MIDP device of these are either compatible with idea of what you might find beneath the “should” have a screen size of 96x54 pixels, PersonalJava or, at the very least, are branches of the J2ME tree. Wondering display depth of 1 bit, have 128KB of aimed at a similar type of device. what to do with it? nonvolatile memory (in other words, Support for MIDP is still emerging, but A developer building applications memory that is retained when the device Motorola has a J2ME software develop- for PersonalJava or MIDP will undoubt- is switched off) for the application com- ment kit, with support for MIDP in their edly be expected to be a “Master of ponents, 8KB of nonvolatile memory for Accompli 008 All-In-One Phone, and the Many Disciplines.” Applications that persistent data, and 32KB for the Java run- i85s (possibly others as well). NTT must work within a limited environ- time (taken from the Mobile Information DoCoMo supports the KVM on some of ment are likely to rely on a certain Device Profile JSR-37 JCP Specification, their i-mode cellular phones. With Sega amount of server-side support. This will Sun Microsystems, Dec. 2000). developing entertainment content for be especially true for MIDP apps (or The first home computer I ever used both, the popularity of the phones would , as they’re called). So not only was a Radio Shack TRS-80 (or Trash 80, as seem assured (see References). will you need a working knowledge of it was affectionately known). At the time, Standard Edition, but probably of the this had 64KB of total memory and pixel The Great Mobile Land Grab servlet API, networking using HTTP depth of 1 bit (I don’t remember what the So success for J2ME appears reason- and/or datagrams, and possibly even screen size was, but I seem to recall the able, considering wide industry support. J2EE (Enterprise Edition). Putting all actual “pixels” themselves were about But why are all these companies so those disciplines together, what can you 3mm X 4mm, or something close) – so the enthusiastic about the idea? do with them? Pretty much anything.

Home J2EEMIDP minimum J2SE specification is scarily The answer would appear to lie – at The first applications to emerge (at close to the average spec of home com- least in part – in the current state of the PC least for MIDP) will be entertainment- puters available in the ’70s. Luckily, the industry. Handheld devices and mobile related. Take a quick look at Bill Day’s J2ME machines themselves will be a good deal phones (games consoles, as well) are sell- archive and you’ll find that a majority of smaller (I hope, because carrying a mobile ing in larger and larger quantities, com- the applications offered are games. This is phone around that’s the size of a Trash-80 pared with what seems to be a downturn not surprising since games (especially would result in one really muscular arm), in the personal computer market. multiplayer) are a good (and fun) way to but the environment you would be devel- Handheld devices are, of course, cheaper learn the capabilities of a platform. Game oping for is not that far removed. than PCs, and a degree more approach- development requires graphics, event (Note: MIDP sits on top of the able to the nontechnical public, and fash- handling, thread control, and sometimes Connected Limited Device Configuration ion is also playing a part in their popular- networking. My personal belief – probably [CLDC] and uses the .) ity. The Compaq iPaq is an undeniably not shared by the majority, but then it’s just sleek piece of hardware (not to forget the an opinion – is that developing games is Foundation Profile Claudia Schiffer Edition Palm PDA more challenging, and therefore more Another profile currently in develop- although, as much as I squint at the thing, rewarding, than developing other types of ment is a device the Foundation says I can’t see the resemblance). So with the applications, purely because it exercises does not require a graphical interface, handheld and mobile market continuing your abilities in all those disciplines. but “...will also be used as the basis for to blossom, Java is, I believe, a logical An added advantage is that buyers of other profiles that will add GUI as well choice for many of these manufacturers. these new mobile phones are more like- as other functionality” (from the JSR The problem with developing soft- ly to download games than other appli- #000046 J2ME Foundation Profile speci- ware using a language compiled to cations, at least until someone comes up fication, Sun Microsystems). The native code (especially for PDAs and with an idea for the product that every- Foundation Profile sits on top of the mobiles) is that portability becomes a one has to have. I’ve lost count of the Connected Device Configuration and major issue. The architecture of each number of times I saw people playing uses the C Virtual Machine. At the platform may differ significantly, and “Snake” on Nokia mobile phones when moment it is only available as part of thus, a developer will have to invest con- they first came out. Sun’s Community Source Licensing, for siderable time and effort to move their Linux or VxWorks, and as such is a little applications from one to the next. Some Ideas bit beyond the scope of this discussion. Therefore, unless the device has a Multiplayer applets and shockwave majority market share, it may be diffi- apps are a good place to start looking for Other Players cult to entice developers to the platform. ideas. Potentially, a basic shockwave app There are many other players in the J2ME may very well solve this prob- should scale fairly well, down to a MIDlet. market, supplying virtual machine soft- lem for manufacturers. The time to port For example, looking at something like ware for numerous devices. Some have an application across multiple plat- Habbo Hotel (www.habbohotel.com), virtual machines that fall within the forms should be greatly reduced; the which uses simple 3D-styled graphics to boundaries of J2ME; others fall some- developer expends less effort to do so, create a chat room with a difference, it is

150 JUNE 2001

Java COM ejip.net www.vergecorp.com

JUNE 2001 151

Java COM J 2 M E

not unreasonable to think that a similar which of the two main J2ME platforms Netscape team had rolled out their first paradigm would work well even in the should you be developing for? browser. At the very least, we could expect restricted MIDP environment. The graph- The decision depends very much on to see a huge games market emerging for ics are sprite-based, and the interface is a your application. PersonalJava provides a Micro Edition over the next few years. simple point-and-click affair (in other much richer API to draw from; the target words, you point your mouse and click, devices have more screen real estate, faster Footnote and your character moves to that posi- processors and more memory. MIDP is Are you working on MIDP or

J2ME tion), so network traffic is relatively light. very limited, which presents its own set of PersonalJava software, be it a game or a “seri- The only really ambitious part of the exer- challenges, the devices (likely to be mobile ous” application? Is your app likely to knock cise would be the chat mode. I personally phones initially) have small screens, a min- the socks off anything else out there? Or do wouldn’t want to sit pushing 44-33-555- imal amount of memory, and a processor you have a Java-compatible device that will pause-555-666-0-6-999-0-66-2-6-33-0- that a snail would find fast, but the rest of be the doohickey of choice for the X-Y-Q-R- 444-7777-0-5-2-7777-666-pause-66 on us will find somewhat taxing. what-letter-are-we-up-to-generation? my mobile just to say, “Hello my name is Competition may also be a deciding If so, please drop me a line for the Jason,” but who knows, the idea might factor in your decision. PersonalJava has possible inclusion of your product in a take off, and as an added bonus, it might been around much longer, so your con- future article. create a thriving industry in repetitive- cept may have been “done to death” on finger-strain-injury medicine. PDAs. Therefore MIDP might be a better Games that were popular in the “days choice (assuming that the application References of old” will also provide a likely source of will scale to a much smaller device; the 1. The J2ME home page: material. Don’t yawn. Porting a classic next best-selling word processor is not a http://java.sun.com/j2me/ game to MIDP might not sound very likely candidate for a mobile phone). 2. The MIDP Frequently-Asked- innovative, or very exciting, but it’s On the other hand MIDlets (MIDP Questions List: another way to learn the technical side applications) may rely quite heavily on http://java.sun.com/products/mid of the platform, as well as the limita- server-side support to provide advanced p/faq.html tions, without having to worry about functionality. Establishing this resource 3. Bill Day’s J2ME archive: game-play mechanics, balancing, and could be a complicated proposition for a http://www.billday.com/j2me all the other little issues that go into the small developer. Issues such as middle- 4. A brief history of Java: design of a game. ware and database platforms, initial and http://ei.cs.vt.edu/~wwwbtb/book/ projected storage requirements, and chap1/java_hist.html

Home J2EEMurmurings from Sun J2SE scalability – to name just a few – all have 5. The two Community Process specifi- Over the last few months, more and to be taken into consideration: setting cations that seem to fall within a more stories have appeared on the Sun up database, middleware and Web similar space to PersonalJava: Web site (and on others) regarding Java servers, to support your app, is poten- http://java.sun.com/aboutJava/co and gaming. More recently, a Sun press tially an exercise in draining your wallet. mmunityprocess/jsr/jsr_062_pprof. release announced the imminent launch Partnerships and development deals html of a new Web site for Java games devel- might be more accessible for a MIDP appli- http://java.sun.com/aboutJava/com opers (www.javagaming.org) to provide cation developer than for PersonalJava. munityprocess/jsr/jsr_075_pda.html resource and up-to-date information to With the market so new, the mobile net- 6. The Mobile Information Device Profile the Java gaming community. Hopefully, works will possibly be quite enthusiastic to Community Process specification: by the time this article goes to print, the fill their software catalogs, if only to keep http://java.sun.com/aboutJava/com Web site should be up and running. one step ahead of the competition. munityprocess/jsr/jsr_037_mid.html This support from Sun is another good C and C++ have an established tradi- 7. The Foundation Profile: incentive to get into game development tion in the PC and console games mar- http://java.sun.com/aboutJava/co for J2ME. There are very few sites dedicat- ket. It has been difficult to argue Java the mmunityprocess/jsr/jsr_046_j2mef ed to game development in Java, so you’re language, or Java the platform, as a nd.html forced to glean information from places replacement for this tried, tested, and 8. Motorola’s press release (last where there may be as much misinforma- trusted technology. Which is not to say November) about Sega developing tion as genuine facts and useful that there isn’t an argument for Java on games for Motorola phones: resources. An example of this is asking a these platforms. However J2ME starts www.motorola.com/NSS/Press/pre question at a general game development off on a more level footing with other ss_archive_2000/20001129.html forum such as, “Has Java3D performance languages, probably on a better footing 9. Information on the Motorola i85s improved enough for games develop- considering the portability advantages. mobile phone: ment?” Replies to this could range from One negative thought in all this is that www.mot.com/LMPS/iDEN/prod- outright flame attacks to “I’ve never tried, it’s not completely clear whether there is ucts/i85s/i85s.html but last time I looked it was garbage,” definitely money to be made in the bur- 10. The Accompli 008: www0.motoro- instead of something practical like, “I’ve geoning mobile market for embedded la.com/developers/wireless/prod- used it for modeling a walk-through of the Java developers. The promise is there, but ucts/matrix/details/index.html?pro AUTHOR BIO architectural design of a new building, will that promise turn into hard cash? Will duct=11 Jason Briggs has been and performance was acceptable, but all that hard graft actually pay off? These 11. Sun’s games press release: officially developing in improved when we did this… .” are questions that, certainly when the www.sun.com/media/pressrel.mar_ Java for three years – technology is just emerging, won’t be clear egaming.html unofficially for just over Decisions,Decisions... until after the fact. I imagine that predict- 12. The new Java Gaming Web site: four. He works as a Java Assuming you’re not just experi- ing the direction the industry is going to www.javagaming.org analyst programmer in menting with the technology, and actu- take would be like trying to foresee the London. ally want to work on a real product, dot-com boom and bust, back before the [email protected]

152 JUNE 2001

Java COM spiritsoft www.spirit-soft.com

JUNE 2001 153

Java COM J2ME Home J2EE J2SE

J2ME,CLDC,and MIDP level user interface APIs. Figure 1 shows the primary classes in The Java 2 Platform, Micro Edition (J2ME) includes virtual these APIs. machine and application program interface (API) specifications for running Java applications in devices with limited computing The High-Level API resources, such as personal digital assistant devices (PDAs) and In the high-level API, Screen is the base class for screen displays cellular phones. J2ME defines different configurations that in and has four subclasses – Alert, Form, List, and TextBox. Other than turn define profiles. a title and a ticker (a string that continuously scrolls across a part of The Connected Limited Device Configuration (CLDC) is the screen), which are available to all Screen subclasses, List and intended for devices that have limited (not always on) connec- TextBox each provide only a single visual element on the screen – tivity to the Internet. The CLDC includes three packages – that is, the structures of List and TextBox are fixed and other com- java.io, java.lang, and java.util – that are subsets of the Java 2 ponents can’t be added to them. List displays a list of choices, with Standard Edition packages of the same name, and the each choice consisting of a string and an optional image. TextBox javax.io.microedition package, which is specific to the CLDC. displays and allows the entry and editing of text. The Alert class The CLDC also defines the kilobyte virtual machine (KVM), a supports the display of both a string and an image. Form can con- Java VM that specifically targets devices with limited computing tain and display any mix of Item objects – one or more resources. CLDC devices have between 160KB and 512KB of ChoiceGroup (containing radio buttons and check boxes), memory available for use by the Java platform. DateField, Gauge, ImageItem, StringItem, and/or TextField objects. The CLDC defines a number of profiles; however, the Mobile The high-level API targets applications for which portability Information Device Profile (MIDP) is the only one that has been is essential and relegates look and feel issues to the platforms finalized as of the writing of this article. The MIDP targets that the application is deployed on. One price of this portability devices such as cell phones and pagers, with a minimum screen is that you have minimal control over layout and display attrib- size of 96x54 pixels. MIDP applications are referred to as utes such as text fonts and color. In addition, with the high-level MIDlets. API, you can’t intercept key events and therefore can’t provide The MIDP contains package javax.microedition.rms for contextual filtering of data input. record management services, javax.microedition. for MIDlet lifecycle management, and javax.microedition.lcdui An Example of High-Level API Limitations containing user interface classes. Within the lcdui package the I’ll illustrate the limitations of the high-level APIs via the MIDP distinguishes between what it calls high-level and low- screen shown in Figure 2.

154 JUNE 2001

Java COM Java Developer’s Journal www.sys-con.com

JUNE 2001 155

Java COM base class for all screen displays and Graphics provides methods Screen for drawing on the screen (although Graphics is also used by the 0..1 Ticckerc internals of the high-level API; meanwhile, in the high-level API, Canvas graphics objects are not accessible to the developer except when using an image). With graphics methods you can draw and fill Alert #paint:void List #keyPressed:void TextBoxTextBox rectangles and arcs, draw lines, and specify fonts and colors. You can also specify precisely where these elements are drawn on

Form Graphics the display. However, the low-level API doesn’t contain any pre-

J2ME Item defined visual components such as text boxes or radio buttons. +append:int+append:in 0..* +drawArc:void +drawChar:void Therefore if you use the low-level API, you have to create your +drawChars:void paint:void +drawImage:void own visual components. +drawLine:void +drawRect:void With the low-level API you can also process key events via DDateFielld +drawRoundRect:void SStringItemtringIte +drawString:void the keyPressed method in Canvas, which is called by the KVM +drawSubstring:void whenever a key is pressed. You can use this capability to provide CChhoiceGrououp TextFieldTextField +fillArc:void +fillRect:void +fillRoundRect:void the user with the ability to navigate between, enter data into, +setColor:void and select values from your custom components. Gaugee +setFont:void ImageItemmageItem +setStrokeStyle:void The UI Framework FIGURE 1 The primary MIDP high-level API classes are in white and the low-level The limitations of the high-level API and the degree of con- API classes in blue trol available in the low-level API drove me to use the latter for my development, and to implement a framework that supports This screen lets users enter expense information into their the creation, placement, and display of navigation between, and cellular phone. An expense consists of an amount, an expense the processing of key presses by, custom components. A class type such as airfare or hotel, and the date of the expense. This diagram of the framework is provided in Figure 3. Since these screen was implemented using the low-level API because the classes are similar in function to some AWT classes, I’ve fol- following obstacles would be encountered if implementing with lowed Swing’s lead and given them names that begin with M (for a high-level one: MIDP), followed by the name of the similar AWT class. Also, • Layout: The amount and date fields are centered on the methods that behave similarly to their AWT counterparts are screen, which is not possible with the high-level API because named the same as in AWT, although the method signatures it doesn’t allow you to specify the position of the elements. may differ. Also, with the high-level API, the layout for most devices is The relationship between MContainer and MComponent is

Home J2EEvertical, meaning J2SE that each focusable item (items that receive the core of the framework. MContainer (see Listing 1) defines input) is always placed on a new line. This means that with the method add, which adds a component to the container. the high-level API you can’t create elements containing mul- The code fragment below shows how the ExpenseItem class, tiple data fields on the same line, such as the amount field in which creates the screen in Figure 2, uses this method to add Figure 2. objects of a custom component to the screen display (for • Custom components: With the high-level API you can’t create brevity I don’t show the dollar sign and cents separators being custom components such as the expense-type scroll list drawn). shown in Figure 2. With the high-level API such a custom component would need to extend Item and then override NumberField dollars = Item’s paint method to paint the custom component on the new NumberField( 5 ); screen. However, Item’s paint method is declared with the add(dollars, x, y); package scope, so any class that extends Item needs to be in NumberField cents = the javax.microedition.lcdui package. new NumberField( 2 ); Even if you elected to place your custom component in this add(cents, x + package, there would be no guarantee that Form’s append dollars.getWidth() + method, which you would call to add the Item to the display, 3 /* spacer */, y); would treat it correctly, as stated in this response to a message posted to [email protected], Sun’s mailing list for Figure 4 shows the relationship between these custom class- J2ME developers: “The high-level Screens like Form don’t es – ExpenseItem extends MContainer and uses NumberField expose the low-level functions to paint your Item and take and MScrollList classes (both of which extend MComponent) events. Most implementations will either not allow you to add for its visual elements. a custom Item to a Form or it will only display the Label at best.” MComponent and MContainer • Processing key presses: While the high-level API’s DateField In exploring the relationship between MComponent and class provides a display similar to the date field in Figure 2, MContainer let’s start by examining the code for MComponent, DateField doesn’t prevent the entry of invalid dates, such as a shown in Listing 2. A component must implement four methods month greater than 12, or a day of 31 when the month is 4. – getHeight, getWidth, paint, and keyPressed. getHeight and Since code that uses the high-level API can’t intercept key getWidth let you position components relative to each other, as presses, there’s no way for you to add such a filtering capabil- shown by the use of getWidth in the previous code fragment. ity. paint and keyPressed will be discussed in detail later. A compo- nent also contains its screen coordinates, which are set by the The Low-Level API MContainer’s add method as seen in Listing 1. In addition, a The low-level API provides far more control over the look and component contains a reference to the container in which it’s feel, but at the potential expense of portability (whether or not placed, which is also set by the container’s add method. Finally, portability is sacrificed depends upon which specific features of a component contains a Boolean indicating whether it has the low-level API are used). In the low-level API, Canvas is the focus.

156 JUNE 2001

Java COM Web Services Edge www.sys-con.com

JUNE 2001 157

Java COM refresh after an event that changes the component’s appear-

com.nextel.ui.MComponentcom.nextel.ui.MComponenom.nextel.ui.MComponenextel.ui.MCompextel.ui.MCom ance, which occurs when characters are entered into a text field jaavvvax.microedition.Icdui.Displaayyableya as the result of key presses. MContainer inherits from the getContainer:MContainer javax.micoedition.Icdui.Canvas +getHeight:int Canvas method repaint, which can be called. Since repaint is +getWidth:int declared with protected scope, a component can call it via the +getX:int +getY:int component’s container reference (recall that in Java, members +hasFocus:boolean #keyPressed:void with the protected access modifier have both package and pro- com.nextel.ui.MContainercom.nextel.ui.MContaine #paint:void #processFocusEvent:void tected scope). #MContainer J2ME #repaint:void In Listing 2 we see that MComponent contains the method #add:void setContainer:void getComponent:MComponent setFocus:void repaint, which calls the container’s repaint. Typically, after any #getComponentCount:int setX:void ##keyPressed:void setY:void change that affects the appearance of the component, the com- #p#paint:void ponent should call its repaint method to ensure that the screen FIGURE 2 Screen for entry of display is updated. As an example, first revisit the code fragment expenses information above, which contains a variable named text. The component ccoom.nextel.ui.MFocusEventn com.nextel.ui.MFocusManager containing this fragment could place digits in the text box by

MFocusEvnt implementing MComponent’s abstract keyPressed method as: +MFocusManager +getEventld:int #changeFocus:void +getSource:MComponent #createFocusEvents:MFocusEvents #keyPressed:void protected void keyPressed( int keyCode ) { char keyChar = (char) keyCode; FIGURE 3 Classes in the UI framework if (Character.isDigit(keyChar)) { text += keyChar;//add to existing text Painting repaint(); In the low-level API a Canvas is written to the screen when the KVM calls the Canvas’s paint method, which is declared as: Key Presses and Focus Management The Canvas class provides the only entry point for process- protected abstract void paint(Graphics g) ing key events; its keyPressed method is called by the KVM to handle keystrokes. Therefore, for custom components to The Graphics object passed in this call has methods that respond to key events the Canvas must pass key events to the draw specific visual elements on the screen. These methods custom components. include: In Listing 1 we see that MContainer’s keyPressed method • drawArc: Draws a curved line passes any key press to the focus manager that was created by

Home J2EE• drawChar, drawChars: J2SE Draws one or more characters MContainer’s constructor. The function of a focus manager is to • drawImage: Draws an image support user navigation between fields. I’ve adopted the con- • drawLine: Draws a straight line vention used in navigating browser forms that moving right (the • drawRect: Draws a rectangle tab key in browsers) moves to the next component and moving • drawRoundRect: Draws a rectangle with rounded corners left (shift-tab) moves to the previous component. On the hand- • drawString, drawSubstring: Draws strings and substrings set shown in Figure 2, the move-right and move-left keys are the • fillArc: Fills in a circular or elliptical arc right and left sides of the four-way navigation key. • fillRect, fillRoundRect: Fills in rectangles with sharp and When any key is pressed and the KVM calls the container’s rounded corners keyPressed method, the container in turn passes the key code to the focus manager’s keyPressed method. In Listing 3 we see that Graphics also has methods setColor, setFont, and set- if the key pressed was the one to move right or left, the focus StrokeStyle (the latter lets you specify whether lines are to be manager’s keyPressed method will, via the changeFocus solid or dotted). method, create MFocusEvents (see Listing 4) and call the Custom components can use the methods in Graphics to processFocusEvent methods of both the component that loses provide their desired visual representation. In Listing 2 we see focus and the component that gains focus. that MComponent declares an abstract paint method, which a In Listing 2 we see that in the component’s pro- subclass implements to display itself on the screen. For exam- cessFocusEvent method an internal flag is set indicating ple, a class that extends MComponent could display a box con- whether the component has focus. One way this flag may be taining text by implementing paint as: used by a component is to alter the way the component is dis- played when it has focus. For example, via the following code String text = "Hello World"; (where “g” is a Graphics object), the component’s paint method protected void paint( Graphics g ) { can display a black background when it has focus and a trans- g.setColor( 0x000000 /* black */ ); parent background when it doesn’t: g.drawRect( getX(), getY(), getWidth(), getHeight() ); g.drawString( text, … g.setColor( hasFocus() ? 0x000000 //black Since MContainer extends Canvas, in order for components : 0xFFFFFF);//clear to be painted on the screen, a connection must be made g.fillRect( x, y, between the container’s paint method, which is called by the getWidth(),getHeight()); KVM, and the paint methods of the components within the con- tainer. Listing 1 shows how this occurs; when a component is The keyPressed method in Listing 3 shows that if the key added to the container, it’s placed in a vector of components pressed is neither the move-left nor the move-right key, the key that the container’s paint method iterates through, calling each code is passed to the keyPressed method of the component that component’s paint method in turn. has focus. MComponent declares this method as abstract, so In addition to painting itself when requested by the con- each subclass must implement code for handling the key press. tainer, a component must also be able to initiate a screen This returns our discussion to the keyPressed code fragment

158 JUNE 2001

Java COM PTG Interactive www.jdj.dynamicbuyer.com

JUNE 2001 159

Java COM 3. A layout abstraction so the developer could specify relative Canvas positions when adding a component to a container instead of com.nextel.ui.MContainer using screen coordinates: In AWT and Swing this is accom- plished via layout managers. Since some of the functionality CommandListeneere that layout managers provide is related to the ability of users ...nextextel.expensePad.Expensppsltemsltes m com.nextel.ui.MComponent to move and resize windows on a desktop display, and year because this ability is not currently present on a cellular phone, I suspect that implementing anything other than very month J2ME simple layout managers for the cellular phone is probably expense types dollars cents day overkill.

com.nextel.ui.MScrollList com.nextel.ui.NumberField Enhancements that address these issues and provide addi- tional functionality, including components such as scroll lists, radio buttons, and check boxes, will be provided in the next gen- FIGURE 4 The classes that implement the expense item entry screen. eration of this framework, which will be available to registered Nextel developers at http://developer.nextel.com in June. shown earlier, and completes our exploration into how compo- nents receive keystrokes. Summary The MIDP high-level API provides little developer control Enhancements over the look and feel and doesn’t support the development of This framework would benefit from a number of enhance- custom visual components. The low-level API does, but doesn’t ments, including the following: provide an AWT-like level of abstraction for using those compo- 1. Repaint only the affected component: Every repaint paints nents. The classes I’ve described here provide the beginnings of the entire screen, which is inefficient in the typical case in that level of abstraction via the delegation of paint operations which a component responds to a key press and so only the from the Canvas to the custom components, and the delegation display of that component needs to change. While I haven’t of keystroke processing from the Canvas to a focus manager and observed any screen flicker from repainting the entire screen then conditionally to the custom components. each time, it would be more efficient to repaint only the affected area of the display. AUTHOR BIO 2. An MPanel class that lets you group and reuse related com- Glen Cordrey is a senior architect at DigitalFocus (www.digitalfocus.com), which develops ponents: For example, with the expense screen shown in Internet applications in Herndon,Virginia. He has over 20 years of experience in application

Home J2EEFigure 2, I could J2SE use one panel to contain the dollars and development, and has been developing with Java for the last 4 years. cents fields and another to contain the day, month, and year [email protected] fields.

Listing 1: MContainer provides contextual management of MComponents }// MContainer import java.util.*; import javax.microedition.lcdui.*; abstract public class MContainer extends Canvas Listing 2: MComponent, the base class for all custom visual components { import java.util.*; private Vector components = new Vector(); import javax.microedition.lcdui.*; private MFocusManager focusManager; abstract public class MComponent protected MContainer () { { final MContainer getContainer() focusManager = new MFocusManager( this ); { return this.container; } } // constructor abstract public int getHeight(); protected void add ( MComponent component, abstract public int getWidth(); int x, // screen int y ) // coordinates final public int getX() { {return this.x;} component.setX( x ); component.setY( y ); final public int getY() component.setContainer( this ); {return this.y;} components.addElement( component ); if ( components.size() == 1 ) public boolean hasFocus( ) { // first component on the screen { return this.hasFocus; } component.setFocus( true ); } abstract protected void keyPressed(int keyCode); } // add abstract protected void paint( Graphics g ); // gets component at this rank, where rank is // container in which this component is placed // the order in which the component private MContainer container; // was added to the container private boolean hasFocus = false; MComponent getComponent ( int rank ) private int x, y; // screen coordinates { Object obj = components.elementAt( rank ); protected void return ( obj == null ? null : processFocusEvent( MFocusEvent event ) (MComponent ) obj ); { } // getComponent hasFocus = ( event.getEventId() == // gets the number of components in the container MFocusEvent.FOCUS_GAINED ); protected int getComponentCount () } // processFocusEvent { return components.size(); } protected void repaint () protected void keyPressed( int keyCode ) { { focusManager.keyPressed( keyCode ); } if ( container != null ) container.repaint(); protected void paint( Graphics g ) } // repaint { // paint each component for ( Enumeration enum = components.elements(); final void setContainer( MContainer container ) enum.hasMoreElements(); ) { this.container = container; } { MComponent nextComponent = void setFocus ( boolean state ) ( MComponent ) enum.nextElement(); { hasFocus = state; } nextComponent.paint( g ); } final void setX(int value) } // paint {this.x = value;}

160 JUNE 2001

Java COM { final void setY(int value) return {this.y = value;} new MFocusEvent( container. }// MComponent getComponent(componentRank), eventId ); Listing 3: MFocusManager provides navigation between MComponents } // createFocusEvent import javax.microedition.lcdui.*; protected void keyPressed( int keyCode ) public class MFocusManager { { if ( keyCode == rightKey && // offsets to next and previous component focusedComponentRank < private final static int NEXT = 1; container.getComponentCount() - 1 ) private final static int PREVIOUS = -1; { // not the last component changeFocus( NEXT ); // Values of the keys to move right and left } private int rightKey, leftKey; else if ( keyCode == leftKey && focusedComponentRank != 0 ) // Container of components to manage focus for { // not the first component private MContainer container; changeFocus( PREVIOUS ); } // The rank of the component with focus else // pass the key stroke to the component private int focusedComponentRank = 0; { // with focus container. public MFocusManager ( MContainer container ) getComponent( focusedComponentRank ). { keyPressed( keyCode ); this.container = container; } leftKey = container.getKeyCode(Canvas.LEFT); } // keyPressed rightKey = container.getKeyCode(Canvas.RIGHT); } // constructor }// MFocusManager protected void changeFocus( int offset ) // NEXT or PREVIOUS { Listing 4: MFocusEvents are delivered to MComponents to notify // notify currently focused component of change them when they gain and lose focus. MFocusEvent event = public class MFocusEvent createFocusEvent( focusedComponentRank, { MFocusEvent.FOCUS_LOST ); public final static int FOCUS_GAINED = 1; container. public final static int getComponent( focusedComponentRank ). FOCUS_LOST = -FOCUS_GAINED; processFocusEvent( event ); private MComponent source; focusedComponentRank += offset; private int eventId; //FOCUS_GAINED or FOCUS_LOST // notify newly focused component of change MFocusEvent ( MComponent source, int eventId ) event = { createFocusEvent( focusedComponentRank, this.source = source; MFocusEvent.FOCUS_GAINED ); this.eventId = eventId; container. } // constructor getComponent( focusedComponentRank ). processFocusEvent( event ); public int getEventId () { return this.eventId; } container.repaint(); // update display } // changeFocus public MComponent getSource () { return this.source; } protected MFocusEvent createFocusEvent( int componentRank, }// MFocusEvent int eventId )

Sun North Solutions woods

www.solutionssite.com www.nwoods.com

JUNE 2001 161

Java COM JDJ Showcase CD (201) 802-3020

162 JUNE 2001

Java COM JDJ Showcase CD (201) 802-3020

JUNE 2001 163

Java COM PERSONAL JAVA Java Thick Clients J2ME with J2ME The pros and cons of implementing Java in restrictive environments

This article introduces the development issues relating to thick clients with J2ME and related Java technology such as PersonalJava. It is intended for developers planning to deploy tra- ditional thick client applications on ‘consumer devices’ such as WRITTEN BY mobile phones, smart phones, PDAs, and set-top boxes. It also cov- GLENN COATES ers material specifically of interest to device manufacturers and

Home J2EE J2SE Original Equipment Manufacturers (OEMs).

Introduction to Thick Clients way. Instead of having to install it via a control over the look and feel; the user A Recap on Thin Clients CD-ROM or downloading via the interface may seem inconsistent when The rather subjective term “thin Internet, the user just enters the URL for browsers from different vendors are client” is fairly well-known nowadays; a the application and performs a refresh if used. The thin client may have to be good example would be a “Web-based necessary. This can solve many of the developed for the “lowest common application.” A thin client doesn’t expensive and time-consuming upgrade denominator” or may have to manage require the developer to design and and management problems usually specific features of different browsers. write the software that runs directly on associated with thick clients. Moreover, there is a risk that it may be the client device. Instead, they typically As we can see, a thin-client applica- susceptible to browser incompatibili- use the features of a browser or some tion does have numerous benefits, ties, idiosyncrasies, or bugs. Browsers other host application in order to pres- though it may have specific disadvan- from different vendors may support dif- ent and manipulate the application tages. In our example of a browser- ferent versions of markup and scripting data. The real “guts” of the application is based thin client, the browser in effect languages. actually server-based, which means it interprets the mark-up language, such A thin client also presents a number can be managed and upgraded centrally. as HTML and JavaScript, in order to of restrictions. For example, it is usually Note: I have used Web-based appli- present the user interface. This means not possible to directly access the cations as an example of thin clients as that when it needs to update a page or device’s storage area, built-in device these are probably the most common. display a new page from the server it’s applications, or other device resources. The thin-client developer generally likely to be slower and less responsive. Although it’s often stated that a thin needs only to develop the server-side Many mobile professionals using a client is easier to deploy and upgrade software that generates the markup, device in the field would benefit from an due to its thin Web nature, it does not such as HTML, and maybe some scripts, asynchronous communication model escape real-world problems. In order to such as JavaScript, that can be interpret- due to restricted bandwidth and unreli- run a thin client, we may have to recon- ed by a browser in order to define the able wireless connections. This may figure the browser or even reinstall the user interface and perform any local cal- include allowing the user to do most of latest browser release. This may be nec- culations or input validation. his or her work offline, only connecting essary if a thin client requires the brows- Figures 1 illustrates the main archi- to the server at key stages in order to er to have the up-to-date Java plug-in, tectural features of a thin client. “synch” and guarantee that a transac- allow cookies, or add digital certificates; As well as reducing client develop- tion is processed once and once only. the list goes on. Many larger companies ment time, this approach also provides a Browsers by their very nature are syn- have strict heavyweight security policies potentially more efficient deployment chronous, and achieving such behavior and busy support workloads, and mechanism. Anyone with a supported would be difficult if not impossible. departments may not even have browser can use the application without An application implemented as a browsers or have predated and different having to install it in the conventional thin client can mean that there is less versions. Upgrading these and configur-

164 JUNE 2001

Java COM WebServices Journal www.sys-con.com

JUNE 2001 165

Java COM PERSONAL JAVA

ing them for a new thin client is no triv- Figure 2 illustrates the main archi- It can be argued that, for more fre- ial matter, especially for mobile devices tectural features of a thick client. quently used, complex or business criti- that are out in the field being used by cal applications it is usually a better idea mobile professionals. Why Develop a Thick Client? to develop a thick client. Table 1 shows the main advantages A thick client has a number of advan- Table 2 shows the main advantages and disadvantages of Web-based thin tages over a thin client. In most cases the and disadvantages of a thick client. clients. advantages have to do with the higher

J2ME level of control that can be gained over How Would a Be Defined – What Defines a Thick Client? the device. As we are not relying on the Thick or Thin? The rather subjective “thick client” is constraints and restrictions of a hosting We have now made some reasonable what many application developers will browser application, we generally have definitions for a thick client in contrast have already developed on numerous more freedom to develop a user inter- to a thin client, but where would an occasions. It is a tier one application face embracing the device’s full user applet fit into these definitions? An designed with a specific task in mind, interface offerings, thus allowing a more applet is a small Java application that is and is installed directly onto a desktop “at-home” feeling for already experi- anchored to an HTML Web page. When machine or mobile device. It may use enced users of the device. Device fea- we select the link, the applet is down- open standards-based protocols such as tures such as file system/storage system, loaded, verified, and run within the HTTP or CORBA, but generally it does built-in applications and other browser and the JVM — that is, if our not use a markup language such as resources, such as infrared or Bluetooth, browser is configured to allow this. This HTML for application presentation. The are usually more accessible if we specif- is done every time we select the applet thick client application alone is usually ically design the application for the link. responsible for presenting the data via a device or device family. This may be very Since an applet is Web-based and user interface. In contrast to Web-based important in the case of a PDA; the runs within the constraints of a browser, thin clients, which use a browser to built-in applications may be what make it is more thin than thick. Another deploy functionality, a thick client must the device so useful; failing to integrate important giveaway is that the user does usually provide most of the application with these may limit the usefulness of not have to install it; the applet is down- features itself. A suitable example is that your application. Additionally, the loaded automatically by the browser of a Web browser. The Web browser is application can generally be better con- when the user selects the appropriate very much a thick client, whereas the trolled and made more robust as it is not HTML link and does not run directly on Web applications that run within the relying on browser bugs or idiosyn- the device. It is, therefore, reasonable to

Home J2EEbrowser can be regarded J2SE as thin clients. crasies. suggest that an applet is thin. Or, maybe it’s a thick thin client! Why Use Java for Thick-Client Development? Productivity and Reduced Risk Most Java developers who have used other development environments, such as C and C++-based ones, prefer Java for Desktop Server a number of reasons, including the increase in productivity and quality. Browser Although good quality software can be, (Thick T1 Internet/Intrn rar neet Server T2 Client) and is, developed in other languages and environments, it requires more skill HTML/Java and effort, which obviously means Script Web Server (()Thin Client) higher costs. Java is a “clean” object-ori- ented language that doesn’t inherit the legacy of C and strips away the often misused parts of C++. Commonly FIGURE 1 Main architectural features of a thin client required features, such as threading and synchronization, are built into the lan- guage itself, and an appropriate garbage collector, when understood properly, usually means fewer memory leaks and is suited to most environ- ments. Desktop Server Prior to PersonalJava and J2ME, developing software for mobile devices Thick usually involved C or C++ or proprietary T1 Internet/Intrn rar neet Server T2 Client languages and toolkits. While some of these toolkits were and still are very pro- Thick Client ApplicationA ductive and appropriate, some were a Application Server developer’s (and Project Manager’s) nightmare that required previous expe- rience and a few “battle scars.” Java’s predecessor, OAK, was originally FIGURE 2 Main architectural features of a thick client designed specifically to address such

166 JUNE 2001

Java COM WebSphere Journal www.sys-con.com

JUNE 2001 167

Java COM PERSONAL JAVA

problems with consumer device devel- Configurations, Profiles, and Per- Dynamic Linking opment. Before Java, just attempting to sonalJava in a follow-up article.) Java Dynamic linking means that a class deploy the same thick-client application provides an abstraction layer between need not be loaded and linked until it is on a different device imposed many the platform and our application, and actually required. This is ideal for many risks, high costs, and delayed time to because it’s ostensibly more open (while application environments and allows for market. Thus, applications were and still under the control of Sun), it helps save more efficient use of resources. are often targeted at one or two mobile us from becoming the victim of the ven-

J2ME devices; some would argue that this can dor lock-in anti-pattern. If we have Built-In Security and Integrity limit the success of the application and problems with a bought-in application Java does automatic runtime checks also the device. or component, it’s much easier to such as array bounds checking, null ref- exchange it for another. As Java is plat- erence checking, and legal cast check- Platform Independence form-independent, it means that we will ing. Arrays are automatically initialized. There should be less need to under- need to “adapt,” rather than port, an Synchronization is built into the lan- stand the intricacies of the target application for a different mobile guage. Security management and class devices. Once a thick client is J2ME device. It means that we can reuse our verification are also integral. CDLC–compliant it should work well on existing skills without having to learn any device that supports that configura- radically different proprietary develop- More Open with Well-Defined tion and has the appropriate Profiles ment environments just because we Standard Extensions installed and any additional pack- want to deploy our application on a new Along with the core Java editions, ages. (I’ll talk more about J2ME, device. numerous standard extensions are

ADVANTAGES DISADVANTAGES Centralized administration and configuration and automatic upgrade. Must run within the constraints and restrictions of the browser. May have to develop the application for the lowest common denominator; or “juggle” differing features. Simpler user Interface. Difficult to “tap into” the device and built-in applications.

Application can be used from any desktop or device that has the appro- Application may be designed to run “best” on a particular browser or brows- priately configured host browser. er version. This may mean browsers need upgrading or reconfiguring.

Home J2EEEasy to upgrade/update, J2SE without the need for a client-side reinstall. Browsers may offer different levels of support for features such as version of markup language and plug-ins.

Functionality such as security, communications protocol, look and feel Browsers may still require re-configuring, for example, digital certificates taken care of by the host browser. may need to be installed.

Great for simple or lightweight applications. Not a generic application – “write once run anywhere.” In the real world there are different web-based models such as HTML, WAP and Imode.

Usually cheaper and easier to develop.

TABLE 1 Advantages and disadvantages of Web-based thin clients

ADVANTAGES DISADVANTAGES Maximum control over device resources and extensions. More development effort required. Longer maintenance cycles.

Full control over user interface. Takes longer to download and install. Takes more time and effort to upgrade.Will need to be explicitly uninstalled when no longer required by user.

Faster application. Still have the problem that devices are different by nature with varying user interfaces and input mechanisms. May still need to target specific devices or device families.

Full control over security. You will need to provide all required features.

Better for asynchronous, connection-less and transaction-oriented Usually requires more software engineering expertise. applications.

Choice of application-level and communication protocols.

More control over end quality and reliability.

Access to device resources and applications.

TABLE 2 Advantages and disadvantages of a thick client

168 JUNE 2001

Java COM SYS-CON Codigo Custom Xpress

www.sys-con.com www.codigoxpress.com

ORDER ONLINE AND GET 10% DISCOUNT GO TO WWW.JDJSTORE.COM TO ORDER

5 years PRINT worth of... pdf files only 99 Features & Articles $79 Product Reviews Check out over 500 articles covering topics such as... Case Studies Java Fundamentals, Advanced Java, Object Orientation, Java Applets, AWT, Tips & Tricks Swing, Threads, JavaBeans, Java & Databases, Security, Client/Server, Java Interviews Servlets, Server Side, Enterprise Java, Java Native Interface, Editorials CORBA, Libraries, Embedded Java, XML, Wireless, IMHOs IDEs, using Java with others, and much more! Questions? E-mail [email protected] & more! easily searchable HTML FORMAT

JUNE 2001 169

Java COM PERSONAL JAVA

available. These extensions are defined executed, with a JVM interpreter. Don’t tion on a number of devices, we will by Sun with industry input via the Java be fooled; software interpretation is by need to produce separate binaries for Community Process. The APIs are well- an order of magnitude slower than each target device. Therefore, unless we known and well-documented, with machine code executing on the same are prepared to produce and maintain ample examples and tutorials to spring- processor. Many Java implementations separate binaries for each target, ahead- board development. The developer is rely on this approach to executing the of-time compilation may not be suit- less open to risk of vendor lock-in and, Java byte code, and while it is suitable able. It is for this purpose that the JIT

J2ME depending on the extension, can replace for many environments, it may not be compiler was invented — to provide the an implementation with a better one for others. As we shall see later, most benefit of both machine independence with minimal impact. mobile devices will have limited pro- and run-time performance! cessing power in terms of a lower clock As memory becomes more compact Java Risks speed in order to reduce battery power and less expensive, compilation will When developing applications with consumption. Where the use of a JVM probably become more widespread on Java, there are a number of common interpreter may provide acceptable per- mobile devices. In addition, JVM chips risks that may manifest themselves in formance on the same processor run- become much more popular as Java embedded or real-time environments. ning at a higher clock speed, it may well becomes more ubiquitous in embedded Actually, these are not “Java” risks per se; struggle at a reduced clock speed. So, and soft real-time systems. Many they are risks associated with JVM depending on the device and the appli- believe it’s the next logical step for JVM implementations and their adoption cation it may be possible to reduce chips to “blossom” and become more within restricted environments. Here much of this risk if there is the option to popular in order to improve perform- are the main ones I’ve come up against: use some form of target compilation, for ance, increase quality, and reduce costs • Speed example, JIT compilation or ahead-of- and power consumption. Shifting the • User interface responsiveness time compilation. software JVM risk as a hardware con- • Memory requirements JIT compilers will compile the byte cern will soon be the norm for most • Memory management — the Garbage code to the target machine code while consumer devices, and is planned as Collector the application is being executed. the next generation of JVMs for many • JVM selection However, there is little point in compil- device manufacturers. An example of ing byte code that is seldom executed, as this is the Moon Java processor Speed this will affect the overall performance (www.VulcanMachines.com). Java may be considered “slow” for a of the application and introduce “code

Home J2EEnumber of different J2SE reasons. This may bloat.” User Interface Responsiveness be due to Java features such as runtime Ahead-of-time compilation involves This factor is related to the issue of checks, security checks, dynamic bind- compiling classes during development. speed discussed above. Of course, the ing, synchronization, and garbage col- These may be the core Java classes, the perceived speed of the user interface is lection. However, another contributing application classes, or hot classes of great importance. It has a huge factor here is the way it is traditionally picked out by the developer in order to impact on the overall usability and per- best manage the perform- ceived quality of the application. These ance/memory overhead trade- two issues can be addressed in much the WHY MIGHT A VENDOR PROVIDE ONLY offs. The classes may then be same way as the speed issues. However, A JVM INTERPRETER? linked with the JVM in order to it is also worth noting that the applica- provide the required perform- tion may not need to be lightning fast in As previously stated, there is no obvious or best-fit ance boost. order to have a responsive user inter- execution method for Java. There are numerous vari- Unfortunately, though, while face. A device may not need to be fast at compilation (via JIT, Hotspot, all in order to give the user the percep- ables and trade offs. However, the reasons why ahead of time) may reduce the tion of speed. For example, the user ahead-of-time compilation or JIT compilation may not speed risk, it may inadvertently should have immediate feedback from be available may include the following: introduce other risks such as the user interface where possible. higher memory overhead, and • Developing a JIT/Hotspot compiler for the embed- power consumption and com- Memory Requirements ded and real-time world is very difficult. Many plexity. Compared to RISC and Many Java implementations have mobile devices simply won’t be able to afford the even CISC machine code, Java previously been criticized for being byte code is very abstract. It is memory-intensive. To be fair, this has extra memory requirements and processing over- machine-independent and is usually been due to the JVM or JIT com- head necessary for compilation. based on the concept of a stack- piler. Remember, we may be running • Vendors usually develop an interpreter first in order based machine interpreter not only our application but a Java byte- to prove the technology and gain experience with instead of a register-based one code interpreter or a just-in-time com- JVM development. They then move on to the more (mainly for portability reasons). piler as well. sophisticated execution models. As such, Java byte-codes can It is also worth noting that if you do represent more functionality in use the traditional byte code interpreter • For some mobile devices, ahead-of-time and JIT less space than their machine in favor of a faster JIT compiler, the technology is just too heavyweight, and a tradi- code equivalents. memory requirements are likely to be tional interpreter is more appropriate. For example, Ahead-of-time compilation lower. Java byte code is an abstract if a regular mobile phone is more likely to support also introduces another poten- stack-based intermediate code. As such, very simple applications, then an interpreter is tial problem. It reduces the it can do a lot more in less space than wholly appropriate. portability of the application. If real target machine code, especially if we want to deploy an applica- you’re using RISC-based CPUs.

170 JUNE 2001

Java COM XML Complete Works www.jdjstore.com

JUNE 2001 171

Java COM PERSONAL JAVA

However, there will be a price to pay – chances are that in this type of environ- 256MB or more of RAM. On a mobile speed. ment any idiosyncrasies will go unno- device we may have anything from 1/2 RAM also needs to be set aside for ticed; the machine will usually be re- MB to 64 MB. This means we need to the JVM’s internal dynamic data struc- booted at least once a day. With most respect the memory available, be realis- tures, such as the constant pool entries consumer devices such as , tic when specifying requirements, and and C stack. The Garbage Collector may PDAs and set-top boxes, however, this take care when designing, coding, and also need a large chunk of RAM depend- simply is not an option. testing our application. We may have to

J2ME ing on the internal algorithms used. If you are a device manufacturer or place more emphasis on profiling, opti- Most of this is often unnoticed on a OEM then understanding the imple- mizing and garbage collection valida- desktop machine where ample RAM and mentation details of the Garbage tion. virtual memory are available, a luxury Collector is imperative. If you a thick- In order to help use our RAM wisely, that consumer devices don’t have. client developer, then knowing how the we may be able to filter out unused There may be only a flash-based file garbage collector will behave (and thus classes, pre-load classes, and execute system in which to store JAR files, appli- affect your program) is also important. the JVM and application directly in flash cation data, and other resources. The ROM. executable JVM or compiled code may JVM Selection be burned into flash ROM and executed If you’re a device manufacturer or Less Processing Power directly from flash ROM, while using OEM, then you will probably have to Compared to a desktop PC, the RAM for stack and heap space only. decide which JVM implementation to processor is likely to run at a much lower However, we may only have RAM avail- integrate. An increasing number of clock speed and provide far fewer MIPS, able; in this case, we have a block of JVMS are being marketed at the embed- in order to conserve the limited battery RAM that is to be used for the JVM code, ded and “soft” real-time industry. power. On the other hand, most users heap and stack space, and also storing However, it is imperative that these are will still compare our application’s JAR files and other resources. Thus, the properly evaluated and understood responsiveness to that found on a desk- limited RAM we have is also taking on before making the deal. This may seem a top machine. the burden of a desktop machine’s hard somewhat naïve statement, but it’s sur- drive. prising how many decisions are made User Interface Thankfully, with the increasing solely on marketing information and so The user interface of a mobile device memory available in small devices, the called “strategic alliances”; hence, usu- is likely to be a major limitation. The memory risks should become less of a ally the marketing and selling of any interaction model may be very different

Home J2EEproblem. J2SE product is geared toward people who from what the developer is accustomed As previously mentioned, the use of hold the purse strings. to in a desktop environment. The user Java chips should become a very attrac- The golden rule here is: be wary of interface components available are like- tive alternative in order to mitigate the what you are told, no matter which ly to be as limited as the available screen risks associated with software-based vir- badge it has been stamped with or how real estate and resolution and display tual machines. Ahead of time, just in glossy the marketing brochures are. JVM quality. The interaction metaphor may time or any other type of compilation is slection will be a pivotal decision that be very different; other input methods simply not necessary as the Java chip will have a bib impact on the success of may be used, such as a stylus, numeric directly executes the Java byte-code; this your project. telephone keypad or soft keyboard. means that portability is maintained Thus, a developer will have to have a while executing the majority of byte- Developing for Consumer Devices “mind shift” in designing and develop- code similar to how a regular CPU exe- So, if we’re used to developing Java ing the user interface for a mobile device cutes machine instructions – fast. This applications for the desktop environ- and fully understand the look and feel of reduces the amount of memory ment, what differences are there when the device. required by obviating the need for inter- developing for consumer devices? Here’s pretation or on-the-fly compilation. It a list of the more important ones. The Bandwidth/Unreliable Connection AUTHOR BIO also means that compiled target bina- important thing to remember is that we Unlike the thick-client application Glenn Coates has been a ries don’t need storing. Because all this are no longer developing for a desktop running on a desktop connected to a practicing software “heavyweight” processing is reduced, it or server environment. We are develop- high-speed network, we may only have engineer for seven years. usually has the advantageous side effect ing for a restricted, embedded and pos- GSM or SMS connectivity. In the case of For the last four years he of reducing power consumption. An sibly real-time environment. a paging device, we may be restricted by has worked with mobile example of this technology is the MOON • Memory availability the number of characters we can send devices and Java, Java chip for deeply embedded Java • Less processing power per month and only be able to commu- developing products such solutions. See • User Interface restrictions and differ- nicate with the server using asynchro- as smart-phones, www.VulcanMachines.com. ing metaphors nous two-way paging messages. We are micro-browsers and digital • Communication also likely to have application protocol set-top boxes. Glenn holds Memory Management – Garbage bandwidth/Unreliable Connection restrictions. For example, we may only a BSc (Hons) degree in Collection • Battery power have sockets or a paging protocol rather computer science and is When developing a Java thick-client • Higher reliability requirements than RMI and HTTP. It’s normal for the also a Sun-certified application for a desktop environment • Lack of file system connection to be unreliable; if too many architect for Java with a powerful high-speed processor, users are on the network our connection Technologies. He works for 256MB or more of RAM, virtual memory, Memory Availability may be dropped halfway through a Vulcan Machines and a mass of hard disk space, it may be As discussed earlier, we know that we transaction. In the mobile world this is developing J2ME Java chip possible to ignore the implementation have less memory on a wireless device. “normal” behavior that needs to be han- technology. details of the garbage collector. The On a desktop PC we may be used to dled as such.

172 JUNE 2001

Java COM Battery Power A mobile device, due to its very nature, will spend most of its time relying on battery power. For this reason, the clock speed is usually very low. The application developer can do other things in order to preserve power, such as making applications easier to use and allowing information to be retrieved quickly.

Higher Reliability Requirements A mobile device, obviously, needs to be available when the mobile professional needs it. The user doesn’t expect to have to reboot the device if they want to call the emergency services. Due to the limited resources, memory leaks or other memory- related problems are likely to manifest them- selves very quickly on a mobile device, dras- tically affecting its usability and therefore its success.

Lack of File System Many mobile devices lack a filing system or may rely on a Flash filing system. Flash fil- ing systems have a maximum number of writes and need careful management to maintain reliability. Fortunately, this is usu- ally provided by the Flash driver. Some mobile devices may not have a filing system at all and a database may be used in its Leapnet place. As a device manufacturer developing a closed mobile device you may have to build the Java thick-client byte-code as part of the JVM and define entry points for your applications. However, if you’re in the majority and developing an application for an open device, then either a filing system or www.leapnet.com an alternative database will usually be avail- able. Summary This first article in a series looking at the development issues associated with mobile thick clients and J2ME has started by clarify- ing the general differences between thick clients and thin clients, while also attempt- ing to define the somewhat subjective terms thick and thin. I then looked at the great advantages of using Java technology for developing thick clients for mobile and con- sumer devices, before balancing this with the potential risks that may be associated with particular Java implementations in restrictive environments. Developing for mobile and consumer devices in contrast to desktop and server environments was then highlighted. In the next article I’ll take a look at Java Editions, in particular J2ME and Personal Java, and also at some of the issues involved in user interface development and architec- tural design of mobile Java thick clients.

[email protected]

JUNE 2001 173

Java COM June 2001 What’s OnlineThis Month...

JDJ Online JDJList JavaDevelopersJournal.com is your Join the JDJList, the new Java mail- source for industry events and hap- ing list community. Join other IT pro- penings. Interested in Java news and fessionals, industry gurus, and JDJ new developments? Check in for up- writers for Java discussions, answers to to-the-minute updates. Can’t get to the technical questions, and more. Voice newsstand? Don’t worry, get the info your opinions and assessments on you need online. You can get it from topical issues or hear what others have anywhere, anytime. to say. Join the JDJList now to monitor the JavaBuyersGuide.com pulse of the Java industry. JavaBuyersGuide.com is your best source anywhere, anytime on the Web Special JDJ Offers for Java-related software and products Check in for special offers on free in more than 20 mission-critical cate- seminars, Web conferences, how-tos, gories, including application servers, and even free software downloads. books, codes, IDEs, modeling tools, profilers, and more. Check the Buyer’s JDJ Readers’ Choice Awards Guide for the latest and best Java prod- Vote for your favorite Java software, ucts available today. books, and services in our annual JDJ Readers’ Choice Awards, January 10 Java Jobs through May 30, 2001. Winners will be If you’re an IT professional and are announced at JavaOne 2001 and honored curious about the job market, you’ve at the JDJEdge 2001 International Java come to the right place. Java Developer Conference and Expo. Developer’s Journal offers a portal for IT professionals, giving them direct access to the best companies in the nation. Simply type in a keyword and a job title along with a location, and get instant results. Search by salary, com- pany, and even industry. Need more help? Our experts can assist you with retirement planning, putting together a resume, immigra- tion issues, and more.

JDJEdge Conference JDJEdge 2001 International Java Developer Conference and Expo will take place in New York City, September 23–26, 2001. Sponsored by SYS-CON Events, the conference program will present exclusive keynotes, and focus on cutting-edge Java technologies in multi- ple simultaneous tracks, night school, and an accelerated weekend program. Look for daily updates, news, and registration information about JDJEdge 2001, the largest Java devel- oper conference and expo ever on the East Coast.

174 JUNE 2001

Java COM %%OffOff the annual SAVESAVE 57 57 subscription rate

Subscribe Receive12 issues of ANNUALANNUAL SUBSCRIPTON COVER PRICE RATE Java Developer’s $69.99 Journal for only $39.99! YOU PAY That’s a savings of $39.99 YOU SAVE 57% off the cover price. Off the Annual 57% Subscription Rate SYS-CON Sign up ONLINE at www.sys-con.com or call 1-800-513-7111 and subscribe today! www.sys-con.com

SYS-CON Reprints (201) 802-3024

JUNE 2001 175

Java COM ColdFusion Edge www.sys-con.com

176 JUNE 2001

Java COM ColdFusion Edge www.sys-con.com

JUNE 2001 177

Java COM XML Edge www.sys-con.com

178 JUNE 2001

Java COM XML Edge www.sys-con.com

JUNE 2001 179

Java COM Oracle Enhances Oracle9iAS Upping the ante The application server battleground continues to heat up. iPlanet has recently announced some major improvements to their product line. Oracle, too, is wrapping up a new release of WRITTEN BY their Oracle9i Application Server (Oracle9iAS) product with ALANWILLIAMSON updates to their caching and Java technologies.

While BEA’s WebLogic and IBM’s enabled J2EE application running on middle-tier servers have the ability to WebSphere are often named as the Oracle9iAS will be able to seamlessly transparently reroute JDBC connections front-runners in the application server take advantage of Akamai’s global net- and database requests to the failed-over race, we’re clearly seeing incredible lev- work of over 10,000 ESI-enabled content node. Depending on how the connec- els of technical advancement across delivery servers (as shown in Figure 1). tions are set up, Oracle9iAS promises to the board in the middleware space. The

Java platform is the technology that Content Assembly/Delivery makes such rapid improvements possi- on Edge using ESI ble – and the development community Edgegee ServSServer Content Generation is the beneficiary of all of this largesse. Client ESI Fragment Oracle and Akamai made news BroB owser Edgege ServerSe EdgegeeeSer ServerSeSer Updates recently when they announced that Web Databaseatabas they’ve collaborated on a new way to Internetternere improve the scalability of Web sites and Edgege SerServer millions of requests applications. The technology is called 1000s of requests 1000s of requests Edge Side Includes (ESI) and it defines a

simplified markup language that identi- millions of requests fies Web-page fragments that can be Inexpensive Infrastructure cached on ESI-enabled servers for faster Less Infrastructure Required delivery to end users. Dynamically gener- FIGURE 1 ESI Deployment Architecture ated Web pages provide a more personal- ized browsing experience, but the result- The J2EE containers in the upcom- provide configurable degrees of TAF ing computational overhead can be over- ing Oracle9iAS are rumored to be with the database – cold, warm, and hot whelming to a site’s infrastructure. extremely lightweight and easy to failover of persistent state. ESI promises to address this issue by install, and are expected to include The new Oracle9iAS release is slated enabling the assembly of both cached enhanced support for EJB 2.0. The prod- to be available on a broad range of and noncached page fragments at the uct also includes updates for perform- hardware platforms, scaling from low- edge of the network or the edge of the ance and scalability, with new load-bal- end uniprocessor machines to high- data center. Edge servers don’t normal- ancing and clustering for Java applica- end SMP clusters, and on all of the ly execute business logic, so they can tions. Oracle hinted that there will also major application server o/s platforms, run on less-expensive hardware and be additional session state replication including Solaris, HP-UX, AIX, Tru64, provide superior performance. and cluster failover capabilities, as well Windows NT, and Linux. Furthermore, Oracle and Akamai have pledged to as Transparent Application Failover the updated performance for J2EE make ESI an open standard and have (TAF) and database state management. applications promises to provide “clus- invited other vendors to join them in Every Oracle9iAS middle-tier server ter” support independently of the submitting proposals to the appropriate communicates with an Oracle database hardware platform or OS being used standards bodies. To use ESI, developers using a connection pool, which multi- (i.e., its cluster capability doesn’t embed ESI tags in their Web pages or use plexes clients on a smaller number of require a specific SMP hardware con- JESI (Edge Side Includes for Java) to gen- connections to the database, improving figuration). This allows J2EE developers erate ESI syntax automatically from J2EE performance and scalability. Every appli- and administrators to be able to lever- applications. Web sites and applications cation writes its long-lived state persist- age these features without being tied to that make use of ESI can be deployed on ently to a JDBC-enabled database. When any OS/hardware platform. application servers or content delivery the Oracle database is deployed in a clus- These exciting new enhancements networks that are ESI-enabled. ter configuration and a specific node in will undoubtedly “up the ante” in the Both Oracle and Akamai will support the database fails, all state maintained in hotly contested application server mar- ESI in their own products, including the the database is transparently “failed- ket. Watch for this release from Oracle upcoming Oracle9i Application Server over” to another node in the cluster. in the near future. and Akamai’s EdgeSuite content deliv- When Oracle9iAS is used in combi- ery network. For example, an ESI- nation with the Oracle database, the [email protected]

180 JUNE 2001

Java COM JDJ Store www.jdjstore.com

Next ajilon Month www.ajilon.com www.sys-con.com

JUNE 2001 181

Java COM Brokat Technologies Achieves ience and accessibility of a cen- Java 2, Enterprise Edition tralized, portal environment for CocoBase Enterprise O/R Compatibility universal component-based (San Jose, CA) – Brokat development and reuse efforts. Provides EJB Database Accesss Technologies’ Brokat Advanced www.flashline.com Server/J version 4.6 has been for BEA Weblogic Server 6.0 branded J2EE compatible for the Major Development in Java Java 2 Platform, Enterprise Testing Achieved with Parasoft’s Edition 1.2 specification from JContract and JTest 4.0 (San Fransisco, CA) – Thought Inc., Sun Microsystems, Inc. J2EE (Monrovia, CA) – ParaSoft has announced the integration of compatibility strengthens Brokat announced the release of Jtest CocoBase Enterprise O/Rs with the Technologies’ 4.0 and a new Java development BEA WebLogic Server 6.0 from BEA portfolio for tool, Jcontract. The new version Systems Inc. CocoBase simplifies the process of mapping relation- financial institu- of Jtest automates unit level al data with EJBs for use with BEA WebLogic. tions, telecommunications com- functionality using the Design by CocoBase boosts developer productivity by instantly mapping panies, enterprises, portals and Contract (DbC) format specifica- relational data, generating entity beans and JSPs, deploying to the e-businesses, everywhere, to be tion information included in the BEA WebLogic Server 6.0, and by eliminating the need to hand- able to leverage a standard com- class. Jcontract, a Jtest add-on or code database access for EJB entity beans and JSPs, which can pliant approach to user-centric stand-alone tool, decrease development time by as much as application development. can verify system- 85%. www.brokat.com. level functionality www.beasys.com and identify class/component Flashline Component Manager misuse by checking DbC con- Offers Convenient and tracts at runtime. PointBase's Java TogetherSoft Enables Together Scalable Web Portal www.parasoft.com Technology-based Database ControlCenter Solution for IBM (Cleveland, OH) – Flashline Receives JDBC Certification WebSphere App Server released Flashline Component Product News from Sitraka (Mountain View, CA) – PointBase (Raleigh, NC) – TogetherSoft Manager, Enterprise Edition (Toronto, ON) – Sitraka has announced that their database is Corporation has announced the (CMEE), which enables, promotes, announced JProbe 3.0, a leading certified through Sun availability of and measures software reuse. performance tuning toolkit for Microsystems’ new third-party Together Control- CMEE’s new Java (now with Java Database Connectivity (JDBC) Center for IBM’s Web-based improved technology certification program. WebSphere Application Server, architecture allows organizations usability), JClass allowing users to hot deploy and to easily scale reuse initiatives to a 5.0, (now with 3D charting), and remotely debug EJBs and servlets broad group of users throughout a DeployDirector 2.0 (now fully to a WebSphere Application Server. distributed enterprise. A Web JNLP compliant). Certification means Sun has www.ibm.com/websphere interface provides the conven- www.sitraka.com validated the PointBase JDBC www.togethercommunity.com technology–based driver for use with J2EE compatible products. Rational Test RealTime PointBase had to pass a suite of over 2000 tests in order to receive Announced at Embedded this certification. www.pointbase.com Systems Conference TogetherSoft Corp Announces WebGain Launches J2EE Compatibility New Products (Raleigh, NC) – Together (San Francisco,.CA) – Rational Software (Santa Clara, CA) – WebGain has ControlCenter 5 has received introduced Rational Test RealTime, a introduced a number of products: J2EE compatibility status from product that automates testing of Studio Professional 4.5, an inte- Sun Microsystems. The product’s embedded, real-time, and distributed grated development suite that integrated development platform applications. It also introduced streamlines the process of design- uses both the J2EE Patterns from Rational QualityArchitect for RealTime. ing, developing, deploying and Sun Microsystems and Rational Test RealTime manages the tedious and error- improving Java LiveSource from TogetherSoft to prone aspects of implementing, deploying, and running an and XML e-busi- automate the deployment of embedded test environment. ness applications; EJBs, EARs, JARs, and WARs. It Rational QualityArchitect for RealTime is integrated with WebGain Application Composer, a also allows clients to extend the Rational Test RealTime to add test automation capabilities to visual authoring and integration TogetherAPI so they can create Rational Rose RealTime. environment that simplifies enter- their own building blocks for Rational has also added support for the Sun Java 2, Micro prise application assembly from deployment to other application Edition platform and Mobile Information Device Profile to existing components, legacy sys- servers. Together ControlCenter Rational Rose RealTime. tems, and Web services; and is the first integrated develop- www.rational.com. Business Designer 1.0, a visual ment platform to earn this status. design and collaboration product. www.togethercommunity.com www.webgain.com

182 JUNE 2001

Java COM Career Opportunities The JDJ Salary Survey The results are in

ore than 1,150 readers worldwide responded to the recent WRITTEN BY M Java Developer’s Journal Salary Survey.The respondents covered a BILL BALOGLU & broad spectrum of IT titles and levels of expertise from entry- BILLY PALMIERI level to executive positions.

They shared information including city, kind of work in various Percentage Distribution of US Respondents their current employer for one state, country, title, current salary, previous parts of the United States. by Regions (958 in total) year or less. salary, years of professional experience, years South Part of this could be due in current position, and years with current The Big Picture West to the fact that many of the company. The average respon- 21% 25% companies that employ these As you may already know, the state of the dent has a total of eight developers are only 1 or 2 employment market for Java developers is years of professional 10% 23% years old. And we all know that one of our favorite subjects, which is why we experience, three years Southwest turnover can be high even with write a monthly column for JDJ. with their current compa- 21% established companies that East/Northeast From this wealth of raw survey data that ny but only two in their Midwest are constantly restructuring filled a 34-page spreadsheet, we set out to current position. As- and downsizing. draw some meaningful conclusions about suming that respondents The results of this survey Salaries by experience (across regions) who’s making what and where. We focused are working with Java in clearly support what we have

in $1000s 0 20 40 60 80 100 120 140 160 our attention on the vast majority of respons- their current position, on casually observed over the es – the 958 people who live and work in the a national average they past several years. Company United States. haven’t been using it for loyalty in the IT industry is That’s not to say we’re not interested in the very long. close to nonexistent. However, . California many skilled IT professionals working in the Eighty-four percent of No that lack of loyalty is clearly a international market. But figuring all the rates the U.S. respondents two-way street. of exchange for a dozen different currencies have been using Java for IT professionals with Java would have been a bit much for the already two years or less, and 63% So. California skills hop from one job to the daunting task that lay ahead of us. of them have been using next (84% of them stay for less

Were we able to draw some significant it for one year or less. /Northeast than two years) for a very good East conclusions about the salaries in the IT and Only 16% of the respon- reason – they can. And they developer industries in the United States? We dents have been working South know they’ll get more money think so. However, when considering the con- with Java for more than at the next position. clusions that we reached, keep in mind we’re two years. The employing compa- looking at a very broad range of respondents Granted, Java has only Midwest nies contribute to this job- working in a wide range of companies. been around for about six hopping phenomenon by con- For example, the salaries for respondents years, but the IT profes- stantly upping the salary ante. who have 1–5 years’ experience working in sionals who work with it Consider this: the average U.S. Southwest 1-5 yrs the East Coast/New England region range have leapt to high-paying respondent has been with his 6-10 yrs from $32K to $350K a year. The average salary positions in an incredibly or her current employer for 11-15 yrs for 1–5 years’ experience in that area is $78K short period of time. Northwest three years and is at a current (which does sound a little more normal). But The old tradition of a salary of $87K. the spread between the lows and the highs young apprentice putting in years of training That average respondent was making can be pretty wild. to learn a trade is now a relic of the distant $71K in his or her previous position. This Part of this is because respondents range past. The role of the seasoned veteran who means that across the United States, from just-out-of-school Web developers to trains that young apprentice has been trans- IT/Java professionals are making an aver- CTOs. We’re also assuming, with just cause, formed as well, but we’ll get to that later. age of 24% more in their current position that many of these people are working at high If you have any doubt that this is an than they did in their previous position hourly contract rates while others are report- extremely fluid industry with an incredible three years ago. ing full-time salaries at permanent positions. amount of turnover, consider these statistics. Is job hopping here to stay in this indus- Are we being forced to compare apples to Seventy-seven percent of IT professionals try? As long as companies continue to pay oranges here? Well, yes and no. We’re looking who responded to the survey have been with 24% salary increases to employees (88% of at highly paid hourly consultants next to their current company for three years or less. whom won’t stay with the company for more salaried employees, but contract or full-time, Sixty-five percent of them have been with than two years), who needs loyalty? In this the bottom line is: these are the dollars that their current employer for two years or less, environment companies are incentivizing IT companies are paying developers to do this and nearly half of them (46%) have been with professionals to keep moving on.

RecruitmentAdvisor Recruitment Advertising Advertising Information: – 800-582-3089 [email protected]

JJavaava COMCOM Career Opportunities

AVERAGES FOR ENTIRE US are distinctly different markets: But while the young guns of IT rule

Years in the profession 8 Southern California, Northern Cali- the West (and most of the country), sen- Years in the current position 2 fornia/Silicon Valley, and the Northwest. iority is still respected in the South and 3 Current salary $87K To get a sense of how IT salaries Southwest, which comprise 35% of the Last salary $71K progress over time, we’ve categorized survey respondents. JAVA EXPERIENCE (CURRENT POSITION) respondents by years of experience (1–5 IT salaries follow a more traditional Duration Cumulative % years, 6–10, 11–15, and 16 or more curve in the South, rising from $75K for > 2 YEARS 16% < 2 YEARS 84% years). 1–5 years to $85K for 6–10, $100K for < 1 YEARS 63% Across the board the vast majority of 11–15, and $119K for 16 years or more. < 10 MONTHS 13% respondents were in the 1–5 years of In the Southwest the curve grows from

(CURRENT COMPANY) experience category, with a huge range $70K for 1–5, $94K for 6–10, $95K for Duration Cumulative % of salaries within that category. 11–15, and $110K for 16 or more years. 23% < 3 YEARS 77% This isn’t too surprising if you keep in Regional differences may also be due 65% mind that Java hasn’t been widely used to the different types of companies that < 1 YEAR 46% for much more than five years, and the employ IT professionals. While the bulk SALARIES BY REGION industry has seen a huge swell in num- of West Coast companies are in the busi-

Northern Cal (119 responded) bers (and demand) within these past ness of creating new technologies and four to five years. fiercely competing for hot-shot talent, Years Average (in $1K) Range (in $1K) 1-5 85 40-170 IT professionals in other regions are 6-10 103 50-185 The Wild Wild West likely to be employed by traditional cor- 11-15 126 75-250 16+ 111 70-200 In Northern California where this porations with more conservative salary

Southern Cal (59 responded) industry was born, the average salary is structures and ranges. $85K for 1–5 years of experience, $103K Years Average (in $1K) Range (in $1K) 1-5 84 55-165 for 6–10, and $126K for 11–15 years. The Personal Picture 6-10 93 70-140 11-15 144 100-220 While we expected salaries at this scene As an IT professional, what should I 16+ 104 78-130 of the high-tech gold rush to be the do with this information? If my salary is East Coast/ New England (217 responded) highest in the country, these averages on the low end of the scale for my region

Years Average (in $1K) Range (in $1K) are only slightly higher than those in and years of experience, should I storm 1-5 78 32-350 Southern California. into my manager’s office with this article 6-10 104 49-300 11-15 116 58-300 Southern California respondents in hand and demand a raise? 16+ 115 60-280 earn an average of $84K for 1–5 years, We don’t advise it. Again, this is a South (247 responded) $93K for 6–10, and a healthy $144K for very broad picture we’re looking at that

Years Average (in $1K) Range (in $1K) 11–15 years of experience. takes only a few key facts about each 1-5 75 25-195 Northwest respondents earn a more respondent into account. We haven’t 6-10 85 40-150 11-15 100 59-207 conservative $80K for 1–5 years, $85K for looked at the résumés of all 958 respon- 16+ 119 65-275 6–10, and $104K for 11–15. You might dents and, frankly, we’d rather not. AUTHOR BIOS Midwest (197 responded) extrapolate that some of them learn the There are also tremendous variations Bill Baloglu is a principal Years Average (in $1K) Range (in $1K) ropes from Mr. Gates, then head south between these markets and extreme dif- 1-5 64 28-112 at Object Focus 6-10 94 53-210 for more sunshine and bigger bucks (but ferences in the cost of living in these (www.ObjectFocus.com), a 11-15 101 65-190 that’s merely idle conjecture). regions. The IT professional making 16+ 84 62-120 Java staffing firm in Silicon One interesting phenomenon is that $75K in the South is most likely living in Valley. Prior to that he Southwest (92 Responded) in every region we examined (with the a much bigger house than his or her was a software engineer Years Average (in $1K) Range (in $1K) exception of the South and Southwest), counterpart in Silicon Valley. 1-5 70 30-120 for 16 years. Bill has 6-10 94 65-250 salary averages took a dip after 15 years If you’d like a more detailed compar- extensive OO experience 11-15 95 60-125 of experience. There are a variety of rea- ison of salary ranges for the same type of 16+ 110 64-212 ,and has held software sons why this might happen. work in different parts of the country, Northwest (27 responded) development and senior The industry’s economy might be there are many good resources avail- technical management Years Average (in $1K) Range (in $1K) indicating here that after 15 years, IT able, including www.salary.com, which 1-5 80 60-118 positions at several 6-10 85 53-114 salaries simply top off. Despite what dot- does in fact compare apples to apples. 11-15 104 90-120 Silicon Valley firms. 16+ 92 87-95 commers were telling us mere months If you know of other resources that ago, the sky is not, in fact, the limit. help IT professionals get a good com- Billy Palmieri is a Industry professionals who’ve been parative picture of salary expectations seasoned staffing industry The Big Country working in IT for more than 16 years nationwide, we’d like to hear about executive and a principal The U.S. respondents to this survey have undoubtedly come up through those as well. of ObjectFocus. Before were fairly evenly spread across the many different types of technologies, We’ve provided a bird’s-eye view of that he was at major regions of the country. Twenty- many of which are no longer used. Yes, who’s making what and where. Will Renaissance Worldwide, a three percent were from the East the mainframe and COBOL experts had these numbers change dramatically by multimillion-dollar global Coast/New England area, 21% from the a heyday during the Y2K era, but it’s a next year’s survey? We don’t doubt it at IT consulting firm where Midwest, 25% from the South, 21% from Java, XML, and wireless world now. all. he held several senior the West Coast, and 10% from the It’s highly likely that many of these management positions in Southwest. senior engineers are voluntarily taking a [email protected] the firm’s Silicon For salary-survey purposes we divid- decrease in pay as they come up to Valley operations. ed the West Coast into three regions that speed on more current technologies. [email protected]

RecruitmentAdvisor Recruitment Advertising Advertising Information: – 800-582-3089 800-582-3089

Java COM ObjectFocus www.objectfocus.com

JUNE 2001 185

Java COM BACK PAGE Cubist Threads

WRITTEN BY BLAIRWYMAN Opportunities lost?

don’t follow the press much. In my As Roy and his band watched silent- So, how did I get here? Why do I get J2SE job, an EDUPAGE subscription is ly, I sat up there with my guitar and sang this chance to share my innermost Iabout as committed as I normally a couple of Beatles tunes I knew pretty while loops and curly braces? get, along with slashdot, the DNRC, well at the time. Afterwards I waited for The answer is simply, “Alan and a few other regulars. I see this as a the crowd to erupt in an unrestrained Williamson.” personal failing on my part but never cacophony of thunderous applause and I had the pleasure of meeting Alan worry too much about it; it’s just one of spontaneous universal acclamation. for the first time at the Java Migration a large list of personal failings. I waited, and waited, and waited; Conference sponsored by IBM If I were going to worry about a per- just as I was thinking of how best to Vienna. I don’t get to travel all that J2EEsonal failing, it would J2ME probably be my tragically and fatally impale myself on much – Vienna is a truly exotic locale apparent and utter incapability to the mike stand, Roy Orbison walked up for a “Midwesterner” like me – so become a legendary rock star. I even had and gently pulled me away from the when someone speaking (something a sort of a shot at it once, a long time ago. spotlight to the side of the stage. like) English introduced himself to When I was in my early twenties, I “I really enjoyed your music,” he me at the catered lunch, I couldn’t fancied myself a sort of folk musician. I said. “Are you going to be around tomor- help but pay attention. Alan intro- had learned a little guitar here and row? Maybe we could get together, if duced himself as being from a com- there, and could carry a tune if the bas- that’s alright, and play some tunes?” pany called “N-ary.” ket was big enough. Well, the late, great “Actually, I’m moving out of town Now, I’ve done some parameter Home Roy Orbison was between major gigs tomorrow,” I said to him. “Sorry.” parsing code so I asked him, “N-ary, eh? and happened to be playing at a local Mr. Orbison looked a little disap- Is that like ‘unary, binary, ternary,’ etc.?” hometown nightspot. As part of the pointed, shook my hand, and wished He said, “Spot on!” So I looked at my tie. show that night the band arranged an me luck. What might have happened I couldn’t see anything on my tie or “open mike” competition, where audi- had I changed my plans and stuck on my shirt, so I looked up quizzically. ence members could come up and sing around? Nobody knows, but instead of It was then that I realized “spot on” tunes with the band. some obscure JNI guru, I might’ve must mean something like “yes.” Now, I was actually moving out of become a “Traveling Wilbury”! To this day, I think that might have town the next day – I had my plane So, what am I doing here if I’m such a been the last time I fully understood tickets in my pocket and was off to see failure? Am I some sort of Java guru? something Alan said to me. the world – but I figured I’d take my Definitely not: I don’t program much So (near as I can tell), Alan has guitar to the open mike and just see actual Java code in my day-to-day work. asked me to contribute to JDJ from what would happen. It was one of However, Java remains at the absolute time to time; either that, or to attend a AUTHOR BIO those “loudest applause wins the core of my daily labor. How can I be ritual festival of log-throwing, haggis- Blair Wyman is a software prize” competitions and I didn’t know “doing Java” if I’m not writing it? Simple, munching kilt wearers. I’m not sure. I engineer working for IBM a soul in the room, but I figured a really. I mostly work on the JVM; the IBM guess if I see this in print I’ll know. in Rochester, Minnesota, rousing rendition of something-or- eServer iSeries JVM, formerly known as home of the IBM iSeries. other would win them over. the AS/400 Developer’s Kit for Java JVM. [email protected]

186 JUNE 2001

Java COM WebGain www.webgain.com

JUNE 2001 187

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

188 JUNE 2001

Java COM