A BZ Media Publication

Volume 1 I Number 4 Fall 2006

www.eclipsereview.com

SOAP? XML? WSDL? ? !!

IMPROVING CODE WITH STATIC ANALYSIS

Web 2.0! AJAX Meets JavaServer Faces

2727 MMusustt-Have-Have EclipseEclipse Plug-InsPlug-Ins Legacy Modernization with... NXTware™ ESB ...another Eclipse plug-in you can’t live without.

Implementing XML and Service Oriented Architecture doesn’t mean starting from scratch. Why not integrate and modernize application functions as you need them in Eclipse?

NXTware ESB provides just-in-time modernization from within an Eclipse development environment. Lower costs and reduce risk by creating SOA interfaces for the business functions you need, when you need them, with NXTware ESB for Eclipse. eCube Systems Learn more about Enterprise Evolution and Enabling Enterprise Evolution NXTware SOA for Eclipse. Call (866) 493-4224 Copyright eCube Systems LLC or visit www.ecubesystems.com. San Mateo - Boston - Houston Legacy Modernization with... NXTware™ ESB ...another Eclipse plug-in you can’t live without.

Implementing XML and Service Oriented Architecture doesn’t mean starting from scratch. Why not integrate and modernize application functions as you need them in Eclipse?

NXTware ESB provides just-in-time modernization from within an Eclipse development environment. Lower costs and reduce risk by creating SOA interfaces for the business functions you need, when you need them, with NXTware ESB for Eclipse. eCube Systems Learn more about Enterprise Evolution and Enabling Enterprise Evolution NXTware SOA for Eclipse. Call (866) 493-4224 Copyright eCube Systems LLC or visit www.ecubesystems.com. San Mateo - Boston - Houston

DGB[LQGG $0

Vol. 1 I No. 4 I FALL 2006

FEATURES Cover Illustration: “Earth and Sky,” by Meg Gencay 18 COVER STORY 27 Must-Have Eclipse Plug-Ins Rick Wayne takes you on a scenic tour of his favorite add-ins, covering lanaguage support, modeling, UI design, integration, frameworks and much more. DEPARTMENTS 27 SOAP? XML? WSDL? 7 Context Happy birthday, Eclipse! It’s been five years, and look Java? Eclipse!! how much the platform and community have grown. You can leverage Web services using the Eclipse Web Tools Platform, as Chrisopher Judd demonstrates. 8 Launchpad The latest tools, technologies and plug-ins for Eclipse developers.

32 Improving Code With 10 Foundation Static Analysis Good news on adoption of the Rich Client Platform, Steve Gütz teaches you how to and a first glance toward Europa. defeat code defects by leveraging Eclipse’s Test and Performance 11 Shoptalk Tools Platform. With Wolfram Workbench, Mathematica users gain a sophisticated Eclipse-based IDE.

13 Projects 38 AJAX Meets The Data Tools Platform makes it easy to work with JavaServer Faces relational . Max Katz shows how you can use component-based development for 41 Perspective building “Web 2.0”–style rich Has the open-source Eclipse platform ruined the Internet applications. commercial tools market—or helped it?

BZ Media LLC | 7 High Street, Suite 407 | Huntington, NY 11743 | +1-631-421-4158 | fax +1-631-421-4130 | www.bzmedia.com | [email protected] President | Ted Bahr Executive Vice President | Alan Zeichick

Eclipse Review is published 4 times a year by BZ Media LLC, 7 High Street, Suite 407, Huntington, NY 11743. POSTMASTER: Send address changes to BZ Media, 7 High Street, Suite 407, Huntington, NY 11743. Ride along is included. Copyright © 2006 BZ Media LLC. All rights reserved. Eclipse Review is a trademark of BZ Media LLC. Eclipse is a trademark of The Eclipse Foundation. Sybase_WorkSpace_Ad.qxp 5/25/06 9:47 AM Page 1

Sybase WorkSpace: Do Something More Interesting

A SINGLE ENVIRONMENT OFFERS WHAT YOU NEED FREEDOM TO CUSTOMIZE BASED ON YOUR BUSINESS NEEDS Sybase WorkSpace is a Java™ toolkit offering the five most important WorkSpace’s modular packaging allows enterprises the flexibility to design and development tools in an integrated easy-to-use, open decide how to assign business critical tasks to developers, rather than source framework: requiring them to fit into ill-fitting “roles” predetermined by a vendor. • development • mobile development You buy only the pieces you need, enabling you to customize your • web application development • enterprise modeling environment as you see fit. • services-oriented development With Sybase WorkSpace, you’re finally free to do the design and MAKES DEVELOPMENT AND DESIGN EASY TO LEARN AND USE development that’s interesting to you. For more information and Using industry-leading integrated model-driven design, visual develop- to download White Papers and an evaluation copy, visit ment and task-based wizards, Sybase WorkSpace automates mundane www.sybase.com/workspace tasks and cuts the typical development tool learning curve, freeing developers to concentrate on what’s important—business logic.

Copyright © 2006 Sybase, Inc. All Rights Reserved. All product and company names are trademarks of their respective owners. CONTEXT From the Editor | by Alan Zeichick

EDITORIAL Editorial Director Alan Zeichick +1-650-359-4763 [email protected]

Copy Editor Laurie O’Connell Happy Birthday, Eclipse! Contributing Editor George Walsh [email protected] ART & PRODUCTION It’s been five years since IBM launched Eclipse as Art Director LuAnn T. Palazzo an open source project. The technology had been Art/Production Assistant incubating inside Big Blue since the late 1990s as a Erin Broadhurst next-generation Java IDE, but IBM’s announcement SALES & MARKETING Publisher that it was open-sourcing Eclipse, on Nov. 7, 2001, set Ted Bahr the platform on the path to super-accelerated growth. +1-631-421-4158 x101 [email protected] Today, Eclipse is second only to Microsoft’s Visual Southwest U.S./Asia Studio in adoption, surpassing Sun’s NetBeans and Robin Nakamura +1-408-445-8154 Borland’s JBuilder in the Java space. [email protected] IBM’s commitment to Eclipse was extensible, standards-based components Northwest U.S./Canada Paula Miller further demonstrated by its willingness for a tools platform upon which soft- +1-925-831-3803 [email protected] to divest itself of its intellectual proper- ware developers can create specialized, ty and form the independent Eclipse differentiated and interoperable offer- Southeast U.S./Europe Jonathan Sawyer Foundation in February 2004. The ings of tools for system management.” +1-603-924-4489 unprecedented moves toward open That’s a new direction for the [email protected] source and open governance launched Foundation, driven by companies like Northeast/Central U.S./Canada Eclipse into orbit. IBM, Cisco, Intel and Compuware. David Lyman +1-978-465-2351 Another advance is the Rich Server [email protected] WHERE NO STANDARD IDE Platform User Interface Framework, or Advertising Traffic HAS GONE BEFORE… RSP-UI. (Gotta love those Eclipse Phyllis Oakes But that’s not what’s sustained it there. acronyms!) This project is conceptually +1-631-421-4158 x115 [email protected] The Eclipse Foundation and its active similar to the Rich Client Platform,

Marketing Manager members have continued to broaden except that it allows the creation of Marilyn Daly the platform’s charter. They’ve intro- pluggable, componentized, server-side +1-631-421-4158 x118 [email protected] duced Eclipse into new areas, going applications, where plug-ins communi- where no standard IDE has gone before. cate with each other through extension List Services Nyla Moshlak To name just a few: The Rich Client points and OSGi services. This project +1-631-421-4158 x124 Platform has taken on a life of its own. hasn’t made much progress lately, but [email protected] The /C++ Development Tool project the concept is fascinating. Reprints showed that a Java IDE doesn’t have to A more active project is the Lisa Abelson +1-516-379-7097 be limited to just Java. The Device Subversive Project, which seeks to cre- [email protected] Development Platform helped ate a Subversion plug-in for Eclipse Accounting programming think inside the box, as with functionality similar to the Eclipse Viena Isaray +1-631-421-4158 x110 did the Embedded Rich Client Platform. CVS Team project. If the project is suc- [email protected] As Eclipse reaches its fifth year, the cessful, the team hopes that Subversion READER SERVICE organization has a number of fascinat- support will become a core Eclipse fea- Director of Circulation ing new projects that are either just set- ture. Polarion Software, which sells Agnes Vanek +1-631-421-4158 x111 ting sail or making progress. Some are application life-cycle tools for [email protected] making more progress than others, but Subversion, is running the project. So Customer Service/Subscriptions that’s what happens in a community. far, it’s on track for release in 2007. +1-631-421-4158 x124 One new project is COSMOS, which The first five years of Eclipse have [email protected] extends the Eclipse platform outside of been exciting—look how far the tech-

BZ Media is an Associate and into more nology, and the organization, have Member of the Eclipse Foundation, www.eclipse.org general IT: “The mission of the Eclipse come in a short time. I can’t wait to see COSMOS Project is to build generic, what happens next.

Fall 2006 www.eclipsereview.com | 7 LAUNCHPAD The Latest Tools and Technologies

GWT Designer Delivers AJAX completion, a C/C++ debugger, a named-user licenses costs ?980, plus GUI for Google Web Tool C/C++ launcher, a parser and index- ?245 of annual maintenance. Instantiations is offering GWT er, a search engine, content assist and www.guidancer.com Designer, a new tool for AJAX Web a Makefile editor and builder. The applications using the Google Web company builds on Eclipse with several SHORT TAKES Tool. GWT Designer is built on OSE-aware plug-ins that help develop- Stylebase is a new open-source WindowBuilder Pro, the company’s ers solve complex system-level prob- tool for maintaining a reuse repository software for creating Java graphical lems in their application code. These for architectural models and design user-interface applications for , plug-ins include a system browser for patterns. The software and the reposi- Mac OS X and Windows. GWT viewing and manipulating OSE system tory assist developers in applying a Designer provides developers with a objects, a pool profiler for browsing quality-driven architecture design to rich WYSIWYG GUI construction envi- and analyzing system memory utiliza- software engineering in a way that ronment. Developers simply drag-and- tion, a run-mode debugger with a pro- promotes software reuse. The tool can drop composites, layouts and controls gram launcher (loader), and a help be used in three ways: as an electron- when building user interfaces, which viewer for viewing OSE documents and ic library, where an architect can can be tested and deployed using the references. All Optima plug-ins support browse the stylebase as a pattern cat- Java-to-JavaScript compiler provided fully distributed debugging, which alogue; for model evaluation; where by Google. GWT Designer also enables any target CPU in a connected the architect detects which patterns includes bidirectional code generation, network to be accessed without the have been used in an architecture a WYSIWYG designer and Cascading need for a direct connection. model and then checks from the Style Sheet support. Its GWT applica- www.enea.com stylebase which quality-attributes are tion launch system has a shortcut for associated with these patterns; and fast launching using the popup menu GUIdancer Tests Without for constructing a new architecture or editor hot key. It also has intelli- Coding model, where the architect searches gent refactoring, where renaming or GUIdancer is an Eclipse-based envi- the knowledge base according to the moving a module class or remote ronment from Bredex for testing desired quality characteristics. service updates the module XML file Java/Swing application GUIs that the stylebase.sourceforge.net and renames any associated Async company claims requires no coding. and Impl classes. The software costs New in version 1.1, released last GNATbench for Eclipse is a plug-in that US$39 for an annual subscription. week, is the ability to execute batch provides editing, browsing and build- www.instantiations.com tests from a command line, support for ing features for Ada (including Ada testing multilingual applications using 2005) development using AdaCore’s Real-Time IDE for Enea’s OSE the same test components, new capa- GNAT Pro toolset on the Eclipse plat- Leverages Eclipse, CDT bilities for trees and tables, and an form. The builder produces executables Optima is a new Eclipse-based IDE for improved user interface. First released for native systems and embedded OSE, a time-time in January as a preview, GUIdancer processors (in the context of Wind from Enea. Optima, which costs $3,000 1.1 for Linux, Mac OS X, Solaris and River’s Workbench), and the debugger per seat, uses Eclipse 3.1.2 and Windows also now includes an API to supports both native and embedded C/C++ Development 3.1.1 to provide extend the tool—without code—for system debugging. GNATbench system-level browsing, debugging, pro- applications that use non-Java/Swing includes an Ada-specific editor, code filing and analysis tools for large-scale components and actions. To avoid the assistance for Ada, code browsing, a distributed systems spanning multiple need for programming, GUIdancer project explorer, an integrated builder processors and operating systems. employs a so-called specification con- and an integrated debugger. The com- Optima uses the Eclipse Workbench cept, which creates modular, reusable pany offers a separate Ada plug-in for and Workspace concept for building tests from source code before an appli- Wind River’s VxWorks, but this plug- images and managing projects, and cation is completed. On the desktop, in produces executables for native provides plug-ins for most software the program requires Java 1.5, which systems, rather than embedded configuration management tools. The is included with the Windows down- processors; similarly, the debugger CDT includes a C/C++ editor with load. The server component runs on supports native system debugging. language-aware highlighting and code Java 1.3. Demo licenses are free; www.adacore.com

8 | ECLIPSE REVIEW Fall 2006 Remember when the sky was the limit?

With Intel® Software Development Products, the Swinburne Center for $VWURSK\VLFVLVVKRZLQJWRGD\·VNLGVDXQLYHUVHÀOOHGZLWKXQOLPLWHGSRVVLELOLWLHV

THREADED APPLICATIONS HELP UNRAVEL THE ORIGINS OF THE UNIVERSE. Take advantage of the power behind multi-core processors by introducing threading to your applications. Threading allows you to use hardware parallelism to improve application speeds. Intel® Software Development Products are on the leading edge of threading technology, giving you the opportunity to discover the performance potential you need. So whether you create applications that model the solar system or enable a gaming system, Intel Software Development Products give your applications the power of parallelism.

Visit www.intel.com/software/products/eclipse for more information.

Copyright Intel Corporation, 2006. All rights reserved. Intel, the Intel logo, are trademarks of Intel Corporation or its subsidiaries in the United States and other countries. *Other names and brands may© be claimed as the property of others. FOUNDATION From the Eclipse Foundation

Good News on RCP Adoption

A recent Evans Data survey indicated strong growth in be late June 2007. The list of projects is the awareness and adoption of the Eclipse Rich Client expected to include the entire Callisto Platform (RCP). A survey of the Eclipse user community indicated project, plus additional ones. Stay tuned for more details. that almost 23 percent of the respondents were using Eclipse RCP. This is a 130 percent increase over a previous 2005 study. More NEW MEMBERS OF THE importantly, the survey indicates strong growth and momentum for ECLIPSE FOUNDATION future RCP usage, with 68 percent of the respondents indicating We would like welcome Simula Labs they will be using it within the next six months. A great sign of a as a new strategic developer of the strong future for Eclipse RCP. Eclipse Foundation. In addition, Sony Ericsson Mobile, ARM Limited, Active ECLIPSE EVENTS bug-fix maintenance release for this Grid andKPIT Cummins have joined as Thanks to BZ Media, the Eclipse com- date. Users can go to the Eclipse update add-in providers. The Eclipse Founda- munity has a great new Eclipse con- site to download Eclipse 3.2.1 and the tion now has 142 member organiza- ference to attend. The second annual new releases of the other projects. tions and more than 750 committers. Eclipse World conference was held Sept. 6–8, 2006, in Boston. By all IN 2007, IT’S EUROPA! PROJECT UPDATES accounts it was a great success and a The planning has started for the next Here is a summary of project reviews great place to get solid technical con- year’s coordinated release train, called that have arisen so far in 2006. We tent on different Eclipse projects. We Europa. Like Callisto, Europa will fea- hope to make this a regular feature of look forward to the EclipseWorld ture a coordinated release of the major this column. It is based on the RSS 2007, which will be held Sept. 6–8 in Eclipse projects. The plans still need to feed at www.eclipse.org/projects/ Reston, Virgina. be completed, but we expect the date to reviews-rss.php. The Eclipse Foundation also launched a new European event in Table 1 Project Updates Germany, called Eclipse Summit Europe. It was held Oct. 11–12 in PROJECT REVIEW DATE Esslingen, Germany, and attracted Parallel Tools Platform 1.0 Released Approved Aug. 15 300 Eclipse enthusiasts. The Summit ECM Rich Client Platform (Apogee) Project Approved Aug. 15 featured four technical symposia cov- Google Summer of Code Project Created and Provisioned Aug. 18 ering topics such as modeling, rich SVN Team Provider Proposal Updated Aug. 20 Aperi Storage Management Project Created and Provisioned Aug. 24 client applications, server-side Eclipse g-Eclipse Proposal Posted Aug. 25 and test-driven development for the Embedded Rich Client Platform 1.0 Released Approved Sept. 11 embedded systems space. Eclipse Orbit Project Created and Provisioned Sept. 22 COSMOS Proposal Updated Sept. 28 MAINTENANCE RELEASE Eclipse Platform 3.2 Release Approved Oct. 2 Subversive Project Proposal Updated Oct. 5 FOR THE ECLIPSE CALLISTO ECM Rich Client Platform (Aprogee) Project Created and Provisioned Oct. 6 PROJECTS g-Eclipse Creation Review Oct. 15 A maintenance release of the Callisto Model-to-Text Transformation Proposal Posted Oct. 16 projects was made available on AspectJ Development Tools 1.4.1/1.5.3 Release Review Oct. 17 September 29, 2006. All 10 projects that Model Development Tools Project Created and Provisioned Oct. 18 Callisto Simultaneous Release Approved Oct. 19 participated in the June Callisto release CDT 3.1 Release Approved Oct. 19 coordinated the availability of their

10 | ECLIPSE REVIEW Fall 2006 SHOPTALK Applications in the Real World | by George Walsh

Wolfram Goes to Math Class, Eclipse Style

It’s a given that any reader of Eclipse Review sees Eclipse key features of Eclipse is that it pro- as a top-notch development environment. Its extensibility vides a great development environ- via plug-ins is an added benefit. Many also know that it can be ment for building Eclipse tools. Eclipse as an IDE is a wonderful tool used a front end or even the basis of an application. While Wolfram in itself.” Research doesn’t go as far as using the Eclipse RCP, it does make Wickham-Jones believes that one use of the first three options, making the company somewhat of a of Eclipse’s strengths is its ability to new power user in the community of Eclipse development. support languages other than Java. “Eclipse has great application devel- Wolfram Research Recently, Wolfram released a new opment mechanisms and useful APIs (www.wolfram.com), based in product called Wolfram Workbench, a and engineering. It’s very suitable for Champaign, Ill., is the developer of version of the product based on building extra plug-ins that add sup- Mathematica, a well-known software Eclipse. Users who currently use port for languages other than Java. application that integrates a numeric Mathematica now have a means of It’s quite common for people to build and symbolic computational engine, customizing the application via the support for Python, Perl and other graphics system, programming lan- functionality inherent in Eclipse, and languages. What we’ve done is to guage and documentation system current Eclipse users now have the build support for Mathematica.” along with connectivity to other appli- ability to use Mathematica as a set of Mathematica is built using a het- cations. plug-ins in their own Eclipse installa- erogeneous collection of programming Mathematica can handle complex tions, offering them mathematical languages. Some of it is built in C, symbolic calculations that involve mil- computation capabilities that can be some in Java, and lot of it in the lions of terms; load, analyze and pro- altered to suit their needs. They can Mathematica language itself. The vide visualization of data; solve differ- also use Workbench to build their application really has no specific ential equations and minimization own technical applications, whether development environment; for the problems numerically or symbolically; they’re addressing engineering, sci- Mathematica functionality itself, there perform numerical modeling and sim- ence, finance or educational markets. is still no alternative but to use ulations ranging from simple control Wolfram’s own custom programming systems to galaxy collisions, financial ECLIPSE AS AN IDE… language. For developing other parts derivatives, complex biological sys- FOR ECLIPSE! of the product, the company has used tems, chemical reactions, environmen- In addition to offering the Eclipse ver- a variety of languages and IDEs such tal impact studies and magnetic fields sion of Mathematica and its capabili- as C++ and Visual Studio. However, in particle accelerators; and facilitate ties in a plug-in form, Wolfram took because Mathematica runs on many rapid application development for advantage of another obvious Eclipse platforms, Eclipse offers the type of engineering companies and financial capability: using it as an IDE. In other flexible support that’s important to institutions. In short, it does math in words, the company used Eclipse to many of its users. a big way. There are nearly two mil- develop for Eclipse. In the future, Wolfram is looking lion users of Mathematica, according “It would be possible to build the toward making use of some of the to Wolfram, in both industry and aca- plug-ins and Eclipse version of newer Eclipse tools that it sees as demia. Mathematica without using Eclipse, very valuable. “We hope to use some but it would be enormously inconven- of the more recent plug-ins to build George Walsh, a technical writer based in ient,” says Tom Wickham-Jones, more tools for Mathematica,” says San Francisco, is a contributing editor to director of kernel technology and lead Wickham-Jones. “All of these plug-ins Eclipse Review. Workbench developer. “One of the have their own extension mecha-

Fall 2006 www.eclipsereview.com | 11 SHOPTALK

nisms. The tools we’re look- the company is investigating ing at in particular are the Figure 1 Wolfram Workbench provides an IDE that’s not just good for is enhanced refactoring. For Web Tools Platform and programming, but for sophisticated numerical analysis. example, people conducting C/C++ Development research often use Eclipse as Tooling. To build tools for sort of a vehicle for imple- the Web version of menting their ideas. Mathematica, we would pro- Wickham-Jones doesn’t vide users with think it’s common to use Mathematica WTP tools. We graph theory techniques by could also use CDT to make themselves in Eclipse use of Mathematica’s own because it’s difficult to sup- extension mechanism to port large source files that hook into C or C++ code.” use a graph to represent the Wickham-Jones believes files, functions and compo- that CDT will become espe- nents that relate to other cially important to components. He states that Mathematica users. “CDT is it will soon be possible to relatively new, but it’s pick- take graphs from source ing up steam. Having a het- code and use the graph the- erogeneous language system under The Wolfram Workbench is an IDE ory features in Mathematica to do one IDE is pretty appealing. That’s for Wolfram products that is actually manipulations on these graphs. relevant to Java because a version of Eclipse that has been Graph manipulation works well in I think they’re much more likely to be customized by adding tools for work- Mathematica, and providing this func- proficient in another language in addi- ing with Mathematica and other tionality to Eclipse users could poten- tion to Java than, say, Visual Basic Wolfram technologies. These tools tially be very helpful. The application programmers. CDT is another universe are all built, as are all Eclipse tools, also offers graph layout tools that can of programming languages. It could with Eclipse plug-ins—the Eclipse support tens of thousands of nodes. even help Mathematica developers extension mechanism. Future Eclipse functionality may only build support for Fortran, which is Wickham-Jones notes that Eclipse be on the drawing board for now, but very important for programmers deal- plug-ins have access to a large and the director of kernel technology sees ing with mathematics. It’s somewhat rich library of functionality that can many exciting possibilities. specialized, but many large research take advantage of many useful fea- Because Wolfram allows users of its labs have a huge investment in the tures such as encapsulation, version- Workbench product to use it in stand- language.” ing, localization, a help system and alone mode or as a set of plug-ins, The fact that Eclipse is an open Web-based updating. In addition to its Wickham-Jones says Workbench pro- source environment can also add library and components, other key vides another important feature. value to developers using Wolfram Eclipse features that Wolfram took “Eclipse makes it very easy to produce Workbench because Eclipse is also a advantage of include the ease with an application that has your own look sort of how-to manual on Eclipse. If which plug-ins can be built. and feel rather than the Eclipse look something doesn’t work, it’s easy to “Eclipse contains a large number of and feel. This is an important step in run the code through a debugger, see wizards and tools for building plug- giving your application a fully profes- your source code and step into the ins,” Wickham-Jones notes. “As you sional appearance, whether you’re Eclipse APIs to determine why things develop, you can easily launch anoth- simply using our products or using aren’t working the way you expect- er installation of the environment that our set of plug-ins to add functionality ed—a useful way to learn things that uses your tools and allows you to to your own. We took advantage of aren’t documented. track down problems. The environ- that feature and assume that users of Wickham-Jones emphasizes that ment makes it easy to create and run our plug-ins will, as well.” the feature provides the hard-core unit tests, which can also boost the Any company or institution that inner knowledge that’s usually quality of your application.” requires extensive mathematical func- reserved for people who have been tionality now has a tool that they can programming for many years. A WORLD OF FEATURES use in Wolfram Workbench. At the Typically, commercial tools don’t offer AND FUNCTIONS same time, we once again see that that capability, but Wolfram provides Wolfram sees a world of Eclipse fea- Eclipse can often be a means to an some of its own source code for exact- tures that complement its products— end, whether it’s used as an IDE or ly the same reason—instructing its and Mathematica functions that could an extension mechanism for other users. be of use to Eclipse users. One avenue products.

12 | ECLIPSE REVIEW Fall 2006 PROJECTS Fundamentals of the Platform | by Larry Dunnell, John Graham, Brian Fitzpatrick and Hemant Kolwalkar

Grab Relational Data With The Data Tools Platform

Dealing with data that’s stored in an outdated relational components communicate with it. form is often the bane of a developer’s existence. However, Typically, you’ll need a driver and that data is typically still valuable and accessing it is a necessity. configuration information to gain access to that data source. Each con- Having an intuitive and relatively easy-to-use means of making it nection is likely to have different available is the goal of the Data Tools Platform. The three founding configuration settings, while the projects comprising DTP—Model Base, Connectivity and SQL location and default values for the Development Tools—meet the platform goals that their names imply driver are usually constant across in the DTP 0.9 release, and form what we’ll call the DTP core. connections. In DTP Connectivity, these requirements are met by the While frameworks and tools are support. Here, we’ll explain the ini- driver template and connection the necessary foundation, you’ll tial steps you’ll use to access rela- management frameworks, along have trouble leveraging DTP tional data sources using DTP. with their associated tools. (www.eclipse.org/datatools) directly Once you establish the connec- without additional components sup- LEVEL OF INTEGRATION tion and populate a domain model porting your specific data source. A data source can integrate with with its contents, the next step is to While you could follow the Apache DTP on several levels. Depending on build tools using these capabilities. Derby specializations provided as your requirements and data source, For relational data sources, DTP has part of DTP, that’s neither practical it might make sense to support all of the SQL Development Tools project. nor desired. Instead, you’d probably these levels, or only some of them. This project contains tools that rather have specialized data source Each DTP core project exposes API you’d expect from an entry-level, support close at hand. That’s where and (where relevant) extension developer-centric SQL tool, includ- the DTP Enablement project comes points. These two elements are the ing a SQL editor, results view, the in: It seeks to offer as many open- touchpoints for DTP integration. ability to execute SQL statements source data sources as possible. The You’ll want to survey the opportuni- and so on. The SQL tools in the cur- Enablement project will serve as a ties that DTP gives for extension, rent DTP release work with relation- clearinghouse for DTP data source noting the places that are useful for al data sources based on the SQL your data source. model in a generic manner. Larry Dunnell is a software engineer at The first thing to consider is Once you specialize a model and IBM, and is a committer for the Data Tools whether the data source’s domain is provide connectivity for a relational Platform as well as the data tools compo- nents in the Web Tools Platform Project. represented in an existing DTP data source, you should get basic Model Base component. As of DTP SQL tooling support by default. In John Graham of Sybase has been develop- 0.9, the Model Base components are many areas, you might want to er on Eclipse since version 1. all EMF-based domain models for adapt the SQL tools to take advan- Brian Fitzpatrick of Sybase has worked relational data sources. If your data tage of specific functionality. If you extensively in Java on Eclipse-based proj- source is relational, it makes sense study the Apache Derby sample ects, eventually becoming a founding com- to specialize the Model Base compo- implementation in DTP 0.9, it mitter on the Eclipse Data Tools Platform. nents for your case, since this shouldn’t be hard to understand and Hemant Kolwalkar is an advisory software avoids duplicating effort and offers use them for other cases. engineer at IBM Rational, and works on the model-driven representation of the development of IBM Rational Data Architect relational domain. MODEL SPECIALIZATION and the Eclipse Web Tools and Data Tools Platform projects. Each data source has a channel, As part of the core, the Model Base or connection, through which other project houses domain object mod-

Fall 2006 www.eclipsereview.com | 13 PROJECTS

els for use with the rest of DTP. To • SQL Query: An abstract view of base vendor documentation. keep the scope manageable in the actual SQL queries first data source releases, DTP’s • SQL XML Query: An abstract EXPOSING THE VENDOR designers decided to concentrate on view of XML data processed in DOCUMENT models for relational data sources. SQL queries Once you’ve generated a database-- Based on the Eclipse Modeling Unlike many other Eclipse plat- specific XMI database vendor docu- Framework (EMF), it includes mod- form components, you’ll need to do ment, you will need to use the els for the following: some work to use the models with org.eclipse.datatools.connectivity.sqm • SQL: Based on the SQL 99/03 your own database. The key steps of .core.databaseDefinition extension specifications, SQL is the basis this process are to create your data- point to expose it. You can extend the for the other models base definition and expand the databaseDefinition extension point for • Database Definition: For spe- Ecore/Genmodel for the SQL Model. org.eclipse.datatools.connnectvity cializations not covered by the .sqm.core using the following defini- SQL Specification DATABASE DEFINITION SURVEY tion: The SQL Model is a metamodel based base. cedures and their detailed parame- ters—are implemented. These values specify a unique 1. What versions do you support? Are the answers to The DTP Model Base provides a name and version string for this the following questions different depending on which Java program to create a new data- given vendor XMI document— version you’re discussing? Each database/version base vendor document and is stored MySQL as the product and 4.0 as combination should be represented by a unique data- base vendor document that will then be exposed via in XML Metadata Interchange (XMI) the version. the org.eclipse.datatools.connectivity.sqm.core format. The Java class uses the If you look at the extension .databaseDefinition extension point. database definition model as a base, point’s file property, it refers to a 2. Are view triggers supported? then goes through the model ele- particular path to the XMI document 3. What's the maximum identifier length? ment-by-element, setting specific in the plug-in that exposes it. The 4. What's the maximum comment length? 5. Is sequence supported? details. It walks through items such directory under runtime/vendors 6. Is MQT supported? as columns, views and triggers, corresponds to [product] underscore 7. Is alias supported? specifying available data types and [version,] just like the XMI file’s 8. For columns: qualities for those items. When the name, MySQL_4.0. A display string a. Is identity supported? Java program is run, it will create an for the product and version is pro- b. Is computed supported? c. Is Identity start value supported? XMI document to serve as the data- vided to make it more human-read- d. Is identity increment supported? e. Is Identity maximum supported? f. Is Identity minimum supported? Table 1 Primitive types supported by the base SQL model g. Is identity cycle supported? 9. For constraints: Character data Binary data Numeric data Other a. Is a clustered primary key supported? b. Is a clustered unique constraint Character Binary Numeric boolean supported? character varying binary varying Decimal date 10. What primitive types are supported: character, deci- mal, double, integer or numeric? The base SQL model character large object binary large object Smallint time supports the types shown in Table 1. For each, you national character Integer timestamp would populate your specialized model, as in the exam- national character varying Bigint interval ple shown in Listing 1. national character large Float datalink To make setting these values easier, the ExampleFor object VendorPrimitiveWrite.java file found at www.eclipse.org/ datatools/project_modelbase/modelbase_doc/ Real xml sampleZip/ExampleForVendorPrimitiveWrite.java can be double precision used.

14 | ECLIPSE REVIEW Fall 2006 PROJECTS

able. In this case, the 4.0_Product String and 4.0_VersionString are Listings offered via the plugin.properties file. I LISTING 1: AN EXAMPLE OF CODE FOR SUPPORTING THE PRIMITIVE TYPES SHOWN IN TABLE 1 EXPANDING THE PredefinedDataTypeDefinition characterDataTypeDefinition = ECORE/GENMODEL DatabaseDefinitionFactory.eINSTANCE.createPredefinedDataTypeDefinition(); Typically, you don’t need to alter the characterDataTypeDefinition.setPrimitiveType(PrimitiveType.CHARACTER_LITER- definition for SQL Model. However, if AL); you do need to add new model defi- characterDataTypeDefinition.getName().add("CHAR"); characterDataTypeDefinition.getName().add("CHARACTER"); nition to the SQL Model, complete characterDataTypeDefinition.setMaximumLength(254); the following steps: characterDataTypeDefinition.setKeyConstraintSupported(true); • Change the SQL Model file to characterDataTypeDefinition.getDefaultValueTypes(). add(DefaultValueType.CURRENT_USER_LITER- add your database element or AL); create a new Ecore that refer- characterDataTypeDefinition.getDefaultValueTypes(). ences the existing SQL Model add(DefaultValueType.NULL_LITERAL); characterDataTypeDefinition.setLengthSupported(true); Ecore file and extend it. characterDataTypeDefinition.setJdbcEnumType(1); • Use the Eclipse framework to characterDataTypeDefinition.setJavaClassName("java.lang.String"); generate a new EMF model.

• Generate code to create a new I LISTING 2: PART OF THE EXTENSION MARK-UP USED IN DTP FOR THE Database Definition Model. EXEMPLARY GENERIC JDBC DRIVER TEMPLATE For example, you may want to add an event and then create a unique

DEFINING A DRIVER TEMPLATE name="%org.eclipse.datatools.connectivity.db.generic.genericDriverTemplate" Access to a database is typically parentCategory="org.eclipse.datatools.connectivity.db.driverCategory"> mediated by a driver. In the simplest required. You could, in fact, use an ODBC driver, a call-level interface (CLI) or other mechanisms as a con- duit to the database. The SQL model information. An advantage is that that can be understood loosely as family, however, expects a JDBC you can specify JAR file names and the same as class and object in Java. interface, so you’d have to map such perhaps even locations if these can The advantage of having global driv- alternatives onto JDBC interfaces to be predicted. These default sugges- er templates and definitions is that use the models. tions make it easier for users to these values tend not to be specific The first question you need to understand what is required for the to tools that consume them, so other answer is whether or not you need a driver template and how to locate the tools that require access to driver driver template. DTP provides a necessary information. definitions can use the global val- generic JDBC driver template in Once defined, a driver template is ues. From a user’s perspective, this which the user can specify the loca- global to the Eclipse instance, driven provides a very important benefit: It tion of the driver archive (jar) and by a preference page. We’re talking enables the definition of a specific standard properties such as connec- about templates here, which implies driver once, rather than having to tion URL, database name and so on. a set of defaults to be overridden. In keep reentering the properties for The disadvantage of this approach is fact, users create a driver definition each tool. that reasonable defaults for specific based on a provided template. A DTP provides a driver manage- databases can’t be expressed, so driver definition is an instance of a ment framework, with associated users have to provide this predictable driver template and is a relationship preference pages and wizards, for

Fall 2006 www.eclipsereview.com | 15 PROJECTS

managing these templates. As a DTP Listings extender, all you need to do is con- tribute to the org.eclipse.datatools I LISTING 3: PART OF THE CONNECTION PROFILE DEFINITION FOR .connectivity.driverExtension. GENERIC JDBC Listing 2 shows part of the extension mark-up used in DTP for read-only properties that are not shown to users, but consumed by downstream tools. The driver man- I LISTING 4: PART OF THE CONNECTION PROFILE DEFINITION FOR agement preference pages and wiz- GENERIC JDBC ards are generated automatically protected Object createConnection(ClassLoader cl) throws Throwable { based on the property values given Properties props = getConnectionProfile().getBaseProperties(); in a template definition. Attributes Properties connectionProps = new Properties(); such as Required are used to deter-

String driverClass = getDriverDefinition().getProperty( mine when a driver definition is considered complete. IDBConnectionProfileConstants.DRIVER_CLASS_PROP_ID); String connectURL = props.getProperty(IDBConnectionProfileConstants.URL_PROP_ID); DEFINING A CONNECTION PROFILE String uid = A connection profile is a group of properties that acts as the particular props.getProperty(IDBConnectionProfileConstants.USERNAME_PROP_ID); connection type’s definition. For String pwd = example, a particular database might props.getProperty(IDBConnectionProfileConstants.PASSWORD_PROP_ID); have one or more associated driver String nameValuePairs = templates (for versions, driver types props.getProperty( IDBConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID); and so on). String propDelim = ","; A connection profile for that data- base is capable of consuming that if (uid != null) { connectionProps.setProperty("user", uid); information in a selected driver defi- } nition and using it to establish a if (pwd != null) { connection to the database. A con- connectionProps.setProperty("password", pwd); nection profile is responsible for } if (nameValuePairs != null && nameValuePairs.length() > 0) { supplying a content provider to String[] pairs = parseString(nameValuePairs, ","); requesting tools, such as the tree- String addPairs = ""; //$NON-NLS-1$ based paradigm found in the DTP for (int i = 0; i < pairs.length; i++) { String[] namevalue = parseString(pairs[i], "="); Data Source Explorer (DSE). connectionProps.setProperty(namevalue[0], namevalue[1]); Once again, the notion of connec- if (i == 0 || i < pairs.length - 1) { tion profile is agnostic with respect addPairs = addPairs + propDelim; to the actual connection type. That } addPairs = addPairs + pairs[i]; is, the connection profile provides } an abstraction over the connection } type, which gives consuming tools Driver jdbcDriver = (Driver) cl.loadClass(driverClass).newInstance(); flexibility in interacting with hetero- return jdbcDriver.connect(connectURL, connectionProps); geneous data sources. As with driver templates, connec- tion profiles are managed by the

16 | ECLIPSE REVIEW Fall 2006 PROJECTS

connection management framework, requests. In this case, the sources will require much more pro- along with associated wizards and JDBCConnectionFactory class pro- cessing, and the benefit to clients is other UI support. Contributions to vides the implementation. Being a the uniform abstraction delivered by the connection management frame- factory, an instantiation provides, in the frameworks. work are made visible by the exten- this case, JDBCConnection objects. sion point org.eclipse.datatools.con- When the client wants to connect to MAKING THE CONNECTION nectivity.connectionProfile. Listing 3 the database represented by this Most of the work in using DTP shows part of the connection profile profile, the code shown in Listing 4 involves creating an EMF-based definition for generic JDBC. is executed in JDBCConnection. model for the particulars of your Keep in mind a few key points. Here, we see the use of properties database. Driver and connection sup- The first is that a connection profile defined by the driver definition and port is attained by leveraging the con- is associated with a given category specified by the user. After these prop- nectivity frameworks. While the defined in the category mark-up. erties are retrieved, the code is fairly information given here is not com- You could reuse a category defined standard for setting up a JDBC connec- plete in every detail, it should contain elsewhere, for example, to add a tion. enough of a trail guide to help you connection profile to the categories In this simple case, why do we need navigate the Apache Derby imple- provided by default. The the overhead of a driver definition and mentation shipped with DTP 0.9 and connectionProfile mark-up is simply connection profile? At first glance, customize it as necessary. a declarative way of setting the cate- these seem like overkill, but the main The DTP Enablement project will gory and name icon in the connec- goal of DTP connectivity is to provide continually include more complete tion profile. The key implementation an abstraction over the notion of con- and complex examples for databases. comes in the connectionFactory sec- nection, encapsulating the implementa- These will serve a dual purpose: pro- tion. A connectionFactory gives the tion details so client tools can work viding data source support close at implementation class that is respon- with connections uniformly. hand to the DTP core and serving as sible for creating and maintaining While the generic JDBC case is further examples of what can be connections based on client straightforward, more complex data built on the Data Tools Platform.

Fall 2006 www.eclipsereview.com | 17

There are hundreds—maybe thousands—of great Eclipse plug-ins available. Which are best? 27 Must-Have Eclipse Plug-Ins: Get Them Now!

nstalling Eclipse is like moving into a new apartment— it’s spacious, intelligently laid out, boasts shiny, cleverly n BY RICK WAYNE Idesigned appliances… but it’s bare. To make an apart- ment livable, you put your stamp on it, you move in your Ruby Development Tools/Radrails furniture and your wall art and your game console. To www.rubypeople.org and www.radrails.org make Eclipse really sing as your development environ- License: Common Public License / ment, you need to extend the basic IDE with tools tailored Eclipse Public License to your tasks and foibles. It takes serious gumption to admit in this magazine In short, you need to go on a plug-in hunt. You could that I code so much in Ruby. But I climbed aboard the simply grab one of the preassembled Eclipse distributions Ruby bandwagon in 2001, when it was nothing but a red set up with whole sets of plug-ins, and there certainly are Radio Flyer squeaking by with Matz, Dave Thomas, Andy some excellent ones out there, such as MyEclipse. But Hunt and a couple of kazoos. These days... breathes there there’s a lot to be said for rolling your own environment, the who hasn’t been swamped by the Rails and I’ve focused here on the a la carte approach. hype? If you’re intrigued by the idea of painless database- It wasn’t easy to choose among the hundreds of plug- driven Web app development, grab these two plug-ins and ins out there, and your mileage may vary. I’ve assembled go for it. RDT makes Eclipse aware of Ruby’s syntax, with some real stars in each of seven categories: syntax coloring and checking, an outline view, Test::Unit • Language support integration and Ruby debugging. (Refactoring is Ruby’s • UI design Achilles’ heel: In RDT, it’s limited to block comment • UML, modeling and process support /uncomment! And I’ll make you Java hacks a deal: You • Back-end integration and framework support don’t bring up autocompletion, I won’t bring up checked • Utilities exceptions.) Radrails provides management tools for con- • Testing and code analysis figuring and running Rails Web applications. Neither has A word on licensing: Free is nice, but I haven’t neg- the laundry list of features that you’ll find in, say, J2EE lected commercially licensed tools either. Somebody is tools, but in a way, that’s the point: Rails frees you from a paying to write these tools, whether it’s for sale, as a lot of that picayune detail. corporate contribution to the community, or the leg- endary spare-time hacker (when I get some, I’ll become oXygen Plug-in Edition one, I always say). It costs either dollars or opportuni- oxygenxml.com ties to develop good software like this, so you should License: Commercial seriously consider paying your share one way or the XML is definitely here to stay, like it or loathe it (YAML, other. Buy, contribute money, or contribute resources anyone?). Many of the features that make XML easy for like time or server space to these projects. We’re all the computers to parse make it hellish for humans to edit— better for it. hence oXygen. This critter handles syntax highlighting and Sermon over. Without further ado... the winners, if autocompletion, DTD and schema validation (including you please! XML Schema and Relax NG), and features both an XSLT transformer and debugger. It also includes refactoring tools LANGUAGE SUPPORT Without getting into a which-language-is-best mud- Rick Wayne ([email protected]) is a software developer for the University of Wisconsin, where he has far too much fun building wrestling match—I know, but I’ll never get you to Java and Web applications. He started coding professionally in 1984, agree—here are some great plug-ins for widely used writing about it in 2000, and teaching it in 2001. languages.

Fall 2006 www.eclipsereview.com | 19 Must-Have Plug-Ins

Figure 1 Omondo EclipseUML generates a ton of UML 2.0 diagrams and sports a handy heard of. Some of the con- pan-and-zoom tool for navigating them. ventions are a little odd to those of you weaned on CUA (“Copy a line with a single keystroke”—huh?). But trust me on this one— it flies. Now, if they’d just ship a Macintosh version...

PHPEclipse phpeclipse.de License: CPL There are plenty of dedi- cated PHP IDEs around, but none of them offer Eclipse’s potent combina- tion of cross-platform com- patibility and a mature toolset for so many devel- opment tasks. PHPEclipse offers syntax coloring for HTML, XML, CSS and of course PHP, with code completion for the latter. You also get a debugger and Eclipse’s highly useful outline view of your code; when it comes time for testing, you can control for XML and XSLT, XQuery, a built-in Subversion client and your test Web and database servers from within Eclipse, special-purpose editors for specific XML dialects like XSL:FO and see the results right in the IDE. for PDF production or other page-formatting tasks, the Scalable Vector Graphics format (with a live preview) and UI DESIGN the Web Services Definition Language (WSDL). WYSIWYG Java UI design tools appeared shortly after the dinosaurs died out, but any prehistoric Java hacker watch- EPIC (Eclipse Perl Integration) ing her Visual Basic colleague at work was likely to turn a e-p-i-c.sourceforge.net fetching shade of green. And my programming partner, License: CPL the Finn, still refuses to do UI in Java. I need to get him Brethren of Perl, I say unto you, suffer no longer one of these. under vi or EMACS! Step with me into the light of Eclipse (guess that’s an oxymoron). At any rate, if WindowBuilder Pro 5.1.0 you’re not digging for Rubies or wrestling Pythons, the http://windowbuilderpro.com Perl world is probably your oyster, and this little plug-in License: Commercial (pared-down version is free) offers syntax highlighting and on-the-fly checking, Third-gen tools like WindowBuilder Pro ease the pain quick-reference documentation, expandable code tem- of layouts, event handlers and alignment that used to be plates, a debugger, an outline view and a regular-expres- our lot. WindowBuilder Pro sports round-trip engineering sion evaluator. of both Swing and SWT, drag-and-drop rearrangement of GridBagLayouts and internationalization support, all in Visual SlickEdit Plug-in pure Swing or SWT—it doesn’t add a single JAR to your .com application! License: Commercial Until the big-forehead aliens gift us with thought-driven Jigloo SWT/Swing GUI Builder 3.9.2 computers, programming is going to be primarily about cloudgarden.com/jigloo editing text. Deal. License: Free for noncommercial use Of course, one way to do so is to put the biggest, Lock-in is beautiful if you’re a vendor, ugly if you’re baddest text-editing tools available into your personal a coder. Jigloo not only does round-trip GUI design, it’s box, and SlickEdit is certainly one of those. I’ve been specifically designed to handle UI code generated by programming for dollars since 1984, and I have to tell hand or in Netbeans, JBuilder or the Visual Editor plug- you that this thing supports languages I’ve never even in. It can convert a GUI from Swing to SWT and vice

20 | ECLIPSE REVIEW Fall 2006 Must-Have Plug-Ins versa, and offers a toolbar button to preview your process that’s useful out of the box, and is supported by interface. tools integrated with Eclipse. (See Per Kroll and Kurt Sand’s article in this magazine, “A Development Library at Your Visual Editor Fingertips,” Summer 2006.) OpenUP/Basic, as its name eclipse.org/vep/WebContent/main.php implies, draws on IBM Rational’s RUP, but is aimed at small- License: EPL er teams and smaller projects. This is definitely a project to The Eclipse Visual Editor Project is primarily infra- watch. structure for generic visual editors in Eclipse, but happi- ly ships with GUI builders for both Swing and SWT. Subclipse Nothing too novel for the end user, of course; you get subclipse.tigris.org drag-and-drop component placement, round-tripping License: EPL (the only state saved is in the Java source code, so you I highly respect the venerable CVS revision-control can edit text or whang GUI components around) and system, but let’s be honest: Subversion is just better. It’s property editors for the components. New in 1.2 (the smarter about offline work and network traffic, the revi- latest version at press time) are support for JFace view- sion numbers are per-commit instead of per-file, and ers, support for Mac OS X and an XML Metadata tags and branches are cheap and simple to use. (And Interchange (XMI) view for developers who want to see one use case alone motivated me to switch: Renaming the internal model. folders. ’Nuff said.) The Subclipse plug-in works very similarly to the CVS Repository Explorer and can handle UML, MODELING AND PROCESS SUPPORT repositories in local files or served up via the Perhaps it’s heretical to proclaim in a tools article that Subversion daemon, WebDAV, HTTP or tunneled communication trumps code-tweaking. But experience through Secure Shell (svn+ssh). Daily operations like shows that when projects fail, it’s usually because the update, commit and compare against the latest or base coders and stakeholders are on different wavelengths. rev are just a right-click away, though I admit I do keep Concision is key, and UML 2.0 is our best shot yet at a the command-line Subversion client around for the concise, accurate, widely comprehensible channel funkier stuff. between modelers, architects and programmers. And even within the programming shop, tools can significantly light- AccuBridge en the day-to-day load. www.accurev.com/accubridge-eclipse.html License: Commercial (free plug-in to SCM product) Omondo EclipseUML Any SCM system stores file revisions, but AccuRev www.omondo.com excels at the edge use cases that are problematic for CVS License: Commercial (single-user free version available) or Subversion: promotion, merging, change packages, Omondo’s EclipseUML supports diagrams common even demonstration of regulatory compliance. The (class, activity) and obscure (robustness, Figure 2 Log4E right-clicks to painlessly add a logging statement to source. deployment), and neatly round-trips from your code, with too many features to list here. The company’s support for XML Metadata Interchange gives us hope that modeling tools will one day be interchange- able—bravo!

Eclipse Process Framework and OpenUP eclipse.org/epf License: EPL Like standards, the lovely thing about software devel- opment processes is that there are so many to choose from. The Eclipse Process Framework project, in incu- bator phase at press time, plans to create a minimal and extensible iterative

Fall 2006 www.eclipsereview.com | 21

Must-Have Plug-Ins

AccuBridge plug-in lets you enjoy stream SCM without written in subsequent regens, so your code in the latter ever leaving the comfy confines of Eclipse. stays safe.

BACK-END INTEGRATION AND FRAMEWORK SUPPORT Hibernate Tools The new UI tools notwithstanding, Java programming www.hibernate.org/255.html today is primarily about server-based enterprise applica- License: LGPL tions, and these plug-ins hook Eclipse up with the While the Synchonizer does one small task well, the machinery that makes it run. Hibernate Tools do… well, basically everything else relat- ed to the Hibernate persistence framework. Not only do Terracotta Distributed Shared Objects the Hibernate Tools bolster your ability to create configu- terracottatech.com/terracotta_DSO.shtml ration and mapping files, they’re round-trip—you can License: Commercial (free plug-in to commercial tool) point the Tools at an existing database (or an existing I’m cheating a bit here. Terracotta DSO is not itself an Hibernate configuration) and get Java, config and map- Eclipse plug-in; it’s no little freeware utility. It’s enter- ping files automagically. The Hibernate Tools provide a prise infrastructure, a slick means of exploiting paral- mapping editor, a Hibernate console manager and a set lelism with minimal pain, scaling your J2EE applications of wizards for configuration and code generation. by sharing their heaps across multiple JVMs. This Eclipse plug-in makes that process easier and more Spring IDE graphical, generating the necessary XML config files for springide.org/project you and allowing you to control the servers. License: Apache When I first started learning about J2EE, I felt rather Hibernate Synchronizer stupid. “Whoa—this is a lot of stuff.” Little did I realize hibernatesynch.sourceforge.net that I was merely ahead of the curve (hey, that’s my License: GNU Lesser General Public License story, and I’m sticking to it like white on rice). Is de-drudginator even a word? Well, it should be. The Spring was born of frustration with J2EE complexity. Hibernate Synchronizer certainly is one. As with any It’s a full-stack application framework that’s consider- mapping framework, Hibernate’s database and code ably easier to use and deploy, while remaining compati- sides take some scutwork to keep in synch; the ble with many of the original J2EE technologies. And Synchronizer is designed to generate value objects, com- the Spring IDE is the Eclipse way to get on that band- posite key objects, data access objects and suchlike auto- wagon, offering a straightforward wizard to create matically whenever the mapping files change. Of course, Spring projects, then a set of editors and builders to anyone who’s used a code generator knows that the extend, modify and validate the config files and beans problems don’t occur the first time you use it; it’s the that make up a project. second, when the blamed thing overwrites all your cus- tomizations, that’s so annoying. Synchronizer cleverly Log4E gets around that by generating abstract base classes log4e.jayefem.de along with an extension class. Only the former is over- License: Parallel free and commercial versions Since you’re not going to Figure 3 Tiger XSLT Mapper visually hooks up source and target XML to create XSLT style. be glued to the debugger for the life of your soft- ware, you’ll occasionally need to know what it’s been up to, after the fact. So: logging. Pretty soon you’ll outgrow println statements and want to use something a little more powerful and configurable; Log4e greatly streamlines incorporation of JDK log- ging, Log4J or Jakarta Commons logging in your projects. You just right- click, and Log4e handles insertion of the appropriate statements; it can also automatically replace those System.out.printlns for you. It’s a tool worth using.

24 | ECLIPSE REVIEW Fall 2006 Must-Have Plug-Ins

UTILITIES Figure 4 The Findbugs Eclipse Plug-in analyzes your source code for common problems, The beauty of the Eclipse integrating with Eclipse’s problem list and source markers. ecosystem is that it encourages these little gems of functionality and integrates them into your work.

QuickREx bastian-bergerhoff.com/ eclipse/features/web/ QuickREx/toc.html License: EPL Perl hacks used to sneer at Java coders, parsing their way through Strings with index() and rindex().Once we got regu- lar expressions, of course, they went from snobbery to sympathy. Sure, regexes are powerful and succinct. Then again, so was APL, and frustrated Java pro- grammers quickly filled up the 12-step groups. Not only does QuickREx allow you to rapidly iterate EHEP (Eclipse Hex Editor Plug-in) toward a regular-expression solution on test text, it ehep.sourceforge.net offers tab-key suggested completions, automatically License: GNU Public License escapes those pesky backslashes for you, and allows Like Garrison Keillor’s “A Prairie Home Companion,” you to compile your best gems in a personal regular- all of our software is sponsored by “Raw… Bits.” And expression library. sometimes, ya just gotta grit your teeth and plunge into ’em. Tiger XSLT Mapper Programmer’s text editors like , Epsilon and www.axizon.com SlickEdit have had this basically forever; frankly, I was License: Commercial nonplussed that Eclipse lacks this feature out of the box.

E If you don’t use Extensible Stylesheet Language EHEP offers a hex viewr of binary files, lets you view Transformations (XSLT) to modify XML streams, or think them under a variety of encoding schemes (for example, that it has just jumped the shark, go on to the next ASCII, ISO8859_5 or MacUkraine), and supports search- plug-in. (If, worse, you think XSLT so transparent that ing for either hex or text strings. tools are redundant, the door is that-a-way, fella.) But if you need this plug-in, you almost certainly need it four TESTING AND CODE ANALYSIS hundred smackers’ worth. It’s nothing less than a point- Test and prevent now, or fix bugs later. It’s really up to and-click mapper for transforms. you (and your manager or customer), but “now” is a lot You drag between the source XML on the left and the cheaper and faster. target XML on the right, it comes up with the trans- forms for you, in your choice of “optimized” or Lattix LDM “human-readable” flavors. The reduction in your Tums lattix.com/products/products.html budget alone might cover it. License: Commercial “Cycles of dependency” concern more than just wel- A Plethora of Plug-Ins fare researchers. Useful code necessarily is complex— but not inevitably unmanageable! Two great places to start looking for more plug-ins are www.eclipseplugincentral.com To “help you discover, analyze, define and control and www.eclipse-plugins.info; both sites organize available plug-ins by category, your architecture,” Lattix built LDM. Peter Varhol’s ranking them by popularity (number of click-throughs) and user rating. A word of recent article in this magazine, “Leaving the Crystal Ball caution: Some of the plug-ins rise to the top (especially in the latter rankings) on Behind” (Summer 2006), discussed this, showing that it pretty small sample sizes. visualizesdependencies in a collapsible matrix, helping you stick to a layered architecture and minimize dependency cycles.

Fall 2006 www.eclipsereview.com | 25 Must-Have Plug-Ins

Parasoft Figure 5 oXygen is a complete XML/XSL editing suite, with syntax highlighting, autocom .com/jsp plete, DTD and schema generation, and XSLT transforms. /products.jsp License: Commercial Combining merciless code scrutiny with auto- mated test-case generation, I predict that Jtest will start by humbling you and fin- ish by empowering you. It applies literally hundreds of rules (the list is cus- tomizable, of course) to a static analysis of your source code, then automat- ically generates test cases to wring it out, and even helps track down the hard- to-spot runtime issues.

Cenqua Clover cenqua.com/clover License: Commercial If you’re using Eclipse and you’re not doing … we need to talk, because I’m interested in how you stay in business. Even if you are, and your devel- lyzing a profiling session post hoc or comparing two ses- opers proudly report creating such-and-so-many unit tests sions. You can slice the loaf several ways: by CPU, by each week… how on earth do you know if they’re writing thread, or by walking the heap to find allocation hotspots. the right ones? Clover is a code coverage tool aimed at find- ing out the answer, and it tells you by statements, branches Findbugs Eclipse Plug-in and methods. Not only does it give you a coverage snap- .sourceforge.net shot, but it reports the trend over time; reports come out in License: LGPL the plug-in’s UI, in HTML, PDF or XML for ingestion into Findbugs is an open-source code analyzer—think of it as some other tool. Clover won a Productivity Award in last lint for Java on steroids. But there’s a crucial difference: year’s Jolt Awards and was well regarded by the judges. Findbugs doesn’t deluge you with an undifferentiated wail about problems pressing and picayune. Instead, it catego- Eclipse Profiler rizes them usefully: correctness, bad practice and style, and eclipsecolorer.sourceforge.net/index_profiler.html applies confidence ratings to its analysis, to emphasize License: CPL what it’s sure is wrong. The Eclipse plug-in, of course, inte- A basic profiler plug-in, the Eclipse Profiler can display grates Findbugs intelligence into the IDE, decorating your running threads and a call tree for a thread. Tooltips pro- source windows with problem markers (and adding lines to vide timing info; you can jump from a call-tree node to its the Problems view); you can control which of its rules are definition in the code. You can also see profile information run against your code, and the level of hysteria you’re will- by class or package, filtered to zero in on the items of ing to tolerate. The rules run the gamut from the obviously interest. Eclipse Profiler can do remote profiling; for exam- broken (test for equality with floating-point numbers) ple, the Tomcat heap, but you’ll need to manually set up through the working-but-troublesome (circular dependen- environment variables or command-line switches on the cies among classes) to JUnit idioms and much more. program being run to do so. YOUR NEW HOME EJ Technologies JProfiler We’ve got the furniture in and the boxes unpacked—pizza- ej-technologies.com party time! (Actually, after cramming all these tools into my License: Commercial IDE, my living space feels distinctly overstuffed.) Your list of If you want to get fancier with your profiling and don’t the best plug-ins may certainly differ from mine—in which mind paying for it, consider JProfiler. As with Eclipse case, we hope to hear from you—a good discussion will Profiler, remote connections require a bit of command-line benefit all of us. So why not drop us a line at feedback tweaking, but JProfiler includes wizards to hook up to @bzmedia.com to get the discussion rolling? Enough with common application servers, and can do tricks like ana- the tools—back to the code!

26 | ECLIPSE REVIEW Fall 2006 Leveraging Web Services Using the Web Tools Platform SOAP? XML? WSDL? Java? Eclipse!

eb services are rapidly becoming the most popu- BY CHRISTOPHER JUDD lar form of integration. This is primarily due to n Wtheir interoperability with any language and plat- form that communicates over HTTP and can manipulate XML. In addition, because it communicates over HTTP, which is commonly firewall-friendly, it’s operationally easier to use than previous remote invocation technolo- gies like CORBA, which required additional ports and protocols. Though it previously lacked native support for pro- ducing and consuming Web services, with last year’s introduction of the Web Tools Platform, Eclipse now includes wizards and a Web Services Definition Language editor for generating Web service servers and clients, as well as server definitions for deploying Web services and tools for testing Web services, including Web Service Explorer and TCP/IP. Here, I’ll discuss a strategy for generating and pack- aging Web service clients using WTP, and how to include and use the Web service client in a simple Web application.

SAMPLE APPLICATION The sample application shown in Figure 1 (see page 28) is a simple dynamic Web page that a travel agent or customer might use to find information about a destina- tion based on zip code. The application uses two .NET Web services found on the public Web services registry X Methods, located at www.xmethods.net. The first Web service is the Weather Forecast service provided by WebserviceX.NET. A service description is available at www.webservicex.net/WeatherForecast .asmx. Later on, we’ll use the GetWeatherByZipCode service to return a seven-day weather forecast as well as place name, state code, latitude and longitude. Christopher Judd is president and primary consultant of Judd The second Web service is a Zip Code Information Solutions LLC. (www.juddsolutions.com). Co-author of “Enterprise service provided by Ripe Development. A service Java Development on a Budget” (Apress, 2003) and “Pro Eclipse JST” (Apress, 2005), he also serves as an industry speaker, open source description is available at www.ripedev.com/testService evangelist and consultant in Java, J2EE, J2ME, Web services and .aspx. Here, you’ll use the zipCodeToAreaCode and related technologies. zipCodeToTimeZone methods to return the area code

Fall 2006 www.eclipsereview.com | 27 Web Tools Platform

and time zones, respec- erated class files. The readme.txt file should contain the Figure 1 Sample tively. version of Axis used to generate the client code as well application as any other generating instructions. These additional WEB SERVICE CLIENT files provide traceability in case the service provider STRATEGY changes the service interface or Axis version conflicts Underneath the covers, arise. WTP 1.5 uses version 1.3 of the popular Apache Axis CREATING A WEB SERVICE CLIENT JAR Web service framework To make a Web service client JAR, create a regular Java found at http://ws.apache Project per Web service. Then put the service’s WSDL .org/axis. To develop a file in the root of the project. The WSDL file can often Web service client, WTP be downloaded from the service provider’s Web site; if and Axis generate the you can’t find it there, ask the service provider to e-mail client-stub Java files based it to you. on the WSDL, which is an With the WSDL in your project, right-click on it and XML document that choose Web Services > Generate Client to invoke the describes the Web service Web Service Client wizard. Alternatively, you can use interface. The WSDL File > New > Web Services > Web Service Client and includes exposed service- enter a URL if you don’t want to include the WSDL in method signatures, com- your project. plex data-type definitions and the URL in which to Figure 4 shows the first step in the Web Service invoke the service. Client wizard. In the Service definition field, you can Figure 2 is a graphical representation of the Weather use the browse button to select a WSDL file in your Forecast WSDL file using the WTP’s WSDL designer. The workspace, on the file system or a URL. In theory, the WeatherForecastSoap service exposes the service methods Client type field can be used to select a client type. At of GetWeatherByZipCode and GetWeatherByPlaceName. this time, WTP includes only a Java Proxy client type. Drilling into the output of GetWeatherByZipCode reveals the graphical presentation of the complex data type returned by GetWeatherByZipCode. AN ALTERNATIVE BEST PRACTICE: TREAT As shown in Figure 3, GetWeatherByZipCode returns a complex type of WeatherForecasts that contains attrib- THE WEB SERVICE AS YOU WOULD A utes of PlaceName, StateCode, Latitude, Longitude and Details. This is an array of WeatherData types that con- THIRD-PARTY COMPONENT OR LIBRARY. tain the day and the URL to a weather map, as well as a temperature for each of the seven days in the forecast. But in the future, this wizard could be extended to sup- A common antipattern is to generate the Web service port other client types—even a .NET client type. client-stub code directly into an application. This is an Below the Client type is an innovative slider bar with antipattern because the generated classes often don’t a graphical representation for selecting how much WTP meet company code-quality and package-naming stan- and Axis will generate. For a Web service client, the dards, and require that at least a handful of files be ver- only level that applies is the first level, Develop client. sion controlled and managed, although they’ll never be Selecting any other level will produce the same results: modified. In addition, it reduces reuse, because each the Web service client proxy code. The only configura- application invoking the service must generate and tion to the right and below that applies to generating maintain its own copies of the same files. the client is Web service runtime; however, just like the An alternative best practice would be to treat the Web limited Client types at this time, the Web service run- service as you would a third-party library. In reality, it’s time is currently limited to Axis. no different than a service provider giving you a JAR file The second page in the wizard prompts for an output to invoke its service, except that you generate the JAR folder using a drop-down box containing a list of Java file yourself. In fact, it’s a good idea to include the origi- source directories. Here, the Java clients will be generat- nal WSDL file and a readme.txt in the JAR with the gen- ed. The wizard also enables the customization of name- space to package mapping if desired. If this option is Figure 2 Representation of the WeatherForecast WSDL selected, another page will be added to the wizard to enable mapping. By default, the wizard will use the targetNamespace attribute in the wsdl:definitions ele- ment to create a Java package for the generated Java source, but be forewarned—this often produces ugly package names. For example, the Zip Code Information service target namespace, http://ripedev.com/xsd/ZipCodeResults.xsd,

28 | ECLIPSE REVIEW Fall 2006 Web Tools Platform

Figure 3 Graphical representation of the WeatherForecast complex types

generates the unusual package name of for your Web service client to make debugging and com.ripedev.xsd.ZipCodeResults_xsd. Note that this using the client easier. package name breaks common Java package-naming Once the Web service client JAR has been created, conventions of using lowercase names and no under- you may delete the Eclipse Java project and generated scores. So, using the namespace to the package-mapping code because you can always regenerate it if necessary page, you can generate the client stubs and complex from the WSDL located in the JAR. data types in more conventional package names. The page contains a table with two columns: The first con- CONFIGURING WTP SERVERS tains the namespace in a HTTP URL format from the Before you can begin creating a Web application in your WSDL, and the second holds the Java package name it workspace to use the generated and packaged Web serv- should map to. Use the add button below the table to ice client, configure a WTP server runtime for your add the desired mappings. application server. Examples of server runtimes include When the Weather Forecast Web service wizard Web container–only servers such as Apache Tomcat wraps up, it generates specific files, as described in found at http://tomcat.apache.org or a full-blown JEE Table 1 (see page 30). In general, though, the wizard application server such as Apache Geronimo, found at generates a service interface as well as a dynamic proxy http://geronimo.apache.org. and stub implementation. It also generates a service To create a server runtime configuration in your locator interface and implementation, and finally, workspace, go to Window > Preferences > Server > JavaBeans/data transfer objects (DTO) for each of the Installed Runtime. Use the Add button to start the New complex types required by the Web service. These class- Server Runtime wizard. On the first page of the wizard, es will be further discussed in the “Using the Web select your desired application server from the list of Service Client” section. available server runtime. Or, if you don’t see your pre- The Web Service Client wizard also adds the follow- ferred application server, use the Don’t see your applica- ing Axis JARs to your project: axis.jar, commons-discov- tion server listed? link. ery-0.2.jar, jaxrpc.jar, saaj.jar, wsdl4j-1.5.1.jar and com- The second page of the New Server Runtime wizard mons-logging-1.0.4.jar. This is important because these is specific to the application server chosen on the previ- JARs must be packaged with your application to use the ous page. The Apache Tomcat 5.5 configuration is typi- generated Web service client. cal of most server configurations, requiring a directory Before packaging your Web service client JAR, make where the application server has been installed, as well sure you create the aforementioned readme.txt file in as a JRE to run the server. your project. In addition to the version of Axis, you may also want to include any namespace to package map- Figure 4 Select WSDL and client type step in Web pings you might have performed. Service Client wizard. To create the Web service client JAR file, use the Eclipse export JAR functionality by right-clicking on your project and selecting Export > Java > JAR file. In the JAR Export wizard, uncheck the .classpath and .project files to prevent them from being included in the JAR. In addition, select a name and location for the resulting JAR file. A good naming convention is a descriptive name followed by ws-client to indicate it’s a Web service client. End the filename with a version number to accommodate future changes made to the Web service. An example filename for the Weather Forecast service is weatherforecast-ws-client-1.0.jar. You may want to generate a source and JavaDoc JAR

Fall 2006 www.eclipsereview.com | 29 Web Tools Platform

Table 1 Generated WeatherForecast service file descriptions USING THE WEB SERVICE CLIENT WeatherData.java Data transfer object representing the WeatherData com- Before writing the code to plex type shown in Figure 2. execute the Web services, the Web service client WeatherForecasts.java Data transfer object representing the WeatherForecasts JARs and Axis JARs must complex type shown in Figure 2. be copied to the Web WeatherForecastSoap.java Service interface containing the getWeatherByZipCode application’s WEB-INF/lib and getWeatherByPlaceName shown in Figure 1. directory so they’ll be included in the Web appli- WeatherForecastSoapStub.java Stub Implementation of the WeatherForecastSoap inter- cation’s class loader at face. runtime. In WTP 1.5, the WeatherForecastSoapProxy.java Dynamic proxy implementation of the Axis JARs axis.jar, com- WeatherForecastSoap interface. mons-discovery-0.2.jar, jaxrpc.jar and saaj.jar can WeatherForecast.java Service locator interface for looking up the be found in the WeatherForecastSoap implementation. eclipse/plugins/org.apache WeatherForecastLocator.java Implementation of the WeatherForecast interface. .axis_1.3.0.v200606181221 /lib directory, and com- mons-logging-1.0.4.jar can WTP shouldn’t have any effect on your application’s be found in the eclipse /plugins/org.apache.commons runtime, so you won’t be required to deploy any WTP _logging _1.0.4.v200606131651/lib directory. These URLs JARs with your application. That’s why Apache Axis is are likely to change as WTP releases new versions, so a used as the Web service framework. Likewise, you must better method for determining the location of the Axis install your application server separately and configure JARs is to look at the Web service client project Java the server runtime configuration to point to the directo- Build Path properties. ry using the installation directory field. Calling a Web service from an Axis-generated class Note: Most application servers require that a JDK client proxy is a boilerplate three-step process, as shown including a tools.jar, not a JRE, be configured in the JRE in Listing 1. In the first step, you create an instance of field since a JDK is required to compile JSPs. Even if the generated locator. In Listing 1, this is an instance of your application has no JSPs, most application server WeatherForecastLocator. admin applications do, so it’s a good practice to use an Next, you look up the service instance using the loca- appropriate JDK for your app server. If you haven’t con- tor’s get method. The get method is overloaded to figured one, use the Installed JREs button to do so. accept a java.net.URL in case you need to call it at a dif- ferent URL than the default specified in the WSDL. This CREATING A WEB APPLICATION often happens if you call different instances of the Web To create a Web application, use WTP’s Dynamic Web service in test environments than and in production. If Project wizard by selecting New > Project > Web > you do this, make sure you externalize the URL and call Dynamic Web Project. On the first page of the Dynamic the getter that accepts a java.net.URL. The final step is Web Project wizard, provide a name and make sure the to call the actual service method and get the results appropriate server configuration is selected in the Target back. Runtime. The remaining page defaults are fine for a sim- The code shown in Listing 1 can be called by just ple Web application, so you can finish the wizard. about any Java code that includes the Web service client Upon completing the Dynamic Web Project, you are JARs and Axis JARs in its classpath. This includes prompted to switch to the WTP J2EE perspective if you Servlets, Struts Actions, JSF, EJB, Swing, unit tests and aren’t already in it. You’ll also have a new project containing even command-line Java applications. Listing 2 demon- a Java source directory of src, a build/classes directory for strates calling the Weather Forecast and Zip Code generated classes as well as a WebContent directory to con- Information service from a JSP scriptlet of an index.jsp tain Web artifacts defined by the Servlet specifications. The page created using the WTP JSP wizard. WebContent/WEB-INF is a special directory that con- Listing 1 Calling the Weather Forecast Web service tains files that aren’t exter- nally addressable via HTTP // create locator WeatherForecastLocator forcastLocator = new WeatherForecastLocator(); when the application is // use locator to look up service class deployed. By default, it con- WeatherForecastSoap weatherForecastSoap = forcastLocator.getWeatherForecastSoap(); tains the required Web.xml // invoke service methods WeatherForecasts forecasts = weatherForecastSoap.getWeatherByZipCode(zipCode); deployment descriptor and a WeatherData[] details = forecasts.getDetails(); lib directory for jars your application depends on.

30 | ECLIPSE REVIEW Fall 2006 Web Tools Platform

DEPLOYING A WEB Listing 2 Complete index.jsp APPLICATION The easiest way to deploy <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO- and test a Web application is 8859-1"%> to right-click on the Web <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> project and choose Run As <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

> Run on Server. A Run on <%@page import="net.webservicex.weather.*"%> Server wizard will be invok- <%@page import="com.ripedev.zipcode.*" %> ed, prompting you to select <% a server to run on. The sec- String zipCode = request.getParameter("zipCode"); ond page of the wizard will if (zipCode == null || "".equals(zipCode)) { list of all the Web, EJB and zipCode = "90210"; EAR projects in your current } workspace if your server is a // Weather full JEE server, or only Web WeatherForecastLocator forcastLocator = new WeatherForecastLocator(); WeatherForecastSoap weatherForecastSoap = forcastLocator.getWeatherForecastSoap(); projects if your server is a WeatherForecasts forecasts = weatherForecastSoap.getWeatherByZipCode(zipCode); Web container. Moving the WeatherData[] details = forecasts.getDetails(); projects from the Available pageContext.setAttribute("forecasts", forecasts); projects list to the Con- pageContext.setAttribute("details", details); figured projects list instructs pageContext.setAttribute("zipCode", zipCode); WTP to deploy those appli- // Zip Code cations on server startup. ZipCodeLocator locator = new ZipCodeLocator(); When you click Finished, ZipCodeSoap zipCodeSoap = locator.getZipCodeSoap(); the server is started and the Object areaCode = (Object)zipCodeSoap.zipCodeToAreaCode(zipCode)[0]; application is deployed. String timeZone = (String)zipCodeSoap.zipCodeToTimeZone(zipCode)[0]; Once the server is started, pageContext.setAttribute("areaCode", areaCode); an internal Web browser will pageContext.setAttribute("timeZone", timeZone); open and navigate to your %> Web application. A server configuration will also be added to the Server view. which can be used to start Travel Agent Zip Code Search and stop the server. The Server view can also be used to restart the server in debug

mode, causing the debugger Zip code: to be invoked when it hits
breakpoints in any Java file or JSP. Place Names: ${forecasts.placeName}
State Code: ${forecasts.stateCode}
And that’s it! Note that Area Code: ${areaCode}
WTP doesn’t provide any Time Zone: ${timeZone}
more functionality for gener- Latitude: ${forecasts.latitude}
Longitude: ${forecasts.longitude}
ating Web service clients Allocation Factor: ${forecasts.allocationFactor}
than is available using the FIPS Code: ${forecasts.fipsCode}
Apache Axis framework’s

command-line utilities or 7 Day Weather Forcast:

Apache ANT tasks. However, its Apache Axis

integration and wizards make generating and pack- aging a Java Web service build, deploy and test JEE applications that use the
${detail.day} client quicker and easier. ${detail.maxTemperatureF}°F/${detail.minTemperatureF}°F
WTP also provides all ${detail.maxTemperatureC}°C/${detail.minTemperatureC}°C
the features necessary to
Web service clients it gen- erates to consume and aggregate Web services.

Fall 2006 www.eclipsereview.com | 31 Take advantage of Eclipse’s testing tools

Improving Code With Static Analysis

s software becomes more complex, the probability BY STEVE GÜTZ of exposing end users to program defects increases n Aexponentially. While it was once possible to modify code and stage a code review with fellow developers, many thousands of dollars. this scenario frequently misses key coding problems due The easiest way to achieve early detection and cor- to inattention to the complexities of the code. rection of defects is to apply automatic tools, and what Today, with modern software projects typically com- better tool than one that’s free? prised of hundreds of classes and many thousands of lines of code, peer review no longer works. To help INTRODUCING THE ECLIPSE TPTP STATIC TOOLS resolve some of these weaknesses in the software devel- In the vast static analysis landscape, you can choose opment process, a range of static analysis tools has from dozens of great commercial tools already available. evolved that automatically detect and often correct com- A quick mon problems in the source code. Figure 1 Defect repair costs Internet search The Eclipse Test and Performance Tools Platform has will produce a static analysis capabilities in addition to its well-known huge collection profiling and runtime testing features. You can use of free tools TPTP’s static analysis framework for performing auto- that detect matic code review for Java and C++ code. It’s also a many coding complete API for developing additional custom rules, problems. So data reporting and even entirely designing your own why do you new forms of analysis. Let’s see how it works. But first, need another? let’s talk about the biggest question: Why? The basic problem with WHY USE STATIC ANALYSIS? all static analy- The real question to ask is “Why not?” Using static sis tools (and analysis tools is the easiest path to writing better code. software tools in general) is that they all look different— Among many other studies over the past two decades, a and act differently. For example, the workflow for 2005 IBM coding practice survey, both internally and of Parasoft’s Jtest product is quite different from IBM Global Services customers, suggests that static Instantiations’ CodePro AnalytiX, even though both ulti- analysis tools can help find 5 to 15 percent of all appli- mately accomplish the same task. The configurations of cation defects—and some empirical studies even claim rules and viewing of results are quite diverse between results as high as 30 percent. Regardless of the quantifi- these and other products. So while it’s common to cation of the results, one measure is certain: The earlier use more than one tool, there is no consistent static a problem is detected in the development cycle, the analysis process. cheaper it is to correct. If you’ve ever enrolled in a software design course, Steve Gütz is a senior software developer and team lead in IBM you’re already familiar with the graph in Figure 1, Rational’s modeling tools group. He has been a committer on the Test which shows the exponential cost of bug fixing. If a bug & Performance Tools Platform for the past two years. Previously, he is detected early, the cost is minuscule; however, finding held senior management and executive positions in several public and private companies, including two of his own successful start-ups. and fixing a bug after customer deployment can cost

32 | ECLIPSE REVIEW Fall 2006 Static Analysis

Additionally, among tools, the rule APIs, data options available from the Eclipse Run… menu. exporting and reporting (if theses feature exist at all) To use the static analysis tool, you must create one or are diverse. more analysis configurations, which are simply lists of When developing the static analysis tool for TPTP, rules you want to apply to your source code. You can the development team had two main have as many configurations as you goals. First, they wanted to make all Figure 2 Static analysis in the like and can use them from many forms of static analysis consistent Eclipse Workbench places in the Eclipse user interface, for the user by offering a common such as the main toolbar and menu, user interface and configuration the Package Explorer or even within process. They also wanted to pro- an editor. vide a consistent and common API Building an analysis configuration for static analysis tool developers to is easy. From the Run… menu, extend the framework. select the Analysis… option, and the Both of these themes are prevalent main configuration dialog will throughout this article, so let’s get appear. This window closely resem- started by installing TPTP’s static bles the configuration dialogs for analysis capabilities into the Eclipse running and debugging applications Workbench. in Eclipse. Select the Analysis entry As noted, TPTP’s best feature is, in the left side of the window and of course, its price—free! You can install it seamlessly create a new configuration using either the Toolbar but- into the Eclipse IDE or almost any tool derived from the ton or context menu in the dialog. Eclipse platform. Users will benefit from the rich collec- Once a new configuration has been created, the right tion of code review rules for Java and C++, while side of the dialog will display a tab folder with two tabs. developers can adopt the API to easily extend the rule The first, the Scope tab, is used to determine the default set to enhance TPTP’s code review capabilities or to range of resources over which analysis will occur. Note enforce internal corporate coding conventions. that the values set in this tab are only a guideline and can be overridden by the user depending on the location GETTING STARTED WITH TPTP AND STATIC ANALYSIS where static analysis is invoked in the Eclipse user Whether you’re a developer or end user, to get started interface. The scope selected in this tab is used only with TPTP static analysis you must meet a few require- when the user starts static analysis from the main menu ments. First, you need an Eclipse IDE, and the easiest or toolbar. For now, leave the scope selection at its way to obtain this is by installing the platform’s full default value: the entire workspace. Callisto release. Note that you can also build up an The second tab in the static analysis configuration Eclipse environment from component pieces, but this is dialog, the Rules tab, provides functionality for selecting more challenging. Regardless of which installation different kinds of analysis and rules. The rule list is pre- method you choose, you’ll find the tools you need at the sented as a tree where the top-level nodes represent the Eclipse Web site (see the list of resources at the end of analysis provider (for example, types of analysis) and this article). You’ll need: the deepest nodes represent rules. All the nodes in • The base Eclipse 3.2 platform between are rule categories, which are simply groupings • Java support (JDT) of rules and categories that match a • C++ support (CDT) if you plan Figure 3 The static analysis particular characteristic. Click the to analyze C/C++code launch configuration Code Review for Java analysis • TPTP 4.2 platform or later provider checkbox to select all rules (you’ll use a TPTP 4.3 build for for Java code. this article) When the rules and scope are If you choose to use Callisto, you configured, click the Analyze button can select and install almost every- to begin the code review process. If thing you need, including the Java not already visible, an Analysis development tools; however, if you Results view will appear, displaying plan to analyze C or C++ code, a historical list of each analysis that you need to download the TPTP has been performed. C++ Code Review components Congratulations! Your first auto- from the Eclipse TPTP Web site—at matic code review is now complete, this point, these components are still in a technical pre- and you can browse the results that have been reported, view state. view highlighted problems in a Java editor, or, in many Once you have an environment set up and Eclipse is cases, perform an automatic quick fix. started, you’ll notice a couple of new user interface ele- One other aspect of TPTP’s static analysis feature is ments. TPTP static analysis adds new toolbar items to the ability to run multiple forms of analysis at the same the Eclipse Workbench, and you’ll also see some new time. This capacity is unique in the static analysis mar-

Fall 2006 www.eclipsereview.com | 33 Static Analysis ketplace. Most commercial vendors would be happy to product has reached a customer. With TPTP’s static sell you a different tool for Java code review or metrics, analysis tools, you can find this sort of bug in seconds, or similar tools for C++ or other languages. early in the development cycle when it costs almost Aside from the multiplied costs of owning several dif- nothing to fix. ferent tools, usability issues often arise, since each tool TPTP currently supports more than 70 Java code probably functions differently. With TPTP, you can sim- review rules (43 C++ rules) to detect many common ply select multiple analysis providers when the configu- programming problems. Of course, not every problem ration is created, and a single analysis process can test reported is serious. You’ll find code review results divid- code for both languages. ed into one of three severities (Severe, Warning, Recommendation), but regardless of severity, the issues WHAT’S IT GOOD FOR? reported are worthy of investigation and correction. So Now that you’ve got a list of static analysis results, what why would you not run TPTP’s code review? It’s easy to should you do with it? Obviously, you’ll want to fix any set up and can quickly examine even large workspaces problems you find, but first, you need to understand to find problems that developers commonly create. Best what the code review is reporting. Let’s look at a simple of all, you can download code review for no cost. code example. Suppose you have a method like the one shown here: DEVELOPING FOR STATIC ANALYSIS Eventually, the rule sets available with TPTP will show public String[] getList( boolean flag ) { their limits. For example, suppose you have an internal if( flag ) { API for which enforcement rules are needed. Many of String[] list = new String[3]; list[0] = “one”; the other free and open source alternatives to TPTP list[1] = “two”; offer no extensibility or restrictive, confusing APIs. Most list[2] = “three”; commercial analysis tools provide rich APIs, but these return list; products can be cost-prohibitive. TPTP offers a better } solution because its code review framework is both cost- return null; effective and simple to extend. New rules can be created } from existing templates or can be constructed as Java When you run Java code review on a class containing classes within an Eclipse plug-in. In either case, TPTP this example, you’ll get the following analysis result for offers you the opportunity to use the power of the the method: Eclipse editing and debugging facilities to create new Avoid returning null instead of empty array rules. So what’s the problem? Well, assume this method is TPTP’s static analysis framework offers a number of used as it is in the following fragment: key extension points; however, when writing new rules, only a few of these are needed. The following table lists for( int i = 0; i < getList(flag).length; i++ ) { all of the extension points defined for static analysis use— // Do stuff note that all extension points are in the org.eclipse.tptp } .platform.analysis.core namespace. Now do you see the problem? What happens if getList() returns null? The for loop will generate a SETTING UP A PLUG-IN FOR NEW RULES NullPointerException, and the application will fail. If the AND CATEGORIES flag that controls the method is invoked by a rarely used The confines of this article prevent a detailed descrip- feature in your product, a basic JUnit test may not find tion of rule plug-in set-up; however, you can find a this problem during development. detailed tutorial on the TPTP Web site (see the While this example is trivial, it highlights a common resources at the end of this article). To define this coding practice that often goes unchecked: The subtle process in its simplest form, take the following steps: problems that could be found easily by a basic automat- 1. Create a new plug-in project in your Eclipse work- ed code review typically evade detection until your space. 2. Add the following plug-in dependencies to the Figure 4 The static analysis results project: a. org.eclipse.core.runtime b. org.eclipse.jdt.core c. org.eclipse.tptp.platform.analysis.core d. org.eclipse.tptp.platform.analysis.codereview .java 3. Define your new categories and rules. Creating New Categories. If you have the source code for TPTP’s Java code review rules installed, open the plugin.xml file and you’ll see the analysisCategory extensions that define all of the categories used in TPTP

34 | ECLIPSE REVIEW Fall 2006 Static Analysis

(See Listing 1). Table 1 Extension points defined for static analysis use (note that all are in the Let’s take a closer look. org.eclipse.tptp.platform.analysis.core namespace) First, notice that the class field of each category Extension Point Description points to the DefaultAnalysis Category analysisProvider Provisions a new type of analysis into the TPTP static analysis class, which is supplied by framework. Analysis providers are the engines that control the the TPTP static analysis parsing of source and execution of rules. framework to provide a complete and commonly analysisCategory Defines new analysis categories. These can be owned by an used class for categories. analysis provider or by other categories. While it’s possible to cre- ate your own category analysisRule Defines a new analysis rule. Rules are the workhorses of static class, the default behavior analysis, responsible for executing on defined criteria and gener- should be the preferred ating results when those criteria are met (or not met). way to supply this func- tionality. analysisRuleQuickFix Defines a process used to correct the results of rules. Quick fixes Category extensions usually encapsulate a refactoring class that manipulates source also declare an id field code directly to eliminate the cause of a generated analysis that should contain a result. unique identifier for the category. Colliding with analysisRuleTemplate Think of rule templates as unfinished rules. Templates can be used identifiers defined by other to create a skeleton for a repetitive rule and provide fields that categories usually pro- can be filled in by either a developer or end user to create new duces undesirable effects rules. since the framework will be unable to distinguish analysisRuleSet Rule sets are used to define a quick selection set of rules. For one category from another. example, a rule set could easily be created that selects all rules One final subtlety of the defined in Joshua Block’s “Effective Java” (Addison-Wesley, category extensions is the 2001). use of the provider and category fields. These analysisViewer Analysis viewers are used to examine the domain-specific results mutually exclusive fields of an analysis. Viewers can take any form that fits the presenta- define where in the analy- tion of data (for example, tree, table, diagram). sis hierarchy the category will be situated. If the analysisExport An analysis exporter is used to define a format for exporting provider field is used, the result data. Defined exporters appear as selectable user interface category is defined as a items when the end user chooses to export data from an analysis top-level category, while provider. defining the category field will cause the new catego- ry to be contained within another category. In either the task for you. If you always extend the case, the value of these fields is the unique identifier of AbstractAnalysisRule class, your job is half finished. the owing provider or category, respectively. Note that This abstract class provides all of the common function- your new category can be placed within an existing cat- ality needed by every rule, and all you really need to do egory defined by TPTP’s Java code review simply by is implement your own worker method to set the rule using the correct identifier (you can find these identi- criteria. fiers in the plugin.xml of the Java rules plug-in). For the example, here you’ll create a rule that Creating New Rules. Defining your own rules is a generates results anytime the Thread.stop() method is two-step process. First, create a rule class. Then, define an used. In basic terms, you want to parse all the source extension to map the rule class into the TPTP static analy- code and look for classes that extend java.lang.Thread sis space. and call stop(). Listing 2 shows an implementation for While a detailed description of rule creation is this rule. beyond the scope of this article, a high-level view can Notice that in Listing 2, the class extends the recom- be offered to help convey the concepts you will mended AbstractAnalysisRule class, which requires it to encounter. For a more detailed discussion of Java code implement an analyze() method. The first step this rule review rules, refer to the tutorials on the TPTP Web site. (and all Java code review rules) takes is to acquire When you’re creating rule classes, the TPTP static information about the Java file being analyzed. You do analysis framework goes a long way toward simplifying this by obtaining the CodeReviewResource instance from

Fall 2006 www.eclipsereview.com | 35 Static Analysis

the analysis provider, as shown in the example rule. severity=”2”/> At this point, you can take one of two paths to imple- ment your rule. First, you can use any of the JDT APIs Notice that the category identifier for your rule speci- implemented in the Eclipse platform, or you can use the fies one that already exists in TPTP. This will plug the simplified API supplied by the TPTP analysis frame- rule into the existing TPTP Threads category. When you work—the latter is streamlined for handling code review start a runtime workbench containing your rule plug-in, queries and generating results, so the AvoidThreadStop the analysis launch configuration dialog should contain example will take this approach. your new rule. After determining the resource being analyzed, the code next acquires a list of method invocations from the IT’S ONLY THE BEGINNING resource, then calls the ASTHelper.satisfy() method. In a short article like this one, it’s difficult to provide This method filters out data that doesn’t fit the filter cri- comprehensive details of a complex subject like static teria. In our example, the code uses the MIFILTER array analysis; however, you’ve gone through some of the to discard any method invocations for methods not basic concepts of the TPTP framework. You should now defined in the java.lang.Thread class and to subsequent- have at least a cursory understanding of how to use the ly discard any methods that are not calls to stop(). What static analysis component from an end-user perspective, remains is a list of calls to Thread.stop(). and if you’re a developer, you should have a footing in Since this rule is trivial, our work is finished. In this place to help create your own rules. case, any method invocations remaining in the list are If you’re interested in a complete step-by-step proce- considered violations of the rule, so the dure for creating your own rules, refer to the TPTP Web generateResultsForASTNodes() method is called to create site, where you’ll find several articles discussing rules as results for each of them. well as more advanced topics not covered here. Finally, the Java class being reviewed could be one Keep in mind that TPTP is an open source project to that extends java.lang.Thread, so you need to take one help the entire community, so if you develop some inter- more step to check any super method invocations for esting rules or integrate a new type of static analysis the same Thread.stop() criteria and create results for provider, by all means submit them to the project so those, as well. that everyone can benefit. With the rule class created, only one easy step remains. The rule needs to be integrated into the static RESOURCES analysis code-review structure so it is available and I Eclipse www.eclipse.org I TPTP www.eclipse.org/tptp selectable by the user. To do this, create a simple exten- I TPTP Static Analysis Tutorial Part 1 – A Consistent Analysis Interface, Steve Gütz and Orlando Marquez, 2006, sion in the plugin.xml as follows: www.eclipse.org/tptp/home/documents/process/development/static_analysis/TPTP_static_analysis_tutorial_part1 .html www.eclipse.org/tptp/home/documents/process/development/static_analysis/TPTP_static_analysis_tutorial_part2

Listings

I LISTING 1 JAVA CODE REVIEW CATEGORIES

. . .

36 | ECLIPSE REVIEW Fall 2006 Static Analysis

Listings

I LISTING 2 AVOIDTHREADSTOP CLASSES public class AvoidThreadStop extends AbstractAnalysisRule { private static final IRuleFilter[] MIFILTER = { new DeclaringClassRuleFilter( “java.lang.Thread”, true ), new MethodNameRuleFilter( “stop”, true ) };

/** * Analyze this rule * * @param history A reference to the history record for this analysis */ public void analyze( AnalysisHistory history) { // Extract the resource being analyzed CodeReviewResource resource = (CodeReviewResource)getProvider() .getProperty( history.getHistoryId(), CodeReviewProvider.RESOURCE_PROPERTY );

// Find matched in method invocations List list = resource.getTypedNodeList( resource.getResourceCompUnit(), ASTNode.METHOD_INVOCATION ); ASTHelper.satisfy( list, MIFILTER ); resource.generateResultsForASTNodes( this, history.getHistoryId(), list );

// Find matched in super method invocations list = resource.getTypedNodeList( resource.getResourceCompUnit(), ASTNode.SUPER_METHOD_INVOCATION ); ASTHelper.satisfy( list, MIFILTER ); resource.generateResultsForASTNodes( this, history.getHistoryId(), list ); } }

Fall 2006 www.eclipsereview.com | 37 Component-based development for Web 2.0 Rich Internet Development: AJAX Meets JavaServer Faces

e’re headed toward an era of dynamic rich BY MAX KATZ Internet applications for the enterprise. Even in n Wthe face of heated debate about these types of applications and exactly where companies are on the think of JSF as bringing Swing-style development to the adoption curve, it’s clear that more and more enterprises Web—building Web applications out of UI components. are building them. If you’re not sure what I’m talking about, I’ll approach I believe that rich Internet applications are superior to it a bit differently. In the JSP world—to print a collection standard Web applications. As human beings, we tend to of records of some sort, you put

..
buy, use or pursue the “better” in daily life—and Web HTML tags, create some sort of loop in Java, and put applications are no different. Consumers and enterprises .... tags inside the loop. Inside, will want to use rich Internet applications, and businesses you could have if statements to do something extra. This must offer such applications, simply because they are is the markup approach; it works, but with JSF this is superior—and if you don’t offer them, someone else will. done a lot simpler. You take a ready-to-use component, You can build rich Internet applications with like dataTable, and bind it to the same collection of Asynchronous JavaScript and XML, and you can build records. The component will then render all of the neces- AJAX applications with JavaServer Faces. JSF is a stan- sary markup and data for you. dard, user interface component–based framework for building Java-based Web applications—with the emphasis A WIDER VIEW on component-based. Let’s zoom out and look at this at a broader level. If The component approach is what gives JSF its power you’ve ever seen an assembly line for cars on TV, you and allows exploitation of AJAX. With JSF, you don’t think would see a door, for example, being attached to a car. in terms of markup, like HTML, any more. Rather, the par- Now, think of the door as a ready-to-use component adigm is development with user interface components. that’s being attached to car. You don’t see engineers building the door on the assembly line. Similarly, with COMPONENT CONSCIOUSNESS JSF, you create Web applications out of reusable JSF A JSF user-interface component has renderers for compo- components. There’s no need for an application devel- nent markup. These are simply Java classes that know oper to create the table component just before he uses it how to generate all the necessary markup (read: HTML) in an application. for a UI component. Just keep in mind that JSF is all You can find hundreds of JSF resources on the Web. To about creating powerful UIs. Java is excellent for the back get started or learn more, try www.jsfcentral.com, an end, but it was always missing something on the UI excellent site with a lot of news and resources. Another side—and that’s exactly what JSF provides. site, www.jsftutorials.net, can help you get started. To For application developers, it’s natural to think in terms work with JSF, all you need is Notepad or any other text- of user interface components. A component can be as based editor, though there are commercial tools that can simple as the familiar input text field to a sophisticated help make it easier. component such as a tree or a tabbed panel. As a devel- But all this is less important than the plain fact that JSF oper, you design the application from your reusable user interface components—if you use Swing or ASP.NET, you Max Katz is a senior systems engineer at Exadel in technical sup- port, training and customer care for the Exadel product line, and also should find this approach familiar. Both technologies uti- conducts online and onsite JavaServer Faces training. lize components to create user interfaces. In fact, I like to

38 | ECLIPSE REVIEW Fall 2006 JSF and AJAX is the only standard Web requires a deep understand- component technology for Figure 1 How the page looks with typical JSF ing of the underlying tech- Java. By contrast, validation nologies, such as JavaServer Pages, portlets JavaScript. In other words, and servlets are standard, creating sophisticated Web but aren’t component- applications with AJAX based, and the Struts frame- technology is challenging work is neither component- and requires experts. It’s based nor standard. Did we not uncommon to spend mention huge industry sup- 80–90 percent of develop- port? Certainly nobody ment time battling wants to stay with a big, JavaScript incompatibilities important application based on a funky open-source among Web browsers and platforms. framework that was invented and developed by one clever programmer! This is why IBM, Oracle, Sun and COMBINING JSF WITH AJAX others are cultivating JSF, carefully selecting the best We know that JSF is a good component-based technolo- ideas for Web development and paying big money to the gy for building enterprise Web applications. We also best architects and developers to improve JSF for the now know that AJAX lets us create rich, fast and inter- rest of us. active Web applications. What if you combine the two JSF’s position as a standard is doubly important technologies to add some “richness” to JSF? If you use because it allows JSF to fully realize its promise as a the two technologies together, take a very powerful user component-based framework. The chances that compo- interface component frame and add AJAX functionality, nents from different vendors will coexist in the same you can build rich enterprise Internet applications. application are much better when the technology is Above, I said that AJAX could get complicated pretty more standardized—a great boon for all enterprise appli- fast. That’s still correct. However, because of JSF’s com- cations developers! ponent architecture, you can easily use AJAX. How? You Another interesting facet of JSF is that it’s a frame- create JSF components that render all the necessary work for both application developers and component JavaScript, HTML and XML. You then simply use JSF developers. Applications developers build Web applica- AJAX-enabled components as out-of-the-box building tions out of JSF user interface components, while com- blocks. This way, you can build rich Internet applica- ponent developers build such components with JSF. tions with JSF and AJAX without writing a single line of

RICH INTERNET APPLICATIONS Look at Google Maps. The application feels a little differ- AJAX4JSF LETS YOU SEND AN AJAX ent than what we’re used to on the Web with the sub- mit-and-wait experience. We get to a page, enter some REQUEST AND SPECIFY WHICH AREAS OF information and click submit. Then, we wait for a reply. It’s pretty much unchanged since 1994, the early days of THE PAGE SHOULD BE UPDATED. the Web. But let’s go back to Google Maps. The applica- tion feels fast; we don’t need to wait for it to reload or JavaScript—all the complexity of AJAX is hidden. refresh. It almost feels like we’re running a desktop This is exactly what I meant by saying that JSF is the application. perfect match for AJAX. A simple JSF component such Google introduced Google Maps as one of the first as an input field knows how to render its entire required truly rich applications, laying the groundwork for the coding. In the same way, a JSF component can send an rise of AJAX as a technique for creating rich applica- AJAX request to the server after some event (such as tions. AJAX allows us to refresh or update only a part of onkeyup) and then update only a part of a page after a a page, instead of submitting a whole page every time. response is sent back. In this case, the component will That’s why the applications feel fast, rich and interac- also know everything about how to render all the neces- tive. With AJAX, you can update only the small part of sary JavaScript and HTML for itself. the page that actually needs to be updated, but don’t The point that I’m trying to make here is this: JSF update the parts that stay the same. components render markup. For an application develop- AJAX itself is not a framework, but a combination of er, it’s not important what’s rendered, simple HTML or existing technologies such as DHTML, JavaScript, complicated JavaScript. The development style remains XMLHttpRequest and DOM (Document Object Model). the same: building Web applications out of JSF compo- You can find numerous AJAX resources on the Web that nents. Using AJAX to make applications interactive will show and explain the underlying technologies in shouldn’t change your development approach or jump more detail. outside the JSF component model; you simply continue AJAX lets you create rich Internet applications. building Web applications out of reusable JSF compo- However, it’s not the easiest technology to use. AJAX nents.

Fall 2006 www.eclipsereview.com | 39 JSF and AJAX

IMPLEMENTING THE IDEA ajax4jsf Now get a little bit more concrete and see what match- Faces Servlet REQUEST making tools are available to put JSF and AJAX in synch. FORWARD Ajax4jsf (http://ajax4jsf.dev.java.net) is an open source INCLUDE framework that does just that. It brings AJAX functional- ity to JSF in the form of a JSF component library. With That’s it. this framework, using just JSF components can add In your actual application, you need to make three AJAX features to an existing or new JSF application. small changes. (You can also just download the finished Because Ajax4jsf provides standard JSF components, it’s application here: http://webdownload.exadel.com/misc a natural extension to JSF. The framework is based on /eclipsereview/a4j-validation-complete.zip.) JSF standards, provides an open architecture and allows 1. Add a taglib declaration for Ajax4jsf, a standard step mixing and matching with any other JSF component for adding any new custom tag library. library, free or commercial. 2. Add an component inside as a easy example, and that’s exactly what you’re going to do child element. This enables the sending of an AJAX here. You’ll take a very simple JSF application and add request to the server as the user types. In other AJAX functionality to it. words, each time a letter is typed, an AJAX request is sent to the server. (You can modify the frequency A SAMPLE APPLICATION of updates.) The request goes through the standard Before you start, plan what you’re going to do. Imagine JSF page life cycle. This is not a client error message; a registration page on the Internet with 10 or more you’ve invoked the standard JSF validator in this fields. You start entering all the information. When example. The reRender attribute will point to an done, you click submit (remember, submit-and-wait). AJAX area (see next step) that you need to re-render You get the same page back and realize that four of the (update) as you send an AJAX request. fields have incorrect information. Whoops. So, you cor- 3. Enclose an component inside an rect and resubmit the page. Wouldn’t it be much better component to make if you could get some feedback as you typed in the val- it part of an AJAX area. You need it to be in an ues—some kind of live validation, similar to desktop AJAX area because you want the dynamic error mes- applications? That’s exactly what you’re going to do sage to be displayed or cleared from just this area with your application—you’ll add live validation. As you without having to hit Submit and update the whole type, you’ll get instant feedback about the correctness of page. the value. That’s all you need to do. In this example, you’ve added AJAX functionality by APPLICATION BEFORE AJAX simply using JSF components. You didn’t change your Now it’s time to check out a sample application: development approach of just using JSF components; the Download it at http://webdownload.exadel.com/misc/ result is still just a standard JSF page. You didn’t have to eclipsereview/a4j-validation.zip. make any changes to any other parts of the application, Open the project in your favorite IDE, and you’ll see a like the configuration file or the managed bean. You standard JSF page, with one input field with an attached invoked the standard JSF page life cycle to validate input. validator. If the value entered is shorter than three charac- That’s how simple it is. ters long, an error message will be displayed. Of course, How does it work? Ajax4jsf lets you send an AJAX you first need to hit Submit for validation to happen. Keep request and then specify which components (areas) on in mind that this is just a standard JSF page. the page to update. Keep in mind that you can update multiple components (areas) at once. ADDING AJAX For example, consider a suggestion-box component To improve this, the moment you’re typing and see that with AJAX. As you start typing into it, the component the value is incorrect, you want an error message shown shows a suggested list of values. You can place any num- without having to click Submit. Use the Ajax4jsf compo- ber of suggestion-box components on a page, but none of nent library to add this AJAX feature to your application. them are able to update any other components on a page. Here’s what needs to be done. So basically, all the AJAX functionally is “enclosed” with- 1. Download the Ajax4jsf framework. in the component. That’s a component-level approach. 2. Copy the files, ajax4jsf.jar and oscache-2.2.jar, into However, for sophisticated applications, you must be able the WEB-INF/lib folder of your application. to specify which components (areas) need to be updated 3. Register Ajax4jsf in the web.xml file: based on some events—page-wide AJAX support—and that’s exactly what Ajax4jsf provides. Ajax4jsf Filter Don’t get me wrong: The component-centric approach ajax4jsf can still be used when appropriate. In fact, combining the org.ajax4jsf.Filter two approaches will give you the ability to create truly powerful rich Internet applications with JSF and AJAX.

40 | ECLIPSE REVIEW Fall 2006 PERSPECTIVE The Present and Future of Eclipse | by Bernard Golden

Company Buster—Or Company Booster?

If you talk to some people, you’ll hear that Eclipse has tool-developer side of the equation. ruined the commercial development tools market. By this While it’s tempting to paint Eclipse way of thinking, a free product has ruined the business prospects of as a company buster, I believe it’s exactly the opposite—it’s a company development tools companies. Many people recount this nostalgical- booster. ly, pining for the days of dozens of tools companies; to their minds, Eclipse is a scourge in the marketplace. ECLIPSE OFFERS THE OOOMPH Just as a booster rocket supplies ini- On the other hand, a vastly more experience is different. I was once tial thrust for a rocket-borne pay- positive perspective is possible. By consulting to a tools company that load, Eclipse provides a tremendous this reading, the existing tools com- provided a high-end, extremely amount of oomph for tools. Instead panies were all exhausted, unprof- capable product. Their tool made of having to create an entire frame- itable hulks that lived in daily fear programmers more productive, no work within which to deliver a spe- of the monster from Redmond. The question about it—but they weren’t cial functionality, a tools company release of the Eclipse framework getting the sales they wanted. So I can rely on Eclipse to take care of a revivified the existing non-Microsoft interviewed a few end users to lot of the heavy lifting—or perhaps players, allowing them to emerge in understand the tool decision-making heavy lift-off would be the right a new form with higher long-term process, and, boy, were my eyes metaphor. potential. opened about the Power of Free. With the many projects in the As one might expect, my view- One woman I spoke with about Eclipse Foundation providing the point leans toward the latter inter- Java development efforts told me technological underpinnings, for- pretation. The tools business has that the company didn’t have the profit tools companies can operate always been a difficult one. budget to purchase fancy tools. I much more leanly and in tighter Microsoft has done an excellent job therefore asked her what they did focus on their special area of expert- in creating a tools/applications/serv- use to do their Java development. ise. Rather than having to fund, er ecosystem for which their solu- I expected to hear something like design, build and maintain a bunch tions are always the best-tuned for emacs or even vi. Her response: of functionality that does nothing to the environment. Notepad. (I guess I’d have to put differentiate their “secret sauce,” With a significant portion of the that organization into the Microsoft tools providers can deliver a highly overall market residing on camp—although one wonders about concentrated functionality payload Microsoft’s plate, that left smaller the quality of code her organization that serves them in the market. portions for the rest of the tools turned out.) Far from ruining the commercial industry. Given the widespread So, for organizations like that tools market, Eclipse has strength- availability of free tools, selling one, Eclipse presents a real opportu- ened it. If you take a look at the development tools is a rough job. nity to move to state-of-the-art tools plug-ins on the Eclipse site, the vari- While it’s tempting to think that within a constrained budget. They ety and specialized capability avail- people will prefer commercial prod- can achieve higher productivity, able are simply amazing. It’s clear ucts to “inferior” free ones, my faster time-to-market, better ability that Eclipse is accomplishing its to recruit and retain skilled employ- job—providing a framework to Bernard Golden is Chief Executive Officer of Navica (www.navicasoft.com), a Silicon ees, and a more satisfied workforce. enable differentiated development Valley consulting firm offering open source (Nobody could be happy program- functionality to find its way into the strategy, implementation and training ming Java in Notepad!) hands of developers throughout the services. Just as important, however, is the world.

Fall 2006 www.eclipsereview.com | 41