Anda di halaman 1dari 19

RIAs OR RIEs – CALL THEM WHAT YOU WILL, THEY’RE HERE PAGE 3

No. 1 i-Technology
-Technology Magazine in the World

JUNE 23-24, 2008 NEW YORK CITY

JDJ.SYS-CON.COM VOL.13 ISSUE:5

Detecting them
with FOSS tools
PLUS...
Java and the Mac
Interactive Storyboarding with JSP
The Rise of Functional Programming
Modernizing Axis1 Services Painlessly

T H E W O R L D ’ S L E A D I N G i - T E C H N O L O G Y M A G A Z I N E J D J . S Y S - C O N . C O M
FROM THE PUBLISHER

RIAs or RIEs –
Editorial Board Call Them What You Will,
Java EE Editor:
Desktop Java Editor:
Eclipse Editor:
Yakov Fain
Joe Winchester
Bill Dudney
They’re Here Jeremy Geelan


Enterprise Editor: Ajit Sagar
Java ME Editor: Michael Yuan Enough with the new words al- perience (UX), whether that means experi-
Back Page Editor: Jason Bell ready.” That was how Sean Voisen menting with JavaFX or AJAX or whatever.
Contributing Editor: Calvin Austin recently ended a discussion about the The tools and platforms that encour-
Contributing Editor: Rick Hightower
burgeoning technology lexicon, which he age and support superior UX are becom-
Contributing Editor: Tilak Mitra
Founding Editor: Sean Rhody thinks can only be explained as “a ploy ing the pre-eminent tools for business
to keep Merriam-Webster in business.” survival and success, and their numbers
Voisen, who designs and builds Rich Inter- are growing all the time, as reflected by the
Production
Associate Art Director: Tami Lima net Applications, web applications, data mushrooming success of the AJAXWord
Executive Editor: Nancy Valentine visualizations, and what he calls “other Conference & Expo series – which in spite
Associate Online Editor: Lindsay Hock fun pieces of Internet-enabled software” of its name is now as much about Rich In-
Research Editor: Bahadir Karuv, PhD
for a living, is not a fan of “RIA” as a term. ternet Applications and Web Development
To submit a proposal for an article, go to
“Marketing gurus create new terminol- Frameworks as about merely AJAX per se.
http://jdj.sys-con.com/main/proposal.htm ogy like ‘RIA’ and ‘Web 2.0’ in order to The runaway success of Apple’s iPhone
force people to engage in new conversa- is another clear indicator of the busi-
Subscriptions tions without them dragging along their ness and market-share power of superior
For subscriptions and requests for bulk orders, please send your baggage of ingrained prejudices about user experience in 2008. Anthony Franco,
letters to Subscription Department:
what something is president of Effec-
888 303-5282 or is not,” Voisen tiveUI, who keynoted
201 802-3012
subscribe@sys-con.com contends. “They also at AJAXWorld in NYC,
One year digital edition subscription: $99.00 (12 issues)
do it – I am convinced summed up the
Two year digital edition subscription: $129.00 (24 issues) – to make themselves inflexion point very
seem smart,” he adds. succinctly: “Last year,
Editorial Offices Voisen’s view is echoed the overall demand
SYS-CON Media, 577 Chestnut Ridge Rd., Woodcliff Lake, NJ 07677 by Ethan Eismann, for RIAs outpaced the Jeremy Geelan is Sr.
Telephone: 201 802-3000 Fax: 201 782-9638
the senior experience qualified supply chain. Vice-President of SYS-
Java Developer’s Journal Digital Edition (ISSN#1087-6944) is design lead of Adobe This trend will con- CON Media & Events.
published monthly (12 times a year) for $99.00 by SYS-CON
Publications, Inc., 577 Chestnut Ridge Road, Woodcliff Lake, NJ Thermo with Adobe’s tinue in 2008. While He is Conference Chair
07677. Periodicals postage rates are paid at Woodcliff Lake, NJ XD team. He disagrees last year brought un- of the AJAXWorld
07677 and additional mailing offices.
Postmaster: Send address changes to:
with “RIA” as a term precedented growth in Conference & Expo
Java Developer’s Journal, SYS-CON Publications, Inc., for two reasons: “First, because like all RIA adoption – especially by Fortune 500 series and founder
577 Chestnut Ridge Road, Woodcliff Lake, NJ 07677. things techy, it’s already obsolete and companies – RIA adoption in 2008 brings of Web 2.0 Journal.
second because it’s limiting.” a new onslaught of risks, rewards, chal- From 2000-6, as first
But Eismann admits that while he hates lenges, and opportunities for companies editorial director and
©Copyright
Copyright © 2008 by SYS-CON Publications, Inc. All rights reserved. No “RIA,” he also loves it: “I love it because it’s of all sizes.” then group publisher
part of this publication may be reproduced or transmitted in now such a part of the common vernacu- In the end – quite aside from whether of SYS-CON Media,
any form or by any means, electronic or mechanical, including
photocopy or any information storage and retrieval system, without lar of web culture that when it’s used, you call them RIAs or RIEs – what matters he was responsible
written permission. For promotional reprints, contact reprint everyone immediately understands that is not words or terminology but business for the development
coordinator Megan Mussa, megan@sys-con.com. SYS-CON Media
and SYS-CON Publications, Inc., reserve the right to revise, republish you are talking about ‘something better and the realities of enterprise computing. of all new titles and i-
and authorize its readers to use the articles submitted for publication. than primitive HTML websites.’” “RIAs are impacting the way that com- Technology portals for
Its limiting factor as a term, according panies like eBay, Ford, Random House, the firm, and regularly
For List Rental Information: to Eismann, has to do with the two words Viacom, GE, Dow Jones, and NBC think represents SYS-CON at
Kevin Collopy: 845 731-2684, kevin.collopy@edithroman.com “Internet” and “application.” Personally about the Internet and desktop software, conferences and trade
Frank Cipolla: 845 731-3832, frank.cipolla@epostdirect.com
he prefers to use the acronym “RIE” – for and are demonstrating how innovative shows, speaking to
‘Rich Interactive Experience.’ thinking can completely change the way technology audiences
Java and Java-based marks are trademarks or registered Front-end engineering experts like they do business,” according to Franco. As both in North America
trademarks of Sun Microsystems, Inc., in the United States and
other countries. SYS-CON Publications, Inc., is independent of
Voisen and Eismann remind us that the president of EffectiveUI, he enjoys unique and overseas. He is
Sun Microsystems, Inc. All brand and product names used on emergence of Web 2.0 technologies and opportunities to see close up how Fortune executive producer
these pages are trade names, service marks or trademarks of
their respective companies.
the iPhone experience have shown that 500 companies are beginning to harness and presenter of
great user interface design makes a big RIAs and leverage them to improve the “Power Panels with
difference, that the era of what Eismann user experience and boost the bottom Jeremy Geelan” on
calls primitive HTML websites is truly line. SYS-CON.TV.
over, and that on the web the new priority Is your company doing the same? If not,
is innovation and optimizing the User eX- why not? jeremy@sys-con.com

JDJ.SYS-CON.com May 2008 3


contents
MAY 2008 VOLUME:13 ISSUE: 5

JDJ Cover Story

24 FROM THE PUBLISHER

RIAs or RIEs – Call Them What

Uncommon
by Kris Lachor You Will, They’re Here
by Jeremy Geelan
...............................3

Java Bugs PRESSROOM


Industry News
............................6
JDJ News Desk

Detecting them
with FOSS tools
CASE STUDY

10
Java and the Mac
It all started with the boss out of Dilbert
by Bob Cusick
...........................8
by S.G. Ganesh
JSP

GET SMART. GET REAL-TIME. Feature Feature Interactive Storyboarding with JSP
Introduction to J-CASE tag library
by Masayuki Otoshi
...........................14
Next generation Internet applications will provide you with instant news
and real-time information without the need for plug-ins or 20th century JSR WATCH
polling techniques. Imagine using your Web browser to monitor ANY Java and Free Software in Brazil
real-time data, from server statistics to your favorite stock portfolio, with Bridging the digital divide
by Patrick Curran
NO polling, NO plug-ins, and NO issues with firewalls or proxy servers! ............................32

GET SMART. GET REAL-TIME. GET POWERED BY KAAZING.


18 28 Do you want to subscribe,
The Rise of Functional Programming Modernizing Axis1 Services Painlessly sign up a friend, or possibly have
an opportunity to write for us?
by Joe Morrison and Kalani Thielen by Michael Galpin Visit www.sys-con.com today!
www.kaazing.com 650.943.2436 sales@kaazing.com
Java Developer’s Journal Digital Edition (ISSN#1087-6944) is published monthly
(12 times a year) for $99.00 by SYS-CON Publications, Inc., 577 Chestnut Ridge Road,
Woodcliff Lake, NJ 07677. Periodicals postage rates are paid at Woodcliff Lake,
NJ 07677 and additional mailing offices. Postmaster: Send address changes to:
JDJ, SYS-CON Publications, Inc., 577 Chestnut Ridge Road, Woodcliff Lake, NJ 07677.

JDJ.SYS-CON.com May 2008 5


PRESSROOM

Industry News President and CEO:


Fuat Kircaali fuat@sys-con.com

President and COO:


DigiSoft Announces General Availability of a Java Enterprise T5140 and T5240 servers deliver
Carmen Gonzalez carmen@sys-con.com
Platform Micro Edition Client Solution for IPTV performance and scalability and help enable
(Las Vegas) – DigiSoft.tv has signed a global customers to consolidate the datacenter into an Senior VP, Editorial and Events:
Binary Value Added Partner agreement with Sun ultra-dense, energy efficient compute environ- Jeremy Geelan jeremy@sys-con.com
Microsystems for the distribution of a Java Plat- ment, optimized and managed by the Solaris 10
form Micro Edition (Java ME) based software Operating System (OS). The SPARC Enterprise
Advertising
stack for IPTV Set Top Boxes (STBs). T5140 and T5240 servers deliver up to 16 times
Sun’s Java technology-based media client higher compute density than competitive two- Advertising Sales Director:
combined with DigiSoft’s middleware solution socket x86 systems and up to 32 times higher Megan Mussa megan@sys-con.com
for IPTV Set Top Boxes enables service providers compute density than competitive four-socket Associate Sales Manager:
to launch high definition (HD) services such as x86 systems. The Sun and Fujitsu SPARC En- Corinna Melcon corinna@sys-con.com
Video and Music on Demand, karaoke, home terprise T5140 and T5240 servers provide up to
Advertising & Events Associate:
shopping, network-based recording (NPVR) three times more performance than competitive
Alison Fitzgibbons alison@sys-con.com
/ time-shifted TV, games and more on a wide RISC systems in half the space.
range of IPTV STBs with H.264 HD and SD www.sun.com
video. Also supported is the latest encryption www.fujitsu.com Events
and watermarking technologies from selected Events Manager:
partners. The combined DigiSoft / Sun software Appcelerator Integrates Rich Internet Application Sharmonique Shade sharmonique@sys-con.com
stack offers IPTV service providers an open, flex- Platform with Google App Engine
ible IPTV middleware solution. (Atlanta) – Appcelerator, a provider of open
The use of Java technology for the software source rich Internet applications (RIA), it has Editorial
stack enables the creation of multi-platform updated its platform to allow applications built Executive Editor:
(converged) Java applications for support on a using Appcelerator to be deployed to the free new Nancy Valentine nancy@sys-con.com
range of Java-based devices, including Blu-ray Google App Engine. Used together, the offerings Associate Online Editor:
Disc players, OCAP and other GEM-based set give developers a route to developing, deploying, Lindsay Hock lindsay@sys-con.com
top boxes, mobile handsets, and personal com- managing and scaling their applications.
puters while requiring minimal re-authoring, Appcelerator is an integrated platform that
simplifying application and service deployment. fuses RIA and service-oriented architecture Production
www.digisoft.tv (SOA). With Appcelerator, developers can as- Lead Designer:
semble interactive web applications without the Tami Lima tami@sys-con.com
Sun and Fujitsu Expand SPARC need for JavaScript or player-based plug-ins. Associate Art Directors:
Enterprise Server Line Web applications can be implemented on Abraham Addo abraham@sys-con.com
(Santa Clara, CA / Tokyo) – Sun Microsystems Java/J2EE, PHP, Ruby, .NET, Python and Perl. Louis F. Cuffari louis@sys-con.com
and Fujitsu Limited have expanded the Sun Appcelerator for App Engine runs on Python,
and Fujitsu SPARC Enterprise server line with the scripting language currently supported by
the introduction of two new systems based App Engine. As Google expands support to other Web Services
on the UltraSPARC T2 Plus processor. Scaling languages, Appcelerator for App Engine will fol- Information Systems Consultant:
from the edge of the network to the heart of the low suit. Robert Diamond robert@sys-con.com
enterprise, the third-generation CMT SPARC www.appcelerator.com
Web Designers:
Stephen Kilmurray stephen@sys-con.com
VoiceObjects Introduces VoiceObjects Desktop for Eclipse Richard Walter richard@sys-con.com

(San Mateo, CA) – VoiceObjects, a personalized phone self-service company, has announced the general availability of its VoiceObjects
Desktop for Eclipse and VoiceObjects Developer Edition. Using these new solutions, developers can create over-the-phone, multi-chan- Accounting
nel applications with personalization features to customize the experience for each user. Financial Analyst:
VoiceObjects 7 suite of products includes VoiceObjects Server for the deployment and management of personalized self-service Joan LaRose joan@sys-con.com
applications over voice, video, text, and Web self-service channels; VoiceObjects Desktop for creating, testing, deploying and moni-
Accounts Payable:
toring applications; and VoiceObjects Analyzer, a Web-based service used for caller behavior, system and application analysis. The
Betty White betty@sys-con.com
release of VoiceObjects Desktop delivers solutions that enable organizations to obtain 1:1 personalization. Built from the ground up
using open standards, VoiceObjects enhances VoiceXML capabilities in delivering applications that meet consumer demand.
Desktop for Eclipse is an Eclipse-based development environment that provides a graphical-use interface for the design, develop- Customer Relations
ment, deployment, testing and administration of voice, video, text and Web-based applications. The solution supports two opera- Circulation Service Coordinator:
tional modes: a network mode that allows for team collaboration, and a standalone mode that allows developers and consultants to Edna Earle Russell edna@sys-con.com
perform offline development and testing.
www.voiceobjects.com

6 May 2008 JDJ.SYS-CON.com


CASE STUDY �
�� ����
�����������
� ��
�� ����

�������������
� ����������
��� ���

Java and the Mac ��


��
���
�� �����

������������
��
by Bob Cusick

It all started with the boss out of Dilbert

T
his is the story of a Mac application
developer (okay – it’s about two of
ers for the iTunes store) it became evident
that something else was necessary, and John
Darren says, “On my Mac, it’s easier to use
Java with Servoy for all the aspects involved
������������������������

ISBN 0-9777622-0-3
them) who set out on a quest to find Allen found it after he came in contact with in delivering business software: writing

���������������
an application development tool Servoy. Servoy is a Java-based environment business rules and workflow rules in a
based on Java so his boss would let him de- that lets the application developer use pre- productive way with very user-oriented and
velop on the Mac platform, which he loved. built scripts AND write in Java. friendly user interfaces. With Servoy I solve
There was only one catch – he had to find a Our hero contacted Servoy, Inc. and those problems. Although it’s Java-based, it
tool that was fast. Traditional Java program-
ming was going to take waaaay too long to
asked them to have a look at a prototype
that was built in WebObjects. The proto-
offers a whole set of functionality that allows
me to focus on what I am good at: writing
���������������������������������������
convert the internal custom programs that type was an application used to manage business software that is very user-friendly,
had been written in an old 4GL. But the boss data around oncology, and it had taken the stable, and scalable. And I can write it much, �� �������������������������������������������������������������������������������������
still wanted the excellent user interfaces that WebObjects team hired by Stanford two much faster in Servoy than in plain Java. � �����������������������������������������������������������������������������������
he was used to – because our hero was good months of coding to come up with a mock- With this tool, I can write one code and de-
on the Mac and could make the screens look up. John was a bit suspicious about Servoy’s ploy to a client’s desktop or over the Web. It
���������������������������������������������

�������
“pretty.” If possible – the boss wanted the response to the prototype: “It’s faster to build eliminates the need for rewriting in PHP and
impossible – make the application run on a this in Servoy than to write you an offer and HTML – Servoy does most of that for me.”

����
desktop AND over the Web – “just in case.” project document.” A couple of days later, So is Java for Mac all hallelujah? No, ������������������������
����
����
Here’s the story of our intrepid hero and how Servoy delivered a working version of the unfortunately it isn’t. Apple is sending very
he searched, and found, a way to meet all prototype. Going ahead with Servoy was mixed messages about Java: on one hand, �����������������
the “Dilbert boss-like” requirements. now a no-brainer for Stanford. John is very Steve Jobs mentions that it’s obsolete; on the from the Worldʼs Leading i-Technology Publisher © COPYRIGHT 2007 SYS-CON MEDIA

John Allen, a researcher at Stanford much a Mac guy: “I just prefer to have a other hand he runs his Web store and iTunes
Medical Center, used to use 4GL environ- no-hassles OS where everything I need is in on it. Also, the Java team at Apple is very
ments to assist the research divisions at this the right place, one that’s stable and doesn’t responsive and can even be contacted per- �� ����
� ���������
well-known university. Stanford Medical is suffer from all types of viruses and malware. sonally with problems. Yet that same team �
�� ����

����������
one of the most advanced research facilities With Servoy, I can work on Mac all day, even isn’t authorized to send you a patch, and �� ����
� ����������
for oncology (cancer), and with the cutting if the applications I use are deployed to Win- you’ll have to wait before a bug fix makes it � ��
��� ���
-edge research it does, there’s no standard dows. What’s nice is that I don’t even have to into an OS X release – which in some cases
� ���� �� �����

���������������
software package that can be used. The build specifically for Windows – Servoy and can take up to six months. Jan Aleman, CEO ��
��
oncology unit’s only solution was code-it- Java take care of this for me!” John was able of Servoy, says, “Mac is the only platform
yourself. 4GL worked well for a long time, to meet all his boss’s requirements, re-train that we have to write specific ‘if’ statements
but a couple of key areas started to become himself on a Java-based product, and stay for. This is because, in particular, the Swing


problematic. 4GLs in general don’t scale very on the development platform he loves – the classes aren’t paid enough attention.” Ac-
well, aren’t very secure due to proprietary Mac. He deploys to Windows, Linux, and cording to Aleman, “This is partly a result
security systems, and worst of all don’t run
very well over the Internet. Stanford, with
even Solaris across the multiple divisions at
Stanford. Many other departments includ-
of Apple not using Swing itself, while at the
same time it’s decided to entirely map it on �������������������������������

ISBN 0-9777622-2-X
�����������������
over 200 buildings, uses the Internet as its ing Child Psychology and the Stanford Law its own set of Aqua GUI components. This
Bob Cusick, managing LAN. Essentially this means the applications School have also adopted Servoy technology is the reason a lot of rather easy-to-fix bugs
director of Servoy, USA, it uses must run secure, with easy deploy- since John first contacted the firm. aren’t solved and actually inspired Servoy to
has one of the oldest ment, and have excellent Web capabilities. Our second example is Darren Clarke, run all our systems on our own technology.
blogs on the Internet Another issue is that it needed to access principal programmer at The Support In fact, before we release a new version to
(started in 1994). He has multiple databases, another problem for Group. The Support Group is a business our public, we run all our internal systems
been writing business propriety 4GL tools – which often have their application consulting firm with offices on it. This way, we feel the pain before our
�������������������������������������������������������������������
applications for over own databases built-in. all over the country. “I love Java, I love my customers do.” �����������������������������������������������������������������������������������������������������������������
15 years, using popular Because of these challenges, Stanford Mac, I love the cross-platform capabilities of Funny enough, Servoy’s CEO uses a Mac ������������������������������������������������������������������������������������������������������������������
4GLs, Oracle, HTML, decided that the 4GL would have to be Java – I just hate the fact that a lot of simple himself too, not just personally but also for ���������������������������������������������������������������������������������������������������������
�������������������������������������
and Servoy. He was the switched to Java, which would deliver things are very difficult to achieve with plain business. “I just got tired of Windows, with
charter technical editor all it needed; however, it turned out that Java!” Darren prefers to develop on his Mac, the viruses, the instability, the slow boot, ��������������������������������������

�������
for FileMaker Magazine programming in Java was much more com- but his customers often use Windows. The the lack of proper command -line tools so I


����
and speaks at developer plex and much more time-consuming (of beauty of Java and Servoy is that it doesn’t made the jump. I’ve noticed that I’m not the
������������������������
conferences all over the course!). After trying some projects in 2003 matter. Business customers often have only one. Once a developer gets to choose,
����
����
world. Visit his blog at with the then-promising WebObjects (a Java complicated business rules – but a lot of he’d rather use the most hassle-free OS out
bobcusick.blogspot.com. environment from Apple used among oth- end users need a very easy-to-use interface. there.” �����������������
from the Worldʼs Leading i-Technology Publisher © COPYRIGHT 2007 SYS-CON MEDIA

8 May 2008 JDJ.SYS-CON.com


FEATURE

Uncommon Java Bugs


Detecting them with FOSS tools

by S.G. Ganesh

A
ny large Java source base can have insidious and In this article we’ll see an uncommon defect and introduce a
subtle bugs. Every experienced Java programmer tool that detects it. We do this for two reasons: to illustrate the kind
knows that finding and fixing these bugs can be of unusual problems that can happen in the code and to intro-
difficult and costly. Fortunately, there are a large duce a FOSS tool that’s suitable for detecting this kind of problem.
number of free open source Java tools available that can be
used to find and fix defects early in the development life- Jlint Figure 1 FindBugs detects the check-for-equality-to-NaN problem
cycle. In this article, we’ll look at a few examples of specific What does this program print?
uncommon1 or unusual defects that can happen in code and To avoid this problem, it’s best to use ‘L’ (upper case letter L) as the
see how different Java static analysis tools detect them. class LongVal { suffix for long constants instead of ‘l’ (lower case letter l).
public static void main(String[] s) { Antic is part of the Jlint tool that’s meant to find problems related to
Testing long l = 0x1l; C syntax. There are quite a few coding problems that are common to
As software gets more complex and ubiquitous, it becomes System.out.format(“%x”, l); languages that use C-like syntax. The problem we saw now is just one Figure 3 The DeadLock.java program results in
more difficult to ensure high-quality code. One common } such problem. Jlint ferrets out Java inconsistencies and bugs. It’s not Figure 2 Test.java program results in NullPointerException a “deadlock condition”
method of finding bugs is testing. But testing can’t cover all } a very sophisticated tool and if you don’t have experience using static
paths and possibilities or enforce good programming practices. analysis tools, JLint is a good tool to start with. Antic works on Java The FindBugs tool is excellent. It detects correctness problems,
Expert knowledge in the form of manual code review by peers is When you run it, it prints 1, not 11 – why? Let’s use a tool to source files and Jlint works on Java class file builds. It’s a command multithreading issues, performance problems, and bad practices.
one of the best ways to ensure good code quality. Code review is detect the problem. The antic tool (that’s part of JLint) finds it: line tool and easy-to-use. It’s available at http://jlint.sourceforge.net. It has less false positives and warns of only critical or important
often used as a mandatory process step for improving the code problems that are likely to be actual defects in code. So, if you’re
and for finding the problems early in the software lifecycle. $antic –java LongVal.java FindBugs pressed for time and want to look at only important problems, this
Since testing and manual code review processes are re- LongVal.java:3:26: May be ‘l’ is used instead of ‘1’ at the end of What does this program print? tool will suit you. It runs on Java class/jar files, so no Java source files
source-intensive, it would be helpful to use automated tools to integer constant are needed to use it. And it runs in a nice standalone GUI. You can
review code. Static analysis tools help considerably in detecting class NaNTest { download it at http://findbugs.sourceforge.net/.
the problems early in the software lifecycle and help enhance The programmer, possibly by mistake, typed ‘l’ (English public static void main(String[] s) {
the quality of the code significantly. letter l) instead of ‘1’ (number one)! double d = getVal(); PMD
There are many high-quality Java tools available in the open if(d == Double.NaN) What’s wrong with the program in Listing 1? If you
source domain. While it’s true that Java programs don’t suffer long l = 0x1l; System.out.println(“d is NaN”); try to run it (as shown in Figure 2) you’ll get a NullPointer-
from traditional C/C++ problems like memory issues and major } Exception!
portability issues, Java software does suffer quality problems Benefits of Using FOSS Java Static Analysis Tools private static double getVal() { What could have gone wrong? PMD detects it and warns of the
like reliability, efficiency, maintainability, and security. A brief return Double.NaN; problem:
S. G. Ganesh is a research discussion on benefits of using FOSS Java tools is given in the Using Java static analysis tools can significantly improve the quality of code. }
engineer at Siemens (Corpo- sidebar. Although static analysis tools can’t cover all the paths or possibilities, it pro- } $ pmd Test.java text design
rate Technology), Bangalore. Before getting into the meat of the matter, let’s discuss why vides significant help in providing coverage in detecting problems early in code; Test.java:3 Overridable method ‘foo’ called during object
Prior to Siemens, he worked bugs happen. First, it’s important to recognize that everyone such tools can also point out programming problems and warn of violations of You might be surprised to find that it doesn’t print anything! What construction
at Hewlett-Packard for makes mistakes, even experts2. Second, compilers only check important and well-accepted programming rules and recommendations. went wrong? The FindBugs tool detects the problem and warns us
around five years. His areas for syntax and semantic violations. Errors in language or API Using static analysis tools has many attractive benefits. A few of the salient about it (see Figure 1). The bug in this program is that the constructor of the Base class
benefits of most of these tools are listed here. Most of the Java FOSS tools:
of interest are programming use, which manifest themselves as bugs, aren’t detected by The bug is that the condition (NaN == NaN) evaluates to false! In calls an overridden method. Constructors don’t support runtime
• Can cover code that’s not covered by testing or dynamic analysis
languages and compilers. His compilers: This is left to static analysis tools and it’s important to the condition (d == Double.NaN), this code checks to see if a float- polymorphism since derived objects aren’t constructed when the
• Find many unusual or uncommon bugs that are usually missed
latest book is 60 Tips on Ob- use them to detect coding problems. Third, programmers and ing-point value is equal to the special “Not A Number” value. The base class constructor executes, the virtual method foo is called from
during testing or manual code review
ject Oriented Programming engineers are under constant pressure to “get-the-work-done” IEEE 754 floating-point standard provides the special semantics of the base class constructor. Since foo is overridden, the overridden foo
• Work even on partial code – fully compilable source isn’t always needed
(ISBN-13 978-0-07-065670-3) under tight schedules; working under “almost-impossible-to- NaN: no value is equal to NaN, including NaN itself. So, the check (d calls the toString method from i, which isn’t initialized yet (note that
• Easily integrate with popular IDEs, so it’s comfortable to use them in
published by Tata McGraw- meet” work schedules results in code that is often substandard your favorite environment == Double.NaN) always evaluates to false. The correct check to use is i gets initialized only after the Derived constructor has completed
Hill, New Delhi. and filled with bugs. So, because of practical problems, most • Are usually easy-to-run –with just a button click from your IDE the condition check Double.isNaN(x). executing). Because of this, the program terminates with a NullPoin-
code developed in the real world has bugs and it’s worthwhile • Are absolutely free and high-quality The FindBugs tool detects this problem and aptly names it terException. For this reason, it’s not a recommended programming
sgganesh@gmail.com using static analysis tools to find them and fix them. “Doomed test for equality to NaN”. practice to call overridable methods from constructors.

10 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 11


FEATURE

The PMD tool checks for problems like possible bugs, design rule Acquiring multiple locks is prone to deadlock, particularly if not DoctorJ, and JarAnalyzer. More information and links on Java tools is provided in the
violations, duplicates, sub-optimal or dead code, suggestions for mi- done in the same order or if the sleep()/wait() in the Thread is called Listing 1 Resource section.
gration to newer JDK versions, J2EE, JavaBeans, JSP, and JUnit rules. It after acquiring locks. In this program, foo and bar acquire locks in class Base {
public Base() {
works on Java source files and can be used from the command line. opposite order and call sleep(). Hence deadlock occurs. Conclusion
foo();
Plug-ins for popular IDEs like Eclipse, JBuilder, and JCreator are also Acquiring multiple locks is not a recommended programming We saw four specific static analysis tools that can be used to detect not-so-com-
}
available. You can download it from http://pmd.sourceforge.net/. practice. However, it’s often required in practice, so when we need public void foo() {
mon defects in code. They are free, easy-to-integrate with IDEs, and easy-to-use.
to acquire multiple locks, we should ensure that we acquire them in System.out.println(“In Base’s foo “); It’s highly recommended to use such tools to improve the quality of the software by
QJ-Pro the same order in the code. } detecting and fixing bugs early in the software lifecycle.
What’s wrong with the program in Listing 2? Alternatively, we can consider using non-blocking locks when }

It’s likely that the program will hang after running successfully for we attempt to acquire multiple locks. The tryLock method in the Resources
class Derived extends Base {
few times as shown in Figure 3; in other words, this program can lead java.util.concurrent.locks.Lock interface provides this ability. It’s also • If you’re interested in a list of the Java FOSS static analysis tools available, check
public Derived() {
to a “deadlocked condition” (the program actually hint at this: the recommended to release locks quickly and not hold the locks for a i = new Integer(10); http://java-source.net/open-source/code-analyzers.
name of the class is Deadlock!). long time; so, it’s not recommended to use sleep/wait methods after } • “A Comparison of Bug Finding Tools for Java” by Nick Rutar, Christian B. Almazan,
The QJ-Pro tool detects it as shown in Figure 4. acquiring a lock; consider using the wait/notify mechanism instead public void foo() { and Jeffrey S. Foster from the University of Maryland provides a detailed technical
The bug in this code is that the code acquires two locks in op- to avoid deadlocks because of holding a lock for a long time waiting System.out.println(“In Derived’s foo “ comparison of Bandera, ESC/Java, FindBugs, JLint and PMD tools. See http://
+ i.toString());
posite order; and after that a sleep/wait method is called – this for a condition to occur. www.cs.umd.edu/~jfoster/papers/issre04.pdf.
}
condition will usually result in a deadlock. The QJ-Pro tool checks for problems like conformance to coding • If you’re using Eclipse, it’s very convenient to use Java tools as plug-ins. The list of
private Integer i;
Locks are the basic Java synchronization mechanism. Using locks standards, coding best practices, misuse of features, and APIs. It } available plug-ins for Java is at http://www.eclipseplugincentral.com/Web_Links-
ensures exclusive ownership for a thread while executing a critical gives lots of violations by default, so you’d have to spend some time index-req-viewcatlink-cid-14-orderby-rating.html.
section. Incorrect use of synchronization can lead to deadlocks. selecting the list of rules you want to run for your project. It works class Test { • The book Java Puzzlers: Traps, Pitfalls, and Corner Cases by Joshua Bloch and
A big problem with deadlocks (as with most multithreading on Java source files and is easy-to-use in its standalone GUI version public static void main(String [] s) { Neal Gafter covers many interesting bugs that can happen in code. Check the link
new Derived().foo();
problems) is that deadlocks are “non-deterministic” – they need not (shown in Figure 5). You can use its plug-ins with popular IDEs like http://www.javapuzzlers.com/.
}
reproduce consistently, and so it’s difficult to detect, reproduce, and Eclipse, JBuilder, JDeveloper or use it as an Ant job. You can get QJ-
}
fix problems related to deadlocks. Pro from http://qjpro.sourceforge.net/. 1
Here the word “uncommon” means the kind of defects we talk about are not defects due to usual pro-
gramming problems like null-pointer access or incorrect casts. The defects we are going to cover are little
Other Tools Listing 2 unusual that they don’t generally occur in programs; at least, they don’t occur everyday when we program.
Other than the four tools covered here – Jlint, FindBugs, PMD, class This {} 2
To err is human: It is only that novices make more mistakes, but experts know common pitfalls, so they
class That {}
and QJ-Pro – there are many other FOSS tools available. For exam- write code with lesser number of defects.
ple, CheckStyle checks for adherence to coding standards such as
class DoSynchronize implements Runnable {
Sun’s. You can get it from http://checkstyle.sourceforge.net/. JCSC public static void foo() throws InterruptedException {
(Java Coding Style Checker) checks for coding style adherence synchronized(This.class) {
and for common bugs. You can get it at http://jcsc.sourceforge. synchronized(That.class) {
Figure 4 QJ-Pro detects deadlock because of acquiring multiple locks net/. There are many more useful tools like Classycle, Condenser, Thread.currentThread().sleep(10);
}
}
}
public static void bar() throws InterruptedException {
synchronized(That.class) {
synchronized(This.class) {
Thread.currentThread().sleep(10);
}
}
}

public void run() {


try {
foo();
bar();
} catch (InterruptedException e) {
System.out.println(“Caught interrupted exception”);
}
}
}

class DeadLock {
public static void main(String []s) {
DoSynchronize pc = new DoSynchronize();
Thread t1 = new Thread(pc);
Thread t2 = new Thread(pc);
t1.start();
t2.start();
}
}

Figure 5 QJ-Pro detects deadlock because of acquiring multiple locks

12 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 13


JSP storyboarding and easy maintenance.
A tool that supports all the features needed
is J-CASE Tag Library. J-CASE takes a different
approach than the other tools. First we create

Interactive Storyboarding JSP files describing use cases and screens. It


generates documents with use case style and
UML diagrams for use cases and navigation
Figure 3 Use Case JSP and Action JSPs

with JSP
maps. Compared to other GUI tools, we can
by Masayuki Otoshi call J-CASE a tool for developers. If you have
expertise in JSP, you’ll understand how to use
the tags, and realize it can extend custom codes Figure 4 Use Case Frame generated by the useCase tag
using other tag libraries.
Introduction to J-CASE tag library In general, you may think we shouldn’t code
for writing storyboards. However, I need to
emphasize that there’s an advantage in writing

A
lot of rework still happens in One of the reasons is that there are few matically generate supplemental them with JSP in the analysis and design phase.
projects applying UML tech- storyboard tools available. In story- documents and diagrams. My experience is that developers typically Figure 5 Actions Frame generated by the actions tag
niques because of conflicts boards, the scenarios defined in use • Use Case Description Style – Since find conflicts and missing requirements, even
and omissions in require- cases are detailed, and abstract screens we’ve already captured requirements though we’ve spent time reviewing the require-
ments. To reduce rework, interactive and process logic are also added. So in use case descriptions, it’s better to ment and specification documents. That’s
storyboarding is effective, but it seems the flows typically become complex, describe storyboards using the same because programming languages are limited in
that projects using the technique are and we can’t easily maintain them format so we can describe them by expressions and requires more precision than
limited because of the few tools avail- without tools. extending existing descriptions. natural language. So, when developers can’t Figure 6 The login screen Figure 7 The confirmation dialog
able. The following features are required translate the requirements written in natural generated by the screen tag generated by the dialog tag.
To improve this situation, this article in storyboard tools: The tools available today fall into language into code, they recognize that’s some- Figure 9 Storyboard document with screens and process results
introduces the J-CASE open source Tag • Interactive Storyboarding – The two groups. One is “storyboard tools” thing wrong or missing. Since J-CASE requires
Library that lets us describe story- storyboards described should be (tools for writing storyboards), and the us to write some codes, we can also get similar
boards on JSPs based on use cases, and able to execute on a simulator or other is “tools for drawing diagrams” recognitions when writing JSPs for storyboards.
explains how to generate document Web site so that stakeholders can like Visio, the UML tool, and Power-
and UML diagrams from the JSPs. experience the story on screens. Point. Create Use Case and Action JSPs Figure 8 Process results generated by the processResults tag
To reduce the rework and improve • Easy Maintenance – The require- Some storyboard tools are avail- Let’s start to create a use case and storyboard
quality of the requirements, we should ments represented on the story- able to generate HTMLs for interactive using J-CASE tags. As a sample use case, I’ll use JSPs. Listing 2 shows two actions that the user
carefully realize the use cases in design boards are often changed. The storyboarding from screen and flow a “Log In” use case available for download on may take on the login page.
stage. There are two approaches to data we need to modify has to be definitions. But these are commercial the J-CASE Web site. Before starting to create The first action represents the event of Main
realize (and see Figure 1): minimized. So tools should auto- products and not cheap. the storyboards, core scenarios have to be cap- Flow Step 2 in Figure 2, and the second one Figure 10 Use case diagram generated by the generateUseCase tag
• Class definitions – Find classes and In the case of tools for drawing dia- tured in use cases. Figure 2 shows the use case is Alternative Flow 1 Step 1. The Action JSP is
define object interactions. They are grams, say, the UML tool, storyboards description of the “Log In” use case. converted as in Figure 5. A dialog to ask the user for a “Yes” or “No”
represented in class and sequence can be expressed using class diagrams J-CASE expresses the use case using two can be represented using the <jc:dialog> tag
diagrams, etc. and activity diagrams. However, the kinds of JSP, Use Case JSP and Action JSP. Main Generate Use Case Document shown in Listing 5.
• Storyboarding – Describe detail UML diagrams created aren’t intuitive- and alternative flows (flows of events) are de- Once you create all Use Case and Action The code generates the dialog frame shown
scenarios based on use case ly understood. It’s not easy to imagine scribed in Action JSPs, and the rest of informa- JSPs, you can execute a <jc:generateUseCase> in Figure 7 when accessing the JSP.
descriptions, and add user interface screens and flows from the diagrams, tion, such as use case ID, name, Brief Descrip- tag to generate a use case document from the The logic of the system process can be de-
information and system processes especially for stakeholders who aren’t tion, and Actor, is described in Use Case JSP. JSPs. The tag requires input and output attri- fined as a Java method in a JSP declaration tag
to be executed. familiar with UML. It also doesn’t In the Use Case JSP, use case information butes. The path of the Use Case JSP is specified (<%! %>). In a JSP that represents a login process,
Figure 1 Two ways to use case realization satisfy the requirements of interactive except flows of events is described using a <jc: in the input, and the HTML path of the use you can define, for example, the authenticate
Ideally both activities are neces- useCase> tag. Use Case ID, name, actor, and the case document to be generated is specified in method shown in Listing 6 that authenticates
sary. However, we tend to neglect the link to the first Action JSP are specified in the the output (see Listing 3). the user by checking the credential parameter.
storyboarding in software analysis attributes of the tag. Refer to Figure 2 again. It’s the use case The method annotated with @JCaseProcess
and design. Use cases only capture Other additional information (Brief Descrip- HTML generated by the <jc:generateUseCase> is automatically executed when the page is
core functional requirements; they’re tion and Actor) is added using a <jc:desc> tag. loaded, and you can see the execution results
not enough for stakeholders to fully tag in the body of the <jc:useCase>. Listing 1 using the <jc:processResults> tag. In case au-
understand how the system will work. represents use case information of the “Log In” Visualize the Use Case thentication fails, you’ll see the process results
They don’t know what they really want use case. Screens, system processes, and so on aren’t as shown in Figure 8.
to do with the system until they see the The Use Case JSP is converted into a Use typically mentioned in use cases to focus on
actual system we develop. Case Frame as shown in Figure 4. By clicking capturing core requirements. Now that the “Log Generate Storyboard Document
Storyboarding visualizes the use the link labeled “[UC01] Log in” you can start In” use case is created, it’s time to describe the After adding screens and processes on the
Masayuki Otoshi cases and shows stakeholders what the experiencing the use case. screens and processes. JSPs, you can execute the <jc:generateUseCase>
develops Web applications screens look like and what happens on In the Action JSP, actions performed by ac- To visualize the pages, J-CASE provides <jc: tag again to generate the storyboard document.
for a manufacturing each screen. It helps them get a better tors are described using <jc:actions> and <jc: screen>, <jc:dialog>, etc. For example, the login When you access the JSP, including the <jc:
company as a senior understanding and we could get more action> tags. Each <jc:action> represents an form can be specified using HTML code in the generateUseCase>, the storyboard.html shown
developer. feedback before moving to implemen- event that the actor (end user or system) can <jc:screen> tag as shown in Listing 4. in Figure 9 is generated. You’ll also see the
tation. Although storyboarding has lots take on the page, and the flow of the events is The <jc:screen> tag is displayed as shown in screens and process results you added on it this
otoshi@mxd.mesh.ne.jp of benefits, why isn’t it more popular? Figure 2 “Log In” use case description represented by making links between Action Figure 6. time.

14 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 15


JSP

Generate UML Diagrams cases and the specifications required


The World’s Leading Java Resource
Is Just a >Click< Away!
The <jc:generateUseCase> tag also for actual implementation. While
accepts useCaseDiagram and navigation- writing storyboards, you’ll find con-
Map attributes, which generate XML files flicts, redundancy, and omissions in
of the UML diagrams. If you execute <jc: the use cases. Visualized screens and
generateUseCase> with those attributes as flows also give us a better understand-
shown Listing 8, XML files that can be ed- ing. To get the benefits, it’s important
ited with EclipseUML are also generated. to choose the right storyboard tool
Figure 10 shows the use case diagram
of the “Log In” use case.
Figure 11 shows the navigation map
according to the requirements of your
project.
This article recommends using a
JDJ is the world’s premier independent, vendor-neutral print resource
that represents navigations among pages
(JSPs). With these diagrams, we can verify
tool that supports creating interactive
storyboarding, and introduced J-CASE Tag for the ever-expanding international community of Internet
technology professionals who use Java.
if there are any conflicts or redundancies Library. It helps you refine use cases and
in defined use cases and flows. define better specifications.

Conclusion Resources
Storyboarding is a technique to J-CASE homepage: http://www5f.biglobe.
Figure 11 Navigation map of “Log In” use case bridge a considerable gap between use ne.jp/~webtest/jcase/

Listing 1: useCase tag Listing 5: Dialog tag

e s !
v y
<jc:useCase id=”UC01” <jc:dialog name=”Confirmation” button=”Yes,No”>

l n
name=”Log in”

l
Are you sure to remove the file?
link=”protected.jsp” </jc:dialog>

e t h i o ition er :
actor=”Consumer User”>

s
<jc:desc name=”Brief Description”>
The user logs in the system.

w t
</jc:desc> Listing 6: Process definition

i
<jc:desc name=”Actor”> <%!

T o n d int E ecem
Consumer user @JCaseProcess(“The system authenticates the user.”)
</jc:desc>
</jc:useCase>
public String authenticate(PageContext pageContext) throws
Exception { d b
String credencial = JCaseUtils.getParameter(pageContext, “cre-

E
dencial”);

M l ow mbe
Listing 2: Actions and action tags

r r, D
<jc:actions>
if (!”valid”.equals(credencial)) {

P
<jc:action name=”Correct Credencial”
throw new Exception(“Invalid ID or password.”);

a
link=”loginProcess.jsp?credencial=valid”>
}
The user enters correct ID and password.

t
</jc:action>

i
<jc:action name=”Invalid Credencial” JCaseUtils.setAttribute(pageContext, “auth_result”, “valid”);
link=”loginProcess.jsp?credencial=invalid”> return “Valid session has been created.”;

S h te
p
g
The user enters invalid ID or password. }
</jc:action> %>
l e
i pe June ia , S
</jc:actions>

c
D u r Sc h ,
Listing 7: Generate the storyboard document
Listing 3: Generate use case document <jc:generateUseCase
<jc:generateUseCase input=”useCase.jsp”
input=”useCase.jsp” output=”storyboard.html”
output=”useCase.html” />
/>

o a r
F M
Listing 4: Screen tag Listing 8: Generate UML diagrams
<jc:screen name=”Login Form” align=”center”> <jc:generateUseCase
<table> input=”useCase.jsp”
<tr><td>User ID </td><td><input type=”text”></td></tr>
<tr><td>Password</td><td><input type=”text”></td></tr>
output=”storyboard.html” www.JDJ.SYS-CON.com
useCaseDiagram=”useCase.uud”

or 1-888-303-5282
</table>
navigationMap=”navMap.uad”
<input type=”button” value=”Submit”>
/>
</jc:screen>

16 May 2008 JDJ.SYS-CON.com OFFER SUBJECT TO CHANGE WITHOUT NOTICE


FEATURE
oriented paradigm (or any paradigm) stops people from </list>
violating unwritten rules. As a result, you have to understand </constructor-arg>

The Rise of
exactly how the ArrayReader and CharReader objects interact </bean>
to predict what will happen. The problem is magnified if your
program is multithreaded. <bean id=”charReader” class=”CharReader”>

Functional Programming
The fundamental problem is that each object behaves <constructor-arg ref=”arrayReader” />
differently depending on its current state. (Obviously the </bean>
second time you call read() on an ArrayReader you get a dif-
ferent result from the first time you call it.) That means that </beans>
in general, if you want to understand what any particular op-
eration is doing to an object, you have to know exactly what Note that we used constructor-based dependency injec-
state the object was in before you invoked the operation. But tion, but it’s common to use setter-based injection in which
to know that you have to know at what point the object was case we would have added setters to each class for the String
created, and the exact sequence of subsequent operations array and Reader dependencies, thus creating even more
Better living without side effects that might have changed the object’s internal state. That’s mutable state. By changing this XML file we can cause our
by Joe Morrison and Kalani Thielen easy if the object reference is assigned to only a local variable program to behave completely differently. Here is a version,
and never shared, but if the object reference can be obtained for example, that provides the CharReader object with its
from anywhere in your application via reflection or a direc- own private ArrayReader and eliminates the confusing shar-

J
tory service, then all bets are off. ing of the mutable state:
ava applications have become steadily harder to un- starting from any type of Reader and returning its output one
derstand and maintain in recent years. Object-oriented character at a time. See Listing 1. Adding Fuel to the Fire by Abstracting Away Object Creation <beans>
programming has proven an effective way to develop Notice that both ArrayReader and CharReader have pri- Design patterns that abstract away the process of object
enterprise applications, but several recent trends are vate, internal state. It’s part of the benefit of object-oriented creation bring a huge amount of benefit in terms of software <bean id=”arrayReader” class=”ArrayReader”>
causing a sharp increase in code complexity. One is the programming that these implementations could be changed configuration management and testability. Such design pat- <constructor-arg>
increasingly common use of the Factory design pat- without affecting any other code as long as the public inter- terns have become enormously popular in recent years, but <list>
tern, abstracting away the object creation process (e.g., the faces are preserved. they are problematic when combined with the use of mu- <value>Foo</value>
creation of servlet objects by application servers, the use of But in real life object-oriented programming, subtle prob- table state. A programmer cannot determine which classes <value>Bar</value>
Spring as a general-purpose object factory, the use of JNDI, lems begin to emerge due to the too frequent use of mutable a particular code sequence will instantiate just by looking at <value>Baz</value>
etc.) Another is the increased use of the JavaBean pattern (i.e., changeable) state. Even this simple Reader example the code, and therefore cannot reason about the code until </list>
with reflection and annotations (e.g., for object serializa- can be hard to understand if readers are shared or accessed the runtime behavior of the object factory is fully under- </constructor-arg>
tion and persistence). The result is that objects have more concurrently from multiple threads. For example, what does stood. For example, let’s say we decide to rewrite our example </bean>
mutable state than ever, and the code causing changes to that the following code example do? based on Spring retaining the exact same behavior as before:
state is increasingly decentralized. Programs are becoming <bean id=”charReader” class=”CharReader”>
easier to write, but harder to debug as complexity spirals out public static void main(String[] args) { public static void main(String[] args) { <constructor-arg>
of control. <bean class=”ArrayReader”>
Functional programming is a model of computation that Reader arrayReader = new ArrayReader (new String[] { “Foo”, BeanFactory factory = new XmlBeanFactory(new FileSystemResource(“ <constructor-arg>
avoids making repeated changes to objects, and computes “Bar”, “Baz” }); applicationContext.xml”)); <list>
outputs from inputs in a stateless way. The implications are Reader charReader = new CharReader (arrayReader); Reader arrayReader = (Reader) factory.getBean (“arrayReader”); <value>Hello</value>
far-reaching; functional programs are more concise, easier Reader charReader = (Reader) factory.getBean (“charReader”); </list>
Joe Morrison is a managing to understand and debug, and can be executed more ef- String s = arrayReader.read(); </constructor-arg>
consultant at Lab49, and ficiently on modern computer hardware. Although functional while (s != null) { String s = arrayReader.read(); </bean>
has over 20 years of experi- programming has been around for a long time there has been System.out.println (s); while (s != null) { </constructor-arg>
ence leading engineering a recent resurgence in interest with the advent of languages System.out.println (charReader.read()); // uh oh System.out.println (s); </bean>
teams in designing and like Scala, which support functional programming and can s = arrayReader.read(); System.out.println (charReader.read());
building complex network- be executed in a standard JVM. But even if you’re writing } s = arrayReader.read(); </beans>
based applications. His code in Java, you can use functional programming patterns } } Kalani Thielen is a Lab49
projects have ranged from and achieve many of the benefits. } This version produces the output: technology consultant,
distributed object research In this article we explain the basic principles of functional As it turns out, the result is: working in the financial
at Verizon Laboratories, to programming, and show some functional patterns that you The underlying classes have not been changed at all, Foo services industry. Prior
value chain management can start using in your Java programs immediately. Foo nor has the main logic, but we have left the instantiation of H to joining Lab49 in 2006,
software at Benchmark- B the classes to the Spring framework. Would you be able to Bar he worked for six years
ing Partners in Boston, to The Problem Baz understand the code sequence above if you hadn’t read the e developing products for the
in-the-trenches SOA projects Object-oriented programming is about being able to de- a introduction to this article? For completeness, here is the ap- Baz publishing, advertising, and
for financial services firms fine packages of state, together with operations on that state. plicationContext.xml file: l communications industries.
in New York. Joe has a Typical object-oriented languages support encapsulation, The B and the a on the second and fourth line of the As a specialist in program-
BMath degree in computer i.e., the notion that the state can only be accessed via the output come from the word “Bar.” It’s confusing because the <beans> With this change to the configuration file, the main loop ming language theory,
science from University defined operations, and polymorphism, i.e., the notion that loop alternates each call to arrayReader.read() that pops a prints Foo, Bar, and Baz as expected, and the CharReader his present work focuses
of Waterloo, and a MS in objects of different types can be treated uniformly. Here is an word from the ArrayReader, with a call to charReader.read() <bean id=”arrayReader” class=”ArrayReader”> prints out individual characters from the word Hello. They on the development and
computer science from MIT. example that shows these concepts. The Reader interface de- that pops a word from the same ArrayReader every time it <constructor-arg> no longer interfere with each other. The question of whether certification of compilers
He is a regular blogger on fines an operation for retrieving information one String at a runs out of characters. The spirit of these classes was to call <list> or not the main ArrayReader’s state is shared (creating the for bond pricing and trading
http://blog.lab49.com/. time. The ArrayReader class implements this interface, start- either the ArrayReader or the CharReader in a loop, but not <value>Foo</value> undesired interaction between the classes) depends on the languages.
ing from an array of Strings and returning them one at a time. to make calls to the same ArrayReader both directly and <value>Bar</value> application configuration file, which illustrates why the
joe.morrison@lab49.com The CharReader class also implements the same interface, indirectly via the CharReader class. But nothing in the object- <value>Baz</value> configuration file must be read and understood to predict the kthielen@lab49.com

18 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 19


FEATURE

behavior of the actual program. When we are talking about 1 + 2 + sum [3, 4, 5] Swiss Federal Institute of Technology, and one of the designers def sum (l: List[Int]): Int = {
configuration files running to hundreds and thousands of 1 + 2 + sum 3:[4, 5] of Java generics. Scala is a multi-paradigm language, smoothly l match {
lines of XML, this can be daunting. 1 + 2 + 3 + sum [4, 5] integrating features of both object-oriented and functional case Nil => 0
This is not a straw man argument. Code like this is getting 1 + 2 + 3 + sum 4:[5] languages. Most importantly it is fully interoperable with Java. case ::(x,xs) => x + sum(xs)
written and deployed every day in mission-critical enter- 1 + 2 + 3 + 4 + sum [5] It compiles to JVM bytecodes (i.e., standard .class files), Java li- }
prise applications. We’ve had to debug some of it. We are not 1 + 2 + 3 + 4 + sum 5:[] braries can be used freely in Scala programs, and it is possible to }
saying that object-oriented programming is bad, or that it’s 1 + 2 + 3 + 4 + 5 + sum [] inherit from Java classes and implement Java interfaces directly
wrong to abstract away the process of object creation. On 1 + 2 + 3 + 4 + 5 + 0 in Scala. An Eclipse plug-in is even available. def main(args: Array[String]) {
the contrary, our point is that mutable state makes programs println (sum(List(1, 2, 3, 4, 5)));
hard to understand, and modern programming practices Having made each step of the computation explicit, the Installation Instructions via the Eclipse Plug-in }
magnify the problem. Complexity in software is inescapable, derivation of the final result is clear. What’s more, we can be If you’re an Eclipse user, it’s easy to get started with Scala
but unnecessary complexity is, well, unnecessary. By attack- certain that each step in the above derivation completely by installing the Scala Eclipse Plug-in. You don’t even have to }
ing the problem at its root (mutable state), we hope to have describes the computation, as we’ve given up the possibil- install Scala first. Just select:
our cake and eat it too. ity of implicit “side effects” happening between steps. You This is slightly more verbose, but similar in spirit to the two-
can imagine that if the “sum” function had a side-effect (like Help -> Software Updates -> Find and Install -> Search for new fea- line Haskell example we started with. The Haskell version didn’t
Functional Programming: An Alternative Approach updating the input list) this simple two-line example would tures to install declare a package, enclosing class, or Main function, so a fair
To understand better how functional programming can become much more difficult to understand. comparison is to look at only the sum function that is six lines
simplify this problem, we’ll first look at an even simpler prob- Because a functional program implies that you can always and create a new remote site called “Scala Plugin Update long in Scala and includes type declarations. Note the pattern-
lem in Haskell (one of the most mature modern functional substitute a function call with its result, there are two very Site” with this URL: matching syntax, for example, the use of :: to match a list and
programming languages). important things that our compiler can do to help us without split the head node from the remaining nodes. This is an example
If you only remember one thing about functional program- any effort on our part. The first is that, according to the prin- http://scala-lang.org/downloads/scala-plugin of a nice Scala feature called case classes that lets you write pat-
ming, it should be this central idea: that it should be possible ciple of referential transparency, the compiler can substitute tern-matching case statements for your own classes as well as
to substitute a function call with its result, without changing the final result for the call to “sum” at compile-time, without Install the feature Scala Plugin UpdateSite. If you get an error built-in ones.
the meaning of a program. This simple principle (generally re- changing the behavior of the program. This has the effect, in that package org.eclipse.pde.runtime is missing, then go back to: Note that it’s not the objective of this paper to be a Scala
ferred to as referential transparency) has radical implications. our example, of doing no runtime computation at all! tutorial. There are already many of those on the Web. But we
At its best, this idea strengthens the intuition we’ve developed In more realistic cases, the compiler may not be able to Help -> Software Updates -> Find and Install -> Search for new fea- want to introduce Scala because it provides excellent support
from high school algebra that, difficult as a problem may be, compute the entire function ahead of time, but with this tures to install for functional programming, fits well with the Java technology
we can write it out in its entirety and solve it by progressively principle as a guide it can still simplify the inevitable runtime stack, and is gaining momentum in the Java community.
simplifying it. computation by partially evaluating as much of it as possible and select The Eclipse Project Updates, expand the category This sum example we started with may be simple, but it already
Rather than taking on the full-grown horror of a decades-old at compile-time. The second thing the compiler can do is to corresponding to your version of Eclipse, and select the Eclipse illustrates how functional programming is different. The obvious way
legacy system, let’s consider a very simple functional program perform the final computation in parallel where possible. Plugin Development Environment. Install it and restart to code this in Java would have been to initialize a counter to zero,
and analyze it in ways representative of real-life concerns. Given some simple properties of the functions involved (in Eclipse. That plug-in includes the required org.eclipse.pde.run- iterate through the list, and keep modifying the counter by adding the
this case, the fact that a + b + c = a + (b + c) = (a + b) + c), the time package, so once it’s installed you should be able to install next value. If you’ve been writing Java code for a long time, you may not
sum [] = 0 compiler could easily generate code to compute the final the Scala plug-in. realize how deeply ingrained it is for us to solve problems by constantly
sum x:xs = x + sum xs sum as (with concurrent evaluation denoted by parentheses): If you are not an Eclipse user, you can install Scala the tradi- modifying variables, calling methods that modify objects, and so on. But
tional way, starting from this URL: in functional programming, your first instinct should be to think of every
This definition is intended to describe a function, “sum,” 1 + 2 + 3 + 4 + 5 + 0 problem in terms of computing an output directly from an input, break-
that adds up all of the numbers in a list. If the input list is (1 + 2) + (3 + 4) + (5 + 0) http://www.scala-lang.org/downloads/index.html ing it into smaller problems that you solve recursively if necessary.
empty (denoted by empty square brackets) the sum is 0. 3 + 7 + 5 Let’s come back to our original problem now and try to apply
Otherwise we can break the list into its head (“x”) and its tail (3 + 7) + (5) Once you’ve installed Scala, create a new Scala Project. Cre- these concepts.
(“xs” – read as the plural of “x”), in which case the sum is just 10 + 5 ate a package called com.lab49.example and within it create a
the head plus the sum of the tail. It might help clarify this to (10 + 5) Scala Object called Main with the following contents: Rewriting Our Original Example
read the function out loud in English: 15 First let’s consider the Reader interface we started with:
“The sum of an empty list is zero. Otherwise, the list has package com.lab49.example;
an initial value x followed by the remaining values xs, and the Remarkably, the compiler can (given just these few rea- public interface Reader {
sum is x plus the sum of the xs.” sonable assumptions) produce a very specialized, efficient object Main { String read();
This is a recursive definition, and although it may at executable from our compact functional program. The key def main(args: Array[String]) { }
first glance seem like an endless loop, the sum will always to passing all of this complexity off to the compiler is that println(“Hello, world!”)
decrease the length of the input list by one until the simplest we go out of our way to leave the compiler as many imple- } The idea of this interface is to provide access to a list of
case (the empty list) is reached. Let’s try it out on an example: mentation options as possible. To summarize this viewpoint: } strings one at a time, presumably so we can do something to
functional programs describe what is to be computed, those strings. But the fundamental idea of this interface is not
sum [1, 2, 3, 4, 5] allowing functional compilers to decide how to compute it. Select Run as Scala Application. If it displays Hello, world in keeping with functional programming, since every time you
Unnecessary complexity creeps into software projects where then congratulations! You have just written your first Scala call read you change the state of the object. Can we come up
Using the principle of referential transparency, and sub- these problems of what and how are intermixed. application. with a more functional way of doing the same thing? Indeed we
stituting the appropriate body of the “sum” function at each can, by changing the responsibilities slightly. Instead of feeding
step, we can proceed to rewrite this as follows: Introduction to Scala Now let’s try rewriting the sum function in Scala: strings to a consumer one at a time, we will instead ask the con-
A good way for Java programmers to experiment with sumer to tell us what work they want done on each string (using
sum 1:[2, 3, 4, 5] functional programming concepts is to give Scala a try. Scala package com.lab49.example; a callback) then we will do it to all of the strings. In Scala the
1 + sum [2, 3, 4, 5] is an interesting programming language first released in equivalent to a Java interface is a trait, so our revised example
1 + sum 2:[3, 4, 5] 2003 by Martin Odersky, a computer science professor at the object Main { will look like this:

20 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 21


FEATURE

trait Reader { Now let’s write the CharReader class. It requires a Reader
def repeatForEach (f: String => Unit) = () upon construction, and provides character-by-character ac-
} cess to all of the items in that reader:
���������������������������
We are replacing the read method with one called repeat- class CharReader (r: Reader) extends Reader { ���������������������������������
ForEach, which takes a callback as an argument. The callback override def repeatForEach (f: String => Unit) = {
must take a string as input and return nothing as output (that’s r.repeatForEach ((s: String) =>
what the Unit type means in Scala), the idea being that repeat- s.toList.foreach ((c: Char) =>
ForEach will invoke the callback for each individual string. We f (c.toString)));
say = () to declare that by default, this method does nothing. }
Now we need an equivalent to the ArrayReader that takes a list }
of strings at construction time, and can be used later to provide
one-at-a-time access to those strings. In Scala you don’t imple- This is more difficult to understand, so let’s work through it
ment an interface, you extend a trait. Furthermore, although step-by-step. The CharReader takes any kind of Reader as an
Scala supports an Array type, we want to use the List type, argument upon construction, and is also a Reader itself – just like
which is immutable and emphasizes our functional style. So we in our original example. Like the ArrayReader it provides a re-
end up with this: peatForEach method that takes a callback argument. Whenever
this method is called with a callback argument f, the CharReader
class ArrayReader (strings : List[String]) extends Reader { calls repeatForEach on its underlying reader, providing its own
override def repeatForEach (f: String => Unit) = { callback, which calls toList.foreach on each String, allowing each
strings.foreach (f); character to be processed individually. The callback f is invoked
} on each character after converting it to a one-character string.
} Scala supports type inference, meaning that you can omit
many of the type declarations without sacrificing any type
This defines a class ArrayReader that extends the Reader
trait and that requires a list of Strings upon construction. Note
that in Scala you can specify arguments in a class defini-
safety at all. Thus you can write this more compactly this way:
�������������������������
�������������������������������������
class CharReader (r: Reader) extends Reader {
tion (almost like a function definition). This means that the override def repeatForEach (f: String => Unit) = {
arguments must be provided in every use of the constructor
��������������������������������
r.repeatForEach (s => s.toList.foreach (c => f (c.toString)));
and they automatically become available as immutable class }
members. Thus the following code in Scala: }

class ArrayReader (strings : List[String]) { Now let’s try using our new classes: ���������������������������������������
}
object Main {
�������������������������������������������������������� ��������������������������������������������������
is analogous to the following Java code: def main(args: Array[String]) {
���������������������������������������������������������
������������������������������������������������������� ��������������������������������������������������������
public class ArrayReader { val arrayReader: Reader = new ArrayReader(List(“Foo”, “Bar”,
������������������������������������������������������ �������������������������������������������������������
“Baz”));
������������������������������������������������������� ����������������������������������������������������������
private final List<String> strings; val charReader: Reader = new CharReader (arrayReader);
������������������������������������������������������ �������������������������������������������������������������
����������������������������������������������������������� �����������������������������������������������������������
public ArrayReader (List<String> strings) { arrayReader.repeatForEach (println);
��������������������������������������������������������� �����������������������������������������������
this.strings = strings; charReader.repeatForEach (println);
���������������������������������������������������������
} }
���������������������������������������������������������� ��� ���������������������
} }
������������������������� ��� ������������������������������
��� ��������������
Once you have an instance of the Scala ArrayReader class, Here’s the output:
������������������������������������������������������ ��� ��������������
at any point in the future you can call repeatForEach and
��������������������������������������������������������� ��� ��������������
pass it a callback, and it will perform the callback on each of Foo
����������������������������������������������������� ��� �����������������������������
the strings in the original list, in sequence. This is equivalent Bar
����������������������������������������������������������
in usefulness to our original ArrayReader class. For example,
here is how you would print out all of the strings:
Baz
F
������������������������������������������������������ ������������������
��������������������������������������������������������� ��������������������������������������������������������
o
������������������������������������������������������� ���������������������������������������������������������
object Main { o
������������������������������������������������������� �����������������������������������������������������������������
def main(args: Array[String]) { B
��������������������������������������������������������� �����������������������������������
val arrayReader: Reader = new ArrayReader(List(“Foo”, “Bar”, a
“Baz”)); r
arrayReader.repeatForEach (println); B

������������������������
} a
} z

22 May 2008 JDJ.SYS-CON.com ��������������������


FEATURE

This looks surprisingly like our original example, doesn’t it? Not all functional programming idioms can be translated tion of the aggregate function, but it’s on a locally created the meaning of the program. The loss of expressive power
We have a Reader interface with ArrayReader and CharRead- into Java, but some of the simpler ones can, and although unshared object, so it’s acceptable. Programming languages from having to avoid the use of mutable state is compen-
er implementations with roughly the same meanings as in the they may seem unnatural at first, they do bring benefits. It’s like Scala that are designed for functional programming sated for by providing better support for manipulating func-
corresponding Java versions. The only difference is that this always worth asking the question: Can I solve this problem would not even require that, since they support immutable tion objects and combining them in useful ways.
example has no mutable state whatsoever. There is no point without the use of mutable state? collections. You can start using rudimentary functional programming
at which any variable is modified from an old value to a new techniques in Java immediately, but advanced techniques
value. Although state is still shared between the arrayReader A Reconciliation Example Summary require better programming language support than Java
and charReader objects (the charReader contains a reference Say you have two lists of information that have to be The use of mutable state makes programs hard to under- offers. Scala is a useful language for Java programmers to
to the arrayReader), it’s simply not possible for them to inter- reconciled. You want to know which items are in one list stand, especially in conjunction with currently popular pro- explore, as it provides excellent support for functional pro-
act inappropriately. Whenever you call: and not in the other, and vice versa. This kind of problem gramming practices in which objects are created indirectly and gramming while fitting smoothly into the Java developer’s
sometimes crops up in financial applications, and is often state sharing is not obvious from reading the code. Furthermore world.
arrayReader.repeatForEach (...) solved by traversing both lists and building a data structure in multithreaded environments, programs relying on mutable
to store the differences (e.g., a hash table). A more function- state are prone to race conditions, requiring the use of locking Additional Reading
a given input of ... will always produce exactly the same al solution to the problem is to write code that can subtract that can impact performance and make programs even harder • Wikipedia: http://en.wikipedia.org/wiki/Functional_
result. There isn’t any method for resetting the iterator either, the contents of one list from another as shown in Listing 3. to understand and debug. programming.
because there’s no such concept in this design. You can call This example shows a functional approach to reconcil- Functional programming offers an alternative approach • Can Your Programming Language Do This?: http://www.
arrayReader.repeatForEach as many times as you like, and ing lists of information, but also shows the kind of com- to solving computing problems based on transforming joelonsoftware.com/items/2006/08/01.html.
each time it will iterate through the entire list with no possibil- promise that has to be made when doing this style inputs into outputs in a stateless way. Functional programs • Bill Venners, Martin Odersky, and Lex Spoon. First Steps
ity of problems occurring. It can be used in a multithreaded of programming in Java. Unfortunately the built-in Java are referentially transparent, meaning function calls can to Scala. May 9, 2007: http://www.artima.com/scalazine/
environment and race conditions won’t even be possible. Race Collection classes do not efficiently support immutable always be substituted with their results without changing articles/steps.html.
conditions can only occur when you have mutable state. lists, so there is no way in the diff function to build up
It may seem like cheating to convert the program to a the result without either using mutation or creating our
functional one by changing the design to use callbacks, but we own immutable collection classes. We chose a practi-
argue that it’s fair game. Functional programming is all about cal approach: Create a fresh LinkedList object when the Listing 1 Listing 2
programming without side effects (i.e., mutating state), and recursion bottoms out then mutate it repeatedly by calling public interface Reader { public interface StringCallback {
String read(); public void doString (final String s);
that means coming up with new idioms for solving familiar addFirst to build up the result. Although this is not func-
} }
problems. In this case, the original iterator-based solution tional, we are doing it in only one place, and we are chang-
was very typical Java code. To achieve the same thing without ing an object that was created within the diff method, is public class ArrayReader implements Reader { public interface Reader {
side effects we had to pass callbacks around (also known as never shared, and has no permanent state after the initial public void repeatForEach (final StringCallback f);
private String[] sourceArray; }
closures, function objects, or anonymous functions) but this is call returns. So the implementation of diff is “mostly func-
private int currentIndex;
very typical in functional languages, which typically provide a tional,” and the rest of the example is completely func- public class ArrayReader implements Reader {
clean, elegant syntax to support that style of programming. tional. This solution has most of the virtues of functional public ArrayReader(String[] s) {
programming in terms of avoiding the problems of shared sourceArray = s; private final String[] strings;
currentIndex = 0;
Functional Programming in Java mutable state, and doesn’t destroy its input lists the way
} public ArrayReader (final String[] strings) {
Let’s explore how we can introduce functional program- the removeAll method would (as defined in the Java Col- this.strings = strings;
ming concepts into our Java code, in case our managers are lection classes). public String read() { }
not yet ready to allow the use of Scala for commercial software if (sourceArray != null && currentIndex < sourceArray.length) {
return sourceArray[currentIndex++]; public void repeatForEach(final StringCallback f) {
development. Unfortunately Java lacks many advanced A Tree Aggregation Example } for (String s : strings) {
functional programming features and its syntax is not ideal Say you have a tree of any type of object. Let’s keep it return null; f.doString(s);
for this. Higher order functions (i.e., functions that operate on simple and represent the tree as an array of Java objects, } }
other functions) are almost impossible to express, especially each element of which could be a leaf node or another } }
}
if you want to make them strongly typed. (Defining strongly array. You might want to calculate a value based on all
public class CharReader implements Reader {
typed higher order functions requires the use of generics and elements of the tree. A functional approach to this public class CharReader implements Reader {
Java’s “type erasure” implementation of generics throws away problem is to define a TreeWalker that can traverse any private Reader reader;
a significant amount of type information at runtime in the in- tree and accept a user-provided aggregation function. private String currentString; private final Reader r;
terest of efficiency. Martin Odersky giveth and Martin Odersky See Listing 4.
public CharReader (Reader r) { public CharReader (final Reader r) {
taketh away.) Once again we rely on Java’s new anonymous class capa- reader = r; this.r = r;
That being said, the recent support in Java for anonymous bility, but we avoid the use of generics because Java’s “type currentString = null; }
classes still allows us to represent our Scala Reader example erasure” implementation of generics would not allow us to }

reasonably faithfully in Java. use instanceof. public void repeatForEach(final StringCallback f) {


public String read () { r.repeatForEach(new StringCallback() {
The reader example is revisited on Listing 2. In this example we created a tree of numbers called my- while (currentString == null || currentString.length() == 0) {
This Java solution is written in a functional style, although Tree with eight nodes. Then we used the TreeWalker twice, currentString = reader.read(); public void doString(String s) {
it may look awkward to most Java programmers. We had to each time passing it a different aggregation rule; one that if (currentString == null)
return null; for (char c : s.toCharArray()) {
introduce a StringCallback interface to represent the callback, knows how to aggregate a tree by adding, and another that
} f.doString(Character.toString(c));
and used the new anonymous class capability in several knows how to aggregate a tree by multiplying.
}
places. However this solution has all the virtues of the Scala The point is that tree traversal and aggregation have String s = currentString.substring(0, 1);
solution. It is immune to the problems associated with shared been factored into a general-purpose capability, and currentString = currentString.substring(1); } });
return s; }
mutable state, and can be used safely in a multithreaded complex operations can be performed on the tree without
} }
environment without any need for locking or any risk of race any need for mutable state. As in the previous example, }
conditions. there is brief use of mutable state in the implementa-

24 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 25


FEATURE

public class Main { System.out.println (“In first list but not second:”);
for (String s : reconciler.diff(firstList, secondList)) {
public static void main(String[] args) { System.out.println (“ “ + s);
final Reader arrayReader = new ArrayReader(new String[] { “Foo”, }
“Bar”, “Baz” });
final Reader charReader = new CharReader (arrayReader); System.out.println (“In second list but not first:”);
for (String s : reconciler.diff(secondList, firstList)) {
System.out.println (“ “ + s);
arrayReader.repeatForEach(new StringCallback() {
}
}
public void doString(String s) {
System.out.println (s);
}
} });

charReader.repeatForEach(new StringCallback() {

Listing 4
public void doString(String s) {
public interface Aggregator {
System.out.println (s);
public Object initialValue ();
}
public Object combine (Object x, Object y);
}
});
}
public class TreeWalker {

}
Output:
public Object aggregate (Object[] tree, Aggregator a) { �����������������������������������������������
Foo
Bar
Baz
Object o = a.initialValue();
for (Object item : tree) { ���������������������������
if (item instanceof Object[]) {
F
o = a.combine(o, aggregate((Object[])item, a));
o
} else {
o
o = a.combine(o, item);
B ������������������������������������ �������������������������������������������������������������
}
a ������������������������������������ ������������������������������������������������������
}
r
return o; ��������������������������������������� ������������������������������������������������������
B
a
} �������������������������������������� ���������������������������������������������������������
z
} ���������������������������������������� ��������������������������������������������������������������
������������������������������������� ���������������������������������������������������������������
public class Main {
���������� ���������������������������������������� ����������������������������������������������������������
Listing 3 ��������������������
public static void main(String[] args) {
��������������������������������������� �������������������������������������������
public class Reconciler<T> { ����������������������
�����������������
public LinkedList<T> diff (final List<T> l1, final List<T> l2) { Object[] myTree = ��������������������������������������������������������������
new Object [] { 4, ��������������������������������������������������� �������������������������������������������������������������
if (l1 == null) 7, ����������������������������������������������������� �������������������������������������������������������
return null; new Object[] {3, 8},
������������������������������������������������������ ������������������������������������������������������������
new Object[] {2, new Object[] { 5, 9 }},
if (l1.size() == 0) ����������������������������������������������������� ��������������������������������������������������
6 };
return new LinkedList<T>(); ��������������������������������������������������������
TreeWalker treeWalker = new TreeWalker(); ��������������������������������������������������� �����������������������������������������������������������
final T head = l1.get(0);
������������������������������������������������������ �����������������������������������������������������������
final List<T> tail = l1.subList(1, l1.size());
Object sum = treeWalker.aggregate(myTree, new Aggregator() { ������������������������������������������������������� �����������������������������������������������������������
public Object initialValue() { return 0; } ����������������������������������������������������������� ��������������������������������������������������������������
if (l2.contains(head))
public Object combine(Object x, Object y) {
return diff (tail, l2); ������������������������������������������������ �������������������������������������������������������
return ((Integer)x).intValue() + ((Integer)y).intValue();
} });
�������� �����������������������������������������������������������
LinkedList<T> result = diff (tail, l2);
result.addFirst(head); System.out.println (“Sum is “ + sum); ��������������������������������������������������������������
return result; ������������������������������������������������������� ������������������������������������������������������������
} Object product = treeWalker.aggregate(myTree, new Aggregator() { ����������������������������������������������������������� ������������������������������������������������������������
public Object initialValue() { return 1; } �����������������������������������������������������
public static void main(String[] args) { public Object combine(Object x, Object y) {
�����������������������������������������������������������
return ((Integer)x).intValue() * ((Integer)y).intValue();
final List<String> firstList = Arrays.asList(new String[] } });
�����������������������������������������������������������
{“Adam”, “Bob”, “Charlie”}); System.out.println (“Product is “ + product); ������������������������������������������������������������ ��������������������
final List<String> secondList = Arrays.asList(new String[] } �����������������������������������������
{“Bob”, “David”});

}
final Reconciler<String> reconciler = new Reconciler<String>();

�����������������������
26 May 2008 JDJ.SYS-CON.com ���������������������������������
������������������������������������������� ����������������������������� ��
FEATURE the AdminClient on a regular basis. It works great and is
reliable – that’s a big part of why Axis has been such a huge
success. Still, Web Services have evolved and you need
more than Axis to take advantage of these advances. For a
simple service like the one in Listing 1, it might not be too
hard to change the code to get it to work on a newer Web Figure 4 Axis service deployed
Service stack. It would still take some work. That work only
goes up for more complicated services. This is where WSAS
comes in. Let’s take a look at just how easy the upgrade is
with WSAS.

Redeploying to WSAS: Using WSDD


You can upgrade your Axis service with WSAS very easily. Figure 5 Link to Bid WSDL
There’s no code to change. There’s no code to generate or

by Michael Galpin
Migrating with WSAS regenerate. There’s no configuration file to alter or add.
All you need is a WSDD and JAR file with the classes for
the service. That’s it. If you’ve been using Axis, there’s a
good chance you already have both of these laying around

I
already.
f you’ve been working with Web Services for a long submitting purchase orders. Let’s take a look at its WSDD For the Axis bid-buy sample we’re using, all we have to
time, chances are you’ve worked with Apache Axis file shown in Listing 1. do is put the class files in a JAR. To do this we move them
and that you have an Axis Web Service somewhere This is a fairly typical WSDD. It describes two services. into a directory structure reflecting the package structure
in your code base. You probably also know about Each service has several operations that can be called. It (samples.bidbuy) and then run Java’s jar command as
the many improvements in Axis2, especially around also describes mappings between the parameter types of shown in Listing 2 (Listings 2 and 3 can be downloaded
support for the more modern WS-* standards. So maybe the service to Java classes. To deploy this you’d use Axis’s from the online version of this article at http://jdj.sys-con.
you’ve been planning on migrating these old Axis services, deployment tool, the AdminClient. com).
but it can be hard to justify spending a lot of time on If you’ve been using Axis over the years, all of this is old Now we’re ready to get started with WSAS. Load up the
something that’s working just fine. However, there’s a great news. You’ve probably seen dozens of WSDDs and used Management Console. Go to the Services tab and you
new migration path available to you: WSO2’s Web Services should see something similar to Figure 1.
Application Server (WSAS.) With WSAS, you can take your Notice the Upload Axis1 Service (.wsdd) Option. That’s Figure 6 Bid WSDL
existing Axis Web Service, redeploy it to WSAS, and then exactly what we want to do. Go ahead and choose that and
with just a few clicks enable things like WS-Security and you’ll see a screen similar to Figure 2.
WS-Reliable Messaging. There’s no need to rewrite or This is a straightforward interface. Simply use the
regenerate any code. Browse buttons to locate the deployment descriptor for
Does this sound too good to be true? It’s not, just your Web Service and the jar file you created for your
read on. service. Then click upload. You should get a confirmation
Figure 1 WSAS Management Console: Services Tab screen similar to Figure 3.
Prerequisites The upload is asynchronous, but shortly afterwards
In this article, you’ll work with WSO2 WSAS. You’ll your list of Service Groups should show a “deploy.wsdd”
definitely want to download the latest version of WSAS. (that was the name of the deployment descriptor from the
You can run it with any Java Web container, such as bidbuy sample) similar to Figure 4.
Tomcat. Or you can run it in standalone mode. This That’s all you have to do! Your crusty old Axis Web
article assumes experience with Axis, and in particular Service is now running on the super-modern WSAS Web
with deploying an Axis Web Service. It references a sample Service stack. Your Web Service is going to benefit greatly
from Axis 1.4. Obviously a familiarity with Web Services in even if this is where you stop. Since it’s running on WSAS
general, and with some of the modern WS-* standards is (and thus Axis2) you’ll get great performance benefits.
very useful. WSAS uses a powerful combination of a StAX parser and
Figure 2 WSAS Management Console: Services Tab the Axis Object Model (AXIOM) for parsing SOAP. This is
Example of an Existing Axis Web Service much more efficient in terms of both speed and memory
Let’s take a typical starting point for a lot of people. You usage than Axis1. The Axis2 architecture also lets you plug
have a service you developed and used Axis to expose as a in whatever data binding you want, such as JAXB. It also
Web Service. There’s a good chance that the service might enables Message Transmission Optimization (MTOM)
not have been originally intended to be a Web Service. May- for your service, by default. This allows for much more
be it was just an internal service used by one application. efficient transport of binary data if your service accepts or Figure 7 Manage the bid service
Michael Galpin is an archi- You then realized it would be valuable to other applications receives binary data. Of course you probably don’t want to
tect at eBay in San Jose, you were developing and used Axis to do this. There are a stop here, as now there’s a whole new world of options that file that WSAS has created to describe your service. It should
CA. He’s been developing couple of different ways to do this with Axis, but the most you’ve just enabled by migrating to WSAS. Let’s take a look look similar to Figure 6.
software since 1998, and powerful and flexible is to use Axis’s Web Service Deploy- at those now. One thing to notice here is the “invokeAxis1Service” sec-
holds a degree in math- ment Descriptor (WSDD.) tion. The bid-buy sample we picked was an RPC-encoded
ematics from the California Let’s take a look at a sample WSDD. Axis ships several Examining the Service on WSAS service, a style of SOAP that’s been deprecated because of its
Institute of Technology. great samples. We’ll use the bid-buy sample. It mimics an In our list of services, click on the WSDL 2.0 link for the Bid brittleness. So what has WSAS done here?
e-commerce system. It exposes a Web Service for doing Service, as shown in Figure 5. First, just because RPC-encoding is far from a best prac-
mike.sr@gmail.com typical e-commerce tasks like requesting a price quote and Figure 3 Upload of WSDD confirmed This should bring a graphical representation of the WSDL tice doesn’t mean that your service isn’t using it. You could

28 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 29


FEATURE

Second, WSAS has created more modern bindings for how WSAS made sure to maintain backwards compatibility
your service. This is for either existing clients that can with the original service, even though the original service
be re-coded or new clients who want to take advantage used the deprecated RPC-encoding format. Once we brought
of new Web Service standards. Again, you didn’t have our service into WSAS, we could easily enable WS-Security
to write any code, yet now there’s a SOAP 1.2 binding to and WS-Reliable Messaging. Finally, WSAS made it especially
your service. This is important, because now we can start easy to pick a powerful Security Configuration, automatically
enabling other SOAP-based technologies, i.e., various WS-* managing the Policy for us.
technologies.
Resources
Managing the Service on WSAS • Take a look at the WS-RM specification from the devel-
Go back to your list of service, but this time click on the operWorks library (http://www.ibm.com/developerworks/
bid link under services. This should bring up the interface library/specification/ws-rm/).
shown in Figure 7. • Learn about the benefits of WS-Security in the developer-
There’s a lot you can do here, but for now let’s click on Works article Implementing WS-Security (http://www.ibm.
the Manage Module Engagements link. That should bring com/developerworks/webservices/library/ws-security.
up the interface shown in Figure 8. html).
The various modules in the Module combo box repre- • WSAS enables WS-Addressing automatically. Learn how Figure 11 Security configuration of bid service
sent Axis2 modules that implement various WS-*. Let’s say important this is in the developerWorks article The hidden
Figure 8 Manage modules for bid service we’re interested in WS-Security. To enable this, we simply impact of WS-Addressing on SOAP (http://www.ibm.com/
pick rampart from the list, as shown in Figure 9. developerworks/webservices/library/ws-address.html).
Click the Engage button, and just like that WSAS will • Read about the Axis2 module system in the developer-
activate its WS-Security module for your service, as shown Works article Web Services and Axis2 architecture (http://
in Figure 10. www.ibm.com/developerworks/webservices/library/ws-
Similarly, you can pick sandesha from the Module list apacheaxis2/).
and WSAS will enable WS-Reliable Messaging for your • Explore the benefits of using a StAX processor in the devel-
service. Let’s take a look at some of the security options we operWorks article StAX’ing up XML, Part 1: An introduction
have available to us. to Streaming API for XML (http://www.ibm.com/devel-
operworks/opensource/library/x-stax1.html).
Security Configuration • Keystores are integral part to your security. Learn all about
Let’s go back to our Service listing (Figure 7) and this them in the developerWorks article Unshackling key man-
time click the Security Configuration link. This will bring agement in Java security (http://www.ibm.com/developer-
up the interface shown in Figure 11. works/ibm/library/it-keyjava.html).
What is this list you see here? This list represents 11 dif- • You’re going to want to download WSO2 WSAS (http://
ferent pre-set security configurations included with WSAS. wso2.com/products/wsas/).
These 11 configurations represent the most common sce- • Read about the latest features in WSO2 WSAS 2.0 (http:// Figure 12 Enabling Triple DES/RSA15 - DK
narios for securing a Web Service. Whatever your security blog.ruchith.org/2007/07/wso2-wsas-20-released.html).
Figure 9 Enabling WS-Security requirements are, it’s probably covered by one of them. • Learn from and interact with the WSO2 community on
Enabling any of them is trivial, just pick its radio button the WSAS Wiki (http://wso2.org/wiki/display/wsasjava/
and continue. For example, let’s say we pick the “Sign and Home).
encrypt - TripleDES/RSA15 – DK” option then we’ll bring • Learn about exposing your services as Web Services easily
up the interface shown in Figure 12. with Axis2 (http://ws.apache.org/axis2/).
Notice that WSAS already has both a trusted certificate • Learn how Axis2 can enable your SOA designs in the devel- Figure 13 Accessing the policy for the bid service
store and a keystore location provided to support encryp-
tion. The Management Console has a Keystore tab (on the
Listing 1: WSDD for Axis bid-buy sample samples.bidbuy.Address”/>
left) that you can use to manage certificates and provid-
<deployment xmlns=”http://xml.apache.org/axis/wsdd/” xmlns: <beanMapping qname=”bid:LineItem” languageSpecificType=”java:
ers. Once you apply the security configuration, you can
java=”http://xml.apache.org/axis/wsdd/providers/java” xmlns: samples.bidbuy.LineItem”/>
go back to the list of services and click on the Policy, as
bid=”http://www.soapinterop.org/Bid” xmlns:reg=”http://www.soapin- <!-- * * * * * * * * * * * * * * * * * * * * * * * * * * *
shown in Figure 13.
terop.org/Registry”> * -->
This will bring up the Policy, shown in Listing 3. The
<service name=”Bid” provider=”java:RPC”> <service name=”BidRegistry” provider=”java:RPC”>
Policy is an extensible way to configure any/all of the WS-*
Figure 10 WS-Security enabled technologies you have enabled for your service. Where did <namespace>http://www.soapinterop.org/Bid</namespace> <parameter name=”className” value=”samples.bidbuy.

this Policy come from? It was generated by WSAS for you <parameter name=”className” value=”samples.bidbuy. RegistryService”/>
very well have partners, both internal and external, that are when you selected the Security Configuration. You can BidService”/> <parameter name=”allowedMethods” value=”Register
using this format when invoking your service. No migration still manually edit this file either to tweak security or to <parameter name=”allowedMethods” value=”RequestForQuote Unregister Lookup LookupAsString”/>
path can simply leave those partners high and dry by telling configure your WS-Reliable Messaging policy. SimpleBuy Buy Ping”/> </service>
them to re-code their client code. So WSAS has deployed a </service>
<beanMapping qname=”reg:Service” languageSpecificType=”java:
fully backwards-compatible version of your service. Any- Summary <beanMapping qname=”bid:PurchaseOrder” languageSpecificType=”j
samples.bidbuy.Service”/>
body using RPC-encoding to invoke your Web Service can In this article we’ve started with an Axis service, and very ava:samples.bidbuy.PurchaseOrder”/>
</deployment>
continue to do so. Not only do you not have to change any easily redeployed it to WSAS. All we needed was its WSDD <beanMapping qname=”bid:Address” languageSpecificType=”java:
code to upgrade to WSAS, your clients don’t either. deployment descriptor and a JAR of all its classes. We saw

30 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 31


JSR WATCH
Advertiser Index
Java and Advertiser URL Phone Page

Free Software in Brazil DataServices World at SOA World dataservicesworld.sys-con.com 888-303-5282 27

Bridging the digital divide Patrick Curran


Fiorano www.fiorano.com/downloads 7

A
couple of recent Brazil-related defend national sovereignty (avoid- care services in Sao Paulo – the largest
news events suggested the ing domination by non-Brazilian cor- city in Brazil, and the fourth largest in InterSystems www.intersystems.com/cache27p 617-621-0600 Cover IV
theme for this column: Java porations), and to conserve national the world with over 20 million people.
in Brazil. First, the annual resources by eliminating software Today the application is in production
International Free Software Forum licensing fees. Because Java is based in Sao Paulo and 20 other cities and is
(FISL) (http://fisl.softwarelivre. on open standards and is freely avail- being implemented nationally. Java Developer’s Journal www.jdj.sys-con.com 888-303-5282 17
org/9.0/www/) was recently held in able, it has been – and is increasingly The system has been open sourced by
Porto Alegre, Brazil. FISL is one of the – adopted by Brazilian government the Brazilian government for use by
world’s most important free software agencies for the development of any public health organization, and
conferences, and more than 7,400 software that delivers services to its its implementation is being con-
Kaazing www.kaazing.com 650-943-2436 4
people attended this year, including citizens, from taxation to health care. sidered in other Portuguese-speak-
many from Sun’s Java organization. For example, in Brazil, health care ing countries, such as Angola and
Second, Sun Microsystems and the is free to all citizens. This posed a Mozambique.
Brazilian organization responsible for variety of organizational and man- A couple of other recent an-
digital television (DTV) conversion agement problems, from tracking nouncements illustrate the strength NetBeans/Sun Microsystems www.netbeans.org Cover II
announced (http://java.sys-con.com/ patients’ records to scheduling ap- of the free software movement in
read/514870.htm) that they would pointments. To solve these problems, Brazil. At this year’s FISL, the Brazil-
join forces to develop an open source a comprehensive health-care auto- ian Ministry of Education announced
content platform based on Java tech- mation system (http://www.infoq. plans (http://news.northxsouth. Northwoods Software Corp. www.nwoods.com 800-434-9820 13
nology for use in the country-wide com/articles/Brasilian-Healthcare- com/2008/04/24/brazilian-govern-
conversion of television applications System) was developed entirely in ment-to-deploy-53k-open-source-
and services. Java. The system is designed to handle labs-serving-52-million-students/)
all the requirements of a public health to deploy 53,000 computer labs
SOA World Conference & Expo 2008 www.soaworld2008.com 888-303-5282 23
Software Livre care information system including throughout the country, giving 52
FISL is a major event in the free scheduling, inventory management, million students access to computer
software world, not only because billing, disease tracking, reporting resources. The computers in the labs
Brazil is a significant emerging and auditing, regulatory compli- will be run as a Linux distribution
economy but also because the Brazil- ance, and security access control. The called Linux Educacional, which is Software FX www.softwarefx.com 561-999-8888 Cover III
ian government, under the presi- system, claimed to be the largest Java based on Debian and the KDE desk-
dency of Luiz Inácio Lula da Silva Enterprise application ever built, was top. Also this month, the Brazilian
(Lula), has championed the cause of first deployed to automate all health Election Supreme Court announced
free software. (SouJava (http://www. SYS-CON e-Newsletters www.sys-con.com 888-303-5282 33
soujava.org.br/display/v/Inicial),
the largest Java Users Group in Brazil
and possibly in the world – they have
more than 18,000 members – is a ma- SYS-CON Media books.sys-con.com 888-303-5282 9
jor participant in FISL. SouJava was
the first Java User’s Group to join the
JCP back in 2005, and its president, General Conditions: The Publisher reserves the right to refuse any advertising not meeting the standards that are
set to protect the high editorial quality of Java Developer’s Journal. All advertising is subject to approval by the
Bruno Souza – now a Sun employee Publisher. The Publisher assumes no liability for any costs or damages incurred if for any reason the Publisher
fails to publish an advertisement. In no event shall the Publisher be liable for any costs or damages in excess
– is a tireless champion of Java and of the cost of the advertisement as a result of a mistake in the advertisement or for any other reason. The
open source.) Advertiser is fully responsible for all financial liability and terms of the contract executed by the agents or agen-
cies who are acting on behalf of the Advertiser. Conditions set in this document (except the rates) are subject
Patrick Curran is Chair of The Brazilians believe that “soft- to change by the Publisher without notice. No conditions other than those set forth in this “General Conditions
Document” shall be binding upon the Publisher. Advertisers (and their agencies) are fully responsible for the
the JCP and Director of ware livre” can help to bridge the content of their advertisements printed in Java Developer’s Journal. Advertisements are to be printed at the
the JCP Program at Sun “digital divide,” (http://en.wikipedia. discretion of the Publisher. This discretion includes the positioning of the advertisement, except for “preferred
positions” described in the rate table. Cancellations and changes to advertisements must be made in writing
Microsystems, Inc. org/wiki/Digital_divide) to ensure before the closing date. “Publisher” in this “General Conditions Document” refers to SYS-CON Publications, Inc.
that all citizens have free access
This index is provided as an additional service to our readers. The publisher does not assume any liability for errors or omissions.
patrick@jcp.org to public services, to preserve and

32 May 2008 JDJ.SYS-CON.com JDJ.SYS-CON.com May 2008 33


JSR WATCH

“ It’s fitting that Java is now the platform of choice for


implementing interactive TV infrastructure and applications,
since the language – back when it was called Oak –
was originally designed for just this purpose”

that the 2008 elections in Brazil no ballot at this stage – the draft is SK Telecom) demonstrates that
will switch from proprietary OS- simply intended to provide the JCP it’s not always so simple. This JSR
based electronic voting machines membership and the public with proposed to define APIs to enable
to systems based on GNU/Linux something that is detailed enough MIDlets to be displayed and acti-
(http://www.techforce.com.br/ to generate useful feedback. I vated on the idle screen of em-
index.php/news/linux_blog/tse_ encourage you to download the bedded devices. The JSR failed its
migrates_to_linux). drafts from the JCP website (follow approval ballot in April 2008. Those
the links below) and to send your voting “no” argued that idle screen
Digital TV in Brazil feedback to the Spec Leads. integration should be handled by
Brazil, like the United States, JSR 303: Bean Validation (http:// JSR 271 MIDP 3, and that a separate
is facing a transition to digital TV jcp.org/en/jsr/detail?id=303), led by JSR defining additional APIs is un-
transmission in the near future. By RedHat, defines a metadata model necessary.
the year 2016, analog transmissions (based on annotations and XML The ballot for JSR 325: IMS Com-
will cease, and all TV broadcast- descriptors) and API for JavaBean munication Enablers (ICE) (http://
ing will be digital. Brazil intends validation, enabling simple and jcp.org/en/jsr/detail?id=325) has
to tackle this transition in a more reusable validation mechanisms at not yet closed (as I write this), but
ambitious manner than the US each tier of the application. since this JSR extends rather than
– defining a digital TV standard JSR 235: Service Data Ob- overlaps with another it’s more
that will not only serve TVs but jects (http://jcp.org/en/jsr/ likely to be approved. The JSR
also mobile devices. In line with detail?id=235), led by IBM and BEA, builds on JSR 281, defining a high-
its policy of providing equal access standardizes Data Objects in terms level framework and API that will
to all citizens, they have chosen of change history, compound data provide Java ME-based devices with
an open source and royalty-free objects, dynamic and generated a simple way to access IP Multime-
approach (http://biz.yahoo.com/ API, metadata, support for XML and dia Subsystem (IMS) Communica-
bw/080304/20080304005617.html?. Web services, neutral representa- tion Enablers for services such
v=1) that defines a Java-based plat- tion of business data, import/ex- as Presence, Instant Messaging,
form for the delivery of interactive port from common formats, valida- Multimedia Telephony, and Push to
services for digital TV devices. The tion and constraints, relationship talk Over Cellular (PoC).
specification builds on the same integrity, and navigation. Finally this month, JSR 113:
Java platform that currently serves JSR 249: Mobile Service Archi- Java Speech API 2.0 (http://jcp.
as the basis for other widely de- tecture 2 (http://jcp.org/en/jsr/ org/en/jsr/detail?id=113), led by
ployed digital television standards, detail?id=249), led by Vodafone and Conversational Computing Corpo-
including OpenCable/tru2way, Nokia, updates the Mobile Service ration, is up for its Final Approval
Multimedia Home Platform, GEM- Architecture (MSA) specifica- Ballot. Version 1 of the Java Speech
IPTV, and Blu-ray Disc/BDJ. tion ( JSR 248) to incorporate new API, which was developed by
It’s fitting that Java is now the component JSRs and to define ad- Sun before the JCP was created,
platform of choice for implement- ditional clarifications and require- defines APIs that allow developers
ing interactive TV infrastructure ments for implementing the JSRs in to incorporate speech technology
and applications, since the lan- mobile devices. into user interfaces for their Java
guage – back when it was called Oak programming language applets
– was originally designed for just Two JSRs Submitted for and applications. Version 2.0 ex-
this purpose. Initial Approval Ballot tends and builds on version 1,
It may seem as if JSR approval and tracks the emerging W3C
This Month’s Active JSRs ballots are a foregone conclusion Speech Interface Framework
This month three JSRs reached and that rejection is unlikely, but (http://www.w3.org/TR/voice-
the Early Draft Review (EDR) the example of JSR 324: On Screen intro/) whenever possible.
stage. The Early Draft is the Expert MIDlet API for Java ME (http://jcp. That’s all for now. On to
Group’s first deliverable. There’s org/en/jsr/detail?id=324) (led by JavaOne…

34 May 2008 JDJ.SYS-CON.com


Embed the fastest engine.

For software developers seeking competitive advantages, InterSystems Caché® makes


applications more valuable by increasing their speed and scalability, while decreasing hard-
ware and administration requirements. This is the fastest database engine you can put in
your applications, and it's the only database that gives you the combined benefits of
object and relational technologies. Thanks to its innovative architecture, Caché spares Java
and .NET programmers a lot of tedious work by eliminating the need for object-
relational mapping. Caché is available for Unix, Linux, Windows, Mac
OS X, and OpenVMS – and it supports MultiValue development. Caché
is deployed on more than 100,000 systems worldwide, ranging from two
to over 50,000 users. Embed our innovations, enrich your applications.

Make
Applications
More
Valuable
Come see product demonstrations at booth #410 at JavaOne, May 6th-9th, San Francisco

Download a free, fully functional, no-time-limit copy of Caché, or request it on CD, at InterSystems.com/Cache27P
© 2008 InterSystems Corporation. All rights reserved. InterSystems Caché is a registered trademark of InterSystems Corporation.3-8 EmbedCache27JDJ

Anda mungkin juga menyukai