Sie sind auf Seite 1von 58

//table of contents /

02 Rich Client
From the Editor JavaFX and Swing

JAVA IN ACTION Migrate Swing interfaces to
15 JavaFX.
Driven by Java
Austrian smartcard system 38
connects patients, providers. Rich Client
Using Transitions
JAVA TECH for Animation in

19 JavaFX 2.0
New to Java Animate nodes in your scene.
Starting Your First 41
Computer Game Enterprise Java
Use Greenfoot to create your Stress Testing Java EE 6
first interactive program. Applications
22 Adam Bien on bugs, bottle-

New to Java necks, and memory leaks.
Introduction to RESTful 47
Web Services (Part 2) Mobile and Embedded
Max Bonbhel on the JSON Getting Started with
response format. GameCanvas
24 Vikram Goyal on the Mobile
Java Architect Sensor API.
Agile ALM for Java
Polyglot Programmer
3 10 32 53
Michael Hüttermann on better- Java Nation Java in Action Rich Client Polyglot
Polyglot Programming

quality software. JAVAONE GREEN LIGHT Programmer
on the JVM
27 How and why to choose a 2011 BRINGS Startup dooApp TOWARD A

Java Architect non-Java language. to support green
Understanding the MOMENTUM Oracle’s Alex
56 A report from the construction. Buckley on the
Hudson Plug-In Fix This world’s biggest JVM Language blog
Development Framework Arun Gupta challenges Java community JavaFX 2.0 reinvigorates client-side Summit 2011.
Extend Hudson with plug-ins. your coding skills. gathering. Plus Java development. Oracle’s Nandini
communty news Ramani talks with Java Magazine
and events. about the key features of the
new release.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//from the editor /



he previous (and Premiere) issue of Java Magazine published synchronously with the on-time general
availability of Java SE 7. Our timing for this issue is almost as good, as production wrapped up just a couple of USER GROUP
weeks after the conclusion of JavaOne 2011, in San Francisco, California.
If you were unable to attend, you’ve probably heard that JavaOne was exciting for a number of reasons, NEEDS YOU
many of which you will read about in this issue. But if I had to choose the most notable theme, it would be the
re-energized, reinvigorated, and resurgent JavaFX platform. Find your JUG here

JavaFX 2.0, now generally available for Windows (and in Developer Preview mode for Mac OS X), allows you
to write apps in plain old Java using standard development tools—unlike 1.0, which required knowledge of a
custom scripting language. Furthermore, at JavaOne, Oracle announced its intention to fully open source the
platform via the OpenJDK Project, and pursue its standardization via the Java Community Process. (Read all
about these developments, and more, in our JavaFX coverage in this issue.) Looks like Java developers working
client-side will finally get their next-generation successor to Swing.
There’s more to the story though. At JavaOne, we also got the updated roadmaps
for Java SE 8, Java EE 7, and Java ME. We got word of the JDK 7 for Mac OS X //send us your feedback /

Developer Preview. And we were reminded that Java developers “code hard in their We’ll review all
suggestions for future
cubicles.” Yes, it was quite a show.
So what’s next? Well, we need to get you ready for Java EE 7 (scheduled for release Depending on volume,
in 2012), which will provide a genuinely standard runtime for cloud-based apps. some messages may
Look for that in the January/February 2012 issue. not get a direct reply. blog

Justin Kestelyn, Editor in Chief BIO


ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation / JAVAONE NEWS /

Cameron Purdy now expanded. and openness was also
Java 8 will be a com- apparent at JavaOne

plete consolidation of the 2011. The JCP has been
Java platform, includ- re-energized by the JavaOne Technical Keynote
ing Oracle JRockit fea- presence of Java user
ture integration into the groups (JUGs) on the JCP

OpenJDK, Project Jigsaw Executive Committee and
(modularity), Project the approval of
Adam Messinger
Lambda (closures), JavaFX (JSR-348). The JUG-led
3.0, enhanced JavaScript initiative “Adopt-a-JSR”

Hasan Rizvi

interop, and more, all fully seeks to expand commu- Java Strategy Keynote
supported on Windows, nity involvement in deter-
Mac OS X, Linux, Oracle mining the future of the
Solaris, and embedded Java platform by promot-
platforms, with added ing active JUG participa-

Brings Focus,
support of new devices as tion in individual JSRs.
well. will Twitter Joins the Party
Java/JDK 8 Roadmap
provide support for all the

In an announcement

JavaOne provided an op- Java Community Keynote
new features. that surprised everyone,
portunity to hear about
Oracle’s long-term vision Java EE, Java ME Twitter’s Rob Benson—a
for investment and in- The focus for Java EE prominent Java stake-
The theme of JavaOne 2011, held October 2–6, was
novation in Java. At the 7 development will be holder with a vested inter-
“Moving Java Forward”—and by the end of the confer-
Java strategy keynote, multitenancy, capacity on est in a highly performant
ence, most attendees were feeling a new momentum
Oracle’s Hasan Rizvi, demand, and autoprovi- Java platform—said that
reminiscent of Java’s initial rush into prominence more
Adam Messinger, and sioning, looking ahead to his company would join
than a decade ago. What Oracle’s stewardship of the Java
Cameron Purdy laid out a a future standardization not only the OpenJDK
platform means was brought into clarity at this year’s
clear roadmap to Java 8. of the cloud platform. The Project but the JCP as well.
JavaOne. The new direction is coherent and focused, es- Java ME focus is conver- Read Twitter’s formal
chewing disjointed efforts that are tangential to the prime Responding to feedback
from the community, the gence of Java ME, Java SE, announcement here.
objectives, ultimately leading to a cohesive Java platform and Java SE for Embedded
Oracle Java team decided Forward, Ho!
where all the pieces fit together synchronously. Big topics Devices, leading to a co-
that Java will return to a In conclusion, JavaOne
at the show included Java/JDK 8; Java Platform, Enterprise herent micro/embedded
two-year major release 2011 was a momentous
Edition (Java EE), Java Platform, Standard Edition (Java Java platform.
cycle (which worked well event. On all fronts, Java is blog
SE), and Java Platform, Micro Edition (Java ME); and the
in the early 2000s). The JCP, Java User Groups, indeed moving forward.
Java Community Process (JCP), Java user groups, and of
release of Java 8 will be Community
course, the Java community. Here are some highlights:
delayed until the summer A new commitment to
PHOTOGRAPHY BY HARTMANN STUDIOS of 2013, but its scope is community involvement
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation / JAVAONE NEWS /

Richard Bair

Nandini Ramani and Adam Messinger


The Duchess network connects women
Java developers from around the world.
At JavaOne 2011, Regina ten Bruggencate,
current president, and Clara Ko, cofounder,
discussed the role of women in IT in a
birds-of-a-feather session.

Women engineers in the Duchess net-
work connect at local Java user group (JUG)
meetings and globally at conferences and
online. Started in the Netherlands, the

JavaFX 2.0 Is Here! At the Java strategy keynote on Tuesday, Oracle Vice President
network saw membership double in the
last year, thanks to very active Duchesses
and supportive JUG leaders and mem-
The big news at JavaOne 2011 was the release of JavaFX of Development Adam Messinger announced that Oracle is sub-

bers. The network now has 400 members
2.0, an advanced Java UI platform for enterprise busi- mitting a proposal to open source the JavaFX platform as a new
in 57 countries.
ness applications—and the next step in the evolution project within the OpenJDK community. Oracle will be working
Duchess promotes “changing the
of Java as a premier rich-client platform. with the JCP to propose JavaFX as an official standard part of the
image of the nerdy guy as being the typi-
At the JavaOne technical keynote on Monday, October 4, Java platform, Messinger said. Oracle intends to initially con-
cal IT professional,” ten Bruggencate says.
Richard Bair, chief architect, client Java platform, at Oracle, tribute the JavaFX UI controls and related libraries; other JavaFX
“The industry is moving toward having
detailed the general availability of JavaFX 2.0 for Windows components are planned to follow in multiple phases.
developers that are willing to and good at
(32-bit XP, 32- and 64-bit Windows Vista, and Windows 7). He Nandini Ramani, vice president of development, Java client
collaborating to make better software,”
also announced NetBeans 7.1 Beta (featuring full JavaFX 2.0 group, at Oracle, generated a lot of buzz at that same keynote
echoes Ko. Join them online and meet
support); the JavaFX 2.0 developer preview for Mac OS X; and with a demo of JavaFX 2.0 running on an Apple iPad 2.0, a
with them at Devoxx.
JavaFX Scene Builder early access. Samsung Galaxy Tab 10.1 running Android 3.1, and an Acer
Key features in JavaFX 2.0 include 100 percent Java APIs, Windows 7 tablet. “We want to hear from the community,”
the new FXML UI markup language, and full Swing integra- Ramani said. “If this is something you want to see, we’re hap-
tion. JavaFX 2.0 provides a Web component based on WebKit, py to make it a priority.” (Read more in the Nandini Ramani
which allows developers to seamlessly mix and match na- interview, “Shock the Senses,” on page 32.)
tive Java capabilities and the dynamic capabilities of Web Looking to the future, full Mac OS X support will coin-
technologies. cide with the Java 7 for Mac release, which will be followed
by support for additional platforms (Linux, Solaris, and so
Duchess President Regina
on). You can listen to Nicolas Lorain’s JavaOne 2011 session ten Bruggencate
“Introduction to JavaFX 2.0” and other JavaFX sessions at
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation / JAVAONE NEWS /

Mike DeNicola John Rose
JAVA Java 8 Lambda Expressions Syntax Decided by JSR-335 Expert Group

COMMUNITY In early September, the Expert Group for JSR-335 (“Lambda Expressions for the Java
PROCESS Programming Language”) made an important decision regarding syntax. Java Lambda expres-
sions will consist of
WINNERS [parameters], [a single arrow ->], and [an expression or statement(s)].

ANNOUNCED Here are some examples:

The winners of the Ninth Annual Java Community Process (JCP) Awards
x -> x + 1
were announced at a JCP ceremony that took place at JavaOne. There
(x, y) -> x + y
are three award categories: JCP Member/Participant of the Year, Most
(x, y) -> { System.out.printf("%d + %d = %d%n", x, y, x+y); }
Innovative JSR, and Outstanding Spec Lead.
Mike DeNicola of Fujitsu won the JCP Member of the Year Award,
The syntax is similar to the lambdas in C# and Scala, with the exception that those languages
for his contributions as chair of the JSR-348 working group.
use => as their arrow. The Java Lambda Expert Group decided that a single arrow -> will provide
DeNicola’s efforts on the JCP reform plans increased the pace of prog-
greater clarity, for example, in Java expressions that also include == and <= operators.

ress on this critical JSR.
Reviewing the Java Lambda syntax decision, Specification Lead Brian Goetz commented:
JSR-292, “Supporting Dynamically Typed Languages on the Java
“Despite extensive searching, there was no clear winner among the alternatives (each form
Platform,” won the Most Innovative JSR Award. The awards committee
had some good aspects and some really not very good aspects, and there was no form that
noted, “As the first JSR specifically designed to support languages other
was clearly better than the others). So, we felt that it was better to choose something that has
than Java, JSR-292 will ensure the long-term success of the Java VM.”
already been shown to work well in the two languages that are most like Java—C# and Scala—
The Outstanding Spec Lead Award went to JSR-292’s John Rose,
rather than to invent something new.”
consulting engineer at Oracle, for his efforts in forging consensus among
For background on closures in Java, see Mark Reinhold’s blog post “Closures for Java.”
the diverse participants in JSR-292, including the Expert Group and the
Soon you'll be able to experiment with Lambda expressions by downloading JDK 8. Visit the
wider Java Virtual Machine language community. Following the awards,
OpenJDK’s Project Lambda site for more information.
Rose expressed being deeply touched by the recognition, and thanked
his colleagues. “Together we introduced fundamentally new instructions
and datatypes into the Java Virtual Machine, an undertaking that was
both ambitious and complex,” he wrote. “Carrying out this work required LIVING THE JAVA LIFE
the dedicated efforts of the JSR-292 Expert Group members, our fellow
Do you code hard in your
engineers, corporate sponsors, and the Da Vinci Machine community.”
cubicle? This original rap
There could only be three winners, but all of this year’s nominees blog
music video, made for
deserve recognition for their significant contributions to the JCP.
JavaOne 2011, celebrates the
“Java Life.” Watch and see if
you’re living the Java life.

ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation / JAVAONE NEWS /

JavaFX Interfaces with the Xbox Kinect

Oracle Public What can you do with an Xbox Kinect and JavaFX 2.0?
Attendees at Oracle Java Evangelist Simon Ritter’s JavaOne
Cloud Provides session “Interfacing with the Interface: JavaFX 2.0,

Java Enterprise Wiimote, Kinect, and More” experienced a hint of what’s

possible when Developer Experience Architect for Java

Jasper Potts
Client Jasper Potts took to the stage for a session-ending
demo. The Kinect has an array of 3-D visualization, audio, and motion sensors
and Scalability

(useful for playing Xbox games). But, it also includes a C++ SDK that provides
programmers with access to data from the sensors.
“Write once, run anywhere” doesn’t have to exclude the cloud. Oracle’s new Java- Ritter and Potts used the OpenNI framework to wrap the Kinect API so it
centric infrastructure service, Oracle Public Cloud, “is based on industry standards could be accessed by JavaFX using Java Native Interface. It took some work,
and supports full interoperability with other clouds and your data center.” A look and some tweaks, but ultimately they were able to access 3-D depth data
at the specs reveals what this means. The foundation of Oracle’s cloud is clus- from the Kinect sensors using this type of JavaFX code:
tered Oracle WebLogic Server 11g application servers running on the Java Platform,
Enterprise Edition 5 (Java EE 5) stack. The toolkit suite includes Servlet 2.5, JSP 2.1, context =

JSF 2.0, Enterprise JavaBeans 2.1 and 3.0, JPA 2.0, JAX-WS 2.1, and JAX-RS 1.1 (Jersey Context.createFromXmlFile(config.getKinectXMLConfig(),
1.9). The architecture is single tenant, with triple mirroring and offsite tape backup, scriptNode);
for greater assurance of data security and integrity. If you’re running an enterprise depthGenerator = DepthGenerator.create(context);
Java applications suite and you need higher availability and elastic scalability, consider DepthMetaData depthMetaData = getDepthGenerator().getMetaData();
Oracle Public Cloud. The service is currently available in limited trial mode. userGenerator = UserGenerator.create(context);
width = depthMetaData.getFullXRes();
height = depthMetaData.getFullYRes();

Considering the demo and the JavaFX technology behind it, Potts said,
“This is a cool 3-D application from JavaFX labs. We showed Duke in 3-D and I
got to pretend to be Duke, with the Kinect controller controlling it. It was a lot
of fun and all went well onstage, so I’m really pleased.”
As Ritter illustrated at the start of his presentation, humans have been
interfacing with machines for a very long time (for example, typewriters were
Linda DeMichiel, Java EE 7 Jason McGee, chief architect, cloud a great invention). Today software developers can apply open source technolo-
specialization lead at Oracle, talked computing, at IBM talked about the blog
about moving Java EE into the cloud at challenges of running Java applications gies such as JavaFX to interface with modern instrumentation devices (like the
the Java EE 7 Platform keynote. on the cloud at the IBM keynote. Kinect). As Ritter said, the thing to do now is “be inspired, go out there, and
build more stuff!”


ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation /


JavaOne, the world’s best conference for the Java com-
munity, is headed for Latin America. JavaOne offers Java
experts and enthusiasts three days of learning and network-
ing focused entirely on all things Java. Sessions and demos
cover everything from building modern applications using

JDK 7 to leveraging JavaFX, creating client-side applications,

Java and more. Connect with some of the world’s foremost Java
experts, collaborate with peers, and celebrate your role in the vibrant and growing
Forward: Java community. Register today!
Workshop NOVEMBER Java conference is orga-
nized by the Belgian Java
ence on Java technol-
ogy in India and is the
2011 QCon International
Software Development
User Group. It features a place to be to learn the
two-day in-depth Devoxx latest in the Java world

More than 300 high school students, children of Oracle employees, parents, and Conference University program, while meeting with like-
teachers attended the five-day Java Summer Workshop, August 8–12, 2011, at Oracle followed by three days minded individuals from
headquarters in Redwood Shores, California. Students created their own animations of conference sessions. across the industry. The
This practitioner-driven
Demos of Java tools, conference focuses on
with Alice and Greenfoot, two award-winning software programs that have been used conference is designed
hands-on labs, birds-of- new and groundbreaking
for years to visually teach Java programming basics. These kids were buzzing with for team leads, architects,
a-feather sessions, and technologies and emerg-
creativity—take a look at the winning Alice animations. and project managers. It
opportunities for attend- ing trends, successful
The Java Summer Workshop focused on building confidence and interest in Java includes two tutorial days
ees to give quick presen- practices, and real-world
and three conference days
and computer science in high school students at a crucial time in their career plan- tations are also on the learning. Session topics
with 18 tracks and more
ning. This investment in the next generation ensures that new talent will enrich the agenda. include Java language
than 80 speakers cover-
Java ecosystem. specifications and stan-
ing relevant and emerging
dards; enterprise Java;
Alice and Greenfoot are free to download, and free workshop training is available on topics in software devel- DECEMBER
Java for mobile devices;
Oracle Technology Network. opment. Don’t miss the IndicThreads Java for multicore com-
featured track, Why Java Conference on Java puting; optimization,
Is Still Sexy. DECEMBER 2–3, scaling, caching, and
PUNE, INDIA performance tuning;
Devoxx 2011 The 6th Annual and more. blog
Hear from the next NOVEMBER 14–18, IndicThreads Conference
generation of Java ANTWERP, BELGIUM on Java is the premier
programmers. This annual European independent confer-


ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java nation /



Patrick Curran The 13th annual O’Reilly Open Source
Convention (OSCON), held July 25–27 in
Portland, Oregon, was colocated with the
inaugural OSCON Java and OSCON Data con-
ferences. Explaining the addition of OSCON
Java, Edd Dumbill, OSCON cochair, said that JAVA, A BEGINNER’S GUIDE, JAVA 7 : THE COMPLETE
the Java platform is the most stable, complete, FIFTH EDITION REFERENCE, 8TH EDITION

and scalable technology for innovations in By Herb Schildt By Herb Schildt
Steven G. Harris Oracle Press (September 2011) Oracle Press (June 2011)
cloud computing and big data. “You see start-
Joe Darcy ups beginning with scripting languages and porting bits of their Learn the fundamentals of Herb Schildt’s classic Java
architecture over to Java when they need scaling,” he added. Java programming in no time programming resource is
OSCON Java keynotes included “Open Source, Java, and from best-selling program- thoroughly updated to cover
Oracle—Cracking the Code” with Steven G. Harris, former Oracle ming author Herb Schildt. the new features in JDK 7.
senior vice president; “JDK 7 in a Nutshell” with Joe Darcy, Fully updated to cover Java This expert guide offers
Project Coin lead engineer; and “Who Needs Standards?” with Platform, Standard Edition 7, comprehensive coverage of

Patrick Curran, Java Community Process chair. Java, A Beginner’s Guide, Fifth the Java language, its syntax,
Edition starts with the basics, keywords, and fundamen-
such as how to compile and tal programming principles.
run a Java program, and then Descriptions of key API
discusses the keywords, syn- libraries are also included. Of
Sonatype It’s natural for open source projects to build upon the work done
by other open source projects. Sonatype is facilitating the availabil-
tax, and constructs that form
the core of Java. You’ll also
course, details on new JDK
7 features, such as try-with-
Brings ity of components from’s large open source project base,
find coverage of some of Java’s resources, type inference via
Projects into the by bringing project artifacts into the Central Repository,
most advanced features, the diamond operator, catch-
Central Repository a leading source for open source Java components. Sonatype’s including multithreaded ing multiple exception types
Nexus Maven service was made available to projects in
programming and generics. (multicatch), upgrades to
May. All projects, regardless of size, have access to the new Maven service. The benefit
Get started programming in NIO, and the fork/join frame-
for the global Java open source community is that project owners can now automate and
Java right away with help from work, are provided.
control synchronization of their project artifacts to the Central Repository. As a result,
this fast-paced tutorial.
any Maven project can now leverage project assets more easily to deliver applications
faster, at a higher quality, and with less risk. Java Magazine subscribers will blog
“Developers now have access to components directly from the Central Repository, re- receive a 40 percent discount.
quiring no debugging or additional configurations,” says Jason van Zyl, Sonatype founder and CTO. Read a sample chapter:
“Java Fundamentals.”


ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
ntil recently, architects, engineers, and construc-
tion professionals have concerned themselves with
making buildings safe, structurally sound, function-
ally appropriate, and, of course, aesthetically pleasing. In

the past few years, as energy costs have risen and concerns
about the environmental impact of greenhouse gases have
grown, those same professionals and others have realized
that they also need to make buildings more resource
efficient and environmentally friendly.
Known as green building, green architecture, or sus-
tainable design, this worldwide movement is changing
the way the buildings in which we live, work, and play are

JavaFX 2.0
Green Light
Startup dooApp supports the work of green building professionals
Christophe Dufour (left), Antoine Mischler (second
from left), and members of the dooApp team test
drive the latest release of their Infiltrea application.
with an innovative testing tool. BY PHILIP J. GILL

ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
To the Web and Beyond with 2.0
Infiltrea has been on the market for about a year now and is
marketed in France with dooApp partner Testoon, a Paris-based

distributor of test and measurement equipment. Testoon pack-
ages Infiltrea with its blower door systems.
With the recent introduction of JavaFX 2.0, Lille, France–based
software startup dooApp has rewritten Infiltrea to take advantage
of the framework’s new features, says dooApp Cofounder and Co-
managing Director Antoine Mischler. These include improved bind-
ing and better debugger and cascading style sheet (CSS) tools.
The most important feature, however, may well be JavaFX’s new
support for Web applications through its WebView component.

In the 2.0 release of Infiltrea, dooApp is Web-enabling its ap-
plication using the JavaFX WebView component. In earlier JavaFX
frameworks, applications had to run on a local desktop device,
such as a PC or Mac. Now, WebView is an embedded browser
for JavaFX 2.0 applications whose features include the ability to
render HTML content from local and remote sources, to execute
JavaScript commands, and to apply effects and animations.

At the same time, dooApp has partnered with a regional as-
sociation of green building professionals to develop a specialized
social network for green building diagnostic and measurement
SNAPSHOT designed and constructed. It is also opening that it would make it easier professionals. The social network will allow Infiltrea users to share
opportunities for innovative software devel- to recruit people with good tips, techniques, and experiences and build a common community
DOOAPP opers to build new tools to address the spe- Java skills and that we would of knowledge across the internet.
Headquarters: cific needs of green building professionals. have a lot of existing libraries “The idea is to integrate the network directly into Infiltrea using
Lille, France One such company is dooApp, a Java startup we could reuse, which would the new WebView component introduced in JavaFX 2.0,” says
Industry: based in Lille, France. make the whole develop- Mischler. “This allows a very tight integration between desktop
Software “Our software makes the work of the green ment process quicker. We and Web applications, in this case Infiltrea and the social network.
Employees: building professional easier,” says Antoine also knew we would have a I think this is one of the most innovative features in JavaFX 2.0
7 Mischler, who cofounded the firm two years lot of tools available to us to and will change the way desktop and Web applications interact.”
Java version used: ago with Christophe Dufour and now serves, manage and test the devel- Mischler says dooApp is already looking at other applications
Java Platform, for green building professionals. Linking up with green building
with Dufour, as co–managing director. “Our opment cycle,” says Mischler.
Standard Edition 6 professionals of all kinds through the social network will help drive
first application, Infiltrea, is dedicated to “We had had a great experi-
the development of future applications. In this way, he hopes,
professionals who measure the airtightness ence with Java before, and we
dooApp and Java can change the way green building professionals blog
of buildings,” explains Mischler. wanted to take that technol-
do their work, just as green building technologies are changing our
Because Mischler and Dufour had both ogy further.”
built environment.
been Java developers in the financial software Infiltrea, built on Java
market, Java was the natural choice as the Platform, Standard Edition 6
development platform for Infiltrea. “We knew (Java SE 6), makes extensive
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
Duke’s Best and Brightest
The Duke’s Choice Awards were created in 2003 to honor extreme
use of JavaFX, a leading a comfortable indoor environment is wasted;
innovation in the world of Java technology. The 2011 Duke’s Choice
Awards, presented at JavaOne 2011, showcased the amazing results user interface, graphics, buildings that are airtight, on the other hand,
of projects supported by thousands of development hours. The win- and media framework for consume less energy because they waste less
ning projects and companies are as follows: developing rich inter- through leakage. “Green buildings need to be

■■ Arquillian. This project simplifies integration testing for Java- net applications in the airtight,” explains Mischler.
based applications. Java environment (see In Europe, regulation EN 13829 mandates
■■ dooApp. Infiltrea is dooApp’s JavaFX and Java Platform, Standard sidebar, page 11). The what is called a blower door test to determine
Edition solution, designed for green building professionals whose software is also the win- if new construction, both residential and com-
job involves measuring the airtightness of buildings. ner of this year’s Duke’s mercial, meets airtightness requirements. It
■■ Inductive Automation. Ignition is Inductive Automation’s Java-
Choice Award for Innova- also defines the testing method, criteria, and
based Web application that integrates different manufacturing tive Green Technology, reporting requirements. Individual countries
machines using a central Web server. presented at this year’s have their own regulations; in France, for
■■ jHome. This complete home automation open source API, based
JavaOne conference in example, RT 2012 and its stricter airtightness

on GlassFish Server Open Source Edition and Java Platform,
San Francisco, California, standard began taking effect in late 2011.
Enterprise Edition (Java EE), enables developers to control
in October. Infiltrea provides an end-to-end solution
anything in their homes.
■■ JFrog. JFrog’s Artifactory is the world’s first binary repository
for the airtightness testing process, says
manager and is built with the Content Repository API for AIRTIGHT, ENERGY Mischler. The application includes a blower
Java specification. EFFICIENT door connection, standard tests and charts,
■■ JRebel. This Java Virtual Machine plug-in enables Java developers Airtightness is one of the and report-writing features. The charts,
Meet Vinny Senger, key measurements of a created with JavaFX, provide the main view
the technical lead of to instantly see any code change made to an application.

jHome, a complete ■■ LMAX Disruptor. This solution is a multithreaded, open source building’s energy effi- of the test’s measurements.
home automation API concurrent programming framework designed for high-performance ciency, and it’s a major
based on GlassFish and low-latency transaction processing. goal of green building.
Server Open Source ■■ Rockwell Automation. This company’s Java-enabled human–
According to the U.S.
Edition and Java machine interface line of products will allow the automated com-
Platform, Enterprise Energy Information
Edition that lets you munication and exchange of data to factory floor lines. Administration, build-
■■ Sodbeans Project. This open source, NetBeans-based module
control anything in ings in the U.S. create
your home. suite is designed to enhance accessibility for the blind in modern 48 percent of all
programming environments.
■■ The Netty Project. This Java-based, new I/O client/server frame-
domestic greenhouse
gas emissions and con-
work enables quick and easy development of network applications.
sume most of the elec-
“The Duke’s Choice Awards showcase the incredible creativity that
takes place every day in the Java community,” says Amit Zavery, vice tricity the nation’s power
president of product management in Oracle Fusion Middleware. “This plants generate. Making
year’s winners demonstrate the countless ways that Java technology buildings more energy
can be used to create innovative applications and products. Put in the efficient reduces both the
demand and pollution. dooApp’s Infiltrea application helps green blog
hands of creative and passionate individuals, Java can have a signifi-
building professionals to measure airtight-
cant impact on our lives.” —Marta Bright When buildings “leak,”
ness, a critical component in green building.
some of the energy their The 2.0 release of Infiltrea is Web-enabled
heating and cooling sys- using the JavaFX WebView component, as
tems consume to create seen here in the project outline view.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
acquires the measurements,”
says Mischler. “With Infiltrea,
the professional has a chart that

shows the pressure in the build-
ing and the airflow in real time.”
Once recorded, the measure-
ments are published in two
reports, directly from Infiltrea.
The first, a technical report, is
a two-pager that includes the
building’s features, the testing
criteria, and a chart of results.

The second is a longer and more
complex legal report that con-
forms to EN 13829. It can include
photos, logos, plans, thermal
surveys, and other relevant data
and can be published in a num-
ber of formats, including PDF,

.docx, HTML, RTF, and others.
“At the end,” Mischler says, “the
software gives a full report to the
professional that conforms to
Antoine Mischler the regulations.”
(center) and the dooApp “The goal of the process is to compute some the holes and penetrations in the building’s Infiltrea doesn’t show where a building is
team brainstorm about indicators saying whether the building is good exterior envelope, including the walls, doors, leaking, however, and that is the next step in
enhancements to the or bad,” says Mischler, noting that good means and windows. The tighter the building, the the process of making a building airtight. If
Infiltrea application. it meets regulatory requirements. fewer holes or leaks there are in a building doesn’t pass, then the diagnostic
A blower door system consists FAST FACT its envelope and the less air that is professional conducts smoke tests to identify
needed from the blower door fan leakage sites. “Once the leakage site is identi-
of a calibrated fan, a door-panel
system, and a device to measure Buildings in to create a change in the build- fied, the professional will seal it and run the
the fan flow and building pres- the U.S. create ing’s pressure. airtightness tests again until all the leakage
sure. The blower door fan is tem-
porarily sealed into an exterior
48 percent of The Infiltrea software runs on
Windows, Mac OS, and Linux; it
sites are identified,” explains Mischler.

doorway and then blows air into all domestic records the test and presents a THE NATURAL CHOICE blog
or out of the building, creating
a pressure difference between
greenhouse gas visual representation of its prog-
ress in real time. “Our software
Going with Java and JavaFX was a natural
choice for dooApp’s green building applica-
inside and outside. The pressure emissions. is connected to the measuring tions. Mischler says that when he and Dufour
difference forces air through all device and to the blower door, and were working as Java developers, they real-
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
ized they wanted to apply their developing Infiltrea we had
expertise to an area in which the choice between Swing and
they both had a strong personal JavaFX,” continues Mischler.
interest: green building. “Swing is the ‘old’ Java graphics

“What we wanted to do was framework. So Swing was a
to bring our technical skills to mature and stable technology
develop innovative software but had some major drawbacks:
for professionals in the green you have to write a lot of code
building sector,” says Mischler. for small results, it’s hard to
“What we had seen is that most style components, and the
software developers in this sec- default look and feel looks a
tor were engineers or architects bit outdated.”
who had moved On the other

into software but DUKE'S GREEN CHOICE hand, he continues,
lacked specific skills
French startup JavaFX “was a new
in software. And we technology that
thought that, as a dooApp is the addressed these is-
result, the tools they
had developed were
winner of this sues and introduced
tons of cool new
not so innovative or year’s Duke’s features, such as Learn more about

user friendly.”
Making the soft-
Choice Award for special effects and
animations, as well
Java technology
ware interface user Innovative Green as CSS skinning.”
with Safari Books
friendly was a high Technology. The choice of Online
priority, so they JavaFX wasn’t made
chose JavaFX as without trepidation,
Infiltrea’s graphics however. “Since it
and user interface framework, was a new technology, making
says Mischler. “We already had the choice of JavaFX was some-
worked a bit with Adobe Flash, what of a gamble,” Mischler
but we knew this was not well concedes. “After considering both
suited to design a professional options, we made the choice to
desktop application because of work with JavaFX and we do not
performance and maintenance regret this today. The technology Use your QR code reader to access information about a
issues,” Mischler explains. is fun and is evolving in the right
“Since [Microsoft] Silverlight is way.” </article> blog group trial or visit
pretty much the same, we didn’t
look at it any closer.”
“We both had experience with Philip J. Gill is a San Diego, California–
Swing, and when we started based freelance writer and editor. With the intelligent library in the cloud
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
Rainer Schügerl, Director of Software Development and Security, SVC

Austria’s E-Health System:

ustria is well known for its advanced and generous

social services—marked by excellent healthcare;
a strong social security system; and an extensive
network of hospitals, physicians, and pharmacies.
Austrian Social Security Law, a public insurance system that
includes 22 institutions offering a variety of insurance cover-
age and social programs, insures most Austrian citizens, and blog
Smartcard system connects patients, providers, hospitals, in recent years this national health system has been bolstered
and pharmacies throughout Europe. BY DAVID BAUM by one of the world’s most advanced programs for smartcards
and electronic health records.

ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
SVC has made a Schügerl has 40 software engineers on his
giant step forward in team, including 20 Java developers. Due to
improving the quality of the sensitive nature of health and medical in-
medical care for citizens formation, the team needed a programming

throughout Austria and language with a robust security architecture.
beyond. By implement- They decided to use Java Standard Edition for
ing the e-card infra- Embedded Devices, which supports the same
structure, the agency platforms and functionality as Java Platform,
replaced a cumbersome Standard Edition (Java SE), along with addi-
Java-powered medical system of paper health tional capabilities for the embedded market
practice units (MPUs) and Today all insured citizens get a smartcard insurance vouchers that had dominated such as support for small-footprint Java run-
smartcard readers enable that verifies their insured status and facili- Austria’s medical world for 50 years. Manual time environments (JREs), headless configu-
healthcare providers to tates the creation, transmission, and stor- processes between insured people, employers, rations, and memory optimizations. Java SE is

read patient records and age of electronic health records. The e-card doctors, hospitals, and the Main Association of ubiquitous on servers and desktop comput-
transmit health records to
system also authorizes citizens to avail them- Austrian Social Security Institutions have been ers, thanks to its high-performance virtual
the SVC data center.
selves of a variety of e-health services, from systematically replaced by electronic solutions machine and exceptional graphics support.
preventive checkups to disease management and e-business procedures governing the To top it off, it has an extremely lightweight
programs. Thousands of healthcare providers transmission, storage, processing, and virtual- deployment architecture and a complete set
have installed special equipment to scan the ization of health and administrative data. of features and libraries for programmers.
smartcards and transmit secure data across a Java applets are ideal for smartcards and

secure health information network that spans SECURE INFRASTRUCTURE similar small-memory devices because they
the Austrian nation and extends to many The Main Association of Austrian Social carry all the essential security features such
other European countries within the scope Security Institutions is a group of statutory as cryptography, authentication, authoriza-
of the NETC@RDS project of the European insurance providers that is respon- tion, and public key infrastructure.
Union. Java is the lingua franca of the system. sible for the country’s health, pen- For SVC, these features ensure
“We chose Java because of the platform sion, and accident insurance. The that new e-card applications can
advantages, especially its tremendous porta- association enlisted SVC to design Java applets securely access centralized re-
bility among CPUs and hardware platforms,” and deploy the e-card system and carry essential sources while protecting critical
says Rainer Schügerl, director of software
development and security at SVC, a public
an associated virtual private net-
work. As a 100 percent subsidiary
security features data from theft, loss, and corrup-
tion. The Java API supports a wide
entity based in Vienna, Austria, that devel- company of the Main Association and are ideal for range of cryptographic services
ops innovative solutions in the field of health of Austrian Social Security Institu- smartcards. including digital signatures, mes-
telematics and e-government. SVC served as tions, SVC has a proven track record sage digests, ciphers, message
the systems integrator for the e-card project. of enforcing transparency and authentication codes, key genera-
“Java provides a stable, high-quality pro- security in the processing of health tors, and key factories, allowing
gramming language that suits all of our and administrative data, whether for clinical SVC developers to easily integrate security blog
needs,” Schügerl adds. “For enterprise- use, administration, or science. Its mission into their application code.
caliber development requiring high avail- is to improve the efficiency of information The smartcard does not contain software
ability, reliability, and security, most Austrian processes among patients, health service functions. Only the cardholder’s adminis-
organizations use Java.” providers, and health administrators. trative data is stored on the e-card—name,
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
Rainer Schügerl (second
from right) takes a break
with members of the
SVC engineering team.
In just seven months,
SVC rolled out 8.5
million e-cards to
Austrian citizens.

academic title, insurance number, data from the smartcard. The MPUs contain procedures of the e-card system.
SNAPSHOT serial number, gender, and user group the application software that initiates secure For the cardholder, medical treatment is
SVC identification—along with certificate and business procedures. They interface with now accessible without administrative bar- identity link parameters. “The e-card is used another piece of equipment called a LAN chip riers and without paper documents. Physi-
Headquarters: primarily as an identification tool for patients card reader to transmit patient data to the cians can verify if a person is insured and
Vienna, Austria and the key to their data,” explains Schügerl. SVC data center over a virtual private health which health insurance institution will pay
Industry: “In order to get paid, doctors insert their pa- information network. for medical treatment. The system veri-
Public services tients’ e-cards into a smartcard reader. The fies insurance coverage for all citizens, even
Employees: administrative patient data is then cross- RAPID ROLLOUT when they are traveling to member states of
checked with a central social security data- In a span of seven months, SVC rolled out the European Union, the European Economic
Java version used:
Java Standard Edition base, which resides in a secure data center.” 8.5 million e-cards to insured citizens, along Area, and Switzerland. “The card allows
for Embedded Only authorized medical practitioners can with GINA boxes to 11,000 providers and them to receive medical treatment in these
Devices 6 read the cards and the associated health medical practitioners. SVC continues to ship member states, for free or at a reduced cost.
records, and they must have special equip- about a million e-cards every year and to The intention is to allow people to continue blog
ment called medical practice units (MPUs) bring new medical practices and health ser- their stay in a country without having to
to do so. Commonly known as GINA boxes, vice providers on board. More than 12,500 return home for medical care, or to take a
each MPU is a special-purpose computer that healthcare providers now have the equip- job in a neighboring country and keep their
hosts a lightweight Java program to obtain ment and have been trained in the business health benefits,” Schügerl explains.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
FUTURE APPS and providers have embraced Stats on a SVC, a provider of health telematics
and e-government solutions based in
The e-card system has been designed to sup-
port a number of future projects, including
these existing and emerging
e-health applications, partly as a
Successful Vienna, Austria, has issued millions

electronic signatures for pharmaceutical pre- result of the robust, Java-based Rollout of e-cards to employed Austrian
citizens, along with thousands of

scriptions, emergency data, electronic vac- security architecture. Data is not special-purpose computers that rely on Java to securely store
cination records, and disease management stored on the card; it is housed and transmit patient data.
programs. For example, a new e-medication in a secure data center. Only
system makes it easier for doctors and phar- authorized providers and ad- E-cards (active) in Austria 8,700,000
macists to share information about potentially ministrators can access these New e-cards issued 850,000 per year
harmful interactions among medications. records, and they must have Healthcare providers connected 12,500
Launched as a pilot project earlier special-purpose equipment. Pharmacies connected 120
this year in three regions of Austria, Hospitals connected 136
SMART CHOICE this service permits pharmacists, GLOBAL EXAMPLE

Care facilities connected 15
SVC chose physicians, and hospitals to see a Following the slogan, “Move
E-card transactions completed 667,763, 920
list of each patient’s current medi- the data, not the patient,” SVC’s
Java because cations. More than 100 physicians, Java-based infrastructure has
Average contacts per day Approximately 500,000

of the platform about 50 pharmacies, and 6 hospi- reduced the cost of healthcare All-time high (December 14, 2009) 629,150

advantages, tals participate in this project. The

service will be fully implemented
administration, improved col-
laboration between healthcare
Source: SVC

especially its during 2012. professionals, and enabled

tremendous “Our research shows that higher-quality services for

portability people 70 years and older take up

to 10 medications per day,” says
patients. Other Java applications
communicate with the Main Association of Germany, Iran, Japan, Kuwait, Lithuania,
among CPUs Schügerl. “Tracking and compar- Austrian Social Security Institutions to sub- Macedonia, the Netherlands, Poland, Roma-
and hardware ing pharmaceutical prescriptions mit medical claims, verify pharmaceutical nia, Serbia, Slovenia, South Korea, Taiwan,
with health records helps them to prescriptions, route disability reports, and Turkey, and Vietnam.
platforms. reduce negative interactions. So far transmit medical records between appro- Java is the de facto standard for these
about 7,000 citizens have partici- priate medical practitioners. smartcard initiatives, with 5 billion instal-
pated in this pilot program.” Within The e-card infrastructure has become lations worldwide. Many technically savvy
the scope of the pilot project, the the foundation of many future applications organizations come to the same conclusion
participation of patients, physicians, pharma- in the burgeoning health telematics sector, as SVC: they depend on Java because it is a
cists, and hospitals is voluntary. including a new “citizen card” that stream- powerful and secure environment for ap-
After nationwide rollout of the e-medication lines e-government services related to tax plications that run on smartcards and other
system, citizens can “opt out” if they decide declarations, alimony payments, student devices with very limited memory and pro-
not to share their health information loans, criminal records, residence registra- cessing capabilities. </article>
online—as some people prefer, due to pri- tion confirmations, insurance data, and blog
vacy concerns. Because of the large number pension accounts. Many other countries
of involved stakeholders, it was not easy to have expressed interest in developing similar Based in Santa Barbara, California, David Baum
balance the different interests and get the Java-based systems, including Australia, Bul- writes about innovative businesses, emerging tech-
project running. But in general, both patients garia, Colombia, the Czech Republic, Finland, nologies, and compelling lifestyles.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//new to java /

Starting Your First Computer Game

Use Greenfoot to create your first interactive program.

I n the Premiere issue of Java turtle’s movement using keys), We need to be able to name of the left arrow
Magazine, I wrote an article which might be a first step toward check whether a key key and—you guessed
about writing your first Java pro- a little computer game. has been pressed. it—right is the name of
BIO gram using the Greenfoot ■■ We need a statement control a turtle the right arrow key.

environment. In that article, we
made a turtle walk across the
Jumping Right In
When we left our turtle’s act meth-
in Java that lets us
state that we want to
on your screen The isKeyDown
method, when called,
screen, either in straight lines or od last time, it looked like this: turn only if the right with your arrow will answer with a value
in circles. or left arrow key has keys. Pretty good of either true (yes, the
Note: If you haven’t done so been pressed. left arrow key is being
already, go to that article to find
public void act()
fun already! pressed) or false (no,
the software you need to install to move(4); Checking for Key the key is not being
follow this project. turn(2); Presses pressed).

Getting an animated graphic } Greenfoot has a method, called
onscreen on your first day is pretty isKeyDown, that lets us check An if Statement
good, but it gets boring after a We observed that this caused whether a given key on the key- The second part we need to make
while if you can’t do anything the turtle to run in a circle, be- board is being held down. This our plan work is a statement that
more with it. So today, I’ll tell you cause the act method is repeat- method is in the Greenfoot class. lets us execute an action (in our
how to add keyboard interac- edly executed when the program We can, for instance, write the fol- case, turning) only under cer-
tion (that is, how to control your runs (see Figure 1). lowing to check whether the left tain conditions (when the left or
Now, we want arrow key is being pressed: right arrow key is pressed). This is
each turtle to run called an if statement.
straight forward Greenfoot.isKeyDown("left") An if statement has the follow-
when we do not ing general form:
press any keys The parameter (inside the
on our keyboard parentheses) is the name of the if (condition) {
and to turn right key we want to check. The alpha- statements;
or left if we press betical keys have their character }
the right or left as their name (for instance, the A blog
arrow keys. key is called a, the B key is called When an if statement is exe-
To achieve b, and so on). The special control cuted, it checks the condition, and
this, we need two keys have names indicating what then it executes the statements
PHOTOGRAPH BY JOHN BLYTHE Figure 1 things: they are; for example, left is the between the curly brackets only
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//new to java /

if the condition is true. (Incidentally, it This code now states that we will turn
public void act()
might be good to introduce some more- minus 3 degrees during every act cycle
professional terminology: the part of in which the left arrow key is held down.
the if statement containing the state- (Note that we can use a negative angle to

ments—the curly brackets and every- turn left.) if(Greenfoot.isKeyDown("left")) {
thing in between—is called the body of Doing the same for the right arrow key turn(-3);
the if statement.) The body may contain to turn right is now simple. We just write }
a whole sequence of statements if that’s a similar statement again, this time
if(Greenfoot.isKeyDown("right")) {
what we want. turning 3 degrees for the right arrow key.
If the condition is false, the body is The complete new act method is shown
just ignored, and execution continues in Listing 1. }
after the if statement. Try it out. Compile your classes, place

a turtle into the world, and run the
Turning on Key Press scenario. See all listings as text
With these two bits together, we can You can now control a turtle on your
now do what we need to do. We need to screen with your arrow keys. Pretty good
write the following: fun already! for the image of the pizza slice in the to create an object of the class that is
Currently, the turtle will continu- food category. Click OK. currently selected in the class dia-
if (the-left-key-is-being-pressed) { ously walk forward. If you want to, you As soon as the classes are compiled gram on the right.
turn-a-bit-to-the-left; can change your code so that the turtle again, you can add a few pizza slices (as ■■ When all your objects are in the world

} moves forward only when you press the well as a turtle) to your world. as you want them to be at the start
up arrow. You do that by adding another Try it out. Let your turtle run around of your game, you can right-click the
This is not real Java code (it’s pseudo- if statement around the move(4) state- to collect pizza. You will notice, though, world background and select Save the
code). We can now fill in the pseudocode ment. The name of the up arrow key that the turtle does not (yet) eat the World to save this world state. This
with real Java code: is up. pizza. It will just run straight across the state will then be re-created auto-
pizza. We will fix that shortly. matically after every compile or reset.
if (Greenfoot.isKeyDown("left")) { What Do Turtles Eat? Pizza!
turn(-3); Next, we want to give the turtle some- Two Tips Collision Detection
} thing to do: collect some food and eat If you worked along and experimented in OK, we have pizza. We have a turtle. The
it. To do this, we need some new objects Greenfoot for a bit, you will have noticed turtle is hungry.
in our world: pizza slices. (Yes, our turtle that you need to re-create all objects in The last bit to do for today is to make
eats pizza. This is not a biology lesson— the world after every compilation. This the turtle notice when it runs into some
it’s a computer game.) can get a little tedious after pizza and to make the turtle
Where do objects come from? From awhile, especially if we have DID YOU KNOW? eat the pizza. For this we
a class. So first, we need to create a new many objects. isKeyDown lets need what’s called collision
Pizza class.
Right-click the Actor class (see
Here are two quick tips to
make your life in Greenfoot a
us check whether detection to detect when
we’ve run into a pizza slice.
Figure 2) and select the New subclass bit easier. a given key is being The full code to do this is
function. In the resulting dialog box, ■■ You can shift-click into the
held down. in Listing 2. This code should
Figure 2 enter Pizza as the class name, and search world. This is a shortcut be added to the end of the
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//new to java /

act method in the Turtle class. There are at the beginning of the first line:
public void act()
several new elements in this code seg-
ment. Let’s look at them one by one. Actor pizza
The first line calls a Greenfoot meth-

od: getOneIntersectingObject(Pizza.class). This declares a variable named pizza if(Greenfoot.isKeyDown("left")) {
This method checks whether the turtle that can hold Actor objects (objects that turn(-3);
intersects an object live in the Greenfoot world). }
TEDIUM CHECK of class pizza (or, in After the first line, the pizza variable
if(Greenfoot.isKeyDown("right")) {
Re-creating all the other words, it asks,
“Are we touching a
holds the pizza object we ran into, or it
holds null if we didn’t run into a pizza
objects after every pizza slice?”). If we slice in this step.

compilation can are touching a pizza Next follows another example of an Actor pizza = getOneIntersectingObject(Pizza.class);

get tedious. slice, this method
returns the pizza ob-
if statement. In pseudocode, the next
lines state the following:
if(pizza != null) {
ject we found. If not, }
it returns a special if(we-have-run-into-pizza) {
value, null, which tells us that we are not remove-the-pizza-object-
touching anything. from-our-world;
See all listings as text
The equal symbol in the first line is an }
assignment operator. It stores the result

of our collision check (the pizza object The condition check is done with the object from the world. Listing 3 shows be used as the condition in an if
or null) in a variable. A variable is a bit of following expression: the complete version of our act method statement.
storage where we can store objects. at this stage. ■■ Collision detection can be used to
In our case, the variable has been if(pizza != null) { Try it out. Once you have written this check whether one object touches
declared using the following statement code, your turtle can walk around and another.
The != symbol eat pizza (see Figure 3). ■■ Variables are used to store objects.
means not equal. So, ■■ The special value null is used to
here we are saying, Conclusion indicate that we do not have an
“If our pizza variable In this article, you learned a bit more object. </article>
is not equal to null…” about writing Java code and about some
The effect is that useful Greenfoot methods.
the instruction in the ■■ If statements can be used to execute

body of the if state- an action only under a certain LEARN MORE

ment is executed condition. • The Greenfoot gallery
only if the pizza vari- ■■ If statements have a condition and a
• Young developer resources
able is not null, that body. The body is executed only if the blog
• ”Wombat Object Basics (Young
is, if we have run into condition is true.
Developers Series, Part 1)”
some pizza. ■■ The Greenfoot.isKeyDown method can

The next line then be used to check for key presses. • ”Wombat Classes Basics (Young
Figure 3 removes the pizza ■■ The Greenfoot.isKeyDown method can Developers Series, Part 2)”
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//new to java /

Introduction to RESTful
Web Services (Part 2)

Handle the JSON response format with an HTML5 Web client.

I n Part 1 of this three-part series, JSON and HTML5 version of Firefox, Opera, Safari, that we want (JSON).

I showed how to quickly cre- JSON is a human-readable data or Chrome. 1. Create the method that will
ate and deploy a Java Platform, format based on JavaScript tech- We will use the HTML5 stor- handle the Web services re-
Enterprise Edition (Java EE) appli- nology. The structure of JSON is age capabilities to store informa- sponse for the seller:
cation that uses Representational easier to parse and extend than tion on the browser, retrieve it   a. Select the Source Package
State Transfer (REST) Web servic- traditional XML. JSON format is later, and finally display it. This node of the AuctionApp
es with NetBeans. The application used by most applications that article was tested with Firefox project and open the
developed in Part 1 provide Web services 6.0.2 and Google Chrome Release file
will be the basis for HOW COOL IS THAT? through Web clients. 14.0.835.186. located in the package com

this second article on
implementing new
HTML5 provides HTML5 is the next
generation of HTML. Let’s Code and Test the JSON
functionalities. very cool It provides new fea- Representation   b. R
 emove the XML MIME type
Now, in Part 2, we functionalities tures that are neces- To begin, we will modify the re- (application/xml) from the
will see in detail how to sary for modern Web sources to ensure that the server @Produces annotation of
use JavaScript Object for storing the applications. It also returns a response in the format the method get(). The class
Notation (JSON) to data in your browser standardizes many
handle the response
returned to the cli-
and accessing features of commonly
available browser
ent. We will also add a the data with technologies that Web
small dose of HTML5, JavaScript after the developers have been
JavaScript, and Ajax to
call the Web services,
page is loaded. using for years to cre-
ate rich Web applica-
store the information tions without the need
locally, and display the for plug-ins.
information later. HTML5 is designed to be cross- blog
Note: The complete source platform, and it does not require
code for the application designed a specific operating system. The
in this article can be downloaded only thing we need is a modern See how to use JavaScript Object Notation with
ALLEN MCINNIS/GETTY IMAGES here. Web browser, such as the latest
HTML5 to store, retrieve, and display information.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//new to java /

should now look like Listing 1. ■■ Call the Web services for the Seller.
  c. Select the Source Package node of ■■ Store the Seller’s information on the
the AuctionApp project and open browser (HTML5 capability). The
public class SellersResource {
the file located concept works like the cookies in your @javax.ejb.EJB

in the package browser, but it’s recommended for private SellerResource sellerResource;
.auctionApp.resource. larger data. @Context
  d. Remove the XML MIME type ■■ Retrieve the information stored in ....
(application/xml) from the the browser. @GET
@Produces annotation of the ■■ Finally, display the information.
public SellersConverter get(@QueryParam("start")
method get() to handle the JSON JavaScript will be used to invoke the
response only. The class should Web service via the XMLHttpRequest ob- ...
now look like Listing 2. ject provided by Ajax technology.

  e. Repeat Steps b, c, and d for each 1. Create a sample HTML page:
resource.   a. Right-click the Web Pages node of
2. Test the JSON and XML response the AuctionApp project and select
format: New; then select HTML.
  a. Build and deploy the project.   b. Type an HTML filename, such as
  b. To test the JSON response, open JsonClient.
your browser and type the re-   c. Type a folder name, such as jsonUI.
source URL http://localhost:8080/   d. Click Finish. See all listings as text

AuctionApp/resources/sellers/. A new resources HTML file is added to
The JSON representation of the re- the project.
source (Sellers) will be displayed. You 2. Edit the created page and modify source URL http://localhost:8080/ handle and parse the JSON message
can see all the Sellers that you already the HTML <body> tag, as shown in AuctionApp/jsonUI/JsonClient.html. sent by the Web service. Finally, HTML5
created in JSON format. Save the result Listing 4.   b. Enter the seller ID (2). provides very cool functionalities for
when prompted by your browser and 3. Add the JavaScript functionality to   c. Click Load seller in local browser. storing the data in your browser and
open the saved file with any text editor invoke the Web services and handle A confirmation message is displayed. accessing the data with JavaScript after
to see the JSON string. the data storage by modifying the 2. Display the stored information: the page is loaded. This allows us to save
If you see the result shown in Listing 3, HTML <head> tag, as shown in   a. Retrieve the information for seller time and bandwidth.
it means your RESTful services are work- Listing 5. #2 from the local storage by click- In Part 3 of this series, we will focus on
ing correctly. Now that the RESTful Web 4. Retrieve and display the stored ing Read Values. the integration of Java API for XML Web
services are up and running, we are ready information: The first name and last name of seller Services (JAX-WS) technology for “big”
to consume them using any client.   a. Modify the HTML <head> tag as #2 are displayed. Web services. </article>
shown in Listing 6.   b. Now you can smile—it works!
Using an HTML5 Client   b. Save the HTML file.
We need to use a Web client. So we are   c. Build and deploy the project. Conclusion LEARN MORE blog
going to quickly build a sample HTML5 We have seen how easy it is to configure • Roy T. Fielding’s dissertation defining the
page front end to allow us to perform the Testing the HTML Client Application RESTful Web services to send a JSON REST architectural style
following tasks using HTML, JavaScript, 1. Call the Web services for seller #2: response to the client. The integration • HTML5: Up and Running, by Mark Pilgrim
and Ajax functionalities:   a. Open your browser and type the re- of JavaScript and Ajax made it easy to (O’Reilly Media, 2010)
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

Agile ALM for Java Developers

Agile ALM makes for better-quality software and happier Java developers.

MICHAEL HÜTTERMANN A gile application lifecycle

management (ALM) is a way
for Java developers, testers, re-
project roles
■■ Uses and integrates light-

weight tools, enabling the

new, and developers should re-
spect the struggles of previous de-
cades, and put results together to
defined process. Release manage-
ment can be differentiated into
a functional part and a technical
BIO lease managers, technical project team to collaborate efficiently get the best solution. In my view, part. To deliver software success-

managers, and decision-makers without any silos ALM evolved from software con- fully, both parts are important
to integrate flexible agile practices ■■ Makes the relationship of given figuration management (SCM), and should be integrated with
and lightweight tooling into soft- or generated artifacts visible, which in turn has its roots in basic each other. Automation and
ware development phases. providing traceability and version control. continuous integration are crucial
Agile ALM synthesizes technical reproducibility Following are some major agile facets of the software release and
and functional elements to pro- ■■ Defines task-based activities ALM building blocks that address delivery process.
vide a comprehensive approach that are aligned with require- and leverage widespread activities Functional release management.
to common project activities and ments, which means the activi- among Java developers. Functional release management

phases, addressing test, release, ties are linked to requirements involves identifying the cus-
integration, build, requirements, and all changes are traceable to Release Management tomer’s requirements, assigning
change, and configuration man- their requirements Release management involves them to releases, and delivering
agement. (See Figure 1.) As a result, from a Java devel- producing software artifacts and the functionality to the customer
With its interdisciplinary ap- oper perspective, agile ALM helps releasing them according to a with high quality. Agile practices
proach, agile ALM integrates proj- developers focus on doing their
ect roles, project phases, and arti- jobs rather than wasting time with
fact types. Agile ALM enriches an barriers or obstacles that reduce APPLICATION LIFECYCLE MANAGEMENT
ALM approach with agile values productivity. Streamlining Java RUN
and strategies. An agile approach development with agile ALM fos- DEFINE REQUIREMENTS
to ALM improves product qual- ters collaboration among cowork- MANAGEMENT
ity, reduces time to market, and ers, leading to improved software TEST
makes for happier developers. quality and better results. MANAGEMENT
In a nutshell, agile ALM Agile ALM provides processes MANAGEMENT
■■ Helps overcome process, tech- and tool chains that are flexible MANAGEMENT INTEGRATION
nology, and functional barriers and open to change. This is one of blog
(such as roles and organiza- the ways in which ALM provides DESIGN
tional units) structure for agile software devel-
■■ Spans all artifact types as well opment. Some underlying aspects
as development phases and of agile ALM are not completely Figure 1
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

are often used to support this process, ■■ Closing the release with a code-freeze time-consuming activities FLEXIBLE STRUCTURE Collaborative Development
and many projects achieve good results interval in order to complete and ship is essential. Writing software collab-
from using the management template the final release Continuous integration Agile ALM provides oratively means that all
known as Scrum. Technical release management. (CI) refers to the automa- processes and stakeholders, especially Java
tool chains that

While defining a thin set of rules, Technical releasing consists of build- tion of the build, test, and developers and testers, work
Scrum fosters discipline and makes ing the software and providing the final release process with the goal on the solution construc-
defects (in software as well as in the pro- product to the customer. Build manage- of integrating the activities are flexible and open tively and with shared goals.
cess) visible. But Scrum is too abstract to ment (comprised of compiling scripts, of colleagues and the work to change. The agile testing matrix
be applied “out of the book.” You must packaging components, and distributing items others produce. This (see Figure 2) defines test
implement and adopt it for software en- components) is essential for agile ALM. can result in a build ecosys- quadrants, which are inte-
gineering. Implementation practices, for Technical release management tem in which a new-code grated and aligned using the
instance, might include distinguishing includes activities to identify configura- commit directly triggers a continuous outside-in and barrier-free approach to

between special development phases, tion items, track and audit changes to build, including compilation, technical software development.
on a micro level, inside a Scrum release. requirements and configuration items, tests, audits, packaging, functional tests, The main drivers of the outside-in
Here are some examples: and integrate and deliver the imple- and deployment. approach are
■■ Opening the release with an interval mentation. In software engineering, All different artifact types, platforms, ■■ Understanding your stakeholders and

to write acceptance tests change is more the rule than the excep- and languages (for example, Java, the business context
■■ Opening the release with an interval tion. Because requirements change, it Groovy, Scala, PHP, COBOL, and others) ■■ Mapping project expectations onto

to get more-detailed requirements is important to keep the requirements should be integrated using a unified tool outcomes more effectively
■■ Closing the release with a frozen zone in sync with their implementations. infrastructure. If no native build system ■■ Building more-consumable software,

that allows developers to work only on Possible gaps between functional and exists for a respective language or plat- making systems easier to deploy
bug fixes, not on new features technical release management should form, non-native build technologies can and use
be bridged. Strategies such be used to include these artifact types in ■■ Enhancing alignment with stakeholder

as version control system the CI farm. goals continuously

AND MANUAL (VCS) hooks help marry both One tool that can serve as your central Acceptance tests determine whether
parts of release manage- tool hub is the build engine Hudson. a system satisfies its specified accep-
Q2 Q3 ment. A leading tool that Integrating Hudson with the tool Mylyn tance criteria, which helps customers
ACCEPTANCE TESTS EXPLORATORY TESTS supports technical release results in a tool chain that spans differ- decide whether to accept the software.
BEHAVIOR-DRIVEN USABILITY TESTS management is Maven. With ent project roles and activities. Then, the This means that acceptance tests also

Maven, the dependencies work on artifacts is traceable, starting tell the programmers what the customer

OUTSIDE- IN between your Java artifacts with the source code in the developers’ doesn’t want them to do.
COLLABORATIVE become visible. workspaces on up to tasks (work items) Executable specifications allow you to
Q1 Q4 in your ticket system. use tools that read the specifications
UNIT TESTS PERFORMANCE TESTS Automation and Using a component repository such automatically (either after manually
COMPONENT TESTS LOAD TESTS Continuous Integration as Nexus helps to differentiate between starting the process or continuously
BEHAVIOR-DRIVEN Automating manual steps source code and Java binaries, and as part of a CI process); process them blog
involves delivering results in the repository operates on binaries against the system under test; and out-
AUTOMATED AUTOMATED an objective and reproducible separately—for example, through stag- put the results in an objectively measur-
way. Automating the most ing binaries from one test environment able, efficient, and readable way. The do-
Figure 2 error-prone, repetitive, and to another environment. main expert specifies the tests in simple
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

formats (for example, based on HTML tools to write acceptance tests, or you
package alm
or Microsoft Excel), and the program can use specialized languages. Scala
writes the results after running the tests and Groovy, both first-class citizens on
import org.specs2._
against the system under test. the Java Virtual Machine (JVM), offer import matcher.ThrownExpectations

Describing requirements in an ex- interesting features for setting up a import specification.Step
ecutable way fosters the barrier-free polyglot ecosystem and leveraging exist- import Thread._
approach. Merging different documen- ing platforms by providing solutions import org.openqa.selenium.WebDriverBackedSelenium
tation mediums (single-sourcing prod- that involve special-purpose languages.
class Selenium2 extends Specification with ThrownExpectations {
uct information) reduces the amount of With Scala and Groovy, you can write
traditional documentation, because the tests, which helps to overcome
lazy val selenium = new WebDriverBackedSelenium(new org.openqa.selenium.
specification is the system’s functional ■■ Barriers between project phases and
firefox.FirefoxDriver(), "")
documentation and, therefore, can be project activities (because coding and

efficiently validated against the current testing move together more closely) def is =
software state. This leads to living docu- ■■ Barriers between artifact types sequential ^
mentation that is always up to date. (because code and executable speci- "This specification smoke tests HotBot search" ^
Step(() => selenium) ^
fications are written on the same uni-
"Enter search token and check the title of the SERP" ! acc^
Behavior-Driven Development fied infrastructure)
Step(selenium.stop()) ^
Behavior-driven development (BDD) ■■ Barriers between project roles
promotes a special approach to writing (because tests are written collabora- def acc = {
and applying acceptance tests that is tively, with mechanisms to use terms import selenium._

different from the traditional test-driven close to the problem domain) open("/")
development (TDD), although BDD also ■■ Barriers between tools (because the `type`("search-Input", "Agile ALM")
promotes writing tests first. same tools are used for programming
getTitle() must startWith("Agile ALM")
With BDD, tests are like functional and testing)
specification stories, normally in a Overcoming common project barriers }
“given/when/then” format. This leads to what I call a barrier-free
specification-oriented technique also approach. The example shown in
uses a natural lan- Listing 1 gives you an impression of See listing as text
AGILE BENEFITS guage to ensure what it can look like to write BDD-
Agile ALM cross-functional com-
munication and to
flavored acceptance tests with Scala
and the Scala specs2 library. Summary languages, and tools to improve software
improves product ensure that business The code in Listing 1 integrates the Agile ALM provides more structure for ag- development practices. </article>
quality, reduces concepts are under- Web application test system, Selenium2, ile software development and helps you
time to market, stood. BDD provides a
ubiquitous language
to smoke test the HotBot Web search.
The defined is method lists specifica-
approach ALM in a determined, pragmat-
ic way. Using an agile approach to ALM
and makes for analysis and em- tion fragments that can be simple text can increase productivity and enhance • Agile ALM (Manning Publications, 2011) blog
for happier phasizes application (a description of the target system) or an results. Streamlining Java development • A Guide to Software Configuration
Management (Artech House, 2000)
developers. behavior over testing.
You can use dedi-
example (including executable code that
returns a result). Fragments are sepa-
with agile ALM integrates various prac-
tices (such as continuous integration and • Configuration Management Principles
cated, lightweight rated and linked by the ^ character. writing acceptance tests collaboratively), and Practice (Addison-Wesley, 2003)
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

Understanding the Hudson Plug-in
Development Framework: Part I

Use the Hudson Plug-in Interface tool to create, build, run, and debug custom plug-ins that extend Hudson
WINSTON PRAKASH AND to meet the specific needs of your projects.

BIO his article is for beginners who to extend Hudson’s functional- Tip: The HPI tool is a Maven Tip: Maven might throw the fol-
are interested in understand- ity. The Hudson Plug-in Interface plug-in. Hudson extensively uses lowing error:
ing the fundamentals of Hudson (HPI) tool helps developers create, Maven, another popular open
plug-in development. Hudson is build, run, and debug plug-ins. source software project manage- [ERROR] No plug-in found for
a popular open source continuous This article is Part 1 of a two- ment and comprehension tool, prefix 'hpi' in the current
integration (CI) tool written purely part series and covers the follow- which can be downloaded from project ..
in Java. Apart from being an open ing topics:
source product, the popularity of ■■ Creating a Hudson plug-in Generating the skeleton plug-in. If it does, add the following en-

Hudson is due to its extensible using the HPI tool The first step is to create the try in the ~/.m2/settings.xml file:
nature, which uses plug-ins and ■■ Extending a Hudson exten- skeleton plug-in, which is a
the plug-in developer ecosystem. sion point to provide a custom bare-bones plug-in. The follow- <plug-inGroups>
Plug-ins allow developers to do implementation ing simple command tells Maven <plug-inGroup>org.jvnet.hudson.
everything from customize the Part 2 will cover the following to create the Hudson plug-in tools</plug-inGroup>
way builds are done and results topics: skeleton’s source code using the </plug-inGroups>
are displayed to enable integra- ■■ Writing a configuration for a HPI tool:
tion with application lifecycle Hudson extension The name of the generated
management (ALM) systems such ■■ Adding a global configuration mvn hpi:create folder depends on the value you
as software configuration man- for a Hudson extension entered for the artifactId. The file
agement (SCM), testing Maven downloads all the structure of the generated folder
and analysis tools, and POPULAR TOOL Creating and Tuning a required software to execute the will have the following layout:
so on. More than 400 Hudson’s Hudson Plug-in command and prompts you for ■■ pom.xml: The Maven Project

Hudson plug-ins, sup-

porting various aspects
popularity First, we’ll look at how to
create a Hudson plug-in
the groupID and artifactID. Object Model (POM) file, which
is used to build the plug-in
of CI, are available for is due to its using the HPI tool, create Enter the groupId of your plug-in: ■■ src/main/java: The folder that blog
free installation. extensible and run a project for the org.sample.hudson contains the Java source files
Hudson provides a
series of extension points nature. plug-in, and view the
plug-in in action on the
Enter the artifactId of your
for the plug-in
■■ src/main/resources: The folder

PHOTOGRAPH BY BOB ADLER that allow developers Hudson test server. sample-plug-in that contains the Jelly UI
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

framework’s view files for the plug-in the results of the implementation pro-
■■src/main/webapp: The folder that con- vided by the plug-in developer for an
tains static resources for the plug-in, extension point by running the follow-
such as images and HTML files ing command:

Building and running a plug-in project.
The next step is to build a project for mvn hpi:run
the plug-in by running the following
command: Because the plug-in project is a
Maven project, the configuration of the
mvn package project is defined in the pom.xml file.
The Maven goal hpi:run is responsible
The project that is created is minimal, for performing several tasks, including Winston Prakash and Susan Duncan discuss Hudson
while onsite at JavaOne 2011.

but it is a complete Maven project. It can starting the Jetty server, adding Hudson
be run without any modification using as a Web application to that server, and
Maven. installing the plug-in to Hudson.
The package command tells Maven to The work subfolder under the plug-in plug-in without packaging the plug-in It's easy to see HelloBuilder in action by
build the project and create an HPI pack- project folder is used as Hudson Home. as a .hpi package, which makes it easy to creating a simple Hudson project—for
age that can be installed directly to a The work/plug-ins folder contains a list of do debugging during development. example, TestProject—and then config-
Hudson server. .hpi files corresponding to various bun- Once the plug-in project has been uring HelloBuilder.
The skeleton plug-in project has a dled plug-ins. The only notable excep- run successfully and the Jetty server has You can add HelloBuilder as a builder to

sample extension, which is fully func- tion is the .hpl file, which corresponds to been started, you can view the Hudson TestProject by using a drop-down menu
tional. You can run the project and see the plug-in project being run. main page by pointing a browser at the in the Build section of the configura-
The .hpl file is a following address: tion page. After you add HelloBuilder as a
simple text file that builder for the project, the Build section
contains metadata http://localhost:8080 shows HelloBuilder as one of the builders.
describing all the The task of HelloBuilder is to print the
items (classes, JAR Examining the sample extension. As message Hello <name> to the console
files, and resources) mentioned previously, the hpi:run com- log, so enter a name in the provided
associated with mand installs the plug-in to Hudson and Name text box.
the currently built adds the plug-in to the Jetty server as a Because HelloBuilder is set as the only
Hudson plug-in. Web application. This plug-in does the builder of the TestProject project, when
Figure 1 This file is gener- following tasks: you start a build, HelloBuilder is asked
ated by the HPI ■■ Adds an extension to the Hudson to perform its task. Once the build is
tool every time the Builder interface. This sample custom completed, you can view the result of
plug-in project is builder is called HelloBuilder, and it HelloBuilder in the build console output.
run by the hpi:run does not do anything fancy. It simply blog
command. Hudson prints the text Hello <name> to the Extending the Builder Extension Point
knows how to build console log. Now let’s look at some of the code that
interpret this file ■■ Provides a UI for configuring the extends the builder extension point so
Figure 2 and load the entire HelloBuilder extension. you understand how to do the following:
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

■■ Extend an extension point. Hudson for contributing to the Builder
public boolean perform(AbstractBuild<?, ?> ab, Launcher launcher,
■■ Implement the methods to extend runs step is aptly called Builder.
BuildListener bl) throws InterruptedException, IOException;
the functionality encapsulated by an Hudson comes bundled with two of the
extension point. most-popular builders: Ant and Maven.

Hudson provides the concept of They are in fact extensions to the Builder
extension points and extensions to facili- extension point. So it is possible for a
tate using plug-ins to add functionality plug-in to provide its own builder exten-
to the core platform. Extension sion as one of the builders of the job.
points are interfaces that Several external plug-ins
encapsulate entry points to exist for other popular build-
extend the functionality of a ers, such as Make, Gradle, See all listings as text
service provided by the Hudson provides Rake, and so on. HelloBuilder,
the concept of

core platform. our example builder exten-
Among the various services sion, is a contrived example class Builder, which is the extension cess to three objects:
provided by Hudson, the extension points to demonstrate how exten- point for the Hudson Builder interface. ■■ Build: An object representing the build

foremost is building a job. A and extensions sions are built. Far more- of the job being performed. Build in
job is a buildable project that
consists of several configu-
to facilitate using sophisticated builder exten-
sions are possible using the
public class HelloWorldBuilder
extends Builder {
turn provides access to important
model objects, such as the following:
rable areas and build steps. plug-ins to add Builder extension point. Let's ■■ Project: The buildable job

The following are some of the functionality to the examine the source code to The Builder class itself is a subclass ■■ Workspace: The folder where the

build steps:
■■ SCM checkout: Based on
core platform. understand how the exten-
sion mechanism works.
of BuildStep, which defines the abstract
method that needs to be implemented
build happens
■■ Result: The result of the build up to

the SCM type, the source Tip: Even though in this ar- by the extension to contribute to the this build step
code is checked out. ticle the sample extension is Builder interface. The abstract method ■■ Launcher: An object that is used to

■■ Prebuild: This step is in- referred to as HelloBuilder, the that needs to be implemented by any launch the build of this job
voked to indicate that the build Java class corresponding to it is called builder extension is shown in Listing 1. ■■ BuildListener: An interface for com-

is starting. BuildStep.perform(..) overridden by municating the status of the build

■■ Build wrapper: This step prepares an Examining the HelloBuilder extension. HelloBuilder will be called by Hudson to steps being performed by this builder
environment for the build. In order for Hudson to understand a include the BuildStep functionality ex- and for sending any console messag-
■■ Builder runs: This step causes the class as an extension, you must do tended by the HelloBuilder extension. es from the build steps to Hudson
actual building to occur, much like the following: Finally, to tell Hudson the class is HelloBuilder uses the BuildListener
calling Ant or Make. ■■ Extend a class that advertises itself as an extension to some extension point, model object to print the Hello message
■■ Recording: This step records the an extension point you must annotate the class with the to the console, as shown in Listing 3.
output from the build, such as ■■ Implement the required abstract @Extension annotation. In Listing 2, the listener.getLogger() gets the logger from
test results. methods to extend the functionality @Extension annotation at the inner class the BuildListener object whose output
■■ Notification: This step sends out noti- ■■ Tell Hudson that the particular class is DescriptorImpl tells Hudson the class is goes to the console. The code simply blog
fications that are based on the results an extension an extension. prints Hello <name> via the logger.
determined so far. Looking at the source code for Examining the BuildStep.perform(..) Modifying the HelloBuilder perform(..)
Builders are responsible for building, you can see that abstract method. The BuildStep method. Because the BuildStep
jobs. The extension point provided by the class HelloWorldBuilder extends the .perform(..) abstract method provides ac- .perform(..) method provides access to
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//java architect /

the Launcher object, it is easy to your external executable. Send the
■■ Use the Launcher object to execute an
List<Cause> buildStepCause = new ArrayList();
console output of your execution to
buildStepCause.add(new Cause() {
external executable. Hudson, as shown in Listing 7.
public String getShortDescription() {
■■ Send the results of the execution to Launcher correctly launches the ap- return "Build Step started by Hello Builder";

the console. plication in the master or slave node the }
These tasks are done by adding the job is running. });
code shown in Listing 4 to the BuildStep Always use the return status of the listener.started(buildStepCause);
.perform(..) method. Launcher to find out whether the ArgumentListBuilder args = new ArgumentListBuilder();
if (launcher.isUnix()) {
Running the plug-in project again execution was successful. The standard
shows the console output shown in output of the Launcher is hooked to the
Listing 5. listener. This sends console output from } else {
If there is an error, the exception cor- the execution to Hudson, and this is args.add("dir"); //Windows

responding to the error is displayed, as how the output of the command to list }
shown in Listing 6. the user directory is displayed in the
Analyzing the HelloBuilder perform(..) build console. String homeDir = System.getProperty("user.home");
method. The code added to perform(..) ■■ Notify Hudson of any failure of the

is contrived, but it explains some of the Build step, as shown in Listing 8.

try {
important concepts. For example: The StackTrace of the exception is int r;
■■ When a build step is started or sent to Hudson via Exception r = launcher.launch().cmds(args).stdout(listener).join();
stopped, let Hudson know about it. .printStackTrace(listener.fatalError(..)). if (r != 0) {

This is done via the Job Build Listener listener.finished(Result.FAILURE);
interface. Summary return false;
The Hudson Continuous Integration
} catch (IOException ioe) {
listener.started(buildStepCause); Server is a popular open source project
ioe.printStackTrace(listener.fatalError("Execution" + args + "failed"));
.. that recently became a technology proj- listener.finished(Result.FAILURE);
.. ect at Eclipse Foundation. It is supported return false;
listener.finished(Result.SUCCESS); by an ecosystem of plug-in developers } catch (InterruptedException ie) {
who develop plug-ins for various aspects ie.printStackTrace(listener.fatalError("Execution" + args + "failed"));
It is important to inform Hudson for of the Hudson CI system. listener.finished(Result.FAILURE);
return false;
two reasons: The Hudson plug-in development
■■ Hudson heuristically shows the environment provides a rich set of
progress of the overall build of extension points with which plug-in
the job. developers can develop custom plug-ins.
■■ When a build step fails, Hudson This article explored the fundamentals of See all listings as text
must stop the overall progress of the plug-in development environment
the build and mark the build as by explaining the various steps involved blog
FAILED. This is done by sending a in developing a simple plug-in using describe how to use the Jelly UI frame-
message to Hudson about the sta- Hudson’s HPI tool. work for configuration, and show how
tus of the build via BuildListener. Part 2 of this series will explore ways to create a global configuration for an • Hudson Website
■■ Use the Launcher interface to launch to configure the extensions in a plug-in, extension. </article> • Maven Website
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
Oracle Technology Network: Oracle Technology Network is the world’s largest community
of developers, administrators, and architects using Java and
Your Java Nation. other industry-standard technologies with Oracle products.
Sign up for a free membership and you’ll have access to:
Come to the best place to collaborate with
other professionals on everything Java. • Discussion forums and hands-on labs
• Free downloadable software and sample code
• Product documentation
• Member-contributed content

Take advantage of our global network of knowledge.


Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners. 11060728
JavaFX 2.0
Shock the Senses
Oracle’s Nandini Ramani talks with Java Magazine about the key

features of JavaFX 2.0. BY MICHAEL MELOAN

avaFX 2.0 is Oracle’s
premier development
environment for rich
client applications.

Designed to leverage
Java’s APIs and cross-
platform flexibility, JavaFX
2.0 provides state-of-the-
art solutions for creat-
ing optimal UIs. Nandini
Ramani, vice president of
Java client development at
Oracle, discusses how this
new Java technology will
help developers to build
advanced systems.

Java Magazine: What are the goals for JavaFX 2.0?

And what advantages does it offer system archi-
tects and developers? blog
Ramani: JavaFX 2.0 is a major modernization for
client-side developers. At the top of the stack, we
have more than 6,500 new APIs for building graph-
PHOTOGRAPHY BY BOB ADLER ically rich, compelling user interfaces. These APIs
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
RICH HISTORY Nandini Ramani (center)
and members of the
JavaFX 2.0 reflects JavaFX 2.0 team discuss
years of rigorous

new capabilities.

testing, and cross- include everything from the ability to play
audio and video, to user interface controls
JavaFX 2.0 can be run standalone, in the
browser, or using Java Web Start. Will you
downloading from a central Web location,
and it handles updates automatically.
platform capability. and layout containers, to a scene graph and describe application areas best suited to each Java Magazine: What strengths does JavaFX
animation libraries, to observable collections of these options? 2.0 offer over Adobe Flash or Microsoft
and UI binding. At the bottom of the stack, Ramani: The standalone mode is appropri- Silverlight?
we have a new windowing library and hard- ate when higher control on the runtime Ramani: First and foremost, JavaFX 2.0 is
ware accelerated graphics library. environment is appropriate. The application built on top of the Java platform, so it reflects
The industry is moving toward multicore is launched from a client-side JAR file, or all the years of rigorous development, testing,
multithreading platforms with GPUs [graphics perhaps bundled as a traditional OS-specific and cross-platform capability that Java brings
processing units], and JavaFX 2.0 leverages executable by using existing third-party tools. to the table. It’s hosted on the efficient and
these attributes to improve execution efficiency When executing in the browser, the JavaFX widely available Java Virtual Machine. Many
and UI design flexibility. Our initial goal is to application is embedded in a Web page using users of JavaFX 2.0 will already be using Java
give architects and developers of enterprise the traditional plug-in model. With Java Web EE for back-end processing, so JavaFX on
applications a set of tools to help them build Start, the application is run on the desktop, the front end allows them to utilize existing blog
better business applications, dashboards, but it’s initially downloaded from the Web, skill sets, tooling, and infrastructure. Every-
richly animated UIs, and mashups that inte- and like a Web application, it can be updated thing they apply to back-end development
grate different Web-based datasources. every time the application is run. This sim- becomes applicable on the front end. In
Java Magazine: Software developed using plifies deployment and update logistics by addition, Java has the largest and strongest
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
ecosystem in terms of third-party libraries shading, or any sort of advanced graphics, Java Magazine: Is HTML5 part of the JavaFX
around. Being able to leverage that kind of hardware acceleration can offer a huge payoff 2.0 landscape?
support for developing client applications is in system responsiveness. And when ap- Ramani: HTML5 technologies are still under
a big plus. plications need to build tables and display development by the W3C. But support for

Java Magazine: Can languages like JRuby, large data sets, Prism can also be valuable. HTML5, as defined today, is built into JavaFX
Scala, and Groovy interoperate with The Prism/Glass combination eliminates the 2.0. Our Web component is based on WebKit,
JavaFX 2.0? need to instantiate and load Swing and AWT which supports HTML5. Many developers are
Ramani: Absolutely. Just as you can run any of classes, which gives JavaFX 2.0 a definite already using WebKit-based browsers. Possi-
these languages on top of the Java platform, performance advantage. ble future developments, like offline storage,
they also all interoperate with JavaFX 2.0. In Java Magazine: How will FXML, the JavaFX 2.0 Web SQL databases, native drag-and-drop,
fact, there’s a project in the Groovy commu- XML-based markup language, add value for and geolocation, will be of interest as they
Watch Introducing nity called GroovyFX, which uses the Builder developers? And will you describe how Scene evolve. We plan to stay in sync with HTML5.
JavaFX 2.0

design pattern for JavaFX applications. Most Builder will be useful for generating FXML? Java Magazine: How do the JavaFX UI control
of this work is being done open source, and Ramani: The fact that FXML is XML-based libraries fit into the JavaFX 2.0 toolset?
many of the language implementers are is a huge advantage from a tools perspec- Ramani: I was a longtime Swing developer
excited about using JavaFX 2.0 technology. tive, because Java IDEs such as NetBeans and myself, and I love its capabilities—a great way
For some Java developers, dynamic scripting Eclipse interoperate easily with XML. Layout to program. But every component in Swing
languages are a vital part of their toolkit, and design for enterprise applications is one of the tends toward rectangular forms. Today, we
JavaFX can seamlessly work with them. trickiest and most-labor-intensive endeavors. need more flexibility. JavaFX 2.0 UI controls
Because JavaFX uses familiar design pat- The visual JavaFX Scene Builder tool mitigates offer the ability to create rounded shapes,

terns, such as POJOs following the JavaBeans the need for hand coding, which is a definite a much wider range of components, and
naming conventions, many of these languages productivity bonus. Also, FXML ties
already have enhanced support for JavaFX into JavaFX Scene Builder in two
right out of the gate. In addition, JavaFX was ways: developers can either pro- COMMUNITY COMMENT
carefully designed with consistent API idioms,
such as event handling, which make it easy for
grammatically make changes and
then generate FXML, or they can “ Making JavaFX open source
is a huge step in the right
other languages to provide syntactic sugar for use JavaFX Scene Builder to design
these APIs. the JavaFX UI components and
direction for this technology. It
Java Magazine: Will you describe an appli- then save them as FXML markup. will enable businesses to use
cation scenario where Prism, the hardware JavaScript can also be seamlessly JavaFX with no fear about
accelerated graphics pipeline, and the new integrated into this scenario. So vendor lockin, and let the community participate
Glass windowing toolkit might offer tangible there’s a great deal of flexibility. and grow the platform in new and innovative
advantages? These tools also allow the use of ways. I have been advocating for this move since
Ramani: Prism handles rasterization and CSS. Once an application is created, the 1.0 release, and am glad that Oracle listened
rendering of JavaFX scenes. It can execute on
both hardware and software renderers. The
a completely new visual look can be
generated without recompilation
to the community and made this possible. ”
—Stephen Chin, a technical expert in RIA technologies and
Glass windowing toolkit is the lowest-level by changing either the style sheet
framework for the JavaFX 2.0 graphics stack— or the FXML code. This is an indus- chief agile methodologist at GXS
it manages timers, surfaces, and windows. try trend, and JavaFX 2.0 provides
When developers need gradients and the toolset.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
LEAPS AND BOUNDS interface that the lambda proposal for

JavaFX 2.0 is a
Java SE 8 requires.
But we don’t have to look to the
leap forward. future for something exciting. JavaFX

2.0 is a leap forward. It offers develop-
Developers can ers the ability to seamlessly mix and

seamlessly mix match Web and media content within

their Java applications using a variety
and match of powerful coding and layout options,

Web and media which can be running inside a browser

or as standalone applications. We
content within believe that a broad range of enterprise

their Java applications will benefit from this multi-
faceted new technology.
applications. Java Magazine: What role will open
source play in JavaFX’s future?
Nandini Ramani and Ramani: At JavaOne, we announced
members of the JavaFX 2.0 skinning via CSS. This new set of powerful Java Magazine: What our intention to submit a proposal to
team discuss the components will allow any developer to build operating systems will be open source the JavaFX platform as a
product’s roadmap. advanced enterprise application interfaces. supported by JavaFX 2.0? new OpenJDK project. We plan to initially

Also, the JavaFX UI controls will be the first Ramani: The first release will support 32-bit contribute the JavaFX UI controls and related
component of JavaFX to be open sourced as and 64-bit versions of Microsoft Windows XP, libraries; other JavaFX components will follow
an OpenJDK project. This will enable devel- Windows Vista, and Windows 7. In addition, in multiple phases. By the time you read this
opers to build their own custom versions of we’ll be releasing a developer preview of the article, we are confident that the OpenJDK
components, which the Swing community JavaFX 2.0 SDK for Mac OS X. A Linux version community will have approved this proposal.
has been doing for many years. will be made available at a later date. You can check the status of the JavaFX project
Java Magazine: Can JavaFX 2.0 code be easily Java Magazine: How will JavaFX evolve on the OpenJDK site. </article>
integrated into existing Swing applications? going forward?
Ramani: Yes, Swing and JavaFX cooperate Ramani: On the client side, we’re trying to Michael Meloan began his professional career writing
well. Within existing Swing applications, you stay in lockstep with the evolution of the IBM mainframe and DEC PDP-11 assembly languages.
He went on to code in PL/I, APL, C, and Java. In addi-
can either add on or embed JavaFX. All Swing Java platform. We will integrate new fea-
tion, his fiction has appeared in WIRED, BUZZ, Chic,
capabilities are retained, but the portions tures as they emerge, like invokedynamic and LA Weekly, and on National Public Radio. He is also a
rendered with JavaFX leverage all the new NIO.2. Two of the biggest enhancements to Huffington Post blogger.
capabilities. For instance, if you want to the Java platform planned for Java SE 8 are
embed a Web browser into your Swing modularization and lambda expressions. LEARN MORE
application, you can do so by embedding JavaFX APIs were specifically designed with blog
• JavaFX home page
the JavaFX WebView. Another option is to both of these features in mind. For example,
• JavaFX 2.0 downloads
rewrite some of the Swing code for JavaFX. the event handling APIs are all designed
It’s a great migration path for existing around SAM [single abstract method] inter- • FX Experience
Swing applications. faces, which happen to be the exact type of • Overview of JavaFX
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//rich client /

JavaFX and Swing Integration

Use the power of JavaFX 2.0 to migrate Swing interfaces to JavaFX.

SIMON RITTER J avaFX 2.0 made its debut at

JavaOne in October 2011 (see
the application.
Note: The source code for the
plication is called StocksMonitor,
and it was created by Hirondelle
are displayed on the screen.
JavaFX uses a scene graph, but as
“JavaFX 2.0 Is Here!” page 3). examples described in this article Systems. It monitors stock mar- long as we can make our JavaFX
BIO JavaFX 2.0 is an advanced Java can be downloaded here. ket trades; displays the data in scene appear to be a Swing com-

UI platform for business and a table; and allows users to cre- ponent, the differences are of no
enterprise applications, and it Important Things to Know ate, edit, and delete portfolios of direct consequence.
represents the next step in the About JavaFX stocks. StocksMonitor is available Thankfully, most of the hard
evolution of Java as a premier rich Because JavaFX 2.0 is a set of through and is work is taken care of by the
client platform. Java APIs, using it for a project distributed under a creative com- JavaFX platform. Included in the
JavaFX 2.0 reduces the learn- within an IDE is simply a matter mons license. JavaFX API is the JFXPanel class.
ing curve for experienced Java of including the JavaFX Runtime The name is a little misleading,
programmers because all that’s file (jfxrt.jar) in the classpath. Integration Basics because this class extends the

required is learning Having done that, you First, let’s look at what’s required Swing JComponent class rather
a new set of APIs and WHAT'S NEXT can go about develop- to treat a JavaFX scene as a Swing than the Abstract Windows
gaining a grasp of use
binding, timeline-
JavaFX 2.0 ing the components
you want to use in your
component. Swing uses a
container-component hierarchy
Toolkit (AWT) Panel class. As
such, we can use this easily in a
based animations, a represents the combined Swing and with layout managers to organize Swing application, but we can’t
scene graph, and so on. next step in the JavaFX application. the way individual components use it in a pure AWT application.
In addition, JavaFX 2.0 Note: For this series
reverses the approach
evolution of Java of articles, we won’t
to Swing and JavaFX as a premier rich delve into the mechan-
This is the first in a
client platform. ics of JavaFX. See the
Learn More section for
series of articles that JavaFX resources.
will show how to mod-
ify an existing Swing-based appli- Sample Swing Application
cation so that the interface can be To demonstrate the power of
migrated from Swing to JavaFX. JavaFX, we’ll use a relatively blog
This series will show how parts of simple Swing application that has
the application can be replaced enough complexity in its com-
gradually with JavaFX to improve ponents but can be easily under- Jasper Potts, the developer experience architect for
PHOTOGRAPH BY BOB ADLER the appearance and usability of stood and modified. The first ap- Java client, talks about the JavaFX 2.0 release.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//rich client /

Listing 1 is a simple example of using need to create a Scene object to hold the
1 public void init() {
this class. Let’s work through the details, parent node reference. When we instan-
2 setSize(300, 200);
because some things aren't obvious. tiate this object, we can also set the size
3 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
In line 8, we instantiate a JFXPanel ob- of the scene in pixels, which will then 4 setLayout(new BorderLayout());

ject, but initially we tell it nothing about be used by the Swing layout manager to 5
what it will contain. That information position the JavaFX component. We also 6 /* Put the JavaFX scene in the middle */
will be provided later. This component set the root node of the scene to be the 7 fxComponent = new SimpleFXComponent(this);
can be added to a Swing Container just graph of objects that will be displayed. 8 final JFXPanel fxPanel = new JFXPanel();
9 add("Center", fxPanel);
as any other Swing component. If we wish to include more than one
To understand how we encapsulate JavaFX scene in our Swing application,
11 /* Construct the JavaFX scene on its own application thread */
the JavaFX scene, we need some details we simply instantiate more JFXPanel 12 Platform.runLater(new Runnable() {
about threads in Swing and JavaFX. objects. To optimize the use of mul- 13 @Override

Swing uses a single event dispatch thread tiple JavaFX scenes, use a single call to 14 public void run() {
(EDT), and JavaFX uses an application Platform.runLater() and have the run() 15 Scene scene = new Scene(fxComponent, 200, 100);
thread. Both effectively do the same method of the inner class perform ini- 16 scene.setFill(Color.BLUEVIOLET);
17 fxPanel.setScene(scene);
thing, which is to process asynchronous tialization for all scenes.
18 }
events that affect the UI (for example,
19 });
button presses, updates to displayed Swing and JavaFX Events 20
values, window resizing, and so on). There is one more basic part of Swing 21 /* Put the Swing button at the bottom */
As a Swing component, the JFXPanel and JavaFX integration that needs to be 22 changeButton = new JButton("Change JavaFX Button");

object must be accessed only from the addressed, which is how the compo- 23
Swing EDT. The only exception to this is nents interact when a Swing component 24 ...
the setScene() method, which must be triggers a change in a JavaFX scene or
26 add("South", changeButton);
accessed from the JavaFX application vice versa. If the JavaFX scene wants to
27 setVisible(true);
thread. interact with Swing components, the 28 }
In order to set the scene for the code must be wrapped in a Runnable
JFXPanel object, we must create another object and placed on the EDT using the
object that implements the Runnable in- SwingUtilities.invokeLater() method, as See all listings as text
terface, which can then be posted to the shown in Listing 2.
event queue and executed at some (un- For the opposite case, where a Swing
specified) time in the future. We use the component needs to interact with a only a few more lines of code than application to add exciting new
static utility method, runLater(), provided JavaFX scene, the code must again be using a normal Swing component. components that are created using
in the Platform utility class, and then an wrapped in a Runnable object, but this Having the JavaFX scene and Swing JavaFX. </article>
anonymous inner class to instantiate the time it must be placed on the JavaFX components interact is also straight-
Runnable object. Due to the inner class application thread using the Platform forward. You just have to remember to
restrictions, the reference to the JFXPanel .runLater() method, as shown in Listing 3. wrap the necessary code in a Runnable blog
must be made final. object and place it on the correct
• Documentation and tutorials
The initFXComponent() method is Conclusion queue for execution.
where the real JavaFX work happens. So far, we’ve seen that adding a JavaFX In the next article, we’ll take this • API documentation (Javadoc)
Because JavaFX uses a scene graph, we scene to a Swing container requires knowledge and start to modify our Swing • JavaFX Showcase
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//rich client /

Using Transitions for Animation
in JavaFX 2.0

Animate the nodes in your scene the easy way.

J avaFX 2.0 is an API and run- commonly used animation tasks. rectangles, and a circle

time for creating rich internet These classes are located in the that you’ll animate a
applications (RIAs). JavaFX was javafx.animation package. This little later.
introduced in 2007, and version article contains an example of The TransitionExample
2.0 was released in October 2011. using the TranslateTransition class project that you’ll
One of the advantages of JavaFX to animate a node, moving it back download in the next
2.0 is that the code may be writ- and forth between two positions section contains starter
ten in the Java language, using in the UI. code for this example,
mature and familiar tools. This and it has an appear-

Figure 2
article focuses on using JavaFX Overview ance at runtime similar
2.0 transitions to animate visual To help you learn how to use the to Figure 2. During the
nodes in the UI. TranslateTransition class, an exam- course of this article,
JavaFX comes with its own ple named TransitionExampleX you’ll modify the code
transition classes, shown in will be employed. As shown in to implement the ani-
Figure 1, whose purpose is to Figure 2, this example contains mated behavior of the
provide convenient ways to do a couple of buttons, a couple of TransitionExampleX
project, which is
also available in the
download. Figure 3
When you click the
Play button, the text on Obtaining and Running the
the button changes to “Pause,” TransitionExample Example
as shown in Figure 3, and the ball 1.  Download the NetBeans
moves back and forth between project that includes the
the paddles indefinitely. TransitionExample program. blog
Clicking the Pause button 2.  Expand the project into a
causes the animation to pause directory of your choice.
and the text on the button to 3.  Start NetBeans, and select
STEVE GRUBMAN Figure 1 change to “Play.” File -> Open Project.
This is an update to an article that was originally published on Oracle Technology Network (July 2011). 38
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//rich client /

4.  From the Open Project dialog box, 5.  To run the application, click the Run
transition = TranslateTransitionBuilder.create()
navigate to your chosen directory and Project icon on the toolbar, or press
// TO DO: Insert code to set the duration to 1500 milliseconds
open the TransitionExample project, the F6 key. The Run Project icon has
as shown in Figure 4. If you receive the appearance of the Play button on .node(ball)

a message dialog stating that the a DVD player, as shown in Figure 5. // TO DO: Insert code to set the fromX property to 0
jfxrt.jar file can’t be found, click the The TransitionExample application
Resolve button and navigate to the should appear in a window, as shown in // TO DO: Insert code to set the toX property to 440
rt/lib folder subordinate to where you Figure 6.
installed the JavaFX 2.0 SDK. You’ll notice that clicking the Play
// TO DO: Insert code to set the autoReverse property to true
Note: You can obtain the NetBeans and Stop buttons has no effect. Your
IDE from the NetBeans site. mission will be to add code that imple- .cycleCount(Animation.INDEFINITE)
ments the behavior de- .build();

scribed previously. Here
are steps you can follow to
implement this behavior:

Step 1: Create a
TranslateTransition See all listings as text
Instance to Animate
the Node

To cause the ball to move cluding the TranslateTransitionBuilder RectangleBuilder, SceneBuilder, and
(also known as translate) class shown in Listing 1. VBoxBuilder.

between two different Go ahead and fill in the lines indicated
positions in the scene, we’ll by the “TO DO” comments, so the code Step 2: Define an Event Handler in the
create an instance of the in Listing 1 turns into the code shown in Play Button
Figure 4 TranslateTransition class. Listing 2. To make the TranslateTransition start,
Take a look at the code in the There are many builder classes in pause, and stop, you’ll define event han- the JavaFX API, and their purpose is to dlers in the buttons that call the appro-
Figure 5 file in the TransitionExample enable a declarative style of program- priate methods on the TranslateTransition
project, which shows ming to create and set the properties object. For example, the starter code in
the starter code for this of objects. For example, the code you Listing 3 from TransitionExampleMain
example. completed in Listing 2 creates an in- .java contains the builder that creates a
Using the stance of the TranslateTransition class, Button instance for the Play button.
TranslateTransitionBuilder and it populates that instance with As you did before, fill in the lines indi-
class to build properties such as the duration of the cated by the “TO DO” comments, turn-
TranslateTransition. animation and the node in the scene ing the code shown in Listing 3 into the blog
The starter code in graph being animated. As you can see code shown in Listing 4. in, other Using methods of the Animation class to
makes use of builder classes builder classes used in this applica- control the animation. All the transition
Figure 6 in the JavaFX 2.0 API, in- tion include ButtonBuilder, CircleBuilder, classes in Figure 1 are subclasses of the
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//rich client /

Transition class, which is a subclass of to an expression that contains the
String playText = "Play";
the Animation class. The Animation class widthProperty of the Scene.
has methods, such as start() and Note: The excerpt in Listing 6 is for
StringProperty playButtonText =
getStatus(), that control and monitor the demonstration purposes only, because new SimpleStringProperty(playText);

state of the animation. As a result of the the use of layout containers (in the ...
code that you completed in Listing 4, javafx.scene.layout package) is the pre- playButton.textProperty()
when the button is clicked, the status ferred approach for dynamically posi- .bind(playButtonText);
of the animation is ascertained. If the tioning nodes within a scene.

animation status is PAUSED, the play()
method of the anima- Step 3: Define an Event Handler in
JAVA POWER tion is invoked; oth- the Stop Button
erwise, the pause() To finish the TransitionExample, you’ll
One of the See all listings as text

method is called. need to enter some code into the starter
advantages of Using binding to keep code from
JavaFX 2.0 is properties updated.
Property binding is a
shown in Listing 7.
The completed code for the Stop
that the code may very convenient and button event handler is very similar to
be written in the powerful feature of what you’ve already coded in the Play

Java language, the JavaFX API, be-

cause it enables you
button event handler. Go ahead and fill
in the code shown in Listing 8, and run
using mature and

to keep the values of the example.
familiar tools. properties automati-
cally updated. The Conclusion
excerpts from Listing 1 JavaFX 2.0 comes with several transi-
that are shown in tion classes that extend the Transition
Listing 5 bind the textProperty of the class, whose purpose is to animate
playButton to a StringProperty that holds visual nodes in your application. JavaFX
the text to be displayed in the button. also contains many builder classes that
As the value of playButtonText is provide the ability to express a UI in a YOUR
updated by the event handler that you declarative style. Plus, JavaFX has a
coded, the text on the button displays powerful property binding capability in LOCAL JAVA
the updated value.
There is another use of property bind-
which properties may be bound to ex-
pressions to automatically keep them
ing in, which updated. </article> NEEDS YOU
is shown in Listing 6 and demonstrates
how to bind expressions. blog
To keep the buttonsContainer node
horizontally centered in the application LEARN MORE Find your JUG here
window, the layoutXProperty of one of • JavaFX Technology at a Glance
the nodes in the scene graph is bound • JavaFX Documentation
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /

Stress Testing Java EE 6

Use stress testing to identify application server configuration problems,
ADAM BIEN potential bottlenecks, synchronization bugs, and memory leaks in Java EE 6 code.

nit and integration tests are the probability of spotting poten- pure business logic and verifying load tests defined by domain ex-
helpful for the identifica- tial concurrency and robustness the expected behavior with auto- perts, we should realize as much
tion of business logic bugs, but problems. Cache behavior, the mated tests and hard numbers. load as possible using developer-
in the context of Java Platform, frequency of Java Persistence API driven stress tests. The goal is not
Enterprise Edition 6 (Java EE 6), (JPA) OptimisticLockException, and Don’t Be Realistic to verify expected scalability or
they are meaningless. Both inte- the amount of memory needed in Load tests are configured by tak- performance. Instead, it is to find
gration and unit tests access your production can also be evaluated ing into account the expected bugs and learn about the behavior
application in a single-threaded easily with stress tests. number of concurrent users and of the system under load.

way. After the deployment, how- Even in the unlikely case of a realistic user behavior. To meet
ever, your code will always be perfect application without de- the requirements, “think times” Stressing the Oracle
executed concurrently. fects, your application server will need to be kept realistic, which My “oracle” application records
typically be unable to handle the in turn reduces the amount of predictions and returns them as a
Stop Talking, Start Stressing load with default factory settings. concurrency in the system. The JavaScript Object Notation (JSON)
It is impossible to predict all non- Stress tests are a heavier the load, the string. (For more information on
trivial bottlenecks, deadlocks, and perfect tool to learn BUG SPOTTER easier it is to find the “oracle” application, see “Unit
potential memory leaks by having the behavior of your Java EE 6 applications problems. Realistic Testing for Java EE.”)
theoretical discussions. It is also
impossible to find memory leaks
application under
load in the first
are always executed load tests are usually
performed too late
Sending a GET request to the
URI http://localhost:8080/
with unit and integration tests. iterations without concurrently. Even in the development oracle/resources/predictions re-
Bottlenecks are caused by locks any stress. Stress- with unrealistic stress cycle and are use- turns a Prediction entity serialized
and I/O problems that are hard test-driven devel- ful only for ensuring as {"prediction":{"result":"JAVA_IS_
to identify in a single-threaded opment is the right
tests, you will learn that nonfunctional DEAD","predictionDate":"1970-01-
scenario. With lots of luck and choice for Java EE. a lot about system requirements are 01T19:57:39+01:00","success":
patience, memory leaks can be
identified with an integration test,
Instead of apply-
ing optimizations
behavior and identify met. They are less
valuable in verifying
"false"}}. Services provided by Java
API for RESTful Web Services (JAX-

but they can be far more easily prematurely, you some bottlenecks or system correctness. RS) are easily stress-testable; you
spotted under massive load. The should concentrate concurrency bugs. Instead of relying need only execute several HTTP
GETTY IMAGES heavier the load, the greater is on implementing on realistic but lax requests concurrently.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /

with the current JDK, you should check Although this colocation is adequate
the VisualVM Website for updates. for the purposes of this article, it blurs
VisualVM is able to connect locally or the results. The load generator should
remotely to a Java process and monitor run on a dedicated machine or at least

it. VisualVM provides an overview show- in an isolated (virtual) environment.
ing CPU load, memory consumption, Sometimes, you even have to run
number of loaded classes, and number distributed JMeter load tests to gener-
of threads, as shown in Figure 3. ate enough load to stress the server. For
The overview is great for estimating re- internet applications, it might be neces-
source consumption and monitoring the sary to deploy the load generators into
Figure 1 overall stability of the system. We learn the cloud.
from Figure 3 that for 1,700 transactions In a stress test scenario, the plain

per second, GlassFish Server Open Source numbers are interesting but unimport-
Edition 3.1 needs 58 MB for the heap, ant. Stress tests do not generate a
67 threads, and about 50 percent of the realistic load, but rather they try to break
CPU. The other 50 percent was con- the system. To ensure stability, you
sumed by the load generator (JMeter). should monitor the VisualVM Overview

Figure 2

The open source load testing tool JavaBeans 3.1 (EJB 3.1) JAX-RS
Apache JMeter comes with built-in HTTP PredictionArchiveResource, delegated to
support. After creating the ThreadGroup the PredictionAudit EJB 3.1 bean, which
and setting the number of threads (and, in turn accesses the database through
thus, concurrent users), an HTTP EntityManager (with exactly one record).
request has to be configured to execute At this point, we have learned only
the GET requests (right-click, select that with EJB 3.1, JPA 2, and JAX-RS,
Sampler, and then select HTTP Request). we can achieve 1,700 transactions per
See Figure 1. second without any optimization. But
While the results can be visualized we still have no idea what is happening
in various ways, the JMeter Summary under the hood.
Report is a good start (see Figure 2). It
turns out that the sample application VisualVM Turns Night to Day
is able to handle 1,700 transactions per GlassFish Server Open Source Edition blog
second for five concurrent users out of 3.1.x and Java DB (the open source
the box. version of Apache Derby) are Java pro-
Every request is a true transaction cesses that can be easily monitored with
and is processed by an Enterprise VisualVM. Although VisualVM is shipped Figure 3
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /


public List<Prediction> allPredictions(){

System.out.println("-- returning predictions");
return this.em.createNamedQuery(Prediction.findAll).getResultList();

See all listings as text

average values. All the lines should be, measure the overhead, every invocation
on average, flat. of the method allPredictions is logged
An increasing number of loaded with a System.out.println invocation, as

classes might indicate problems shown in Listing 1.
with class loading and can lead to an Instead of 1,700 transactions per sec-
OutOfMemoryError due to a shortage ond, we are able to perform only about
of PermGen space. An increasing 800 transactions per second, as shown
number of threads indicates slow, in Figure 5.
asynchronous methods. A ThreadPool Let’s take a look at the VisualVM
Figure 4 configured with an unbounded num- Sampler output shown in Figure 6. More
ber of threads will also lead to an time is spent in ThreadPrintStream

OutOfMemoryError. And a steady in- .println() than in the most expensive
crease in memory consumption can database operation.
eventually lead to an OutOfMemoryError The actual EJB 3.1 overhead is neg-
Figure 5 caused by memory leaks. ligible. The $Proxy285.allPredictions()
VisualVM comes with an interesting invocation is in the very last position and
profiling tool called Sampler. You can orders of magnitude faster than a single
attach and detach to a running Java pro- System.out.println.
cess with a little overhead and measure Having a reference measurement
the most-expensive invocations or the makes identification of potential bottle-
size of objects (see Figure 4). necks easy. You should perform stress
The sampling overhead is about 20 tests as often as possible and compare
percent, so with an active sampler, you the results. Performing nightly stress
can still achieve 1,400 transactions per tests from the very first iteration is
second. As expected, the application desirable. You will get fresh results
spends the largest amount of time com- each morning so you can start fixing
municating with the database. potential bottlenecks. blog

How Expensive Is System.out.println? Causing More Trouble

A single System.out.println can lead to Misconfigured application servers are a
Figure 6 significant performance degradation. To common cause of bottlenecks. GlassFish
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /

Server Open Source Edition 3.1 comes The method JNDIConnector.connect()
WARNING: RAR5117 : Failed to obtain/create connection from connection pool
with reasonable settings, so we can re- became the most expensive method.
[ SamplePool ]. Reason : com.sun.appserv.connectors.internal.api.PoolingException:
duce the maximum number of connec- It even displaced the Reply.fill() method
In-use connections equal max-pool-size and expired max-wait-time. Cannot allocate
tions from the Derby pool to two con- from its first rank. more connections.

nections to simulate a bottleneck. With The package org.eclipse.persistence WARNING: RAR5114 : Error allocating connection : [Error in allocating a connection.
five concurrent threads (users) and only is the JPA provider for GlassFish Server Cause: In-use connections equal max-pool-size and expired max-wait-time. Cannot
two database connections, there should Open Source Edition 3.1, so it should allocate more connections.]
be some contention (see Figure 7). give us a hint about the bottleneck’s
The performance is still surprisingly location. There is nothing wrong with
good. We get 1,400 transactions per the persistence layer; it only has to wait
second with two connections. The max for a free connection. This contention is
response time went up to 60 seconds, caused by the artificial limitation of hav-

which correlates surprisingly well with ing only two connections available for See all listings as text
the “Max Wait Time: 60000 ms” con- five virtual users.
nection pool setting in GlassFish Server A look at the JNDIConnector.connect
Open Source Edition 3.1. A hint in the method confirms our suspicion (see in-use connection becomes free or the GlassFish Server Open Source Edition
log files also points to the problem, as Listing 3). In the method JNDIConnect Max Wait Time is reached. The method 3.1 exposes its monitoring and man-
shown in Listing 2. .connect, a connection is acquired from a can block up to 60 seconds with the agement data through an easily acces-
Also interesting is the Sampler view in DataSource. In the case of an empty pool, GlassFish Server Open Source Edition sible Representational State Transfer
VisualVM (see Figure 8). the method will block until either an default settings. This rarely happens (REST) interface.

with the default settings, because the To activate the monitoring, open the
server ships with a Maximum Pool Size GlassFish Admin Console by specifying
of 32 database connections. the Admin Console URI (http://
Figure 7 localhost:4848). Then select Server,
How to Get the Interesting Stuff select Monitor, and then select Configure
The combination of JMeter and Monitoring. Then select the HIGH level
VisualVM is useful for ad hoc measure- for all components. Alternatively, you can
ments. In real-world projects, stress activate monitoring by using the asadmin
tests should be not only repeatable but command from the command line or by
also comparable. A history of results using the REST management interface.
with visualization makes the resul- Now, all the monitoring information is
tant comparison and identification of accessible from the following root URI:
hotspots easier. http://localhost:4848/monitoring/
VisualVM provides a good overview, domain/server. The interface is self-
but the really interesting monitoring explanatory. You can navigate through
information can be obtained only from the components from a browser or from blog
an application server in a proprietary the command line.
way. All major application servers pro- The command curl -H "Accept:
vide extensive monitoring information application/json" http://localhost:4848/
Figure 8 via Java Management Extensions (JMX). monitoring/domain/server/jvm/memory/
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /

usedheapsize-count returns the current busy threads, queuedConnections, errors,
{"message":"","command":"Monitoring Data","exit_code":"SUCCESS",
heap size formatted as a JSON object committed and rolled-back transactions,
(see Listing 4). heap size, and the time stamp. You can
"lastsampletime":1308569037982,"description":"Amount of used memory in
The most interesting key is extract such information from any other bytes","unit":"bytes","name":"UsedHeapSize","starttime":1308504654922}},

usedheapsize-count. It contains the application server through different "childResources":{}}}.
amount of used memory in bytes, as channels and APIs.
described by the description tag. The Listing 6 shows how to access REST
good news is that the entire monitoring services with Jersey. The managed bean
API relies on the same structure and can DataProvider uses the Jersey client to
be accessed in a generic way. access the GlassFish Server Open Source
Edition’s REST interface and convert
Monitoring Java EE 6 with Java EE 6 the JSON result into Java primitives. The

Executing HTTP GET requests from the fetchData method is the core function-
command line still does not solve the ality of DataProvider, and it returns the
challenge. To be comparable, the data populated Snapshot entity.
has to be persistently stored. A periodic Every five seconds, the
snapshot between 1 and 30 seconds MonitoringController @Singleton EJB
is good enough for smoke tests and 3.1 bean shown in Listing 7 asks the
stress tests. DataProvider for a Snapshot and persists
It turns out that you can easily persist it. In addition, the persisted data is ex-

monitoring data posed through REST. You can access all
GO FOR AVERAGE with a simple snapshots using http://localhost:8080/
Java EE 6 stm/resources/snapshots, and you will
In a stress test application. JPA 2, get Snapshot instances as a JSON object
scenario, the EJB 3.1, Contexts (see Listing 8).
plain numbers are and Dependency
Injection (CDI),
Interestingly, a Java EE 6 solution is
significantly leaner than a comparable
interesting but and JAX-RS re- Plain Old Java Object (POJO) implemen-
unimportant. Stress duce the task to tation. Periodic timer execution, transac-

tests do not generate only three classes.

The JPA 2 entity
tions, and EntityManager bookkeeping
are provided out of the box in Java EE 6
a realistic load, but Snapshot holds the but must be implemented in Java
rather they try to relevant moni- Platform, Standard Edition (Java SE).
toring data (see
break the system. To Listing 5). Automating the Stress Test
ensure stability, you The entity Using the StressTestMonitor (STM) blog
should monitor the Snapshot repre-
sents the inter-
application, we can collect application
server monitoring data systematically
average values. esting data, such and persistently, and we can analyze See all listings as text
as the number of and compare the stress test results after
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//enterprise java /

each run. This approach is not perfect, and Execute Stress Tests. You don’t have
though, because both the stress test and to create a shell script or a batch file. The
Event<Snapshot> escalationSink;
the load generator must be started and commands can be executed directly by
stopped manually. Hudson or Jenkins. public void gatherAndPersist(){

A continuous integration (CI) tool, VisualVM can still be used to moni- Snapshot current = dataProvider.fetchData();
such as Hudson or Jenkins, is capable tor the application in real time or em.persist(current);
of automating the whole lifecycle and identify the hot spots. All the relevant if(current.isSuspicious())
can easily deploy STM and start the load monitoring data is persisted in a data-;
generator automatically. base table and can be analyzed easily
Hudson and Jenkins support a peri- after the test.
odic build execution (for example, with
a single configuration tag: @midnight). Nice-to-Haves See all listings as text

With Hudson or Jenkins, setting up a The solution described so far is good
nightly executed stress test only takes enough for getting started. The inter-
minutes. You have to deploy the STM esting parameters, such as JVM and pool data is accessible under http:// in real time, sent using e-mail, or just
application first and launch the stress application server monitoring data, are localhost:4848/monitoring/domain/ aggregated and exposed with JMX.
test generator afterward. For a GlassFish gathered and persisted automatically server/applications/com.abien_
Server Open Source Edition deploy- during a nightly job. Because of JSR-77 TestingEJBAndCDI.war_1.0-SNAPSHOT/ Conclusion: No Excuses
ment, this requires just a single line: (the management and monitoring PredictionAudit/bean-pool. Java EE 6 applications are always
asadmin deploy --force […]/ API), all application servers All the monitoring data is stored in executed concurrently. Even with un-

StressTestMonitor.war. STRESS IS GOOD also provide access to the a single table, which makes the data realistic stress tests, you will learn a
JMeter can also be started
without the GUI in headless
Stress-test-driven statistics of all deployed
Java EE components.
available to tools such as JasperReports
or Eclipse BIRT. Charts and reports are
lot about system behavior and identify
some bottlenecks or concurrency bugs.
mode. It requires another development is Application-specific EJB only a few clicks away. The Snapshot The earlier and more frequently
line: jmeter -n -t predictions the right choice for beans (usually the facade entity is exposed through JSON, stress tests are executed, the more you
.jmx -l predictions.jtl. The to your business logic) can which makes it “consumable” by all will learn about the application’s run-
parameter -n prevents the Java EE. Instead of be monitored using exactly JavaScript and JavaFX applications time behavior. Application server config-
GUI from appearing, the applying optimizations the same mechanism. as well. uration problems, potential bottlenecks,
parameter -t specifies the
configuration file (created
prematurely, you You will get the number
of concurrent requests,
Furthermore, the Snapshot entity is
a Java class and can contain additional
synchronization bugs, and memory
leaks can also be identified during
with JMeter in GUI mode), should concentrate the current number of validation or processing logic. It is trivial stress tests. </article>
and -l specifies the log file, on implementing active instances (and, thus, to escalate “suspicious” Snapshot
which can be analyzed with
JMeter after the test.
pure business the number of concurrent
transactions accessing
instances with CDI events, as shown in
Listing 9.
A Hudson or Jenkins “Free logic and verifying the bean), and business A suspicious Snapshot listener will
• Real World Java EE Night Hacks—
Style Software Project” the expected behavior method runtime statistics,
such as slowest and aver-
only have to implement a method with
Dissecting the Business Tier (2011)
build with two build steps an annotated parameter to receive the
(Execute Windows Shell with automated tests age execution times. event public void onSuspiciousEvent(@ • Sample Java EE testing code on
Command or Execute Shell) and hard numbers. For example, Observes Snapshot snapshot){}. Project Kenai Web page
does the job: Deploy STM PredictionAudit EJB bean All suspicious events can be analyzed • StressTestMonitor application
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//mobile and embedded /

Getting Started with GameCanvas
and the Mobile Sensor API

Learn the concepts behind developing a location-aware game using the Mobile Sensor API.

A s location-aware applica- rather, it introduces the concepts sensor on your phone and broad- The game state is reflected on

tions have become de rigueur, for how to combine location data cast that to the other player so the screen, and the screen is thus
there has been an increasing de- with mobile sensors to make a that her phone can catch it. updated. The loop pauses for a
mand to include location-based game that can be the launching predetermined interval to let the
features in gaming as well. Most pad for a complete game. It in- Understanding Gaming game refresh itself.
smartphones these days support troduces these concepts from a From the simplest coding per- The Java Platform, Micro
the concepts behind location- single player’s perspective. spective, gaming is the art of Edition (Java ME) API provides five
aware games and applications, Note: The source code for the repeatedly executing the same classes that help with the devel-
and Java is not behind in this re- game I develop in this two-part piece of code and updating screen opment of games: GameCanvas,

spect. The Location API, JSR-179, series can be downloaded here. variables depending on the user’s Layer, Sprite, TiledLayer, and
provides all the nuts and bolts you (and game engine) input. A loop LayerManager. All these classes are
need, so it is quite easy to incor- The Game for repeatedly executing code is in the
porate location-based features The idea behind the game that I required in order to do the same package and provide attributes
in your games. For a quick over- develop in this two-part series is thing over and over again until and properties over and above the
view of this API, see my article on simple. There is a red ball on the something in the gaming envi- normal classes.
gaming basics. screen (see Figure 1), and you, as ronment changes, due to either
This article is the first article in the first player, have to roll the ball an external event (a player quits,
a two-part series. In this article, left or right. Your friend, who has a for example) or an internal event
I introduce the concepts behind compatible phone and game, has (a time-out interval, for example).
developing a location-aware to “catch” the ball as it falls off The loop checks an instance vari-
game, and I discuss how to use your screen. able to make sure that none of
the Mobile Sensor API, JSR-256. Two things have to be done to those events has happened, and
In Part 2, I will cover the enable this. First, your gaming if none has, the repeated execu-
Location API and explain the con- MIDlet needs to know if there are tion continues.
cepts required for combining loca- other players near you who have The loop checks for game blog
tion data with information from the capability of being a catcher, inputs from the player and the
sensors to make a complete game. while you announce your avail- environment and responds to
PHOTOGRAPH BY This two-part series is not about ability. Second, you need to roll them by updating its own inter-
GETTY IMAGES developing a full-fledged game; the ball using the accelerometer nal variables and the game state. Figure 1
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//mobile and embedded /

In this article, I explain the details of onscreen buffer. Once the drawing to buffer. Each call to getGraphics() returns game confirms that a current loca-
the GameCanvas class, because that is this offscreen buffer is completed, this a new object, so it is prudent to reuse tion for Player 1 is present and then
the only class we use for our example buffer can simply be copied across to the the Graphics object; however, each such sends a request to the server to find
code. For more details on gaming in actual onscreen buffer. The copy opera- newly returned object writes to the same players around that location.

general and on the other classes, refer to tion is not as expensive as the direct offscreen buffer (as mentioned before, 4. The server returns a list of players,
my gaming basics article. rendering operation; hence, the load on each GameCanvas gets its own buffer). along with some unique identifiers.
the CPU is not as intense. This process You can do all normal operations with 5. Player 1 selects a fellow player and
The GameCanvas Class minimizes the flicker that might be pro- this newly returned Graphics object. You requests that the server start the
The Java ME API recognizes that a lot of duced as the CPU completes the copy. can draw rectangles, images, and lines. game with the selected player.
MIDlets will be game-centric and, there- Offscreen buffer in GameCanvas. By All simple 2-D rendering operations can 6. Once Player 1 has requested that
fore, it provides the GameCanvas class. providing an automatic offscreen buf- be implemented. The actual Graphics ob- a game with a selected player be
This class does everything that the nor- fer, the GameCanvas class minimizes the ject has some default characteristics such started, the game should notify the

mal Canvas class does, but it is extended work that is required by the developer as color (black), font (default font), stroke central server and initiate the load-
to provide game-specific attributes, to maintain this buffer. This buffer is style (solid), and so on. You can change all ing of the game on Player 2’s device.
such as an offscreen graphics buffer and the same size as the device’s display of them to suit before rendering is done. 7. After the initial handshake, Player 1’s
the ability to query key status. area. The area that should be copied screen should show the ball in the
The need for an offscreen buffer. Why is across can be limited so that only parts Game Workflow bottom middle of the screen.
having an offscreen buffer important? of the actual screen are modified. This To help you conceptualize the Mobile 8. Then Player 1 can turn his phone left
Because it is an implementation of the process of copying from the offscreen Sensor API use of this game, let’s think or right to move the ball.
double-buffering philosophy that is buffer to the main screen is usually of the workflow for getting this game 9. Behind the scenes, the game should

used to minimize flickering while ren- called flushing. Flushing is implement- started. Writing down the workflow of engage the tilt accelerometer and
dering images in a game on the graph- ed in the GameCanvas class by using the the game should help us design and gather data from it.
ics display. If there were no offscreen flushGraphics() method. Flushing doesn’t code it. 10. If Player 1 is tilting the phone left
buffer, the game would suffer from flick- clean this offscreen buffer; it simply 1. Player 1 starts the game, and the along the y axis, the ball should
er issues, which would make it difficult copies the contents of the buffer to game automatically searches for move left in the x axis (relative to
to play the game. the device screen. Therefore, it is your the current location in terms of GPS its position on the phone screen).
When displaying content responsibility to clean this coordinates. If the location is not Similarly, if Player 1 tilts the phone
on a device’s screen, the WHAT GAMERS WANT buffer before starting to do available, the phone displays a mes- right along the y axis, the ball should
CPU process that is required
for drawing the screen is
As location-aware another rendering opera-
tion; otherwise, the new
sage and the player cannot play.
2. Once the location is found using the
move right in the x axis (relative to
its position on the phone screen).
usually intensive. Hence, applications have rendering operation will specified criteria, the game notifies 11. Once the ball reaches the boundary
if the drawing operation is become de rigueur, mix with or override the the server about the coordinates. conditions of 0 or screen width, the
done very quickly, the CPU
lags. This lag produces a
there has been an previous render.
Access to the actual
The server registers the coordinates
using the phone’s International
server should be notified, and the
waiting Player 2’s screen should
flicker effect. increasing demand graphics element is pro- Mobile Equipment Identity (IMEI) be located.
To minimize this flicker,
the drawing operation is
to include location- vided by the getGraphics()
method of the GameCanvas
number, latitude, and longitude
(and, optionally, the name of Player 1
12. If Player 2 is at the same location
and has tilted the phone at the same

done in an offscreen buffer. based features in class, which returns a as well). tilt, she should be able to “catch”
This buffer is in memory, gaming as well. handle to the Graphics 3. When Player 1 is ready to play a game, the ball. The server should indicate
and it is separate from the object for the offscreen Player 1 presses the Find button. The success or failure accordingly.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//mobile and embedded /

To keep things simple, in the follow- sor, and if it does, we determine whether
// the graphics object for this screen
ing sections I will show you the interac- we can connect to it and receive data
Graphics g;
tions only from Player 1’s perspective. from it, as shown in Listing 2.
The server and Player 2 interactions are If the sensor is not found, then the public TiltCanvas() {

easy to code and conceptualize, so I game cannot be played, and the player
will leave these as an exercise for you. should be informed. When it is found, super(true);
First things first: we need to create our we make a connection to it, and set the
GameCanvas and add the code for the TiltCanvas class as the listener for receiv- SensorInfo sensors[] =
Mobile Sensor API. ing the data from it.
"acceleration", SensorInfo.CONTEXT_TYPE_DEVICE);
The sensor sends the current title of
The TiltCanvas Class the device along the three axes: x, y, and if (sensors == null || sensors.length == 0) {
The TiltCanvas class is responsible for z. Because we only want to know how System.err.println("Nothing found!");

handling game interactions and imple- the player has tilted the device along the } else if (sensors.length > 1) {
menting the Mobile Sensor API code. vertical axis, we use only the y axis data. System.err.println("Too many sensors found!");
Listing 1 shows the constructor. So, if the player tilted the device more } else {
tiltSensor = sensors[0];
The TiltSensor constructor does the than the previous tilt, the ball is rolled to
try {
initialization by opening a connection the right. On the other hand, if the play-
to the sensor for the accelerometer, er tilted the device less than the previous // make a connection to this sensor
and it also loads the basic ball image. tilt, the ball is rolled to the left. Once we connection = (SensorConnection); connection.
Note that it makes a call to the super- have reached the end of the screen, ei- setDataListener(this, 10);

constructor because TiltCanvas extends ther along the left or right side, we notify
GameCanvas. the server with the current data. // load the ball image
ballImage = Image.createImage("/red_ball.jpg");
There are game specifics in this listing
class TiltCanvas extends that I haven’t discussed yet. Listing 3
setupCorrect = true;
GameCanvas implements shows the corresponding code for this } catch (IOException ex) {
DataListener, Runnable class that is responsible for drawing the ex.printStackTrace();
ball depending on the location data it }
We also need to implement the gets from the dataReceived method. }
DataListener interface of the Mobile This is a very standard method for
Sensor API to receive data when the de- a gaming application. The screen is
vice is tilted. Besides this, the Runnable cleared, and based on the current game
interface is implemented to run the data, objects on the screen are redrawn. See all listings as text
code in a thread. In our case, the current position of the
ball is drawn on the screen along the x
Mobile Sensor API Implementation axis, because the y axis is presumed to class. We also saw how to incorporate
In our game, we want a particular type of be constant. the Mobile Sensor API into the specific
sensor. This sensor is universally known game we were building. • “J2ME Tutorial, Part 3: Exploring the
as the acceleration sensor. So, in the Conclusion In the next article, we will learn how Game API of MIDP 2.0”
constructor of our TiltCanvas class we In this article, we discussed the basics of to incorporate the Location API into our • “Working with the Mobile
find out whether the device has this sen- gaming and the need for the GameCanvas game. </article> Sensor API”
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

Polyglot Programming on the JVM

Tips about how and why to choose a non-Java language for your project

T he following is an excerpt
from The Well-Grounded
Java Developer, which Manning
Within the pyramid, you can
see three well-defined layers:
domain-specific, dynamic, and
Publications is due to release in stable. Table 1 shows these three OF THE APPLICATION DOMAIN

January 2012. layers in more detail. RAPID, PRODUCTIVE, FLEXIBLE GROOVY, JYTHON, CLOJURE
The phrase polyglot program- As you can see, there are pat- DYNAMIC DEVELOPMENT OF FUNCTIONALITY
ming on the JVM is relatively new. terns in the layers—the statically CORE FUNCTIONALITY, STABLE, JAVA, SCALA
It was coined to describe projects typed languages tend to gravitate STABLE WELL-TESTED, PERFORMANT

that utilize one or more non-Java toward tasks in the stable layer. Table 1
BENJAMIN J. EVANS AND Java Virtual Machine (JVM) lan- Conversely, the less powerful and
MARTIJN VERBURG guages alongside a core of Java more specific-purpose technolo- However, these same attributes particular feature (for example,
code. One common way to think gies tend to be suited to domain become a burden in the middle superior concurrency support) that

about polyglot programming is roles at the top of the pyramid. and upper tiers of the pyramid; is important to your project. In
as a form of separation of con- In the middle of the pyramid, we for example: most cases, however, you should
cerns. As you can see in Figure 1, see that there is a rich role for lan- ■■ Recompilation is laborious. not throw out working stable layer
there are potentially three layers guages in the dynamic tier. These ■■ Static typing can be inflexible code and rewrite it in a different
where non-Java technologies can languages are also the most flex- and lead to long refactoring stable language.
play a useful role. This diagram ible; in many cases, overlap might times. At this point, you may be asking
is sometimes called the polyglot exist between the dynamic tier and ■■ Deployment is a heavyweight yourself, “What type of program-
programming pyramid and comes either of the neighboring tiers. process. ming challenges fit inside these
from the work of Ola Bini. Let’s dig a little deeper into this ■■ Java’s syntax is not a natural fit layers? Which languages should
diagram and look at why Java isn’t for producing DSLs. I choose?” A well-grounded Java
the best choice for everything on A pragmatic solution is to play developer knows that there is no
the pyramid. to Java’s strengths and take ad- silver bullet, but there are some
SPECIFIC vantage of its rich API and library criteria you can consider when
Why Use a Non-Java Language? support to do the heavy lifting evaluating your choices.
DYNAMIC Java’s nature as a general-purpose, for the application—down in the
statically typed, compiled lan- stable layer. How to Choose a Language blog
guage provides many advantages. If you’re starting a new project for Your Project
STABLE These qualities make the language from scratch, you might also find Once you’ve decided to experi-
a great choice for implementing that another stable layer lan- ment with non-Java approaches
JOHN BLYTHE AND BOB ADLER Figure 1 functionality in the stable layer. guage (for example, Scala) has a in your project, you need to iden-
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

tify which parts of your project best suit coverage and a shortage of developers and porting to a different delivery tech- environment. This can help reduce risk
a dynamic layer or domain-specific layer who fully understand it. nology without too much disruption, if and alleviate any worries they might have
approach. Table 2 highlights some tasks However, there is more to a system it turns out that the attempted technol- about the new solution.
that might be suitable for each layer. than just its core processing. For exam- ogy stack was not a good fit for the team Note: DSLs are typically built using a

There is a wide range of natural ple, this is a situation where better tests or system. dynamic (or, in some cases, stable) layer
use cases for alternative languages. would clearly help. Scala has a great language, so many of them run on the
However, identifying a task that could testing framework called ScalaTest. This Does It Interoperate with Java? JVM via the languages they were built in.
be accomplished with an alternative enables developers to produce JUnit- You don’t want to lose the value of all Some languages interoperate with
language is just the beginning. You now like tests for Java code but without a that great Java code you’ve already Java more easily than others. We’ve
need to evaluate whether using an al- lot of the boilerplate that JUnit seems written. This is one of the main reasons found that most popular JVM alterna-
ternative language is appropriate. Here to generate. So, once they are over the organizations are hesitant to introduce tives have good interoperability with
are some useful criteria that we take initial learning curve, developers can a new programming language into Java. Run a few experiments first to

into account when considering technol- be much more productive at improv- their technology stack. However, with really make sure you understand how
ogy stacks: ing the test coverage. ScalaTest also alternative languages that run on the the integration can work for you.
■■ Is the project area low risk? provides a great way to gradually intro- JVM, you can turn this concern on its Take Groovy, for example. You can
■■ How easily does the language inter- duce concepts such as Behavior-Driven head—so it becomes about maximizing simply import Java packages directly
operate with Java? Development to the codebase. These the existing value in your codebase, not into its code using the familiar import
■■ What tooling and testing support is concepts can really help when the time about throwing away working code. statement. You can build a quick
available for the language? comes to refactor or replace parts of the Alternative languages on the JVM are Website using the Groovy-based Grails
■■ How easy is it to compile, test, build, core—regardless of whether the new able to cleanly interoperate with Java framework and yet still reference your

and deploy software in this language? processing engine ends up being written and can, of course, be deployed in a pre- Java model objects. Conversely, it’s very
■■ How difficult is the learning curve? in Java or Scala. existing environment. This is especially easy for Java to call Groovy code in a
■■ How easy or difficult is it to hire devel- Or, suppose that the operations important when discussing this step with variety of ways and to receive familiar
opers with experience in this language? users would like to have a Web con- the production management folks. By Java objects. One example use case
Let’s dive into each of these areas so sole built so they can administer some using a non-Java JVM language as part of could be calling out to Groovy from Java
you get an idea of the sorts of questions of the noncritical, static data behind your system, you’ll be able to make use of to process some JSON and having a
you need to be asking yourself. the payment-processing system. The their expertise in supporting the existing Java object be returned.
developers already know Struts and
Is the Project Area Low Risk? JavaServer Faces, but they don’t feel LAYER EXAMPLE PROBLEM DOMAINS
Let’s say you have a core, payment- any enthusiasm for either technology.
processing rules engine that handles This is another low-risk area to try out DEV-OPS
more than 1 million transactions a day. a new language and technology stack. BUSINESS RULES MODELING
It is a stable piece of Java software that One obvious choice would be Grails.
has been around for more than seven Developer buzz, backed up by some PROTOTYPING
years, but there are not many tests for studies (including one by Matt Raible), DYNAMIC INTERACTIVE ADMINISTRATIVE/USER CONSOLES
it and there are plenty of dark corners is that Grails is the best available Web TEST-DRIVEN DEVELOPMENT (TDD) AND BEHAVIOR-DRIVEN DEVELOPMENT (BDD) blog
in the code. The core of this engine is framework for productivity. CONCURRENT CODE
clearly a high-risk area for a new lan- By focusing on a limited pilot in a STABLE APPLICATION CONTAINERS
guage, especially because it is running low-risk area, the manager always has
successfully and there is a lack of test the option of terminating the project Table 2
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

Is There Tooling and Test Support? means that the team needs to think cent, and their development teams will rapid Web development for the dynamic
Most developers underestimate the carefully about how to divide up a proj- change throughout the course of a year. layer or modeling enterprise messaging
amount of time they save once they be- ect, especially for deployment of sepa- Some languages, such as Groovy and for the domain-specific layer.
come comfortable in their environment. rate but related components. Scala, are becoming established enough It’s worth emphasizing again that the

Their powerful IDEs, build tools, and test that there is a pool of developers to core business functionality of an existing
tools help them rapidly produce high- Is It Difficult to Learn? hire from. However, a language such as production application is almost never
quality software. Java developers have It always takes time to learn a new lan- Clojure is still finding its way to popular- the correct place to start when introduc-
benefited from great tooling support for guage, and that time only increases if ity and, therefore, finding good Clojure ing a new language. The core is where
years now, so it’s important to remem- the paradigm of the language is not one developers is difficult. high-grade support, excellent test cover-
ber that other languages might not be at that your development team is familiar Again, the reimplemented languages age, and a proven track record of stability
quite the same level of maturity. with. Most Java development teams can potentially help here. Few develop- are paramount. Rather than start here,
Some languages (for example, Groovy) will be comfortable picking up a new ers might have JRuby on their résumés, choose a low-risk area for the first de-

have had long-standing IDE support language if it is object-oriented with a but because it is just Ruby on the JVM ployment of an alternative language.
for compiling, testing, and deploying C-like syntax. there is actually a large pool of develop- Finally, always remember that every
the end result. Other languages might It gets harder for Java developers ers to hire from. team and project has its own unique
have tooling that is not as fully matured as they move further away from this Note: One word of warning about the characteristics that will affect the lan-
yet. For example, Scala’s IDEs are not paradigm. Scala tries to bridge the gap reimplemented languages: Many exist- guage choice. When choosing to imple-
as polished as those of Java, but Scala between the object-oriented and the ing packages and applications written, ment a new language, managers and
fans feel that the functional worlds, but the jury is still out for example, in Ruby, are tested only senior techs must consider the nature of
WHEN TO EVALUATE power and con- on whether this fusion is viable for large- against the original, C-based implemen- their projects and team.

ciseness of Scala scale software projects. At the extreme tation. This means that there might be A small team composed exclusively
There is a wide range more than make end of the popular alternative languag- problems when trying to use them on of experienced propellerheads might
of natural use cases up for the imper- es, a language such as Clojure can bring top of the JVM. When making platform choose Clojure for its clean design,

for alternative fections of the

current genera-
incredibly powerful benefits but can also
represent a significant retraining re-
decisions, you should factor in extra
testing time if you are planning to lever-
sophistication, and power. Meanwhile,
a Web shop that is looking to grow the
languages. However, tion of IDEs. quirement for development teams. age an entire stack written in a reimple- team quickly and attract young develop-
identifying a task that A related
issue is that
One alternative is to look at the JVM
languages that are reimplementations of
mented language. ers might choose Groovy and Grails for
the productivity gains and relatively deep
could be accomplished when an alter- existing languages. Ruby and Python are Summary talent pool. </article>
with an alternative native language well-established languages with plenty For the polyglot programmer, languages
language is just the has developed a
powerful tool for
of available material with which devel-
opers can educate themselves. The JVM
fall roughly into three programming
layers: stable, dynamic, and domain-

beginning. You now its own use (such incarnations of these languages could specific. Languages such as Java and
• The Well-Grounded Java Developer
• Scala in Action (Manning, 2010)
need to evaluate as Clojure’s awe- provide a sweet spot for your teams to Scala are best used for the stable layer
• AspectJ in Action, Second Edition
some Leiningen begin working with an easy-to-learn, of software development, while others,
whether using an build tool), the non-Java language. such as Groovy and Clojure, are more (Manning, 2009) blog
alternative language tool might not suited to tasks in the dynamic or • DSLs in Action (Manning, 2010)

is appropriate. be well adapted

to handle other
Do Developers Use the Language?
Organizations have to be pragmatic;
domain-specific realms.
Certain programming challenges fit
Note: Use code evans0735 to
save 35 percent on your next
languages. This they can’t always hire the top two per- well into particular layers, for example, purchase .
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

JVM Language Summit—
Toward a Universal VM

Oracle’s Alex Buckley talks with Java Magazine about the 2011 JVM Language Summit
and the evolution of the JVM and the Java platform. BY MICHAEL MELOAN

technical directions a fascinating presentation cover-
that began at the ing eclectic territory, including
first JVM Language a wish list of JVM features going
Summit in 2008 are forward, such as tail recursion, tail
now coming to frui- call optimization, continuations,
tion, primarily due properties, class file extensions,
to the availability of and more-intrinsic types, such as
the Java Platform, unsigned integers.

Standard Edition 7 Rémi Forax presented a
(Java SE 7) cookbook of techniques for utiliz-
invokedynamic ing invokedynamic that are ap-
instruction and plicable to many languages. And
method handles Oracle’s Brian Goetz talked about
(JSR-292). how to compile lambda expres-
Alex Buckley, Language imple- sions into JVM bytecode (coming
Specification Lead for menters talked in Java SE 8), in a way that doesn’t
the Java Language and
JVM at Oracle T he JVM Language Summit,
which took place July 18–20,
2011, at Oracle’s Santa Clara
of participants to cross-pollinate
technologies through presenta-
tions and conversations. Alex
extensively about how
they use invokedynamic
to improve speed and
generate extra class
files and that gives the
Java compiler a great
campus, explored the state of the Buckley, specification lead for the efficiency. JRuby, Jython, In many cases, deal of flexibility in how
art in language design and imple- Java language and JVM at Oracle, JavaScript (Oracle’s the same tool to represent lambda
mentation on the Java Virtual
Machine (JVM). It was an open col-
talked with Java Magazine about
the event and related themes.
Nashorn), Fortress
(Oracle’s scientific pro-
suite can be expressions at runtime.
This is accomplished
laboration among VM architects, Java Magazine: What were some of gramming language), used on the JVM by using invokedynamic blog
runtime engineers, tool builders,
compiler experts, and language
the most memorable topics at this
year’s JVM Language Summit?
and even a Smalltalk
variant (Rtalk) were all
regardless of the to set up the creation
of the lambda expres-
designers. The Summit presented Buckley: There was a strong sense represented. Cameron source language. sions, which are simply
PHOTOGRAPHY BY BOB ADLER an opportunity for a wide range at this gathering that many of the Purdy from Oracle gave blocks of code, a bit like
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

a method, but without all the surround- JVM regardless of the source language. Buckley: The implementation of lambda Java Magazine: What are some examples
ing class structure. Java Magazine: Oracle’s upcoming expressions (Project Lambda) is a good of how lambda expressions could ben-
Java Magazine: Will you give us an over- Nashorn JavaScript interpreter was cov- example. It’s something of a challenge, efit Java developers in a tangible way?
view of some of the most important ered at the JVM Language Summit. Can because the JVM is conceptually stream- Buckley: Lambda expressions are rel-

languages running on the JVM? And how you give us some details? lined and very focused. The JVM has no evant with APIs. The bulk of what
might they be used with Java to improve Buckley: Nashorn is an Oracle-led proj- knowledge of a lambda expression, a developers do involves utilizing some-
developer productivity and create more- ect currently scheduled to be available closure, or a continuation. It has no one else’s APIs. A very common task in
flexible and robust applications? to developers in JDK 8. It’s an imple- knowledge of type inference or any other Java programming is iterating through
Buckley: Large systems today succeed mentation of JavaScript running on language feature that might be designed a collection of business objects, finding
based on their technical architecture. the JVM, targeted specifically for the in support of lambda expressions. ones that match some requirement, and
That architecture typically has many benefit of Java developers. We want to For many years, we could add features passing that result on to the next step of
loosely coupled components, each ful- expose JavaScript to Java collections and to the Java language that mapped directly the program.

filling a very specific purpose. Typically, Enterprise JavaBeans. And we want to to JVM features, or in the case of gener- Rather than extracting items and writ-
these components collaborate by shar- ensure that the boundary between Java ics, did not show up in the JVM at all. That ing code to perform those operations
ing data in a relational database, or a and JavaScript is as thin and interoper- era of direct mapping is over. With Project (and hoping that nobody else is mutating
message bus, or by exposing XML ser- able as possible. Lambda, we needed a way to represent the collection at the same time), using
vices to each other. The more loosely The development of a JavaScript lambda expressions on top of the JVM in lambda expressions simplifies things
coupled this architecture, the easier it is interpreter is partially motivated by the a way that is efficient and extensible. In dramatically. If you can pass code, in the
to choose the best language for the dif- fact that much of the world is moving terms of disk space, memory usage, and form of a lambda expression, to a library,
ferent components. toward HTML5 for cross-platform GUIs. other overhead, anonymous inner classes you are basically passing it to the collec-

User interfaces are generally Web- HTML5 offers many JavaScript APIs for were not a reasonable solution. tion itself. Then, concerns such as thread
based and written in HTML or JavaScript, accomplishing some very useful tasks, The invokedynamic instruction pro- safety become the responsibility of the
with middleware often written in Java, such as location sensing or database vided the solution. It essentially facili- library implementer, rather than the
and back-end logic written in Java, Ruby, access in the browser. The scope of tates quick access to method handles. responsibility of the calling programmer.
or Scala. Groovy is fairly common at HTML5 has expanded far beyond “mark- Method handles are really function High-level operations improve soft-
build time, and server-side JavaScript is up” for layout, and the natural way for pointers, and function pointers are a ware readability and performance.
growing in popularity. these additional front-end services to be way of manipulating
A well-designed architecture is clear exposed is through JavaScript. Nashorn individual blocks of
about the functional components and would allow a non-browser JavaScript code, which is what
how they interact. Then the appropri- program running on the client or server lambda expressions
ate language can be chosen for those direct access to standard JavaScript APIs are all about. The
components. Organizations are search- and the vast collection of Java APIs. goal is to give the Java
ing for the right mix of productivity and The use of invokedynamic and method compiler a great deal
maintainability in the languages they handles makes implementing JavaScript, of flexibility in how
use. Especially on the JVM, components which is an extremely dynamic and to represent these
can be swapped in and out over time. weakly typed object-based language, on lambda expressions at blog
Sometimes a Java component is rewritten the JVM surprisingly straightforward. runtime. That is
in Scala, and sometimes a JRuby compo- Java Magazine: How will the accomplished by using
nent is rewritten in Java. In many cases, invokedynamic instruction be directly invokedynamic to set Brian Goetz, From Lambdas to Bytecode
the same tool suite can be used on the useful to the Java language in Java SE 8? up their creation.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//polyglot programmer /

Listing 1, Listing 2, and Listing 3 show an makes it much more natural to design
double highestScore = 0.0;
example of code simplification through and use “higher-order functions” in
for (Student s : students) {
the use of lambda expressions. which the programmer specifies just
if (s.gradYear == 2011) {
In Listing 1, existing collections im- the atomic operations to be performed if (s.score > highestScore) {

pose external iteration. The client of the on the data, and the collection figures highestScore = s.score; }
collection determines how to iterate. out how to accomplish the task. Using }
The implementation of accumulation this technique, many applications can }
is overspecified, and computation is be written in a way that is more compact
achieved through side effects (assign- and reliable. In a sense, lambda expres-
ment to highestScore). sions are the fundamental primitive
Listing 2 uses internal iteration, so the in a programming language, and
iteration and accumulation are embod- now they can be implemented in an See all listings as text

ied in the library. For example, filtering efficient manner.
can be done in parallel, and the client is Java Magazine: As specification lead for
more flexible, more abstract, and less the JVM and the Java language, will you implement in terms of specification. environments 50 years from now! At this
error prone. give us some insight into the process of It’s a much more structured process level of the platform, everything must be
Listing 3 uses lambda expressions, Java evolution through specification? than most open source projects, though impeccably stable and reliable.
which represent “code as data.” The Buckley: The Java Community Process I think the worlds of open source and The Java SE platform is evolving in
lambda expression is introduced with [JCP] provides the framework for community standards are moving a deliberate and mature way, through
special syntax using zero or more-formal the evolution of the Java language, closer together. multiple implementations, the stan-

parameters. Parameter types are op- the core Java APIs, and the JVM. A Java It’s important to have a deeply in- dardization process, and adoption by
tional and may be inferred, and the body Specification Request [JSR], such as volved Expert Group like John Rose had major language implementers. Some
may be an expression or statements. If JSR-292, that modifies the JVM ulti- for JSR-292. Expert Group members say that the ship moves rather slowly.
the body is an expression, there is no mately becomes part of the Java SE contribute their deep experience. For But when a great ship finally leaves port,
need for return or ;. Platform Specification. instance, a language implementer for it’s quite a sight. </article>
We refer to internal iteration when It takes multiple years to make this JRuby might say, “My life would be easier
the collection is responsible for iterating kind of major change because we not if the JVM helped me do this . . . .” As a
or in some way process- only have to create the JSR progresses, external contributors Michael Meloan began his professional career
ing its data. By passing the THE FUNDAMENTALS design space correctly, but also provide reports and the benefit of writing IBM mainframe and DEC PDP-11
programming logic to the we also need to allow time “in the trenches” observations. assembly languages. He went on to code in
collection and letting the In a sense, lambda to specify things precisely I think JSR-292 did a remarkable job PL/I, APL, C, and Java. In addition, his fic-
collection iterate through expressions are the enough to answer imple- coming up with a design that satisfies tion has appeared in WIRED, BUZZ, Chic, LA
Weekly, and on National Public Radio. He is also
its elements, the program is
potentially much more
fundamental primitive menters’ questions but
generically enough to avoid
language implementers and is fully im-
plementable with proper performance
a Huffington Post blogger.

efficient and robust than in a programming implementation-specific by all the major JVM vendors. The design
with external iteration, language, and now they artifacts in the design. that was committed to will be part of
• JSR-292: “Supporting Dynamically Typed
where the iteration logic
lives in the user’s program.
can be implemented in In other words, we don’t
specify the platform in
the Java SE platform “forever,” because
while JVM implementations come and Languages on the Java Platform”
Having lambda expres- an efficient manner. terms of various software go, the JVM itself is a lasting entity. There • Project Lambda
sions in the language implementations; we will probably be class files in computing • Java SE
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
//fix this /

Hint: Check the
HttpServlet API in
the Java EE 6 API.

In the last issue, Arun Gupta, a Java

evangelist at Oracle, posed a challenge about the 2 THE CODE

CDI specification and asked readers for a fix. Consider the following piece of code to have database access
The correct answer is #2: “beans.xml” is required within a Servlet:
to enable injection. The CDI specification requires @WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
“beans.xml” in the WEB-INF directory in order for bean injection public class TestServlet extends HttpServlet {
to work. So even though the code is fine, a missing file did not @PersistenceContext
allow the EJB injection to go through. EntityManager em;

And now, for Gupta s latest challenge. protected void doGet(HttpServletRequest request,
HttpServletResponse response) {
// Invoke methods on Entity Manager


Java EE 6 allows you to create Web applications very 3Is thisWHAT S THE FIX?

easily using annotations on POJOs. A POJO can be code guaranteed to work in a multithreaded environment?
1) Of course. All the samples are written this way.
easily converted to a Servlet by adding @WebServlet 2) No. Servlets are re-entrant, and EntityManager is not thread-
and extending HttpServlet. A POJO becomes a JPA safe. Instead inject as
bean by adding @Entity. Each method of a Java class @PersistenceUnit EntityManagerFactory em;

becomes implicitly transactional by adding @Stateless. and then get EntityManager within the doGet() method.
Following the convention-over-configuration paradigm, 3) Database access in Servlets must be done through EJBs only. The
correct way is to move the database code in an EJB, inject the
the deployment descriptors are optional for most of the EJB in this Servlet, and invoke methods on the EJB.
common cases. 4) EntityManager injection will not work in Servlets. Instead use
Persistence.createEntityManager to obtain EntityManager in the
doGet() method and then invoke operations on it. blog


Look for the answer in the next issue. Or submit your own code challenge!
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011
Learn Java 7
Editor in Chief Publisher
Justin Kestelyn Jeff Spicer
Senior Managing Editor Production Director and
Caroline Kvitka Associate Publisher

From the Source

Community Editors Jennifer Hamilton +1.650.506.3794

Cassandra Clark, Sonya Barry, Senior Manager, Audience Development
Yolande Poirier and Operations
Java in Action Editor Karin Kinnear +1.650.506.1985
Technology Editors Associate Publisher
Janice Heiss, Tori Wieldt Kyle Walkenhorst +1.323.340.8585
Contributing Writer
Kevin Farnham
Contributing Editors
Northwest and Central U.S.
Tom Cometa +1.510.339.2403
Southwest U.S. and LAD
—Oracle University—
Blair Campbell, Claire Breen, Karen Perkins Shaun Mehr +1.949.923.1660
Northeast U.S. and EMEA/APAC

DESIGN Mark Makinney +1.805.709.4745
Senior Creative Director
Francisco G Delgadillo Mailing-List Rentals
Contact your sales representative.
Design Director
Richard Merchán RESOURCES
Contributing Designers Oracle Products
Jaime Ferrand, Paulina McFarland
Production Designer
+1.800.367.8674 (U.S./Canada)
Oracle Services
New Java SE 7 Training
Sheila Brennan +1.888.283.0591 (U.S.)
Oracle Press Books Engineering-Developed Courseware


ARTICLE SUBMISSION Taught by Oracle Experts

If you are interested in submitting an article, please e-mail the editors.
SUBSCRIPTION INFORMATION 100% Student Satisfaction Program
Subscriptions are complimentary for qualified individuals who complete the
subscription form.
MAGAZINE CUSTOMER SERVICE  Phone +1.847.763.9635
Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer
that your mailing address or e-mail address not be included in this program, contact
Customer Service.
Copyright © 2011, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or other­wise
reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLY
information is intended to outline our general product direction. It is intended for information purposes only, and may not be
Click for Details, Dates, and to Register
incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied
upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s
products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or its blog
affiliates. Other names may be trademarks of their respective owners.
Java Magazine is published bimonthly with a free subscription price by
Oracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600.

Digital Publishing by Texterity

Copyright © 2011, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates.
ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////   NOVEMBER/DECEMBER 2011