You are on page 1of 70

//JANUARY/FEBRUARY 2012 /

10
JAVA VS.
33
PROJECT
68
FIX THIS
SPAM COIN IS A Test your
Mollom eliminates TIME-SAVER knowledge How Java EE is evolving to become the
unwanted postings How Java SE 7’s with a Swing cloud computing platform standard
from Websites language changes conundrum
worldwide streamline your
code

ORACLE.COM/JAVAMAGAZINE
//table of contents /

COMMUNITY
COMMUNITY 41
02 Java Architect
From the Editor Understanding Hudson

JAVA IN ACTION
4 Plug-Ins
Our Hudson series continues.
Java Nation
News, events, and happenings 45
in the Java community. Rich Client
JavaFX and Swing
JAVA IN ACTION Go from Swing to JavaFX.
14 49
The Engine of Choice Enterprise Java

JAVA TECH
Java puts Choice Hotels front Lightweight Publish-
and center on Google Maps.
Subscribe
Adam Bien on CDI.
JAVA TECH
19 53
New to Java Enterprise Java
Shall We Play a Game? GlassFish Clustering
and High Availability

ABOUT US
Michael Kölling gives us a play-
able version of our turtle game. Scale apps horizontally.
22 60
New to Java Enterprise Java
Introduction to RESTful Wake Up and Smell
Web Services the Coffee
Max Bonbhel tackles JAX-WS. Have fun with Java EE 6.
30
Java Architect
63
Mobile and Embedded
10 26 33 68
Looking Ahead to Developing Proximity Java in Action Cloud/Java EE Java Architect Fix This
Java EE 7
A tour of Java EE 7 JSRs
Awareness
Use the Location API.
WINNING THE
WAR AGAINST
TAME THE PROJECT
COIN:
In this issue’s
code puzzler,

CLOUD
SPAM WITH THE JAVA Marek Piechut
37 65 JAVA LANGUAGE challenges your
Java Architect Polyglot Programmer knowledge of
With Dries HAS EVOLVED!
Using JLayer in Your Using Maven to Buytaert at the Additions to the
Swing.
blog
Swing Applications Compare JVM Scripting helm, Mollom Oracle’s Cameron Purdy on how Java language
Create effortless effects. Languages eliminates Java EE is evolving to become the in Java SE 7 will
Give scripting languages a try. unwanted post- cloud computing platform standard help you be more
ings from Web- productive.
COVER ART BY I-HUA CHEN sites worldwide.
PHOTOGRAPH BY DAVE BRADLEY
01
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//from the editor /

COMMUNITY
S

JAVA IN ACTION
GIVE BACK!

JAVA TECH
ometimes, buzzwords are for real. Cloud computing is one such example: most will agree that the
term itself is overused and lacks a clear, universally accepted definition. But we can also agree on the impor- ADOPT A JSR
tance of understanding cloud computing’s likely impact on the application development process. Pretending
otherwise would constitute a serious breach of career-management duty.
In some quarters, that impact is expressed in the context of the emerging “DevOps” principle, which calls
for developers to use their programming powers to free themselves from the burden of IT operations. Cloud Find your JSR here

ABOUT US
computing, by almost any definition, is a key DevOps enabler.
Currently, the Java EE platform lacks the abstractions that allow Java developers to move confidently in that
direction. But with Java EE 7 (JSR-342; final release expected later in 2012), that will change—with the inclu-
sion of updated APIs, roles, and more that will bring support for cloud service requirements such as multi-
tenancy, elasticity, and scalability directly into the standard. As a result, apps written to target Java EE 7 app
servers (which will in fact become services themselves) will be much more natively cloud-aware than they are
today. What could be more DevOps-friendly than that?
Our interview with Cameron Purdy, Oracle vice president of Java EE development, //send us your feedback /

reveals the reasoning behind these efforts in more detail. (You can also review the We’ll review all
suggestions for future
Java EE 7 JSRs.) And as usual, you’ll find this issue packed with informative,
improvements.
actionable articles on other subjects as well—including wrap-ups of JavaOne Latin Depending on volume,
America and Devoxx 2011, a Swing JLayer primer by Josh Marinacci, an introduction some messages may
to Java SE 7’s Project Coin features by Julien Ponge, and more. Enjoy it! not get a direct reply. blog

Justin Kestelyn, Editor in Chief BIO

PHOTOGRAPH BY BOB ADLER

02
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /JAVAONE LATIN AMERICA NEWS /

COMMUNITY
PROMISES DELIVERED
At the Java strategy keynote on the first day of JavaOne Latin America, Oracle

JAVA IN ACTION
executives stepped through Oracle’s Java technology roadmap for Java SE, Java
NEWS ROUNDUP EE, Java ME, and JavaFX. “Last year at JavaOne Latin America, Oracle was full

JavaOne
of promises,” said Georges Saab, vice president of development, Java Platform
Group. “This year we can say Oracle delivered on those promises: Java SE 7,

LATIN
JavaFX 2.0, and increasing transparency in the JCP [Java Community Process].”
Nandini Ramani, vice president of development, Java client platform, announced
the release of JavaFX 2.0.2. She explained that starting with JavaFX 2.0.2, JavaFX

AMERICA
is available under the same license and business model as Java SE. This includes
the ability to distribute the JavaFX runtime (or Software Development Kit) for

JAVA TECH
2011
third-party developers with their application(s), subject to the terms and condi-
tions of the license. (Developers can follow and join the JavaFX open source proj-
ect at OpenJFX.) The technical keynotes on the second day provided more details
on each of these technologies.

Arun Gupta Stephen Chin

ABOUT US
Georges Saab
Arun gupta and Stephen Chin
JavaOne Latin America 2011
was held in São Paulo, Brazil,
December 6–8, 2011. The regional
JavaOne conference included great
FOCUS ON JAVAFX The source code for the Henley Sales
keynotes, deep technical sessions, There was lots of buzz around JavaFX. At Dashboard is available as part of the
engaging hands-on labs, a bustling the technical keynote, the JavaFX demos JavaFX Sample Showcase (currently
only for Windows).
Oracle Technology Network lounge, generated the most interest, especially the
JavaFX game running on a desktop and two
booth swag (Duke T-shirts!),
different tablets. The other demo that sparked a lot of interest was the Henley
wonderful conversations, and even Sales Dashboard, a client/server application for a fictional global automobile
a maté tasting. company. The front end was developed with JavaFX, displaying real-time sales
data via MySQL and deployed on Oracle GlassFish Server. At the standing-
room-only session “XML-Free Programming: Java Server and Client,” Stephen blog
Chin, chief agile methodologist at GXS and Java Champion, and Arun Gupta,
Java evangelist at Oracle, discussed how to build Web apps with a JavaFX client
and a Java EE server.
Nandini Ramani
PHOTOGRAPHY BY LOAINE GRONER AND ARUN GUPTA

04
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /JAVAONE LATIN AMERICA NEWS /

COMMUNITY
Bruno Souza BEST FOR LAST: THE COMMUNITY KEYNOTE
The JavaOne Community Keynote was informative and funny. Fabiane Nardon
Parleys.com Brings
Sessions to You

JAVA IN ACTION
and Bruno Souza of Brazilian Java user group SouJava opened the keynote
with their list of the top five developments in Java for the year: 5) Java on Mac
to OpenJDK, 4) SouJava and the London Java Community getting seats on the Couldn’t make it to JavaOne or Devoxx?
JCP Executive Committee, 3) Twitter adopting Java for improved performance, That needn’t stop you from “attending”
2) Java SE 7 being released, and 1) JavaFX being made open source. Nardon many of the most important conference
then discussed women in technology and, with SouJava members Yara Senger, Ana Abrantes, sessions. You can do so at Parleys, the
and Loiane Groner, announced the formation of jDuchessBR, a group for Brazilian women using GlassFish-powered e-learning platform in-
Java. Then Vinicius Senger gave a demo of the Duke’s Choice Award winner, jHome, showing that vented by Java Champion, Belgian Java User
what you can do with Java is limited only by your imagination: adjust the lights in your house Group leader, and Devoxx Founder Stephan

JAVA TECH
via Twitter, brew coffee, or monitor someone’s heart rate remotely (Arun Gupta was the guinea Janssen. The Parleys team recorded 40 per-
pig). The keynote concluded with cent of the JavaOne 2011 sessions, along with
a twist on the Java Life video en- a substantial sampling of Devoxx 2011 ses-
titled Real Java Geeks. See what sions and interviews.
Java developers do when they A Parleys technical session presentation
aren’t in their cubicles (or offices, provides you with a full educational experi-
home offices, or coffee shops). ence, including audio, slides, and video of

ABOUT US
Fabiane Nardon talks about When they’re not coding hard, Java developers surf, hike, ride demos from the sessions. You hear and see
zero downtime and the motorcycles, fish, practice jujitsu, and so much more. almost everything the session’s live attend-
amazing performance of ees heard and saw—with the added benefit
Java EE. THE COMMUNITY THAT RIDES TOGETHER . . . that you can pause, back up, and review a
Geek Bike Ride
In true community spirit, Fabiane Nardon and session segment or slide any time you like.
other SouJava members put together a Java com- You can watch Parleys presentations online,
munity bike ride the Sunday morning before or you can download them for offline viewing
JavaOne Latin America. Nardon arranged for bike using the free Parleys Desktop application.
rentals and matching jerseys, and “bike angels” Visit the Parleys JavaOne channel to view
made sure no one was left behind. Nearly 30 rid- popular sessions from JavaOne 2011 includ-
ers enjoyed slightly overcast and cool weather and ing “Introduction to JavaFX 2.0,” “Java EE 6:
a wonderful route through São Paulo, thanks to The Cool Parts,” and “The Heads and Tails of
Sunday lane closures just for bicyclists. The riders Project Coin.”
looked great in their fabulous Duke bike jerseys.
The route was 12 miles (22 kilometers)—check
out the GPS documentation and full redundancy. The group rode at a leisurely pace that allowed blog
Stephan Janssen
everyone to chat and meet new friends. The group even visited two parks and a street fair along talks about the
the way. Affectionately called the Geek Bike Ride, it had just the right combination of exercise, challenges of
technology, and fun. Watch for #geekbikeride to join or start a community bike ride near you. putting on Devoxx.
PHOTOGRAPHY BY ARUN GUPTA
AND TORI WIELDT

05
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /

COMMUNITY
Joe Darcy

Devoxx

JAVA IN ACTION
Richard Bair
Heads
to France
To celebrate its 10-year
success, Devoxx will
expand to France, in
the first conference

JAVA TECH
modeled after Devoxx
in Belgium. At Devoxx
Brian Goetz, Mark Reinhold, Ben Evans
Michael Heinrichs
France, April 18–20,

Devoxx 2011:
2012, 75 percent of
Shaun Smith platform-as-a-service enhancements in Java EE the sessions will be in
7 and GlassFish Server Open Source Edition 4. French and 25 percent
TECHNICAL IMMERSION Spec leads presented specifics on JSRs: Oracle’s in English. The Paris

ABOUT US
Marek Potociar on JAX-RS 2.0 and the upcom- Java user group behind
Devoxx 2011 celebrated its 10-year anniversary in Antwerp, Belgium, ing and sought-after client API; Oracle’s Shaun this event promises a
in November 2011. Sold out every year weeks in advance, Devoxx has Smith on JPA 2.1; Oracle’s Nigel Deakin on Java Devoxx experience plus
become the biggest Java developer conference in Europe, with 3,350 Message Service 2.0; and Ehcache Founder Greg spring in Paris and, of
attendees from 40 countries and more than 170 well-known speakers Luck on javax.cache. course, wine. A call for
giving 150 sessions over five days. JavaFX 2.0, released at JavaOne, had a papers is open, and
The conference is a technical immersion. Junior and seasoned big presence too. Oracle technical leads Jasper Potts, Richard Bair, Oracle is a sponsor.
developers learn about platform improvements and better and faster Michael Heinrichs, and John Yoong and two community leaders, Peter
application developments with a mix of keynotes, technical overviews, Pilgrim and Stephen Chin, presented seven talks for a full immersion
three-hour sessions, hands-on labs, 30-minute “Tools in Action” on features, deep dives about animations and custom bindings, and
talks, and the traditional birds-of-a-feather discussions. an open mic session. The “Why We Should Target Women” panel
Henrik Stahl and Cameron Purdy of Oracle talked about Oracle’s attracted a full house as well. Only 1 percent of Devoxx attendees are
investment in and innovation around the Java platform with the upcom- women, so the discussion centered on encouraging women into the
ing releases of Java SE 8, Java EE 7, and JavaFX 3.0. Mark Reinhold, Joe field and the conference. Here are a few of the ideas discussed:
It’s all happening in Paris.
Darcy, and Brian Goetz, Java SE architects and technical leads at Oracle, 1.  Parents should encourage their daughters to play with Legos and
explained the latest progress with Project Coin, Project Jigsaw (modu- learn programming. blog
larity), and Project Lambda in a series of sessions and casual discus- 2.  More organizations should target young women in high school and
sions with developers. Java EE 7 development will be multitenant, on college to expose them to programming. Women need mentors
demand, and autoprovisioned for the cloud platform. Jerome Dochez, (men or women) to learn to become speakers at conferences and
a GlassFish architect at Oracle, discussed cloud infrastructure and to promote themselves better. PHOTOGRAPHS COURTESY OF DEVOXX
06
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /

COMMUNITY
Adopt-a-JSR

JAVA IN ACTION
WHAT’S NEW AT JAVA.NET Want to help move Java forward? Is there some specific
enhancement to the Java platform that would ben-
AFTER A YEAR OF UPHEAVAL AND REBUILDING, JAVA.NET IS GROWING efit you and your industry peers? Your Java user group
Sonya Barry
AGAIN, WITH 80 TO 90 NEW PROJECT REQUESTS PER WEEK, GROWTH IN (JUG) can make that happen by participating in the
MEMBERSHIP, AND NEW COMMUNITY VOLUNTEERS TAKING OVER LEADERSHIP ROLES IN SEVERAL Adopt-a-JSR program. To contribute to a JSR, your JUG
COMMUNITIES. Plans for 2012 include new hardware and performance improvements, adding will have to join the Java Community Process (JCP)—a

JAVA TECH
another level of social and group functionality (starting with Java user groups and then the Java procedure that is being streamlined for JUGs as part of
Community Process), a complete redesign in how communities are structured, and improve- the JCP’s new openness. JUGs have already contributed
ments to the project catalog and search facilities. Sonya Barry, Java.net community manager, significantly to changing the JCP through their involve-
says she has heard many great ideas from community members that she will be looking into, ment in JCP.next.
ranging from opening the API so users can create mobile apps that work with the site and im- As London Java Community leader (and JCP mem-
proving search engine optimization on projects and people to using geotags to let users know ber) Martijn Verburg (@Karianna) notes, “there are
where their nearest Java user group is. genuine domain experts in JUGs that can serve as EG
Java.net blog posts on a variety of topics are receiving considerable attention, and innovative

ABOUT US
[Expert Group] members; skilled developers that can
new Java-centric open source projects are underway (and seeking added participation from the help with RI [reference implementations] and TCK
developer community as well). [technology compatibility kit] implementations; and
Recent Java.net blogs of note include Osvaldo Pinali Doederlein’s JavaFX Balls 3.0, enthusiastic hordes that can help test early versions,
Mamadou Lamine Ba’s What JSF Should Become?, Santiago Pericas-Geertsen’s JAX-RS 2.0— give feedback, and help deal with project overheads
Client API, Cay Horstmann’s Operator Overloading Considered Challenging, and Tushar Joshi’s such as mailing lists and issue trackers as well as pro-
Concentrating on Task in Hand (Similar to Mylyn) in NetBeans IDE. moting the JSR in general.”
Innovative new Java.net projects include JSF extension points, an easy-to-use, powerful
drop-in/plug-in system for Java EE; SWELL, an English-like domain-specific language for
Swing testing; and the Vorpal XMPP Component Framework, an injection-based XMPP com-
ponent framework for Jabberwocky. More than 2,200 diverse Java.net open source projects are
available. They welcome your participation.

Martijn Verburg explains the


Tori Wieldt talks Adopt-a-JSR program.
with Sonya Barry blog
about the Java.net
migration.

PHOTOGRAPH BY CAITLIN YOUNGQUIST

07
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /

COMMUNITY
Twitter and Azul Elected to the JCP
EVENTS

JAVA IN ACTION
Twitter and Azul Systems were elected to the Java Community
Process (JCP) Standard/Enterprise Edition Executive MOBILE WORLD CONGRESS FEBRUARY 27–MARCH 1, BARCELONA, SPAIN
Committee (EC) in the JCP’s fall 2011 election. The companies
bring widely recognized expertise in Java Virtual Machine “Redefining mobile” is the theme of
(JVM) performance to the JCP at a critical time in the history this year’s mobile technology and
of Java’s evolution. business conference. More than
n
In April 2010, Twitter engineers announced that they
you ca 60,000 attendees are expected
– rs
had achieved a three-times performance improvement in Twitter search, in part lona n Selle for this event, which includes a

JAVA TECH
ce
Bar om Ro
by replacing their Ruby on Rails stack with a new Java service built on the JBoss art: r conference program, exhibition,
t one f and awards program. App Planet,
Community’s highly scalable NIO client/server socket framework, Netty. At ge
JavaOne, Twitter’s Attila Szegedi spoke about the team’s accomplishment at the a conference in its own right, is the
session “Everything I Ever Learned About JVM Performance Tuning at Twitter.” Azul world’s largest gathering of apps
develops high-performance Java products, such as the Linux-optimized Zing JVM developers—more than 10,000
and the C4 Pauseless Garbage Collector. The companies were elected to the two are expected.
open election EC seats out of an unusually large field of nine candidates.
FEBRUARY Jfokus 2012 MARCH

ABOUT US
FEBRUARY 13–15,
Java Performance QCon London 2012

NetBeans IDE 7.1 Released


STOCKHOLM, SWEDEN
Tuning Workshop TRAINING MARCH 5–6,
Jfokus is the largest annual
FEBRUARY 6–9, SYDNEY, CONFERENCE MARCH 7–9,
conference for anyone
AUSTRALIA LONDON, ENGLAND
NetBeans IDE 7.1, launched in January 2012, is the first integrated who works with Java in
QCon London is the sixth
This four-day course will
development environment (IDE) to support JavaFX 2.0. Developers be led by Kirk Pepperdine,
Sweden. The conference
annual London enterprise
can create JavaFX applications completely in the Java programming is arranged together with
Java performance tuning software development
language using industry-leading development support provided by Javaforum Stockholm, a
expert, Java Champion, conference designed for
NetBeans. Also available is support for creating JavaFX FXML–based Swedish developer com-
and international speaker developers, team leads,
applications or traditional Java-based JavaFX applications, and JavaFX munity and Java user
and trainer. Each day will architects, and project
group. With speakers
Preloader applications to customize the startup experience of a JavaFX application. have a topic: introduction managers. Day two of the
from Sweden and around
Developers can also package their applications as a standalone application, a Java to performance, the Java development track focuses
the world, the conference
Web Start–based application, or an in-browser application. Debugging the JavaFX Virtual Machine, tooling, on hard-core Java.
focuses on development
application UI is now simplified with the new GUI visual debugger, which can also be and performance tuning
with Java and surrounding
used with Swing-based UIs. in practice.
techniques.
This release introduces batch refactoring tools that enable projectwide refactorings, blog
including an extensible “inspect and refactor” tool, new refactorings and code hints, a
block selection mode, and an import statement organizer, among many other Java edi-
tor enhancements. NetBeans IDE 7.1 supports Oracle WebLogic Server 12c, providing
industry-leading Java EE 6 support to developers using the Oracle WebLogic platform. ILLUSTRATION BY I-HUA CHEN, PHOTOGRAPH BY RON SELLERS

08
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java nation /

COMMUNITY
JAVA BOOKS

JAVA IN ACTION
JAVA PROGRAMMING JAVA 7 NEW FEATURES JAVA 7 FOR ABSOLUTE MURACH’S JAVA
Charles Oliver Nutter Agnes Crepet Andrew Lee Rubinger
By Poornachandra Sarang COOKBOOK BEGINNERS PROGRAMMING,

JAVA TECH
Oracle Press (January 2012) By Richard M. Reese and By Jay Bryant 4TH EDITION

Heroes of Java Java Programming fea-


tures hands-on program-
Jennifer L. Reese
Packt (May 2012)
Apress (December 2011)

Java 7 for Absolute


By Joel Murach
Mike Murach & Associates
(November 2011)
There are many heroes of Java out there—people ming exercises and exam- Java 7 New Features Beginners introduces the
who are making significant contributions on a daily ples based on the author’s Cookbook offers a prac- new core open source Java Get a fast start in Java,
basis within the Java ecosystem, thereby building 10-plus years of teaching tical, recipe-based ap- Development Kit. The and then master all the
Java’s future in the most practical way possible. Java to experienced pro- proach for learning about book focuses on practi- core skills you need to
Often their work is performed far away from the fessionals. This Oracle the new features of Java cal knowledge, providing be a professional Java

ABOUT US
public spotlight. Software architect and author Press guide covers all the 7. The book starts with all the bits and pieces an developer. By the end
Markus Eisele is highlighting these people and new Java features, includ- coverage of new lan- utter novice needs to get of Chapter 6, you’ll be
their efforts in his new interview series, The Heroes ing multilingual support, guage improvements. started programming in writing fail-safe, object-
of Java. support for JavaScript and Subsequent chapters Java. The book teaches oriented applications
The series is not about celebrities; rather, the other scripting languages, address new features of Java development in a with business classes and
focus is on “people displaying courage and some- JavaFX, and several other Java 7 while incorporat- language that anyone can objects. By the end of the
times even self-sacrifice for the greater good,” modifications to the lan- ing these new language understand. It provides book, you’ll be working
says Eisele. Heroes in the series include Marcus guage. Java programmers improvements when simple, step-by-step ex- comfortably with features
Lagergren, Oracle JRockit architect and team lead; will find exactly what they possible. Content includes amples that make learn- such as inheritance, inter-
Andrew Lee Rubinger, JBoss software engineer; need to know in order to NIO techniques, GUI ing easy, allowing you faces, arrays, collections,
Cay Horstmann, author and professor; Charles integrate these new fea- improvements includ- to pick up the concepts. threads, GUIs, files, and
Oliver Nutter, JRuby developer; and Java user tures into their skill set. ing window methods, the It also offers clear code databases (using JDBC).
group leaders Martijn Verburg and Agnes Crepet. The author also provides new JLayer class, various descriptions and layout At every step, you’ll save
If you’d like to suggest someone worthy of inclu- thorough coverage of Java dialog-box-related meth- so that you can get your time by using NetBeans.
sion in the series, Eisele invites you to post a com- syntax, the event model, ods, and much more. The code running as soon as Read a sample chapter.
ment to his lead Heroes of Java entry. book is currently available
blog
threads, network pro- possible.
gramming, I/O program- as a RAW book (read as it
ming, and applets. is written).

PHOTOGRAPHS COURTESY OF MARKUS EISELE

09
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
JAVA IN ACTION
JAVA TECH
Winning the War
Against Spam
WITH JAVA

ABOUT US
Mollom eliminates unwanted postings from Websites worldwide.
BY DAVID BAUM AND ED BAUM

G
ot spam? Who doesn’t! But if you think finding and delet- breeding countless unsolicited automated messages and comments Dries Buytaert,
ing a few hundred spam messages from your inbox or like invasive bacteria. This infestation weakens worldwide productivity Mollom cocreator, at the
Website is a challenge, try deleting a few hundred million. and threatens to compromise the way the Web works. The battle for company’s Burlington,
That’s the volume that leading spam-fighters such as Dries the internet is raging, and it’s us against the spambots. Massachusetts, office blog
Buytaert battle each day. As cocreator of Mollom, a Java- These spambots—automated programs that assist in sending and
based technology that processes hundreds of requests per second posting spam—are getting smarter and more intrusive all the time.
to keep the invading horde at bay, Buytaert is continually confronted Thankfully, defensive strategies keep getting better too, as evidenced
with the “dark side” of the internet: it has become a petri dish of sorts, by Buytaert and his team. They recently migrated Mollom from home- PHOTOGRAPHY BY DAVE BRADLEY

10
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
Buytaert drops in and manage a Website, you know how complex
answers questions spamming strategies have become. Some
from participants in
spam messages on blogs and forums are tar-
a class at Mollom’s
Burlington, geted toward readers in an attempt at prod-

JAVA IN ACTION
Massachusetts, uct marketing or phishing (trying to acquire
office. information such as usernames, passwords,
and credit card details). However, the spam
reliability, scalability, that Website administrators battle most is
and availability of a tactic deployed in an attempt to increase
an enterprise-scale page rank on search engines such as Google.
information system.” “The more incoming links you have to your
sites, the more relevance Google will give to
BEYOND PHISHING those sites,” explains Buytaert. “The spam-

JAVA TECH
Internet spam and mers’ goal is to abuse Websites’ comment-
SNAPSHOT the tactics used by ing systems to create links back to their own
spammers have Websites in an effort to get the number one
MOLLOM
mollom.com become increas- spot for certain keyword searches.”
ingly sophisticated Buytaert says the strategies these spam-
Headquarters:
Antwerp, Belgium since first appearing mers use are becoming so clever that it’s often
Industry: on internet bulletin difficult to label the invasive content as spam.

ABOUT US
Open source software board systems (BBSs) “They provide contextually relevant comments
Employees: in the 1980s. Back along with links back to their sites,” he says.
4 then, spamming was “The line between what’s spam and what’s
Java version used: as simple as repeat- not gets blurry. Identifying and blocking these
Java EE 6 ing a word or phrase types of abuses is becoming very difficult for
over and over to Website owners and administrators.”
scroll other The challenge of blocking
grown systems to GlassFish Server Open users’ text off the screen. By the early this type of spam gets even
ACCURATE AIM
Source Edition—the open source version of 1990s, spam had evolved, and mul- greater when you consider
Oracle GlassFish Server—to better manage tiple repeat postings began to flood Mollom’s efficiency its volume. Since Mollom’s
the demands of keeping some of the world’s Usenet, where the first commercial rate at identifying launch in 2008, the service
busiest Websites free from spam.
“Java is a great fit for what we do,” Buytaert
spam messages appeared.
Today, most of us know spam as
spam is 99.96 has blocked more than half
a billion spam messages.
says. “Because Java is part of a much larger an abuse of our e-mail inboxes. And percent. Only 4 In fact 82 percent of all
technology ecosystem that includes lots of even though only a small percent- messages out of the comments on the sites
blog
development tools and open source applica- age of people purchase the products Mollom monitors are spam.
tion servers like GlassFish Server Open Source (or fall prey to the scams) advertised 10,000 succeed Buytaert is a prominent
Edition, it enables us to create a hosting through spam, these e-mail mes- in fooling its Java figure in the Java com-
service for thousands of customers with the
back-end infrastructure that delivers the
sages continue to proliferate because
of their extremely low cost. If you
programs. munity. In 2008 when he
was at Belgium’s Ghent
11
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
back to the community. makes it easier for people to visit Mollom-
That led me to start protected Websites. Mollom achieves this
working on Mollom.” feat by deploying other antispam techniques
first. For example, it uses a clever trick based

JAVA IN ACTION
TYPE THESE LETTERS, on JavaScript to hide form fields from human
THEN DO A BACKFLIP view. People don’t see the form fields, but
As kids, most of us spambots assume the form fields are visible
probably never dreamed so they fill them out. When they do, their
that we would someday submissions are blocked. This technique is
be asked to prove to a known as a honeypot.
computer that we’re Text analysis is another element of the
human. Yet that’s what Mollom solution. Like Defensio or Akismet
the ubiquitous CAPTCHA (the latter being the default spam filter in

JAVA TECH
antispam solutions WordPress blogs), Mollom examines the writ-
accomplish with their ten content of a post to establish whether it’s
tedious challenge/ a legitimate submission or spam. The prob-
response tests. The dis- lem is, sometimes it’s difficult to determine.
torted backgrounds and When used alone, text analysis can wrongfully
warped text provide a classify a legitimate post as spam, and block a
problem easy enough for genuine user. “Mollom recognizes that some

ABOUT US
Buytaert and Mollom University defending his PhD thesis about most humans to solve, while impeding most posts can be difficult to categorize,” Buytaert
team members break for Java performance and improvements, his automated software. We dutifully squint at the explains. “It’s not always black or white, spam
a quick lunch. defense committee included the father of the twisted letters and numbers and retype them. or not spam. So we have a third category:
Java programming language, James Gosling, Not only is it a nuisance to Website visitors; it’s unsure. When Mollom is unsure if a post is
who was then senior vice president at Sun also discriminatory against visually impaired spam or not, it serves a CAPTCHA.”
Microsystems, and Michael Hind, a senior people. And some spambots are becoming Because it’s a hosted software-as-a-
IBM staff member for Java research. smart enough to solve the CAPTCHA chal- service application, Mollom benefits from
Buytaert is best known as the founder and lenges by using advanced optical network effects. All the
project lead of the Drupal project, an open character recognition techniques. people using the system
source content management platform that Mollom’s solution to spam JAVA ON THE FRONT LINES work together, provid-
powers about 2 percent of all the Websites on is unique in that it intelligently Java-based Mollom has ing feedback that helps
the internet. He has been using Drupal for his
personal blog for many years, and as his blog
combines three of the most effec-
tive defenses against unwanted
blocked more than half a the spam-identifying
classifiers improve. In
became more popular over the years, spam automated comments while billion spam messages. other words, Mollom
comments proliferated. “I was wasting time remaining mostly invisible to Approximately 82 continually gets smarter.
blog
manually removing unwanted content from
the site,” Buytaert says, “and I noticed a lot of
legitimate site visitors and com-
ment posters. Mollom only deliv-
percent of comments “Using these network
effects, we can even
other people in the Drupal community with ers a CAPTCHA challenge as a on the sites Mollom observe spambots as
the same problem. I saw an opportunity not last resort—for most cases, a monitors are spam. they assault multiple
only to improve my situation, but also to give CAPTCHA is never shown, which sites simultaneously,”
12
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
Mollom:
Buytaert says. “We know that’s Buytaert clears his head
The initial not human behavior. It helps us by Mollom’s “campfire,”

Under the version of a place where staffers can


identify and block these malicious
the back brainstorm or just relax.
automated programs.”

Hood

JAVA IN ACTION
end for By intelligently combining all
Mollom, a these techniques and only using this, we need a technology
Web service that keeps invading the CAPTCHA as a final test to that can keep a lot of data in
hordes of spambots at bay, was
weed out the small number of persistent memory so we can
based on a custom Java SE–based
false positives and false negatives, instantly classify content.”
XML-RPC server. To allow increased
Mollom provides the best-possible When Buytaert created
focus on Mollom’s core Machine
Learning technology, Mollom co- quality in terms of blocking spam Mollom with his partner,
creators Dries Buytaert and Benja- while delivering the best-possible Benjamin Schrauwen, they
user experience for visitors to the initially built everything from

JAVA TECH
min Schrauwen decided to switch to
a Java EE 6 back end, hosted on a sites it protects. scratch. But as Mollom grew
GlassFish Server Open Source to the point where it was
Edition 3.1.1 cluster. The Mollom ENLISTING JAVA handling millions of mes-
team now extensively uses several Mollom is a real-time service, sages per day, Buytaert and
core technologies such as JAX-RS eliminating spam, filtering pro- Schrauwen found that they
with Jersey, the Java Persistence fanity, and safeguarding all kinds were spending too much
API, and Enterprise JavaBeans 3.1 of sites—from small blogs that time on infrastructure-

ABOUT US
(both singleton and stateless may only get one spam message related issues. That’s when
session beans). This has enabled per week to large social networks they switched to GlassFish
the team to quickly develop an
such as Europe’s Netlog, with its Server Open Source Edition.
extended REST version of their API.
85 million registered users, and “We migrated to GlassFish
For storage, Buytaert and Schrau-
large media companies such as because it let us worry less
wen chose a Cassandra cluster,
because the back end is very write- Sony Music Entertainment, which about memory management,
intensive. Cassandra also allows the host hundreds of popular art- XML parsing, database connection pooling, quality of our service is equally important,”
Mollom team to easily scale the ists’ sites. When someone makes REST handling, and a lot of other factors that Buytaert says. “Our efficiency rate is cur-
storage layer across multiple data a comment on a protected site, make big information systems work,” Buytaert rently 99.96 percent. That means if we see
centers. Currently Mollom is running that site sends the comment to says. “It lets us scale that runtime environment 10,000 messages, we make four mistakes.
on dedicated machines, and to Mollom. Mollom analyzes the more effectively. By migrating from our home- We know we are helping to keep the Web
further reduce maintenance work, content and then returns a reply grown Java-based solution to GlassFish, we a little bit cleaner. In business terms, that
Buytaert and Schrauwen plan to to the site. “It’s important for freed ourselves to focus more on the domain- means Website owners can spend a lot less
move the infrastructure to Amazon’s us to have a low latency so we specific challenges of Mollom. It’s a great fit.” time worrying about the content that doesn’t
cloud environment, and to take can process complex statistical Buytaert says new users can get Mollom belong and more time creating valuable ser-
advantage of the upcoming cloud analysis in milliseconds,” Buytaert up and running within minutes. They simply vices for their user base. </article> blog
features in GlassFish Server Open explains. “Visitors to Websites create an account on mollom.com, install a
Source Edition.
don’t want to wait after clicking plug-in, and enter public and private keys. David Baum and Ed Baum are freelance writers
Submit to see if their comments “The volume of spam comments we block specializing in innovative businesses, emerging tech-
were accepted. To accomplish is one measure of Mollom’s success, but the nologies, and compelling lifestyles.
13
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
JAVA IN ACTION
THE ENGINE OF CHOICE

JAVA TECH
A new rate and availability information service,
powered by Java, puts Choice Hotels front and center
on Google Maps. BY PHILIP J. GILL

T
Rain Fletcher hanks to the internet, the business

ABOUT US
(left), vice model and distribution channels that
president, sustained the travel and hospitality
application industry for more than two decades
development
have been transformed. The latest generation
and architecture,
Choice Hotels of mobile technologies only intensifies the
International, competition for internet traffic and reserva-
updates Todd tions between hoteliers, traditional distribution
Davis, chief systems, and a plethora of online travel agen-
technology cies, including Expedia, Travelocity, and Orbitz.
officer, on In such an intensely competitive environment,
current
any new technology or service that brings more
projects.
eyeballs to a hotel chain’s site, bypassing dis-
tribution partners as well as rivals, can offer
a significant opportunity to gain competitive
advantage and add revenue, says Rain Fletcher,
vice president, application development and blog
architecture, at Choice Hotels International.
“Our goal is to drive as many of our reserva-
tions onto our Website or into our call center
PHOTOGRAPHY BY as possible,” explains Fletcher.
PHIL SALTONSTALL
14
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
A typical day for Fletcher: back-to-back meetings with staff and
vendors; a quick phone call while grabbing coffee.

JAVA IN ACTION
JAVA TECH
ABOUT US
That’s why Choice Hotels, one of the drop-down box that shows you the hotel so we definitely have enterprise-class prob-
SNAPSHOT world’s largest lodging chains, was intrigued and the rate for that hotel from a number of lems to solve. Java is uniquely positioned as a
CHOICE HOTELS by the prospect of adding Google to its port- different sources. If you click on the link for development platform to solve those.”
INTERNATIONAL folio of distribution partners. The Web search Choice Hotels, it takes you to our Website to
choicehotels.com
giant asked Choice to participate in a new book that specific hotel.” THE CORE OF CHOICE
Headquarters: information service that it was developing for That link is a “deep” click-through that Founded in 1939 and based in Silver Spring,
Silver Spring, Maryland
its popular Google Maps and Google Places brings potential customers directly to Choice’s Maryland, with IT operations in Phoenix,
Industry:
Hospitality services. The new service, launched in July own Website—where, it is hoped, they will Arizona, Choice Hotels is one of the lead-
Revenue: 2011, displays real-time hotel room availabil- book a room. According to ing lodging companies in
US$642 million in FY 2010 ity and rates alongside location maps. Fletcher, Java was uniquely the world. Structured on the
Employees: “If you go to maps.google.com or even just suited as the language and EARLY DAYS franchise model, the chain
1,800 (U.S. only)
Java version used:
google.com and search for hotels in Phoenix platform to create this unique, Choice started out as a has more than 6,000 hotels
or Los Angeles, for instance, you’ll get a map innovative service. in the U.S. and in more than
Java Development Kit 6 with pinpoints with letters—A, B, C, D—next “Java is a true enterprise- loose affiliation of seven 30 countries around the
to them,” explains Fletcher. “The letters cor- class development platform,” independent motel globe. What began as a chain blog
respond to a hotel that’s on the nav [naviga-
tion] bar at left. The nav bar displays informa-
says Fletcher. “We operate at
internet scale. We do US$7
owners in Florida in the of motels has blossomed into
Choice’s 11 brands, which
tion about that hotel, including the name, billion in revenue a year 1930s. range from budget Econo
location, and star rating. Then there’s a little through our central channels, Lodge and Rodeway Inns and
15
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
JAVA IN ACTION
JAVA TECH
ABOUT US
Fletcher catches up midrange Quality Inns and Comfort Suites that information out to its Website, reserva- that manage our existing suite of distribution
with his staff during a to full-service Cambria Suites and the bou- tion call center, and third-party distributors. channels is quite complex,” says Fletcher. “It
hallway mini-meeting; a tique and historical hotels that are part of the Twenty years ago, these distributors has grown over the course of 15 years. When
Choice staffer crushes his Ascend Collection. included global distribution systems (GDSs), the first GDS, OTA, and online travel agen-
ping-pong opponent (an
Like others in the lodging industry, Choice’s such as Sabre, Worldspan, and Galileo, and cies started popping up, we needed to allow
Oracle rep) while Fletcher
looks on. IT infrastructure is a hodgepodge of decades- members of the Open Travel Alliance (OTA). people to book against our inventory system-
old legacy systems, some based on the first When the travel industry began to estab- atically. The technological landscape was very
computerized reservation system—originally lish a presence online, Choice added online different back then, and there’s always been
designed for the airline industry 25 years travel bureaus such as a lot of pressure to
ago—mixed in with newer systems based on Expedia, Travelocity, and PEAK PERFORMANCE deliver on those sys-
proprietary languages and protocols and some Orbitz to the mix as well. tems, so they haven’t
more-recent technologies, such as C, Java, While Choice cooper- Choice’s Google Interface service necessarily gotten the
and even a little .NET. Its core is its central ates with these partners, handles up to 750,000 transactions care and feeding that blog
reservation system (CRS), which stores up-to-
date information about Choice’s inventory of
it also competes with
them, notes Fletcher.
a day and is capable of a peak rate of they should have.”
When the Google
rooms, room rates, and availability. Layered on “The ecosystem or 540,000 transactions per hour. opportunity came
top are applications and processes that push the set of applications along, however,
16
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
really didn’t want to do that; we wanted to The Google Interface consists of three com-

More Than an App: The Google Interface project has given embrace our new architecture and start to
abstract those other systems so that, hope-
ponents, all written in Java. One component is
a custom Java EE Connector Architecture (JCA)
AN ARCHITECTURE
Choice Hotels International more than
a new and innovative way to market its fully, we can retire them one day soon.” adapter that interfaces with Choice’s CRS. The

JAVA IN ACTION
rooms to potential guests. It has also Indeed, the set of Java tools, standards, second component decides which informa-
given the lodging company a new standard for its IT systems architecture: Java. and frameworks the Choice IT team put tion needs to get pushed out to Google, and
Before the Google Interface project, Choice’s Phoenix, Arizona–based IT opera- together to develop the Google the third, a scheduler, guarantees
tions didn’t have an overall systems architecture or even a systems architecture Interface has become the com-
SPEEDY DELIVERY
that the published data is never
department, says Rain Fletcher, the company’s vice president, application develop- pany’s IT architectural standard. more than seven days old.
ment and architecture. “There was never anybody who said, ‘This is how we’re going Choice Hotels Scalability and performance
to develop software,’ so developers were left to their own devices,” Fletcher explains. THE STANDARD OF CHOICE had less than were important considerations
That approach may have worked in the past, but today Choice faces a complex,
fast-changing business environment, fueled in large part by the Web and mobile
The Google team had three
unusual technical requirements
three months for choosing Java, but Choice
had other reasons as well, says

JAVA TECH
devices. To stay on top, the company needs core IT systems that can adapt just for Choice’s new hotel information to develop its Fletcher. With Java, the company
as quickly.
To bring its systems up to date, Choice is migrating from its current legacy envi-
service. First, they wanted Choice Google Interface would achieve both hardware and
to maintain the cache of data on software vendor independence.
ronment to a new service-oriented architecture (SOA), in which business processes Google’s computers and systems, service. Choice already had Java expertise
are packaged as discrete reusable software components or enterprise services. rather than feed it out to Google to in-house—indeed, 80 percent
Because of the Google project, Choice’s new SOA is based on Java, including cache. Second, Google wanted only of its IT staff already had some
the language and its related frameworks and APIs. In addition to the benefits of a rolling 90-day supply of room and Java knowledge. Java talent is also

ABOUT US
portability, scalability, and high performance, Java is especially suited to deliver on rate information—a mere subset of the data widely available in the marketplace. Most
the promise of SOA environments. “Java has great support for SOA-based lan- in Choice’s CRS. And third, the information important of all is Java’s status as a premier
guages such as XPath, XML, and XSLT,” notes Fletcher.
had to be updated every seven days or less, language and development platform for
The proof is in the payoff. Choice is gaining four reusable enterprise services
whether it had changed or not. “They assumed enterprise applications.
from the Google project: hotel distribution information, room availability, rate
that the cache was stale after seven days, and “As a language, it is mature, well under-
changes, and inventory. Two of these services—hotel distribution and room avail-
they would stop exposing that rate and avail- stood, and has a robust and expressive suite
ability—are already being reused to power the company’s push into mobile devices
ability information,” explains Fletcher. of powerful APIs,” says Fletcher. The Google
with its Choice Mobile application for Apple iPhone and Android–based devices.
Executives on the business side at Choice Interface project, in fact, uses a number
saw the project as an intriguing extension of those APIs, including JCA and the Java
of Choice’s distribution platform. “All of a Message Service (JMS).
sudden this was the most important project “We made the decision to standardize
Choice’s IT staff quickly realized it had to in the building,” says Fletcher, adding that on Java as our standard development plat-
think outside the box. “We didn’t want to existing staff was requisitioned to work on the form specifically because of projects such as
deliver the Google Interface on the existing project in addition to their current workloads. our Google Interface,” Fletcher concludes,
platform,” explains Fletcher. “The exist- With all hands on deck and the support “which required complex logic, very high
ing tools that we had used over the last 15 of Java and the Java platform, the Google performance, and the ability to get to market blog
years to build those interfaces would have Interface went live in mid-October last year. quickly.” </article>
supported this also, although it would have Today it is available to any Google Maps or
been quite complex because of the unique Google Places user and can handle up to Philip J. Gill is a San Diego, California–based
requirements that Google presented. But we 750,000 transactions per day. freelance writer and editor.
17
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
Data Quality Tools for Java
BEFORE
Telephone Verification Name Parsing & Genderizing
john smith iii phd
melissa data corp.
Geocoding 22382 Empresa 92688
7145895200
john@800miAL.con
Address Verification &
Standardization
AFTER
Melissa Data Corp.
Email Address Verification John Smith III PhD
22382 Avenida Empresa Ste 100
Rancho Santa Margarita, CA 92688-2112
949-589-5200
John@melissadata.com
Delivery Indicator: Business
*Highlights indicate added and/or corrected data.

Realtime NCOALink
Change-of-Address
Web Services & APIs Web Service
available
Duplicate Elimination

Now, finding the right data verification tools doesn’t have to be so puzzling. • Global address verification for 240 countries
Melissa Data offers customizable APIs, Web services and enterprise appli- • Clean and validate data at point-of-entry or in batch
cations to match your budget and business needs. For solutions to cleanse, • Correct misspellings, missing directionals, and confirm deliverability
validate and standardize your contact data, we’re ready to help you find the • Enhance addresses with County, Census, FIPS, etc.
perfect fit. • Append rooftop lat/long coordinates to street addresses
• Update records with USPS and Canadian change of address info

Request free trials at


MelissaData.com/myjava or call 1-800-MELISSA
//new to java /

COMMUNITY
Shall We Play a Game?

JAVA IN ACTION
Improving and extending the code leads to the first playable version of our turtle game.

MICHAEL KÖLLING I n the last two issues of Java


Magazine, I introduced the
beginning of a little computer
it is a good idea to take a minute
to improve the structure of our
code. Specifically, our act method
at the beginning containing some
asterisks. For example, the eat
method starts with this:
as the previous version—it is
functionally equivalent. However,
because we have chopped it up
BIO game, written in Java using the is getting somewhat long, and it into smaller pieces, it is now

JAVA TECH
Greenfoot environment. We cre- is starting to take some effort to /** easier to read, and we can more
ated a keyboard-controlled turtle read it and work out what it does. * Look for pizza and eat it easily recognize what the act
that walks around eating pizza. In general, we should strive to if we see some. method does.
In this article, we’ll start mak- keep our methods short and clear. */ You should make the same
ing things more interesting by We can do this by breaking the act changes in your own code.
introducing a predator that’s after method into multiple methods, This is a method comment. A
our turtle—not only must our each defining one logical task. comment is written for the pro- Snakes on a Plane!
turtle collect pizza slices, but it In our example, our act method grammer (not for the computer). It Now that we have improved our

ABOUT US
must do so while avoiding being does two logically distinct tasks: explains, in plain English, the pur- code structure, we can move for-
eaten by a snake! ■■ Movement (moving forward pose of the method that follows. ward and add to our project. We
You can download the project as and possibly turning) The lines following the com- now want to introduce an enemy
it was at the end of our last article ■ ■ Looking for pizza (and possibly ment define the method. You will of our turtle: snakes.
here. We will continue from where eating it) notice that the method bodies Start by creating another sub-
we left off, so if you We can move each of contain exactly the same code class of Actor, named Snake, with
missed the last articles, these two tasks into a that was previously in the body of a snake image. (Remember, you
CLASS ACTION
it might be a good idea separate method, and the act method in Listing 1. can create an Actor subclass by
to look at them first to You can find out then call each method Now, in Listing 2, the act right-clicking the Actor class and
see how we got this far. about methods from the act method. method contains only calls to the choosing New subclass. Name the
Listing 2 illustrates this. two new methods: class Snake and choose a snake
Cleaning Up Our Code available in the In this version of the image from the Animals category
The turtle’s act method, Greenfoot code, we have defined public void act() (see Figure 1.)
as we left it last time,
is shown in Listing 1.
classes by two additional meth-
ods, moveAndTurn and
{
moveAndTurn();
Compile your scenario and
place a few snakes into your world
Before we go on to add looking up the eat. Have a good look at eat(); (see Figure 2). You might want to blog
more functionality to Greenfoot class Listing 2 to see how this } save the world again (right-click
our program (and, in
the process, make our
documentation. was done.
Each of the method Note that this version of our
the world background and choose
Save the World) to add your
PHOTOGRAPH BY JOHN BLYTHE code more complex), definitions has a section code does exactly the same thing snakes to the saved world.
19
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3
Snake Behavior moveAndTurn, eat) into the Snake class.
public void act()
Initially, our snakes don’t do anything. Do this by using copy and paste to
{
We would like them to move around the replace the empty default act method in
move(4);
screen randomly and try to eat the turtle. the Snake class. Make sure you watch the

JAVA IN ACTION
The goal for the player, then, is to control brackets—the class body still needs an if(Greenfoot.isKeyDown("left")) {
the turtle and eat all pizza slices while opening and closing curly bracket. turn(-3);
evading the snakes. At this point, you might like to }
We can start by copying all three compile and run your scenario to test
if(Greenfoot.isKeyDown("right")) {
methods from the Turtle class (act, what it does. It’s not exactly what we
turn(3);
want yet, but it does
}
something. (You will see
that the snakes follow your Actor pizza = getOneIntersectingObject(Pizza.class);

JAVA TECH
key presses, just as the if(pizza != null) {
turtle does.) getWorld().removeObject(pizza);
There are two things }
}
we’d like to change in
the class Snake from the
copied turtle behavior.
First, snakes should eat
turtles, not pizza. And

ABOUT US
second, snakes should
move around on their own
(randomly), rather than be
controlled by the keyboard.
We can make the first
change by going to the
Figure 1 snake’s eat method and
replacing all mentions of
“pizza” with “turtle,” as
shown in Listing 3.
Pay attention to capi-
talization: Uppercase and
lowercase letters must be
used exactly as shown.
When writing Turtle (with
a capital T), we are refer- blog
ring to the Turtle class.
When writing in lowercase
(turtle), we are referring to See all listings as text
Figure 2 a variable.
20
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
Test your scenario. Snakes should eat the turn method (instead of the number Improving the Game For now, I’ll leave you to explore these
turtles, not pizza. 3 we used previously), the snake should There are many ways in which you can methods yourself. (The most interesting
walk more randomly: improve this game. Instead of talking classes to look at initially are the Actor
Random Walking you through some of them right now, I’ll and Greenfoot classes.) In the next issue

JAVA IN ACTION
At the moment, the snakes are still con- turn(Greenfoot. show you something more useful: how of Java Magazine, we will explore some
trolled by the same keyboard keys that getRandomNumber(20)); you can find out more for yourself. more of them.
steer the turtle. That’s not good. We can So far, I have introduced various use- Tip: You can see and download many
change this, first by making snakes run If you try this, you will notice that the ful methods that we could use, such Greenfoot Java programs on the
in circles. snake is still moving in a circle, albeit a as move and turn in the Actor class and Greenfoot Website.
Remove the code from the body of somewhat irregular one. The reason is getRandomNumber from the Greenfoot
the snake’s moveAndTurn method that that the turns—even though somewhat class. So how do you find out what other Conclusion
implements the keyboard-controlled random—are always right turns. methods there are for you to use? In this article, you learned a few specific

JAVA TECH
turning, and replace it with a simple To fix this, we need to make the snake The answer lies in looking up the things about Java code and some gen-
turn(3) statement. Your method should turn left as well. Turning left is done by class documentation. Choose Greenfoot eral principles:
now look like this: turning at a negative angle. Instead of Class Documentation from Greenfoot’s ■■ Code should be structured so that you

turning between 0 and 20 degrees, we Help menu. This will open a Web have small methods and each does
public void moveAndTurn() would like to turn between minus 20 browser that lists all the classes one logical task. (The act method
{ degrees and 20 degrees. of the Greenfoot system. (You will itself should often contain only calls
move(4); We can achieve this with the follow- see that there are six classes: Actor, to other methods.)
turn(3); ing change: World, Greenfoot, GreenfootImage, ■■ Random numbers can be used to cre-

ABOUT US
} GreenfootSound, and MouseInfo.) ate random behavior in your program
turn(Greenfoot. Click the Greenfoot class to see the (such as random movement).
Try it out. Snakes are now moving getRandomNumber(40)-20); documentation for this class. If you scroll ■■ You can find out about methods

on their own (even though it’s in a very down a bit on the page, you will see a list available in the Greenfoot classes
predictable pattern). That is, we first get a random num- of methods available in this class. There by looking up the Greenfoot class
Now we want to make the movement ber using 40 as the specified limit, and are the getRandomNumber and isKeyDown documentation.
more random. To do this, we can use a then we subtract 20 from it. The result methods that we have used already and ■■ Class documentation is provided

method from the Greenfoot class called will be between –20 and 20. (Actually, a good number of other ones. in javadoc format, which shows
getRandomNumber. This method will if you think carefully about it, this is The format this is displayed in is you information about all available
give us a random number between 0 slightly incorrect. The result will be called javadoc. It is a standard format classes and about each method
and a specified limit. For example, the between –20 and 19. Can you figure for documenting Java methods, and within each class. </article>
following will give us a random number out why? Can you correct this? It is not this helps in determining what par-
between 0 and 19 (the specified limit actually very important in our context ticular classes can do. The documenta-
itself is always excluded): to correct this slight imprecision—the tion includes the return type (what the
snake is moving erratically, so a little method returns to you when you call
Greenfoot.getRandomNumber(20) bias does not hurt much.) it), the signature (that is, its name and blog
Try this turn instruction (instead of parameters), and a comment explaining LEARN MORE
We can use this method to make the the previous turn(3)) in your own code. what the method does. Here, you can • Java API
turns of the snake less predictable. If we You will see that the game suddenly find out all about other available meth- • ”Getting Your Feet Wet” in the Premiere
use a random number as a parameter to becomes a lot more interesting! ods and how to call them. issue of Java Magazine
21
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
Part 3
Introduction to RESTful
Web Services

JAVA IN ACTION
MAX BONBHEL RESTful Web services versus JAX-WS Web services: The face-off!
BIO

I n Part 2 of this three-part Protocol (SOAP) Web services, guage for describing Web services Prerequisites

JAVA TECH
series, I showed how to handle such as security, reliability, and and how to access them. A WSDL The following software was
a RESTful Web service response transactions. document is written in XML and used to develop the application
to the client in JSON representa- Note: The complete source code specifies the location of the Web described in this article:
tion format. We also used HTML5, for the application designed in this service and the operations (or ■■ NetBeans, which can be down-

JavaScript, and Ajax to call the article can be downloaded here. methods) the service exposes. loaded here
Web service, store the informa- SOAP, which is written in ■■ JAX-WS implementation

tion locally, and display the infor- What Are JAX-WS Web XML format, is one of the proto- (included in NetBeans), which
mation later. Services? cols used with Web services for is the Java EE specification

ABOUT US
Now, in Part 3, we will create a Unlike RESTful Web services, enabling applications to exchange (JSR-224) for building SOAP
complete application based on JAX-WS Web services are gener- information over HTTP. In this Web services
a Java API for XML Web Services ally used for larger applications article, we will see how SOAP uses ■■ AuctionApp, which can be

(JAX-WS) Web service and see that demand several channels XML for transmitting messages downloaded here
in detail how to use a JavaServer of communication among plat- between applications. Note: This article was tested using
Faces (JSF) client to access and forms, and they provide tools for
consume the Web service. In the integration and interoperability.
end, we will have two JAX-WS allows us to
types of Web services in QUICK WIZARD develop and deploy Web
one application. This will We will use theservices easily using
allow us to compare and
easily choose the type of
Web Service the Java platform.
JAX-WS provides many
Web service that best fits Client wizard protocols to facilitate
our needs. provided by thecommunication among
Part 3 ends the series,
but it is also a good
NetBeans IDE systems, such as SOAP
(1.1 and 1.2), XML, HTTP, blog
segue to a new three- to create a Weband more.
part series that will focus service in five WSDL (Web Services
In this screencast, Max Bonbhel provides an
PHOTOGRAPH BY
ALLEN MCINNIS/GETTY IMAGES
on the different aspects
of Simple Object Access
minutes. Description Language)
is an XML-based lan-
introduction to his article.
22
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
LISTING 1 LISTING 2
JAX-WS Web service via a JSF
package com.bonbhel.oracle.auctionApp.ws;
application.
import javax.jws.WebService;
Let’s Add and Test the import javax.jws.WebMethod;

JAVA IN ACTION
JAX-WS Web Service import javax.jws.WebParam;
To begin, we need to add the import javax.ejb.Stateless;
SOAP Web service capability to
our existing application. /**
Figure 1
* @author Max Bonbhel
  1. Add the new Web ser-
*/
NetBeans IDE 7.0.1, but as of this writ- vice in the AuctionApp
@WebService(serviceName = "AuctionAppSOAPws")
ing, the latest version of the NetBeans application: @Stateless()
IDE is 7.1.  a. Open the AuctionApp in NetBeans public class AuctionAppSOAPws {

JAVA TECH
IDE version 7 or later. /** This is a sample web service operation */
Real-Life Application for JAX-WS Web  b.  Right-click the AuctionApp project @WebMethod(operationName = "hello")
Services with NetBeans 7.0.1 note and choose New. Then select public String hello(@WebParam(name = "name") String txt) {
return "Hello " + txt + " !";
In this practical section, we will build a Web Service.
}
real-life application step by step so that Type AuctionAppSOAPws in the Web
 c. 
}
you can learn quickly the basics of the Service Name field and type com
JAX-WS Web services. .bonbhel.oracle.auctionApp
We will use the NetBeans GO BIG .ws in the Package field. Then See all listings as text

ABOUT US
IDE for developing a typical
enterprise application that
Unlike RESTful click Next.
 d.  Select the Implement
will show you how to access Web services, Web Service as a   2. N
 ow add a specific operation to the  g.  Click OK.
and consume a JAX-WS Web JAX-WS Web Stateless Session Bean Web service that will extrapolate the 3. Edit and modify the generated
service (an external service
that resides in the applica-
services are box in the upper part
of the New Web Service  a. 
amount of the bid by item:
Open the Web Services node of
operation, as shown in Listing 2.
4. Test the JAX-WS Web services:
tion tier) from JSF client generally used for dialog box. the AuctionApp project and right-  a.  Right-click the AuctionApp project
applications. larger applications  e.  Click Finish. click the AuctionAppSOAPws node. and choose Deploy.
What we are going to do NetBeans generates the Then select Add Operation.  b.  Expand the Web Service node
is add new capabilities to that demand structure for the new Web  b.  Type extrapolateAmountBid in the of the AuctionApp project. Then
the AuctionApp we started several channels service with a sample Web Name field and type double in the right-click the AuctionAppSOAPws
creating in Part 1 of this
series of articles by doing the
of communication service and all the resources
we need to operate our Web  c. 
Return Type field.
Click Add in the lower part of the
node and choose Test Web Service.
A tester page is displayed in your
following: among platforms, service. Add Operation dialog box. browser. If you see the page shown
■■ Add a new JAX-WS Web
and they At this point, the source  d.  Type amountBid in the Name field in Figure 1, it means your JAX-WS
blog
service that extrapolates
the amount of the bid.
provide tools for code for the Web service can
be edited in the editor. Your
and type double in the Type drop-
down list.  c. 
Web services are working correctly.
Type two numbers in the tester
■■ Generate the WSDL file. integration and AuctionAppSOAPws.java file  e.  Click Add again. page: 80 for amountBid and 100
■■ Create a Web service
interoperability. should look like the code  f.  Type factor in the Name field and for factor.
client to consume the shown in Listing 1. type int in the Type drop-down list.  d.  Click extrapolateAmountBid.
23
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
AT YOUR SERVICE The result of the  g.  Click Finish.  d.  Click Finish.  f. Accept all other default settings.
operation is displayed   2. Create the entities based on the   4. Use the Web Service Client wizard The package name will be taken
JAX-WS allows in Figure 2. datasource we created in Part 1 of to create the Web service client. from the WSDL file.
us to develop this series: (We will assume that the JAX-WS  g.  Click Finish.
and deploy Web

JAVA IN ACTION
Let’s Consume  a.  Right-click the Web service is an external service NetBeans generates the struc-
the JAX-WS Web AuctionAppWebServiceClient that resides in the application tier ture of the new Web service client,
services easily Services with a JSF project and select New. Then select over the network. So, we will use as shown in Figure 3.
using the Java Client Application Entity class from Database. the URL to the JAX-WS Web service Note: If the WSDL file cannot be down-
It’s time to create a  b.  In the Databases Tables dialog box, WSDL file.) loaded, click Set Proxy and then specify
platform. Web client to con- select your datasource in the Data  a.  Make sure the AuctionApp the proxy server.
sume the JAX-WS Source drop-down list. we started creating in
Web services we cre-  c.  In the upper part of the Databases Part 1 of this series is

JAVA TECH
ated. So we are going Tables dialog box, select the BID, up and running. If it
to quickly build a sample front-end JSF SELLER, and ITEM tables and is not, right-click the
application to allow a user to perform the click Next. AuctionApp node and
following tasks:  d.  In the Entity Classes dialog choose Deploy.
■■ Enter information for the seller, item, box, type a Package name,  b.  Open the Web Service
and bid. such as com.bonbhel.oracle node of the AuctionApp
■■ Extrapolate the amount of the bid .auctionAppWebServiceClient. project and right-click
using the JAX-WS Web service.  e.  Accept all other default settings, the AuctionAppSOAPws

ABOUT US
■■ Display the information. and then click Finish. node. Then select
We will use the Web Service Client NetBeans generates the Seller.java, Properties.
wizard provided by the NetBeans IDE Item.java, and Bid.java files.  c.  Notice that the URL of
to generate the code and everything we   3. The client implementation we are the WSDL file is shown
need for looking up a Web service. going to build consists of JSF pages in the upper part of
Let’s code this application in five based on the entities just created, so the Properties dialog
Figure 2
minutes. create the JSF pages: box. You need it for a
  1. Generate the initial NetBeans  a.  Right-click the later step.
project: AuctionAppWebServiceClient  d.  Right-click the
 a.  From the File menu, choose New project and select New. Then select AuctionAppWebService­
Project. JSF Pages from Entity Classes, click Client node and choose
 b.  From Categories, select Java Web. Add all, and click Next. New. Then select Web
 c.  From Projects, select Web  b.  Type a Session Bean Package name, Service Client.
Application. such as com.bonbhel.oracle.auction-  e.  In the New Web Service
 d.  Click Next. AppWebServiceClient.facade, and Client wizard, specify
 e.  Type a project name, type a JSF Classes Package name, the URL to the Web blog
AuctionAppWebServiceClient, and such as com.bonbhel.oracle.auction- service WSDL file:
click Next. AppWebServiceClient.controller. http://localhost:8080/
 f.  Make sure the server is GlassFish  c.  Type a Folder Name, such as AuctionAppSOAPws/
Server (or similar wording). jsfClient, and click Finish. AuctionAppSOAPws?wsdl. Figure 3
24
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//new to java /

COMMUNITY
LISTING 3 LISTING 4
5. Add the extrapolateAmountBid opera-  b.  Put your cursor anywhere inside
private double extrapolateAmountBid
tion provided by the JAX-WS Web the source editor.
(double amountBid, int factor) {
service to the client classes:  c.  Expand the Web Service
com.bonbhel.oracle.auctionapp.ws.AuctionAppSOAPws
 a.  Open the Source Packages node of References node of the port = service.getAuctionAppSOAPwsPort();

JAVA IN ACTION
the AuctionAppWebServiceClient AuctionAppWebServiceClient return port.extrapolateAmountBid(amountBid, factor);
project and double-click the project and drag the extrapolate­ }
BidController.java file located in the AmountBid node inside the
controller package com.bonbhel source editor.
.oracle.auctionAppWebService- Note: Alternatively, you can right-click
Client.controller. anywhere in the source editor and
choose Insert Code. Then select Call
Web Service Operation and click the

JAVA TECH
extrapolateAmountBid operation in
the Select Operation to Invoke See all listings as text
dialog box.
6. The extrapolateAmountBid() method
appears at the end of the BidController AuctionAppWebServiceClient gration of RESTful Web services and
Figure 4 class code, as shown in Listing 3. project and choose Run. JAX-WS Web services in the same appli-
7. We need to add some application The list of all entries is displayed, as cation allowed us to compare them so
logic in the BidController class in shown in Figure 4. we can choose the type of Web service

ABOUT US
order to extrapolate the amount 2. Invoke the JAX-WS Web service to that best fits our needs.
of the bid (by factor, which is 100) display the extrapolated amount of NetBeans provide many tools and
when the user is editing or viewing the bid: services for creating Web services for
the bid entry. So call the  a.  Click the Show all Bid Items link the client side and for consuming and
extrapolateAmountBid operation to display the list of bid entries, as accessing over the network external
to extrapolate the bid: shown in Figure 5. services that reside in the application
 a.  Open the BidController.java file in  b.  Click the View link of any Bid item tier. </article>
Figure 5 the source editor. to see the newly extrapolated
 b.  Modify the public String prepare­ amount of the bid. In our case it’s
View() method, as shown in Carolis’ Bid, as shown in Figure 6.
Listing 4. As you can see, the amount of LEARN MORE
the bid changed from 800.0 to • NetBeans documentation, training,
Testing the Client Application 80000.0. and support
1. Run the JSF client application:  c.  Now you can smile, because it • ”Developing JAX-WS Web Service Clients”
 a.  Make sure the AuctionApp we works!
• ”Binding WSDL to Java with JAXB”
started creating in Part 1 of this blog
• ”Advanced Web Service Interoperability”
series is up and running. If it is not, Conclusion
right-click the AuctionApp node We have seen how easy it is to configure • ”Web Services Learning Trail”
and choose Deploy. a JAX-WS Web service and consume it • Oracle University: Developing Web
Figure 6  b.  Right-click the from a JSF application client. The inte- Services Using Java Technology, Java EE 6
25
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
Cloud/Java EE
Tame the Cloud

JAVA IN ACTION
Oracle’s Cameron Purdy on how Java EE is evolving to become the
cloud computing platform standard. BY MICHAEL MELOAN

T
he enterprise land-
scape is increas-

JAVA TECH
ingly complex, with
information flowing from
more sources than ever
before. The emphasis is
shifting from standalone
applications to dynamic
shared environments

ABOUT US
that will enhance scal-
ability, automation, and
efficiency. Cloud computing
promises to be a transfor-
mational technology for
Java EE. Cameron Purdy, vice
president of Java EE develop-
ment at Oracle, provides an
Java Magazine: How will cloud computing deliver
overview of the key issues in
advantages in the enterprise space?
this arena and how they will
Purdy: At this fairly early stage in the development
affect enterprise developers
of cloud technology, the major focus is on PaaS
and customers.
[platform-as-a-service] capability. A number of
infrastructure cloud vendors offer dozens or even
hundreds of servers as easily as buying something
on an e-commerce site. This is a move toward blog
decentralization and democratization of IT infra-
structure. It offers abstraction of hardware and
software elements all the way up to development
PHOTOGRAPHY BY DAVE BRADLEY
ART BY I-HUA CHEN environments and middleware components, which
26
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
frees developers to focus on enterprise solu- ations in its products? Java Magazine: What are the most important
tions. This approach offers real benefits in Purdy: Sure. For example, within Oracle aspects to consider when implementing a
terms of operational simplicity, time to mar- WebLogic Server 12c, we provide support for cloud-oriented enterprise architecture?
ket, and cost savings. dependency injection, the Java Persistence Purdy: There are three key concepts related

JAVA IN ACTION
At Oracle, we’ll be looking at how PaaS will API [JPA], and a uniform build process via the to deploying enterprise PaaS solutions:
affect different roles within an organization, Maven WebLogic Plug-in, as well as for Agile availability, elasticity, and multitenancy.
PRIMED FOR CLOUD
such as development, QA, operational stag- development methodology in concert with In general, applications will be running on
The container-based ing, and actual production operations. Then Hudson Continuous Integration. These stan- virtual machines in a remote environment
architecture and its we need to integrate these considerations dards make enterprise applications easier to controlled through a Web-based console.

inherent abstraction into our own suite of products, as well as


work with our industry partners to standard-
build as well as operate. Significant improve-
ments have also been realized in managing
Because there is no physical access to a local
system, the ability to mitigate problems is
of resource access ize the model, the APIs, and the overall Java and achieving high performance in virtual- dramatically reduced. To ensure availability,
make the Java

JAVA TECH
EE platform specifications. ized environments, which is a prerequisite systems need to be more autonomic. They
Java Magazine: Can you provide an example in PaaS environments. At Oracle, we deliver need to be self-healing. One of the ways to
EE platform well of how Oracle is reflecting these consider- these optimizations with Oracle VM. achieve this resiliency is through redundancy.
suited for cloud
computing.

ABOUT US
(From left to right)
Oracle’s Mac Hale,
director of soft-
ware development;
Cameron Purdy,
vice president of blog
Java EE develop-
ment; and Jim
Gish, consulting
member of techni-
cal staff, talk shop.
27
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
Maintaining availability, even in the event of and memory demands by a particular tenant. EE 7. The major theme in Java EE 6 was ease
hardware failure or electrical failure, requires Managing and restricting how many resources of use, and that continues in Java EE 7. But
that the application be running in multiple a tenant can consume is one of the funda- the prime mover for Java EE 7 will be the
places, and possibly in multiple data centers, mental challenges of multitenant systems. cloud. The container-based architecture and

JAVA IN ACTION
to prevent a single point of failure. We need to make sure that a tenant can’t its inherent abstraction of resource access
Availability is also facilitated through the chew up an entire CPU or use so much mem- make the Java EE platform well suited for
concept of elasticity. Applications need to be ory that a system is brought to its knees. We cloud computing. This approach ensures
robust enough to seamlessly operate while a want to provide building block technologies to that portable applications can target single-
given server is down for maintenance or due to manage these issues for our customers. machine deployments as well as large cluster
failure. They must also be able to respond to As we revisit each aspect of Java EE, multi- installations without fundamental changes
additional capacity demands from increases tenancy, availability, and elasticity will all be to the programming model. The move to
in concurrent users or fluctuations in process- important considerations in planning with cloud computing is a further evolution of this

JAVA TECH
ing load. Elastic applications must be able to our partners for the future of the platform. powerful paradigm.
add resources dynamically, which fits very well Java Magazine: What new capabilities will the Multitenancy will be supported via virtual
with the cloud computing metaphor. Java EE 7 release offer? servers mapping requests to a tenant. And
The concepts of availability and elasticity Purdy: We are working very closely with our there will be more emphasis on CDI [Contexts
are both in concert with enterprise architec- industry partners to define and deliver Java and Dependency Injection], the JPA,
tures built around PaaS and IaaS [infrastruc-
 racle’s Mike
O ture as a service].
Lehmann and
Arun Gupta Multitenancy is also an important principle

ABOUT US
discuss Oracle in cloud computing. It refers to the ability
WebLogic Server to collocate multiple users within a single
12c at Oracle environment. A CRM [customer relationship
OpenWorld Latin management] system, for example, would
America 2011 in
São Paolo, Brazil. need to provide service to a number of differ-
ent companies. Each company represents a
different tenant. And those tenants could be
supported by dedicated hardware, or virtu-
alized, providing each tenant with a virtual
machine or a set of virtual machines within
a given hardware infrastructure. There are
many levels of multitenancy, even down to
multiple tenants inside a single JVM [Java
Virtual Machine].
There are trade-offs across the board in
multitenant architectures. Security, resource blog
utilization, and cost issues are at the fore-
front. Creating isolation and protection within
a JVM is an important area of investment right In Oracle's Burlington, Massachusetts, office, Oracle Architect Gene Gleyzer updates
now. We are also looking at how to meter CPU Purdy on his current projects.
28
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
JSR for Java SE, to ensure alignment across ronments, and we’re looking forward to sup-
the Java SE and Java EE platforms. porting this approach in the Java EE platform.
Java Magazine: Modularity and lambda Java Magazine: Any closing observations on
expressions are major themes for Java the importance of the cloud for the future of

JAVA IN ACTION
SE 8. How will Java EE benefit from these enterprise systems?
developments? Purdy: I believe we’re on the cusp of a new
Purdy: We see a broad set of possibilities for wave of innovation. We saw this roughly 15
these capabilities. Modularity is an impor- years ago, with a surge of development around
tant area of focus for Oracle toward Java EE. Web-oriented technologies. And 10 years
It will yield benefits in scalability, robustness, ago, with the release of J2EE, we saw the rise
and maintainability. Project Jigsaw is the of business applications moving to the Java
OpenJDK effort to design and implement a EE platform. Right now it’s happening again,

JAVA TECH
standard module system for the Java SE plat- as incredible investments are being made to
form. Its implementation take advantage of what cloud technology can
Dave Carrano, software
in Java SE 8 will provide provide in terms of cost savings and flexibility.
engineer, shares his work
with Purdy; Alex Gleyzer, an instrumental building Concurrently, we’re moving toward sig-
vice president of develop- block for evolving the Java nificantly enhanced user experiences that
ment, talks with Purdy enterprise platform. will be provided by HTML5. This confluence
about Java EE 7. We’ve already been able of important new technologies represents
to leverage the work of a unique opportunity to evolve the Java

ABOUT US
the OSGi [Open Services Enterprise platform and bring new partners,
Gateway initiative] to organizations, and developers into the arena.
build modularity into It will powerfully expand the technological
Oracle GlassFish Server landscape and the entire enterprise market.
and GlassFish Server I expect to see wonderful levels of innova-
Open Source Edition. With tion as we begin to explore the possibilities of
Project Jigsaw coming to HTML5 and cloud technology. It’s incredibly
Java SE, we will continue to exciting to be a part of it. </article>
proliferate this approach
with standards like OSGi
JAX-RS [Java API for RESTful Web Services], and integrate these efforts very closely with
Michael Meloan began his professional career writing
JSF, Servlets, and EJBs. capabilities supported by the JVM. IBM mainframe and DEC PDP-11 assembly languages.
We also expect the Java EE 7 platform to Regarding lambda expressions, they’re He went on to code in PL/I, APL, C, and Java. In addi-
add support for new and evolving technolo- typically useful in implementing aggregate tion, his fiction has appeared in WIRED, BUZZ, Chic,
gies in the Web space, including WebSockets operations that can frequently be parallel- LA Weekly, and on National Public Radio.
and HTML5, and a modern HTTP client API as ized using multicore processors. We’ve seen blog
defined by JAX-RS 2.0. opportunities for leveraging this in technolo-
Modularity and versioning capabilities gies like JDBC, JPA, EJBs, JMS filtering, and LEARN MORE
are also being investigated. This work will be many other areas. Lambda expressions have • Java EE at a Glance
coordinated with the upcoming modularity been powerful in other languages and envi- • Oracle WebLogic Server
29
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
Cloud/Java EE
Looking Ahead to Java EE 7

JAVA IN ACTION
Get educated about Java EE 7 JSRs.

ARUN GUPTA
W ith the release of Java EE 7 Possible inclusion of JAX-RS Project page Java Servlet 3.1 Specification
■■ ■■

BIO scheduled for the second 2.0 in the Web Profile, revised ■■ Mailing list archive, jsr338- (JSR-340)
half of 2012, projected JSRs are all JMS 2.0 API experts@jpa-spec.java.net, ■■ Optimize the PaaS model for
up and running. The Java EE 7 ■■ Technology refresh for several users@jpa-sepc.java.net Web applications

JAVA TECH
release, which will reflect the existing technologies and pos- ■■ Multitenancy for security, ses-
evolving needs of the industry as sible inclusion of Concurrency JAX-RS 2.0: The Java API for sion, and resources
it moves into the cloud, is date Utilities for Java EE (JSR-236) RESTful Web Services (JSR-339) ■■ Asynchronous IO based on NIO2
driven: anything not ready will be and JCache (JSR-107) ■■ Client API—low level using ■■ Simplified asynchronous
deferred to Java EE 8. ■■ Status: builder pattern and possibly a Servlets
Here is an update and sum- ■■ Approved by the JCP higher level on top of that ■■ Utilize Java EE concurrency
mary of the key features of differ- ■■ Spec leads: Linda DeMichiel, ■■ Hypermedia—easily create and utilities
ent specifications in the Java EE 7 Bill Shannon (Oracle) process links associated with ■■ Enable support for WebSockets

ABOUT US
platform. ■■ Project page resources ■■ Status:
■■ Mailing list archive, ■■ Form or Query parameter vali- ■■ Approved by the JCP

Java EE 7 Specification (JSR-342) jsr342-expert@javaee-spec dation using Bean validation ■■ Spec leads: Shing-Wai Chan,

■■ Main theme: to easily run .java.net, users@javaee- ■■ Closer integration with @Inject Rajiv Mordani (Oracle)
applications on private or pub- spec.java.net ■■ Server-side asynchronous ■■ Project page

lic clouds request processing ■■ Mailing list archive, jsr340-

■■ The platform will define an Java Persistence 2.1 (JSR-338) ■■ Server-side content negotiation experts@servlet-spec.java
application metadata descriptor ■■ Support for multitenancy using “qs” .net, users@servlet-spec
to describe the PaaS execution ■■ Support for stored procedures ■■ Status: .java.net
environment such as multi- and vendor function ■■ Approved by the JCP,

tenancy, resources sharing, ■■ Update and Delete Criteria Early Draft available, Expression Language 3.0
quality of service, and depen- queries Draft Javadocs (JSR-341)
dencies between applications ■■ Support for schema generation ■■ Spec leads: Santiago Pericas- ■■ Separate ELContext into pars-
■■ Embrace latest standards like ■■ Persistence Context Geersten, Marek Potociar ing and evaluation contexts
HTML5, WebSocket, and JSON synchronization (Oracle) ■■ Customizable EL coercion rules
and have a standards-based ■■ CDI injection into listeners ■■ Project page ■■ Reference static methods blog
API for each one of them ■■ Status: ■■ Mailing list archive, and members directly in EL
■■ Remove inconsistencies ■■ Approved by the JCP jsr339-experts@jax-rs-spec expressions
between Managed Beans, EJBs, ■■ Spec lead: Linda DeMichiel .java.net, users@jax-rs-spec ■■ Adding operators like equality,
PHOTOGRAPH BY
MARGOT HARTFORD Servlets, JSF, CDI, and JAX-RS (Oracle) .java.net string concatenation, and size of
30
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
■■ Integration with CDI such as generat- CDI, OSGi support for JSF artifacts ■■ API for managing built-in contexts ■■ Status:
ing events before/during/after the ■■ Support implementation of Portlet ■■ Embedded mode to allow startup ■■ Approved by the JCP

expressions are evaluated 2.0 Bridge (JSR-329) outside Java EE container ■■ Spec leads: Yannis Cosmadopoulos

■■ Status: ■■ Support for HTML5 features like ■■ Declarative control over which pack- (Oracle), Cameron Purdy (Oracle),

JAVA IN ACTION
■■ Approved by the JCP HTML5 Forms, Metadata, Heading ages/beans are scanned in an archive and Gregory Luck (Software AG)
■■ Spec lead: Kin-man Chung (Oracle) and Section content model ■■ Injection for static members such as ■■ Project page

■■ Project page ■■ Flow management, listener for page loggers ■■ Mailing list archive

■■ Mailing list archive, jsr-341- navigation events, and new compo- ■■ Send Servlet events as CDI events
experts@el-spec.java.net, users nents like FileUpload and BackButton ■■ Status: Java State Management (JSR-350)
@el-spec.java.net ■■ Status: ■■ Approved by the JCP, Early Draft ■■ API that can be used by applications
■■ Approved by the JCP, Early Draft available and Java EE containers to offload the
Java Message Service 2.0 (JSR-343) available ■■ Spec lead: Pete Muir (RedHat) responsibility of statement manage-

JAVA TECH
■■ Ease of development—changes to ■■ Spec lead: Ed Burns (Oracle) ■■ Project page ment to third-party providers with
the JMS programming model to make ■■ Project page ■■ Mailing list archive, twitter feed different QoS characteristics
the application development simpler ■■ Mailing list archive, jsr344- ■■ Java SE–based callers can access
and easier experts@javaserverfaces-spec- Bean Validation 1.1 (JSR-349) the state data by querying the state
■■ Remove/clarify ambiguities in the public.java.net, users ■■ Integration with other Java EE specs providers
existing specification @javaserverfaces-spec-public ■■ JAX-RS: Validate parameters and ■■ Providers with different QoS can be
■■ Integration with CDI .java.net return values on HTTP calls added, and API callers can query to
■■ Clarification of the relationship ■■ JAXB: Convert constraints into XML meet their criteria

ABOUT US
between JMS and other Java EE specs Enterprise JavaBeans 3.2 (JSR-345) schema descriptor ■■ Package: javax.state and javax.state
■■ A new mandatory API to allow any ■■ Enhancements to the EJB architecture ■■ Method level validation .provider
JMS provider to be integrated with to enable PaaS, such as multitenancy ■■ Apply constraints on group collection ■■ Status:
any Java EE container ■■ Factorization of container-managed ■■ Extend the model to support AND ■■ Approved by the JCP

■■ Multitenancy and other cloud-related transactions to use outside EJB and OR style composition ■■ Spec lead: Mitch Upton (Oracle)

features from the platform ■■ Further use of annotations ■■ Status: ■■ Project page

■■ Status: ■■ Alignment and integration with other ■■ Approved by the JCP ■■ Mailing list archive, jsr-350-

■■ Approved by the JCP specifications in the platform ■■ Spec lead: Emmanuel Bernard experts@java-state-management
■■ Spec lead: Nigel Deakin (Oracle) ■■ Status: (RedHat) .java.net
■■ Project page ■■ Approved by the JCP ■■ Project page

■■ Mailing list archive, jsr-343- ■■ Spec lead: Marina Vatkina (Oracle) ■■ Mailing list archive Batch Applications for the Java
experts@jms-spec.java.net, ■■ Project page Platform (JSR-352)
users@jms-spec.java.net ■■ Mailing list archive, jsr-345- JCACHE: Java Temporary Caching API ■■ Programming model for batch appli-
experts@ejb-spec.java.net, users (JSR-107) cations and a runtime for scheduling
JavaServer Faces 2.2 (JSR-344) @ejb-spec.java.net ■■ API and semantics for temporary, and executing jobs
■■ Ease of development—making con- in-memory caching of Java objects, ■■ Defines Batch Job, Batch Job Step, blog
figuration options dynamic, make Contexts and Dependency Injection including object creation, shared Batch Application, Batch Executor,
cc:interface in composite compo- for Java EE 1.1 (JSR-346) access, spooling, invalidation, and and Batch Job Manager for the stan-
nents optional, shorthand URLs for ■■ Global ordering of interceptors and consistency across JVMs dard programming model
Facelet tag libraries, integration with decorators ■■ Package: javax.cache ■■ Package: javax.batch
31
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
■■ Status: been formed, but you can still
■■ Approved by the JCP participate by joining the pub-
■■ Spec lead: Chris Vignola licly visible aliases and reviewing
(IBM) the drafts. The Oracle-led JSRs GET TOMORROW’S

JAVA IN ACTION
■■ Project page are all running transparently
■■ Mailing list archive,

issues@jbatch.java.net
with dedicated projects on Java
.net enabling, for instance, pub-
INFORMATION, TODAY!
lic access to EG discussions and
Concurrency Utilities for thus anticipating the require-
Java EE (JSR-236) ments set by the newly voted JCP
This JSR has been ongoing for 2.8 rules.
several years and should be All the JSRs following JCP 2.8

JAVA TECH
revived and completed in time are run more transparently. Here
for Java EE 7. are some JCP 2.8 highlights:
■■ Provides a clean, simple, ■■ Names of the EG members

independent API by building are publicly visible.


on JSR-166, making it appro- ■■ EG business is reported on a
You have Java questions.
priate for use within any publicly readable alias.
We have Java answers.
Java EE container ■■ The schedule is public, cur-

■■ Package: javax.util.concurrent rent, and updated regularly. Get unlimited online access to

ABOUT US
■■ Status: ■■ The public can read/write to a
technology books as they’re written.
■■ Approved by the JCP wiki to discuss the status
■■ Spec leads: Anthony Lai, so far. Rough Cuts available through
Naresh Revanuru (Oracle) ■■ There is a discussion board on
Safari Books Online are
■■ Project page: TBD jcp.org.
■■ Mailing list archive: TBD ■■ There is a public read-only
pre-published manuscripts that
issue tracker. authors have released on Safari
Java API for JSON Processing All of this will be integrated Books Online before the book is
(JSR-353) in GlassFish—the reference
available anywhere else. With
The Java API for JSON Processing implementation for Java EE 7.
JSR has now been filed as </article>
Rough Cuts you get the latest
JSR-353. technology information before
■■ Status:
anyone else. It’s almost like cheating
■■ Approved by the JCP

■■ Spec lead: Jitendra


– without the guilt.
Kotamraju (Oracle) blog
■■ Project page

■■ Mailing list archive


LEARN MORE
The expert groups (EGs) for • Java EE Platform Specification Find out why technology professionals go to Safari Books
most of the JSRs have already • GlassFish Online for all their Java answers. Request a group trial and
32 learn more at: safaribooksonline.com/java
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
Part 1
Project Coin: The Java Language
Has Evolved!

JAVA IN ACTION
JULIEN PONGE Three additions to the Java language in Java SE 7 will help you be more productive.
BIO

P roject Coin is an OpenJDK each feature, and also to provide /* The value 123 in decimal, by a combination of zeros and

JAVA TECH
project that initiated the Java some background on the impli- octal and hexadecimal */ ones up to the size of the under-
language changes that were stan- cations for implementing each byte decimal = 123; lying primitive type. The decimal
dardized as part of Java SE 7 under of them, especially since they all byte octal = 0173; number 123 can be written as the
JSR-334 in the Java Community maintain backward compatibil- byte hexadecimal = 0x7b; following binary literal:
Process (JCP). The project is self- ity with prior versions of Java SE.
described as follows: The impact of each change was The rules are simple. A decimal // 123 in binary
“The goal of Project remarkably balanced number is a literal comprising a byte binary = 0b01111011;
Coin is to determine STRING SWITCH with a scientifically combination of digits between

ABOUT US
what set of small lan- sound analysis of mil- 0 and 9, an octal number starts If fewer digits are provided than
guage changes should Java SE 7 allows lions of lines of existing with a zero, and a hexadecimal expected for the underlying primi-
be added to JDK 7. That strings to be Java code. number starts with 0x. With the tive type, the missing digits are
list is:
■■ Strings in switch
used in switch Part 1 focuses on the
addition of binary inte-
advent of Java SE 7, you can now
specify a number as a binary lit-
considered to be at the beginning
of the representation, and they
■■ Binary integral literals statements. gral literals, underscores eral by starting it with 0b followed are given a value of zero. Thus, the
and underscores in in numeric literals,
numeric literals strings in switch state-
■■ Multi-catch and more ments, and type infer-
precise rethrow ence for generic instance creation.
■■ Improved type inference for Note: The source code for the
generic instance creation examples described in this article
(diamond) can be downloaded here.
■■ try-with-resources statement

■■ Simplified varargs method Binary Integral Literals


invocation” and Underscores blog
This article is the first in a two- Prior to Java SE 7, numeric literals
part series covering each item could be specified either in deci-
of Project Coin. The goal is to mal, octal, or hexadecimal forms, Julien Ponge provides a brief introduction to his
PHOTOGRAPH BY
MATT BOSTOCK/GETTY IMAGES present the immediate usage of such as in the following:
article about Project Coin.
33
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3
previous example could be written with (1______2___3 is the same as 123 or
private static void basicSwitch(int value) {
one less digit: 1_2_3), they can appear only between
switch (value) {
digits. They cannot be put at the begin-
case 2:
// 123 in binary ning or at the end of a numeric literal, System.out.println("Number 2!");

JAVA IN ACTION
byte binary = 0b1111011; before or after the point in a floating- case 1:
point number, in or after a binary or hexa- case 3:
There are arguably a few readability decimal literal prefix, and before or after System.out.println("A number in the [1, 3] range: " + value);
problems in literals as the number of a long (L) or double (D) suffix. Hence, the break;
default:
digits increases. While hexadecimal and following literals raise a compiler error:
System.out.println("A number outside the [1, 3] range: " + value);
binary literals start with a clear prefix
}
(0x and 0b), octal literals start with a int a = _123_; }
zero, which can be confusing. Indeed, it long b = 123_L;

JAVA TECH
is naturally tempting to interpret 0173 int c = 0x_abc;
as 173 instead of 123. In a bid to increase int d = 0_x_abc;
readability, Java SE 7 adds the ability to double e = 1000_._666_666_D;
introduce underscores as part of numeric
literals. As an example, 1200645790 can Possible correct literals would be See all listings as text
be written as 1_200_645_790. Back to
the examples based on the number 123, int a = 123;
we can rewrite them as follows: long b = 1_2_3L; with integer values, such as in Listing 1. statement is still based on an integer

ABOUT US
int c = 0xa_b_c; In Listing 1, a message is printed for value that is arbitrarily assigned by the
byte decimal = 123; int d = 0xa_bc; cases where value is equal to 1, 2, or 3. Java compiler to each enumerated value.
byte octal = 0_173; double e = 1000.666_666D; A special case exists when value is 2, Java SE 7 allows strings to be used in
byte hexadecimal = 0x7B; because a message is printed before switch statements, too. This is interest-
byte binary = 0b0111_1011; This change in the specifications of passing over the execution to the han- ing, because strings are often used in
the Java language is transparent to the dling cases of values 1 and 3. Other cases conditions for control-flow branching.
Of course, underscores can also be Java Virtual Machine and existing byte- are collected as part of the default case. Listing 3 is an example reflecting the use
used in float, double, and long numeric code and libraries, because the Java The switch statement is not limited to of strings in switch statements.
literals. A double number ends with D, compiler simply ignores underscores. int. It also works for char, byte, and short, A NullPointerException is thrown if the
while a long integer ends with L. Thus, Similarly, the new binary literals are as well as the object wrapper types value to be switched on is the null value.
the following literals can benefit from treated as a new case beside octal and Character, Byte, Short, and Integer. Java Also, the case statements need to be on
underscores: hexadecimal literals. SE 5 introduced the support of enumer- string literals or any constant expression
In summary, these changes are light- ated types, and they can also be used in of java.lang.String type.
double doubleValue = 1.111_222_444D; weight yet beneficial for improving switch statements. Listing 2 illustrates The addition of strings in switch state-
long longValue = 1_234_567_890L; the readability of code manipulating switches on enumerated types. ments did not require any modification
long longHexa = 0x1234_3b3b_0123_cdefL; numeric literals. Switching on enumerated types is to the Java Virtual Machine bytecode. blog
based on the value returned by the ordi- Rather, this functionality was imple-
There are, however, certain rules to Strings in Switch Statements nal() method of java.lang.Enum, the base mented as syntactic sugar, where the
respect in the usage of underscores. In the Java programming language, the class of all enumerated types, and that compiler infers semantically equivalent
While they can be repeated at will switch control-flow statement works returns an integer. Hence, such a switch code, but it is based on integer switches.
34
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6
In order to understand how this consider the declaration of strings and
public static boolean isTrue(String s) {
works, we can use the javap decompiler replace the code with the following:
String str = s.trim().toUpperCase();
tool, which ships as part of the Java SE
int jump = -1;
Development Kit, and analyze the gen- List<String> strings = switch(str.hashCode()) {

JAVA IN ACTION
erated bytecode for the isTrue() method new LinkedList<Integer>(); case 2404:
above. The equivalent Java code is shown if (str.equals("KO")) { jump = 3; }
in Listing 4. Of course, this code does not com- break;
Java compilers are free to implement pile. There is a necessary concordance case 2497:
if (str.equals("NO")) { jump = 4; }
switch statements with strings differently between the parametric types in a vari-
break;
as long as the semantics are preserved. able declaration and instance creation.
case 2524:
The string switched on is compared Having to repeat explicit types on each if (str.equals("OK")) { jump = 0; }
for equality against the case label. The side of such assignments is considered break;

JAVA TECH
generated code starts by a first switch to be redundant by most developers. case 87751:
statement based on the hashCode() value Java SE 7 introduces a new syntax for if (str.equals("YES")) { jump = 1; }
of the string constants being used. This calling the new operator, which is called break;
case 2583950:
acts as a way to directly jump to the com- diamond or simply “<>.” It is used in
if (str.equals("TRUE")) { jump = 2; }
parison between the switched string and place of a parametric type argument
break;
the possible case constants. list such as <String, List<String>> when case 66658563:
Note that the hashCode() value alone is we instantiated contacts in the example if (str.equals("FALSE")) { jump = 5; }
not enough to compare strings, because above. The compiler interprets it as a }

ABOUT US
the risk of collisions between different point where the types shall be inferred switch(jump) {
strings having the same hashCode() value from the context and usage. case 0:
case 1:
is too high. It is even relatively easy to Back to the declaration of strings of
case 2:
construct a string with a given hashCode() type List<String>, it is easy to infer that
return true;
value (see Joe Darcy’s post, Unhashing the type for a LinkedList to be assigned case 3:
a String). When a string is matched, an must resolve as LinkedList<String>. The case 4:
integer is set based on the index of the code above can thus be rewritten as case 5:
original case statement, and it is used shown in Listing 6. return false;
in the subsequent switch statement The change is marginal when a default:
throw new IllegalArgumentException("Not a valid true/false string.");
that contains the original instructions single parametric type is used, such
}
intended for the string case statements. as for strings, but it becomes much
}
more interesting when more of them
Improved Type Inference for Generics are involved, especially when they also
Generics were added in Java SE 5 to require nested parametric types, such as See all listings as text
increase the type safety in programs. for the declaration of contacts.
They are especially useful when dealing Diamond may be used with spaces blog
with Java collections. Listing 5 shows a between < and >, but this is discouraged: It must be noted that a type declara- does not have the same type as one cre-
typical usage of generics on collections. tion involving diamond should not be ated with new LinkedList().
There is, however, a strong sense List<String> strings = confused with a raw type. Hence, an As with all good things, certain restric-
of ceremony in this code. Let us just new LinkedList< >(); instance created with new LinkedList<>() tions limit the applicability of generic
35
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 7 LISTING 8 LISTING 9
type inference with diamond. Especially, types. To understand this issue, let’s
Diamond.java:43: error: cannot infer type arguments for HashMap;
diamond cannot be used on anonymous consider the following class definition:
Map<String, String> dmap = new HashMap<>() {
inner classes. Some developers enjoy
^
initializing a collection, especially maps, class SomeClass<T extends reason: cannot use '<>' with anonymous inner classes

JAVA IN ACTION
using an anonymous inner class and an Serializable & CharSequence> { } 1 error
instance-initializing block such as in
the following: This class has a parametric type T with
a restriction that it must be a subtype
Map<String, String> map = of both Serializable and CharSequence.
new HashMap<String, String>() { Internally, the compiler understands See all listings as text
{ T as an intersection type, that is, a
put("foo", "bar"); Serializable+CharSequence type. However,

JAVA TECH
put("bar", "baz"); the intersection of two interfaces does We can check the content of such files est reifiable type to be tested, but it is
} not result in a runtime type that can with the javap decompiler that comes neither a CharSequence nor a Serializable,
}; be represented inside the Java Virtual with the Java Development Kit, as shown the compilation fails for a good reason.
Machine bytecode specifications. Hence, in Listing 8. This change in the Java language was
We could be tempted to take advan- it is not a denotable type. The compiler This helps in understanding why anticipated by many developers, and it
tage of diamond as follows: performs generic type erasure and uses anonymous inner classes are problem- should lead to an increased concision in
a type that does not violate the seman- atic when combined with diamond. source code. This should also reduce the
Map<String, String> dmap = tics of the program while being deno- Indeed, the following declaration is apparent friction that some developers

ABOUT US
new HashMap<>() { table. Consider this: valid: had with generics.
{
put("foo", "bar"); SomeClass<?> foo = SomeClass<?> bar = Conclusion
put("bar", "baz"); new SomeClass<String>(); new SomeClass<>(); This article introduced three additions
} to the Java language in Java SE 7 that
}; This code compiles, because However, the declaration in Listing 9 will certainly help you be more produc-
Serializable+CharSequence satisfies as a generates an error. tive. In the next article, we will cover
But the code in Listing 7 does not supertype for String. Now, we can even Let us put ourselves in the shoes of the remaining three items of Project
compile. create an anonymous class from it: the compiler for a moment. We are Coin. </article>
The updated Java Language requested to generate a class whose
Specification requires that the usage SomeClass<?> fooInner = supertype is SomeClass<T extends
of diamond be forbidden for any new SomeClass<String>() { }; Serializable & CharSequence>. We now LEARN MORE
anonymous class definition. need to infer a denotable type to be • Project Coin mailing-list archives
This might seem surpris- REDEFINED You should not forget used instead of the nondenotable type
• Project Coin blogs
ing, especially given the Diamond cannot
that each anonymous class Serializable+CharSequence, but clearly,
• Latest maintenance review of the Java blog
previous example, where declaration yields a genu- the context gives us no clue for how to
you would naturally infer
be used for any
ine class declaration in the do that. To put it another way, we do
Language Specification

HashMap<String, String>. The anonymous form of a .class file in the not know of any denotable subtype to • Java SE 7 API
reason for this is related to
the problem of nondenotable
class definition.
form EnclosingClass$1.class,
EnclosingClass$2, and so on.
Serializable+CharSequence that could be
used here. Given that Object is the clos-
• “Language Designer’s Notebook:
Quantitative Language Design”
36
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
Using JLayer in Your
Swing Applications

JAVA IN ACTION
Creating lots of interesting effects is effortless in Java SE 7
JOSH MARINACCI thanks to the new JLayer component in Swing.
BIO

JAVA TECH
n 2005, I cowrote the O’Reilly Swing needed something better, ponents and then manipulates
book Swing Hacks with Chris and Java SE 7 has finally provided their input and output. When the
Adamson. In this book, we it: JLayer. child component draws itself,
detailed one hundred interesting Java SE 7, many years in the JLayer can draw on top of the child,
ways to push Swing to its lim- making, has lots of new stuff apply transforms, or redirect
its. Many of the hacks involved under the hood but few new the child into a buffer for later
Figure 1
installing a custom repaint man- client-side APIs. One big excep- manipulation.
ager or otherwise manipulating tion, however, is the new JLayer You can also track and modify ■■ Creates a LayerUI overlay that

ABOUT US
how components were drawn to Swing component. the mouse and keyboard inputs to knows how to draw on top of
the screen. While they were a lot This clever class is a tool for the component. With these sim- buttons
of fun, the hacks could be con- achieving all sorts of interesting ple tools, you can create overlay ■■ Creates a JLayer to combine the

voluted and dangerous. We had effects with standard Swing code, indicators and transition effects, button and the overlay
to work around bugs and eccen- and best of all, it doesn’t require apply blurs and color blending, The LayerUI sub-
tricities in Swing, including dif- any hacks. Everything is built build animated spinners, add class implements the
ferences between the platforms. right in so you can quickly build custom right-click menus, and paint(graphics,jcomponent)
We also dug into private APIs that interesting applications and know monitor keystrokes. method. The call to super.paint(g,c)
could and did change over time. that they will work. JLayer started Let’s start with a few simple draws the button normally, and
At the end of the life as the open source examples to see how it works. then the g.fillRect() call fills the
NO HACKS NEEDED
day, we had a book JXLayer component, Note: The source code for the component with translucent red
full of hacks—fun JLayer is a tool for which was created by examples described in this article (the “128” in the Color constructor
code snippets that achieving all sorts ofAlexander Potochkin, can be downloaded here. is to make it 50 percent opaque).
did interesting things
but could break at
interesting effects and it has since been
added to the Java SE 7 Example of Drawing on
Figure 1 shows transparent red
drawn on top of a control.
any moment. They with standard core APIs. Top of a Control Notice that the component to blog
were great for playing Swing code, with no At its most basic, Listing 1 shows how to draw on be drawn on is included as an
around but not good
enough for heavily
hacking required. JLayer is a Swing
container. It holds
top of a control with transparent
red. The code does three things:
argument to the paint method.
This is very important. The LayerUI
PHOTOGRAPH BY
CHRIS PIETSCH/GETTY IMAGES used production code. regular Swing com- ■■ Creates a button is typed to the component it will
37
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4
POWERFUL SWING
draw on (JButtons, in this over in red. Any valid field
case), but it doesn’t store
JLayer is a very will be drawn over in blue. public class JLayerTest1 {
an internal reference to the powerful addition The code in Listing 2 is
public static void main(String[] args) {
LayerUI<JButton> overlay = new LayerUI<JButton>() {
component. to Swing that makes fairly simple. It creates a @Override

JAVA IN ACTION
Instead, the current
JLayer is passed in, and from
many previously hard panel with a box layout
containing three fields, each
public void paint(Graphics g, JComponent clayer) {
super.paint(g, clayer);
the JLayer, you can get the or impossible effects wrapped in a JLayer. g.setColor(new Color(255,0,0,128));
wrapped component with easy to do in a clean Listing 3 is the overlay.
}
g.fillRect(0,0,clayer.getWidth(),clayer.getHeight());
getView(). This means the
LayerUI is independent of
and supported way. The isValid function
checks each field with a
};

the component it is drawn regular expression to see JButton button = new JButton("I'm a regular button");
on top of and can be reused whether it’s valid. In JLayer<JButton> layer = new JLayer<JButton>(button, overlay);

JAVA TECH
with multiple components. This impor- Figure 2, the zip code field is currently
tant feature of the JLayer design lets not valid because it contains a letter. JFrame frame = new JFrame("foo");
you create reusable objects that can be If you replace the x with a number, the frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(layer);
applied throughout your application. field will turn blue.
frame.pack();
For example, if you are doing form
frame.setVisible(true);
validation and want to decorate any Event Filtering Example }
invalid form with a red overlay and an The field validator works quite well. }
x graphic, you have to define this over- However, notice that the valid fields

ABOUT US
lay only once. Then you can reuse the are clickable.
same instance on all your components. Let’s suppose we want to let the user
This clever design makes the JLayer and edit only invalid fields. We can block all
LayerUI far more flexible than previous mouse input to the valid fields using
skinning efforts. another feature of JLayer: input filtering.
Listing 4 shows some additional
Field Validator Example methods for filtering mouse input. See all listings as text
Next, we will create a simple invalid field Notice first that the LayerUI now sets
decoration. Any invalid field will be drawn and resets the LayerEventMask when
the UI is installed and uninstalled. By rent component is valid and consumes ment the ComponentUI API that is
default, the JLayer won’t mess with the event. part of Swing’s Look and Feel system.
mouse events at all because it would If the field isn’t valid, it just calls ComponentUI defines the JComponent
slow down the app. super, which will block click events to return type of installUI and uninstallUI.
To turn on event filtering, you have valid fields. A more advanced version of You can always cast this to a JLayer and
to set a layer mask when the LayerUI is this code could disable keyboard access then call getView to get the underlying
installed in the JLayer, which is what the as well. component being decorated. blog
installUI and uninstallUI methods do. You might wonder why the paint
Then the code overrides the process- method of LayerUI passes in a Real-World Examples
MouseEvent method to filter the mouse JComponent instead of a JLayer. That’s So far we’ve used JLayer for some trivial
Figure 2 events. It checks to see whether the cur- because LayerUI still has to imple- overdrawing effects, but there are many
38
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 5 LISTING 6
more-useful things you GOING DEEP The code in Listing 5
public static void main(String ... args) {
could do with it. Let’s look at again creates a LayerUI
a few. The JLayer is created instance with a paint
LayerUI<JPanel> overlay = new LayerUI<JPanel>() {
@Override
When trying to debug only once and set on method. This time it recur- public void paint(Graphics g, JComponent clayer) {
the topmost panel.

JAVA IN ACTION
applications it’s common sively goes through the super.paint(g, clayer);
to want to know the bounds component and its children drawBorders(g,clayer);
of every component in the Because the LayerUI to draw borders. It also }
frame, for example, when is recursive, it can writes out the simple name private void drawBorders(Graphics g, JComponent clayer) {
g.setColor(Color.ORANGE);
one of your components
seems to be invisible.
draw on top of child of the component’s class
if the component doesn’t
g.drawRect(0, 0, clayer.getWidth(), clayer.getHeight());

While you could print this components as deep have any children. (It skips
if(clayer.getComponentCount() <= 0) {
g.drawString(clayer.getClass().getSimpleName(), 5, 15);
information to the console, in the hierarchy as components with children }

JAVA TECH
with JLayer you can simply to avoid overdraw on for(Component comp : clayer.getComponents()) {
draw debugging informa- necessary. nested panels.) if(comp instanceof JComponent) {
tion directly on top of the Note that the JLayer is cre- g.translate(comp.getX(),comp.getY());
drawBorders(g,(JComponent)comp);
components. ated only once and set on
g.translate(-comp.getX(),-comp.getY());
The example shown in the topmost panel. Because
}
Listing 5 and Figure 3 draws the the LayerUI is recursive, it can draw on }
borders of every component in orange. top of child components as deep in the }
It also writes the name of the compo- hierarchy as necessary. };

ABOUT US
nent’s class. This is handy if you want The code in Listing 6 is similar to what JPanel panel = new JPanel();
to tell the difference between many but- we’ve done before, but it draws any panel.setLayout( new BorderLayout());
panel.add(new JLabel("Header Label"), BorderLayout.NORTH);
ton subclasses. disabled component using a blur. That
panel.add(new JButton("Quit"),BorderLayout.SOUTH);
way, the user knows it is
panel.add(new JButton("EAST"), BorderLayout.EAST);
really disabled. panel.add(new JButton("West coast"), BorderLayout.WEST);
In this case, if the JPanel subpanel = new JPanel();
component is enabled, subpanel.setLayout(new BoxLayout(subpanel, BoxLayout.PAGE_AXIS));
super() is called to draw subpanel.add(new JTextField("this is your name"));
normally. If the compo- subpanel.add(new JTextField("000-000-0000"));
subpanel.add(new JTextField("6666x"));
nent is not enabled, the
panel.add(subpanel,BorderLayout.CENTER);
code creates an image
JFrame frame = new JFrame("foo");
buffer and calls super() frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
on the graphics context frame.add(new JLayer(panel,overlay));
from the image. This frame.pack();
draws the component frame.setVisible(true);
into the image instead blog
of onto the screen.
Then the code applies
a simple blur operation See all listings as text
Figure 3 to the image and draws
39
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 7
crazy with JLayer by building a magnify-
@Override
ing glass that will magnify whatever is
public void paint(Graphics g, JComponent c) {
underneath the mouse as the mouse
//draw regular
moves, as shown in Figure 6. super.paint(g,c);

JAVA IN ACTION
The code shown in Listing 7 is roughly //draw into buffer
Figure 4 the same as before. The difference is Graphics2D g2 = img.createGraphics();
that this time it scales the graphics int ih = img.getHeight();
before drawing into an image. Then it int iw = img.getWidth();
//fill with white
draws the image back to the screen with
g2.setPaint(Color.WHITE);
a nice round clip.
g2.fillRect(0, 0, img.getWidth(), img.getHeight());
Drawing components into a tempo- //render view component scaled and translated
rary image is a really useful technique Graphics2D g3 = (Graphics2D) g2.create();
Figure 5

JAVA TECH
because there are so many ways to post- g3.translate(-pt.x + iw, -pt.y + ih*2);
process an image. To further extend the g3.scale(2, 2);
magnifying glass, you could add a dis- g3.translate(-pt.x/2 - iw/4, -pt.y/2 - ih/4);
super.paint(g3,c);
tortion filter to give the scaled image a
g3.dispose();
rounded effect.
//draw black border
g2.setPaint(Color.BLACK);
Conclusion g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.
JLayer is a very powerful addition to VALUE_ANTIALIAS_ON);

ABOUT US
Swing that makes many previously hard g2.setStroke(new BasicStroke(3));
or impossible effects easy to do in a g2.draw(new Ellipse2D.Double(0,0,iw,ih));
g2.drawRect(0,0, iw-1, ih-1);
clean and supported way. JLayer proves
g2.dispose();
that Swing still has a lot of life left in
//draw image to screen
it, and Java SE 7 provides new ways Shape oldClip = g.getClip();
of extending Swing to do interesting int mx = pt.x-img.getWidth()/2;
things. (And being more generified is int my = pt.y-img.getHeight();
Figure 6 always nice, too.) g.setClip(new Ellipse2D.Double(mx,my,iw,ih));
The examples shown here are just the g.drawImage(img, mx, my, null);
g.setClip(oldClip);
that final image to the screen. Figure 4 tip of the iceberg. You could use JLayer to
}
shows an example of a button that can implement status overlays, busy indica-
be blurred, and Figure 5 shows a tors, global right-click menus, and
blurred button. much more. </article>
Because the JLayer repaints any time
its view control changes, we don’t need
LEARN MORE
to track any state. A toggle button can blog
To learn more about JLayer, read the Java
simply toggle the enabled property of the
docs for JLayer and LayerUI:
button, and Swing takes care of the rest.
As a final example, Listing 7 shows • JLayer See all listings as text
how you can do something completely • LayerUI
40
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
Part 2
Understanding the Hudson Plug-in
Development Framework

JAVA IN ACTION
WINSTON PRAKASH AND Add a UI component to configure a Hudson extension locally or globally.
SUSAN DUNCAN
BIO

T his is Part 2 in a series of called Jelly, a server-side render- path hierarchy similar to the pack- Because HelloWorldBuilder

JAVA TECH
articles for beginners who are ing technology that uses a render- age name of the model class plus extends the Builder extension
interested in understanding the ing engine to convert XML-based the name of the model class itself. point, any Jelly content put in the
fundamentals of Hudson plug-in Jelly definitions (tags) to client- Hudson uses the namespace of configuration file org/sample/
development. Hudson is a popular side code: HTML, JavaScript, and the class package plus the model hudson/HelloWorldBuilder/
open source continuous integra- Ajax. Hudson provides a number name as the folder hierarchy. For config.jelly is included in the job
tion (CI) tool written purely in Java. of Jelly tags for your convenience. example, in Part 1 of this series, configuration page to configure
Part 1 covered creating a Hudson A Hudson plug-in’s model the model class HelloWorldBuilder the HelloWorldBuilder extension
plug-in using the HPI tool and cre- objects are bound to these tag has the package name org.sample in the builder section of the job

ABOUT US
ating custom implementations. attributes via Java Expression .hudson. So the configuration configuration.
Part 2 covers adding, either Language (JEXL). When the file must reside in the follow- The HelloBuilder extension
locally or globally, the UI configu- tags are rendered into HTML, ing folder: org/sample/hudson/ provides a UI for the user to
ration elements a plug-in needs. JavaScript, and Ajax, the rendered HelloWorldBuilder. configure. The UI provided by the
code includes information from HelloBuilder extension provides a
Configuration File Convention the model objects to Local Configuration simple text box for users to input
Providing a configuration for a which the attributes are WHY JELLY? Hudson uses another their name.
plug-in means providing some
sort of UI with which the end
bound. Using simple Jelly
tags is a powerful way to
Using simple convention to tell
whether the configura-
Open and look at config.jelly
by exploring the resource folder in
user can configure your plug-in. express your UI. Jelly tags tion file is meant for the plug-in project. The content
In addition, the configuration UI The Jelly files used to is a powerful local configuration or of the file is very simple (see
provides feedback to the user
about the validity of the input.
render the UI have the
extension .jelly. They
way to express global configuration. If
the configuration file is
Listing 1). It is a pure XML file
with Jelly syntax.
There are two ways to config- reside in the resources your UI, rather named config.jelly, it There are two main tags playing
ure an extension. One is local to directory of the plug-in. than writing is used as a local con- the role of user interaction:
blog
the area of the functionality the
plug-in extends, and the other is
Hudson uses a heuristic
convention to find these
lots of HTML, figuration file, and its
content is included in
■■ entry tells Hudson that the

enclosed tags are considered


through the Hudson-wide global Jelly files. The folder JavaScript, the configuration of the to be user interaction elements

PHOTOGRAPH BY BOB ADLER


configuration.
Hudson uses a UI technology
under which these Jelly
files must reside has a
and Ajax. functionality that this
extension extends.
and they are submitted via an
HTML form.
41
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 1 LISTING 2
How does Hudson know
<j:jelly xmlns:j="jelly:core" xmlns:st="jelly:stapler" xmlns:d="jelly:define"
to get the content from
xmlns:l="/lib/layout" xmlns:t="/lib/hudson" xmlns:f="/lib/form">
this file and display it as
<!--
help content for the field? Creates a text field that shows the value of the "name" property.

JAVA IN ACTION
The trick is in the name When submitted, it will be passed to the corresponding constructor parameter.
of the file. By convention, -->
Hudson looks for a spe- <f:entry title="Name" field="name">
cific filename in the same <f:textbox />
Figure 1
</f:entry>
folder that contains the
</j:jelly>
config file. The name of
the file should be help-
{fieldName}.html. See all listings as text

JAVA TECH
In the config.xml file we
have the following:
Figure 2 When Hudson is stopped and name.jelly in the job configuration page,
<f:entry title="Name" restarted with the above Jelly help file, which itself is another Jelly file.
■■ textbox renders a simple HTML text field="name"> clicking the Help button for the same text The entire Jelly file is given to the Jelly
field whose value will be sent back to <f:textbox /> field displays the text shown in Figure 2. renderer to render into the client-side
the server. </f:entry> Note that ${app.displayName} is code. The Jelly renderer is responsible for
replaced with Hudson, which is the name substituting the corresponding value for

ABOUT US
Understanding the UI Rendering field="name" indicates that the text of the application. the JEXL expression after evaluating the
Let’s take a closer look at how the UI is box should be used as an entry field with expression. The first part of the expres-
rendered from the Jelly file. In Part 1 of the name Name. So, based on conven- UI and Model Object Interaction sion evaluates to the model object and
this series, we created a Hudson project tion, the help text for that field should Now let’s see how the UI interacts with then to the method name of the model
called TestProject. Open the TestProject exist in a file named help-name.html. Hudson model objects. HelloBuilder is a object. By default, Hudson registers
job configuration page by clicking the The content of the help-name.html Hudson model object. It encapsulates three identifiers for the model objects to
Configure link. Scroll down to the build file is pure HTML. You can include data. The UI can interact with this model the JEXL expression evaluator:
section and view the Say Hello World images, text, and hyperlinks in the to get and display its data, get informa- ■■ app, which is the Hudson appli-

builder and its configuration. Click the content to emphasize and enhance your tion from the user via fields in the UI, cation itself. For example, ${app
Help button (“?”) on the right side of the help text. As mentioned in the example and update the model data. .displayName} evaluates to Hudson
text box. It displays online help text, as help text in Figure 1, if The help file, help- .getDisplayName().
shown in Figure 1. you want to use informa- WHAT'S INSIDE? name.jelly, contains a ■■ it, which is the model object to

Let’s find out where this help text


comes from. The content of config
tion from Hudson model
objects, you should have
The content of the JEXL expression ${app
.displayName}. When the
which the Jelly UI belongs. For
example, ${it.name} evaluates to
.jelly has no such help text. Once again, Jelly content in the field help-name.html file is server side of the Hudson HelloWorldBuilder.getName().
convention comes into play. The folder help file and the file pure HTML; you can application receives the ■■ h, which is a global utility function blog
containing the config file also has a file
named help-name.html. Open the file
extension should be .jelly
instead of .html. Listing 2 include images, text, request to render the job
configuration page, it
called Functions that provides
static utility methods. For example,
using an editor and notice that it contains shows an example file and hyperlinks. includes both the snip- ${h.clientLocale} evaluates to
the exact help text shown in Figure 1. called help-name.jelly. pets config.jelly and help- Functions.getClientLocale().
42
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 3
it has a name parameter,
<?xml version='1.0' encoding='UTF-8'?>
as follows:
<project>
<actions/>
@DataBoundConstructor <description></description>

JAVA IN ACTION
public HelloWorldBuilder <keepDependencies>false</keepDependencies>
(String name) { <creationTime>1314407794225</creationTime>
Figure 3 this.name = name; <properties>
} <watched-dependencies-property/>
</properties>
<scm class="hudson.scm.NullSCM"/>
The annotation
<advancedAffinityChooser>false</advancedAffinityChooser>
@DataBoundConstructor <canRoam>true</canRoam>
hints to Hudson that this <disabled>false</disabled>

JAVA TECH
extension is bound to a <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
field, and upon the UI sub- <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
Figure 4 <triggers class="vector"/>
mission, it must be recon-
<concurrentBuild>false</concurrentBuild>
structed using the value of
<cleanWorkspaceRequired>false</cleanWorkspaceRequired>
Because the expression ${app the submitted field.
<builders>
.displayName} evaluates to Hudson, Also the model must have a getter <org.sample.hudson.HelloWorldBuilder>
which is the name of the Hudson appli- with the name of the field in the config <name>Winston</name>
cation, “Hudson” gets inserted into the .xml file to get the data for the second </org.sample.hudson.HelloWorldBuilder>

ABOUT US
field help text. time around when the project is config- </builders>
While the UI displays the data of a ured again, for example: <publishers/>
<buildWrappers/>
model, the input from the user in the UI
</project>
updates the model data when the config- public String getName() {
uration page is submitted by the user. In return name;
this case, the value of the name the user } See all listings as text
enters in the UI (“winston”) is updated in
the model. This information is persisted along
When the configuration page is sub- with the project configuration, as Note: Do not press the Enter (or Return) rendered that, behind the scenes, con-
mitted, Hudson re-creates the model by shown in Listing 3. Note that the key. Doing so will submit the configura- tacts the Hudson server and asks what
passing the corresponding value via the value of the name field is saved as the tion page. message should be displayed.
constructor. Hence, the constructor of HelloWorldBuilder configuration under If you enter just a two-letter word (for These Ajax requests are easily observ-
the model object must have a param- the builders section. example, xy) in the name field and click able using Firefox and Firebug. When
eter whose name matches the name of elsewhere, the information message config.jelly is rendered by Hudson,
the field. In our configuration we have UI Validation Methodology shown in Figure 4 is displayed. the Jelly tag <f:textbox /> renders the
<f:entry title="Name" field="name">. In the job configuration page, under Let’s examine how Hudson displays Ajax code required to do the checking. blog
So the constructor of your the build section of HelloBuilder, if you this information message. Again, as Firebug displays the Ajax request info
HelloBuilder must have a parameter remove the value from the text field and seen in Listing 3, config.jelly does not shown in Figure 5.
named name. If you look at the con- click elsewhere on the page, a validation include the messages. The magic is in The Ajax request shown in Listing 4 is
structor of the class HelloWorldBuilder, error message is displayed (see Figure 3). the Jelly file rendering. Some Ajax code is sent to the Hudson server.
43
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//java architect /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6 LISTING 7 LISTING 8
Global Configuration
GET /job/TestProject/descriptorByName/org.sample.hudson.HelloWorldBuilder/
Until now, we have con-
checkName?value=xy HTTP/1.1
centrated on how to con-
Figure 5 Host: localhost:8080
figure a plug-in at the job User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:6.0.1) Gecko/20100101

JAVA IN ACTION
level. However, some of the Firefox/6.0.1
configuration of an exten- Accept: text/javascript, text/html, application/xml, text/xml, */*
sion could be global. For
Figure 6 example, if you use Git for
source configuration man-
Hudson evaluates this request, agement (SCM) in a project, you might
finds the extension HelloWorldBuilder, want to configure two different jobs to
executes the method checkName(), and force Git to check out from a different See all listings as text

JAVA TECH
returns the result. Again, Hudson uses repository. So in both the projects, the
the convention doCheck followed by Git SCM plug-in must be configured to
{nameOfTheField} as part of the Ajax URL. use two different repository URLs. the builds of various jobs that use the checkbox. Once the global configura-
Note: By default, for every f:textbox tag in However, if the Git SCM extension HelloWorldBuilder would say hello in tion is submitted, by convention,
the Jelly config file, Hudson will render needs to know about the Git native either French or English. Hudson calls the method HelloBuilder
the Ajax check. However, if your exten- binaries, placing the Git configuration The global configuration of the .DescriptorImpl.configure() and passes a
sion class does not include the corre- UI that configures the Git binary loca- HelloWorldBuilder plug-in is done in the JSON object corresponding to the page
sponding method (in this case, tion at the job level makes little sense, Hudson configuration page in the Hello submission. It is up to the extension to

ABOUT US
doCheckName()), Hudson will silently because it doesn’t vary from project to World Builder section (see Figure 6). find its submitted value and then apply
ignore the check request. project. It makes sense to put such a Here, the user sets the global con- it. HelloWorldBuilder defines this method
The doCheckName() method is straight- configuration in Hudson’s global con- figuration to control whether French is as shown in Listing 8.
forward. The Ajax request specifies the figuration page. used as the language. In global.jelly, the In this method, the Boolean value of
checkName method with the parameter For Hudson to include the configura- checkbox is defined as shown in Listing 7. the field useFrench is obtained and used
value as {..}/checkName?value="xy". Hence, tion of a plug-in in its global configura- When the user edits the Hudson to set HelloWorldBuilder.useFrench. The
the parameter value of doCheckName tion page, the configuration must be configuration page, the decision about next time HelloBuilder.perform() is called
must be annotated with the annotation declared in a file called global.jelly. The whether this checkbox should be during the build of the job, HelloBuilder
@QueryParameter. Also, the method must namespace convention for this file is selected comes from the extension .useFrench is consulted and based on its
return a FormValidation object, which similar to the convention for local con- itself. The JEXL expression ${descriptor value, the hello message is written in
determines the outcome of the check. figuration. For the HelloWorldBuilder .useFrench()} would resolve to either French or English.
See Listing 5. global config file, it is org/sample/ HelloBuilder.DescriptorImpl.useFrench(),
The method doCheckName returns hudson/HelloWorldBuilder/global.jelly. which is defined as follows: Conclusion
FormValidation.error(..) when an error In Part 1 of this series, we saw that The Hudson plug-in development envi-
occurs. The HTML sent back to the client the HelloWorldBuilder.perform(..) method public boolean useFrench() { ronment provides a rich set of extension
displays the text in red along with an error includes the code shown in Listing 6. return useFrench; points with which plug-in developers blog
icon (see Figure 3). If FormValidation HelloWorldBuilder can be configured } can develop custom plug-ins. In this
.warning() is returned, the HTML sent to say hello in either French or English. article, we explored ways to configure
back displays the message in yellow along The configuration of which language useFrench is a field in HelloWorldBuilder. the extensions in a plug-in using the
with a warning icon (see Figure 4). to use is set globally. Once set, all This field is set to true if the user selects Jelly UI framework . </article>
44
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//rich client /

COMMUNITY
Part 2
JavaFX and Swing Integration

JAVA IN ACTION
Migrate a Swing application to use the richness of JavaFX without
completely rewriting the application.
SIMON RITTER

I n Part 1 of this three-part series, The application has been ken out into columns. TableView TableView so it can be displayed.
BIO

JAVA TECH
we looked at how to use the well organized into packages, provides the TableColumn API, In the original application, the
JFXPanel class to wrap a JavaFX allowing us to easily identify which supports features such as data model is encapsulated in the
scene into a component that could the relevant parts. For our pur- cell factories for customizing cell Quote class. To enable us to use
be added to a Swing Container. poses, we’ll be modifying the contents, column reordering by this as the model for a TableView,
In this article, we’ll build on StocksMonitorMainWindow and the user at runtime, and column we need to add support for JavaFX
that to show how we Quote classes and nesting to group sets of columns. binding, which uses JavaFX prop-
can migrate a Swing CSS SUPPORT replacing the QuoteTable Using a TableView control is erties. For each column that we
application to use the
An exciting class with a new similar in design to the JTable want to display in our table, we

ABOUT US
richness of JavaFX with- QuoteFXTable class. component in Swing. The model- need a property of the appropri-
out having to rewrite it feature of For the sake of view-controller pattern is used, so ate type, an accessor method for
completely. The sample the JavaFX simplicity, the aim a data model needs to be con- the property, and a method to call
Swing application will
be modified to replace
platform is will be to make the
QuoteFXTable class
structed that can be passed to the when the values are changed.

the table component to support for fully compatible with


show how we can use cascading style the existing QuoteTable
some of the exciting
functionality of JavaFX
sheets (CSS). class. To do this, we
will need to imple-
to improve the look and ment the Observer and
feel of the application. PropertyChangeListener
interfaces and include a
Structure of the Sample setQuoteTable method with the
Application correct signature.
The sample application,
StocksMonitor, provides a Swing- JavaFX TableView Control blog
based interface to allow a number The JavaFX API provides the
of stock prices to be tracked. The TableView control, which is
code for this application can be designed to visualize an unlimited Stephin Chin talks about JavaFX with Java Magazine’s
PHOTOGRAPH BY BOB ADLER downloaded here. number of rows of data, bro-
Tori Wieldt at Devoxx 2011 .
45
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//rich client /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3
Table Data Model GET VISUAL the superclass, instantiate a
public Quote(Stock aStock, BigDecimal aCurrentPrice, BigDecimal aChange) {
Listing 1 shows the changes
that need to be made to the
The JavaFX API new QuoteFXTableNode object,
and add a Runnable task to the
fStock = aStock;

Quote class. provides the JavaFX application thread to


fCurrentPrice = aCurrentPrice;
fChange = aChange;
TableView

JAVA IN ACTION
For the name of set the scene graph. stockProperty =
the stock, we create a
SimpleStringProperty, which is
control, which Notice that we do not need
to concern ourselves with
new SimpleStringProperty(this, "stock", fStock.getName());
priceProperty =
a concrete implementation is designed the size of the scene or table, new SimpleFloatProperty(this, "price");
of the abstract StringProperty
class. This property is then
to visualize because this is handled auto-
matically by the Swing layout
changeProperty =
new SimpleFloatProperty(this, "change");

associated with the name an unlimited manager and JavaFX scene


percentChangeProperty =
new SimpleFloatProperty(this, "percentChange");
value of the Stock object. number of graph. All the required meth- profitProperty =
rows of data,

JAVA TECH
For the other values, we cre- ods pass the call through to new SimpleFloatProperty(this, "profit");
ate SimpleFloatProperty objects. the QuoteFXTableNode class percentProfitProperty =
Note that the accessor meth- broken out into where the real work happens. new SimpleFloatProperty(this, "percentProfit");
ods don’t follow the conven- columns. Listing 3 shows part of the
validateState();
tion of getNameOfProperty. QuoteFXTableNode class.
}
They simply make the method For each column that we ...
name the same as that of the want in the table, we need to /* New methods required for JavaFX table */
property instance. instantiate a TableColumn object. We public void updateValues() {

ABOUT US
The updateValues method simply sets use generic type parameters to define setPrice(fCurrentPrice.floatValue());
the values of the individual properties the type of the TableView (Quote) and setChange(fChange.floatValue());
setPercentChange(getPercentChange().floatValue());
using the existing methods and refer- the type of the data to be displayed in
setProfit(getProfit().floatValue());
ences in the Quote class. this column (a string for the name of the
setPercentProfit(getPercentProfit().floatValue());
stock and float for the numeric values). }
TableView Node as a Swing The cell value factory needs to be set to /**
Component specify how to populate the cells within * @return the stockProperty
Now that we have the appropriate data a single TableColumn. For this common */
model we can construct our TableView case, where we are populating the cells public StringProperty stockProperty() {
return stockProperty;
and wrap it using JFXPanel. This requires using a single value from a Java bean,
}
two classes, one to act as the Swing we use the PropertyValueFactory class.
/**
component (QuoteFXTable) and one for The constructor for this takes the name * @param stock The stock name
the TableView node (QuoteFXTableNode). of the property that contains the data */
Listing 2 shows the QuoteFXTable class. for this column (which will match up to public void setStock(String stock) {
To be compatible with the the property in the Quote class). Having stockProperty.set(stock);
QuoteTable class, we implement the defined all the columns, we add these to } blog
PropertyChangeListener and Observer the table using the setAll method.
interfaces and extend JFXPanel, which is The implementation of the
a subclass of JComponent. The construc- setQuoteTable method is trivial. We clear See all listings as text
tor simply has to call the constructor of and set the list of quotes to be displayed
46
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//rich client /

COMMUNITY
LISTING 4 LISTING 5
and then call the update method for each Listing 4 and Listing 5 show the code for
@Override
quote. This handles changes to both the QuoteFXPriceCell class.
protected void updateItem(Float value, boolean empty) {
stock prices as well as to the portfolio, If you refer back to the code in
super.updateItem(value, empty);
such as adding or deleting stocks. Listing 3 for the QuoteFXTableNode class,

JAVA IN ACTION
The only other change required you will see that in addition to setting if (empty)
to complete the integration of the cell value factory for the price col- return;
the TableView is to modify the umn, we also set the cell factory to a
StocksMonitorMainWindow class to Callback object. All the call method needs setText("" + value);
icon = new QuoteCellGraphic();
replace the QuoteTable reference and to do is return a new instance of the
setGraphic(icon);
instantiation with QuoteFXTable. QuoteFXPriceCell class. We pass it a refer-
ence to a list of quotes, which we’ll need float change = quotes.get(getIndex()).getChange().floatValue();
Let’s Make It Interesting to determine the change in price.

JAVA TECH
Right now, all we’ve done is replace To change the way the cell is rendered, if (change > 0.0)
the JTable component with a TableView we override the updateItem method. For icon.setUp();
node. That’s nice, but it doesn’t make everything to work properly, it is impor- else if (change < 0.0)
icon.setDown();
our UI significantly better. Let’s use tant that we call the overridden method
else icon.setNoChange();
some more JavaFX code to make the at the start. Because null is a valid value
display more interesting. for a cell, we check the empty flag and do SimpleDoubleProperty faderProperty = new SimpleDoubleProperty();
For a stock price nothing if the flag is true. We also return opacityProperty().bind(faderProperty);
FEEL THE POWER monitor, it would if the value is null, because this value

ABOUT US
Modifying the style be good if we could
highlight when a
has no meaning to us in this context.
The text for the cell is set using the value
Timeline faderTimeline = new Timeline();
faderTimeline.getKeyFrames().add(new KeyFrame(Duration.ZERO,
sheet will change change happens: passed as an argument. new KeyValue(faderProperty, 1.0)));

the look and feel red for a decrease TableCell extends from the Labeled
faderTimeline.getKeyFrames().add(new KeyFrame(new Duration(500),
new KeyValue(faderProperty, 0.1)));
of the application and green for an
increase. To make
class, which is common to all controls
that have a text label (such as a button).
faderTimeline.getKeyFrames().add(new KeyFrame(new Duration(1000),
new KeyValue(faderProperty, 1.0)));
without the need this visually interest- This also provides support for includ- faderTimeline.setCycleCount(3);
to change the code. ing and to attract ing a graphical icon with the text of the
}
faderTimeline.playFromStart();
the user’s eye, we’ll label. This icon is a node, so it can be a
Style sheets are have the price flash complete scene graph, if required. The }
very powerful on the screen. The QuoteCellGraphic class provides a node,

and can be used to number will fade in


and out to give it a
which graphically shows whether a price
has gone up, gone down, or is unchanged
completely change “softer” feel. by using a colored triangle or rectangle.
the look of an To do this, we’ll We can reference into the list of
blog
application when need to provide our
own customized
quotes that we got in the construc-
tor using getIndex from the IndexedCell
there are numerous TableCell class to interface. Once we know how the price
JavaFX nodes. render the cells of has changed, we can make the appropri- See all listings as text
the price column. ate icon from QuoteCellGraphic visible.
47
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//rich client /

COMMUNITY
To make the price flash, we create a This is very simple. We create a style
Timeline, which varies the opacity of the that has the name we used in the Java
cell from 1.0 to 0.1 and back again over a code and specify a pseudo-class that
period of one second. The cell is made means this style will be used only on

JAVA IN ACTION
to flash three times by setting the price cells that are filled. Two param-
cycleCount appropriately. eters are specified: one to set the color
the cell is filled with and one to set the
Skinning
Another exciting feature of the JavaFX
color of the border.
Modifying the style sheet will change YOUR
LOCAL JAVA
platform is support for cascading style the look and feel of the application
sheets (CSS). Many nodes without the need to
implement support for GET RICH change the code. Style

USER GROUP

JAVA TECH
CSS, including TableCell. sheets are very power-
Adding a style sheet to
You can migrate a ful and can be used to
Swing application to
NEEDS YOU
an application is pretty completely change the
simple. If you refer back to
the QuoteFXTable class in
use the richness of JavaFX look of an application
when there are numer-
Listing 2, you will see that without having to engage ous JavaFX nodes.
after we create the scene in a complete rewrite. Find your JUG here
in our Runnable task, we Conclusion

ABOUT US
add a reference to a CSS In this article, we’ve seen
file to the style sheet list of how we can migrate a
the scene. This references a CSS file that Swing application to use the richness
we include in the same package as the of JavaFX without having to engage in
QuoteFXTable class. a complete rewrite. We’ve modified a
Now look at the QuoteFXTableNode sample Swing application to replace its
class again in Listing 3, specifically the table component in order to make use
call method of the Callback class that of the exciting functionality of JavaFX to
we pass to the setCellFactory method of improve the application’s look and feel.
the price column. Here, we create a new In Part 3, we’ll look at ways to replace
QuoteFXPriceCell object and add to the one of the configuration menus in our
style class list a reference to the name sample application. </article>
we use in our CSS file to set parameters.
The CSS file is shown below:

.fx-table:filled { blog
LEARN MORE
-fx-background-color:
• JavaFX documentation and tutorials
lightblue;
-fx-border-color: black; • JavaFX 2.0 API documentation (Javadoc)
} • JavaFX showcase
48
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
Lightweight Publish-Subscribe
Communication

JAVA IN ACTION
Java EE 6 and CDI can be used for lean, efficient implementation of local publish-subscribe communication.
ADAM BIEN

T he ancient—in internet 2.x components to be “legally” javax.jms.MessageProducer Listing 3 shows the actual busi-
BIO

JAVA TECH
time—J2EE specification invoked asynchronously. Service wrapped with an EJB 3.1 bean, ness logic. After the injection of
used Java Message Service (JMS) Activator can be considered a were generated with NetBeans 7 the SynchronousService EJB 3.1
as a workaround for asynchro- decorator that adds asynchro- (using Alt+Insert on a Microsoft bean into ServiceActivator, the
nous invocation of synchronous nous nature as a cross-cutting Windows system or Ctrl+I on a method message(String message)
services as well as for the dis- concern to an already existing Mac system). However, the gen- is decorated with the asynchro-
tribution of local events. JMS, EJB interface. erated source code for the whole nous onMessage method in the
unchanged in Java EE 6, has a The decoration usually com- lifecycle of the project must be message-driven bean.
verbose API. prised a JMS queue with a javax maintained. Note: The implementation

ABOUT US
With Contexts and Dependency .jms.MessageProducer as sender A message-driven bean on the described here is already simpli-
Injection (CDI) 1.0 (JSR-299) and and a message-driven bean as other end of the queue receives fied. In the original J2EE imple-
Enterprise JavaBeans (EJB) 3.1 an asynchronous receiver. Even the message, casts it to a javax mentation, Dependency Injection
(JSR-318), the J2EE workarounds a Java EE 6 implementation of .jms.TextMessage, extracts its pay- wasn’t available, so EJB 2 compo-
and patterns aren’t necessary. Service Activator is not lean. You load, and passes it to the synchro- nents also required the use of Java
JMS is still essential for true need to implement a transac- nous service. Listing 2 shows the Naming and Directory Interface
messaging, but it is no longer tional message sender, which asynchronous receiver. (JNDI) lookups to get access to
required for the implementa- uses a javax.jms.Queue and a The message-driven bean in other components. The imple-
tion of asynchronous processing javax.jms.ConnectionFactory, to Listing 2 is used only for asynchro- mentation of the local EJBHome
or the implementation of a local create and send a nous invocation of and local interfaces, as well as the
Observer pattern. javax.jms.Message KEEP IT SIMPLE the synchronous existence of standard and propri-

Asynchronous Invocation
instance. Java EE
6 helps you only
The main goals of EJB bean. None
of the JMS fea-
etary XML deployment descrip-
tors, was also necessary. Service
As described in the “Context” by the acquisition JMS 2.0 will be tures or qualities Activator was a complex solution
section of the Service Activator of the resources simplicity and tight are used. We are to a trivial challenge.
blog
pattern, “Enterprise beans and
other business services need a
with Dependency
Injection (JSR-330).
integration with the interested only in a
nonblocking invo- The Java EE 6 Answer
way to be activated asynchro- The major parts of Java EE 7 specifications, cation by a thread Java EE 6 made the implementa-
PHOTOGRAPH BY
THOMAS EINBERGER/
nously.” The Service Activator the code in Listing 1, especially with CDI. from the applica- tion of the Service Activator pat-
GETTY IMAGES pattern was the only way for EJB which shows tion server’s pool. tern obsolete. Listing 4 shows the
49
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
Service Activator equivalent NOT NECESSARY remote communication.
@Stateless
in Java EE 6. Also, the JMS implemen-
The entire JMS overhead Java EE 6 made the tation is not type-safe. You
public class ServiceClient {
@Resource(mappedName = "jms/serviceactivator")
can be replaced with a single implementation of need to wrap the actual private Queue serviceactivator;
the Service Activator

JAVA IN ACTION
javax.ejb.Asynchronous anno- payload into an appropriate @Resource(mappedName = "jms/serviceactivatorFactory")
tation. The semantics of javax.jms.Message (for exam- private ConnectionFactory serviceactivatorFactory;
both approaches, however, pattern obsolete. ple, a string in a javax.jms
public void broadcast(String message){
are not identical. In the case .TextMessage) at the sender
Connection connection = null;
of Service Activator, you side and unwrap it in the Session session = null;
could use persistent queues message-driven bean. The try {
to make the invocation more robust. unwrapping requires you to check the connection = serviceactivatorFactory.createConnection();
The application server would redeliver a type multiple times and cast the payload session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

JAVA TECH
message until the processing succeeds. into the desired type. CDI “eventing,” MessageProducer messageProducer = session.createProducer(serviceactivator);
In the @Asynchronous case, there is on the other hand, is type-safe. The messageProducer.send(createTextMessage(session, message));
}catch(Exception e){
only one attempt. If it fails, the transac- payload arrives in the message listener
throw new EJBException("Cannot send message: " +e,e);
tion will be rolled back and you would “as is.” No wrapping and unwrapping is } finally {
need to implement any recovery by required. if (session != null) {
yourself. On the other hand, java.util Although the spirit of Service Activator try {
.concurrent.Future makes it easy for an still exists, the entire JMS-related imple- session.close();
EJB 3.1 bean to return a pointer to the mentation is obsolete in Java EE 6. You } catch (JMSException e) {

ABOUT US
/*. . .*/
return value. Listing 5 shows the “fire can usually replace the vast majority of all
}
and forget” approach with its result. Service Activators in J2EE with a single }
Service Activator was primarily @Asynchronous annotation in Java EE 6 for if (connection != null) {
designed for unidirectional fire-and- local event distribution. try {
forget communication. In order to return connection.close();
the value of a Service Activator imple- Publish-Subscribe: The Principle } catch (JMSException ex) {
/*. . .*/
mentation, you need to create and send EJB 3.1 made the Service Activator pat-
}
a temporary queue with the message tern obsolete. The CDI specification, on }
and register another message-driven the other hand, can be used for lean }
bean as “result listener” at the tempo- and efficient implementation of local }
rary queue end. The Java EE 6 future- publish-subscribe communication. The private Message createTextMessage(Session session, String messageData) throws
based solution is orders of magnitude publish-subscribe pattern (or pub/sub) JMSException {
TextMessage tm = session.createTextMessage();
leaner than the J2EE “best practice.” is defined on Wikipedia as “a messag-
tm.setText(messageData);
JMS destinations are remote by ing pattern where senders of messages, return tm;
convention. Although most of the JMS called publishers, do not program the }
providers offer local queues as well, messages to be sent directly to specific } blog
don’t rely on that. @Asynchronous receivers, called subscribers. Published
methods, on the other hand, are messages are characterized into classes,
usually local, although it is also pos- without knowledge of what, if any, See all listings as text
sible to use @Remote interfaces for subscribers there may be. Subscribers
50
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 6 LISTING 7 LISTING 8 LISTING 9 LISTING 10
express interest in one or more classes, like to distribute. Listing 6 shows a CDI
@Stateless
and only receive messages that are of String broadcaster.
public class MessageBroadcaster {
interest, without knowledge of what, if The message is sent with a single
@Inject
any, publishers there are. This pattern invocation of the fire method. CDI events Event<String> event;

JAVA IN ACTION
provides greater network scalability and are transaction-aware and EJB 3.1 beans public void broadcast(String message){
a more dynamic network topology.” are transactional by convention. Because event.fire(message);
The key point of publish-subscribe there is no configuration (annotation or }
is its dynamic nature. Listeners and XML), the broadcast method is going to }
broadcasters can come and go. There is a be executed within a transaction.
dynamic N:M relation between listeners The listener is required to implement
and broadcasters; there is no require- only a void method with a single param-
ment for the existence of any. A broad- eter annotated with the @Observes See all listings as text

JAVA TECH
caster could send a message without annotation. Listing 7 shows a CDI String
the existence of any listener. There listener. The type of the parameter
could be several listeners without any denoted with the @Observes annotation tenuous messages. You could, of course, Then, annotate the corresponding
broadcaster. The must match the type of the fired pay- extend the type of the message by wrap- parameter:
“message” in the load. Only then does the message get ping the string with a custom event
WRITE MORE CODE
publish-subscribe delivered; otherwise, it just disappears. class. Listing 9 shows a custom event public void onImportantMessage
Although a JMS definition does not, Unlike JMS, with CDI you can easily class for event dispatching. (@Observes @Importance
publish-subscribe however, have to observe successful and unsuccessful However, introducing types is a poor (Importance.Degree.HIGH)

ABOUT US
be a javax.jms transactions with a single listener at approach for mimicking destinations. It
implementation .Message. It is bet- the same time. You only need to set the results in class explosion and unneces-
String message){}.

is more powerful ter to think about during element of the @Observes annota- sary bloat. CDI provides an elegant solu- There is still one deficiency: You need
and flexible, it messages as events
or payloads. With
tion. Listing 8 shows an example of how
to listen to commits and rollbacks at the
tion with qualifiers. Listing 10 shows
a qualifier for message dispatching. A
to inject an Event for every channel with
the given qualifier. Instead of injecting
also requires that CDI and EJB 3.1, same time. The message gets delivered qualifier is an annotation denoted with the Event with different qualifiers mul-
significantly more you can implement only in the specified transaction phase. the @Qualifier interface. @Retention tiple times, you can select the Qualifier

code be written. lean publish-sub-


scribe communica-
The @Observes(during=) element makes
CDI events particularly useful for the
should always be set to RUNTIME, and
with @Target, you need to choose the
on the fly, as shown in Listing 11, which
shows dynamic channel selection. For
tion without JMS. implementation of batch job monitoring elements to which you would like to apply the on-the-fly selection of the message
Java EE 6 (and or audits. You can easily track all success- the annotation. The @Qualifier annotation listener, you only have to pass a Qualifier
CDI, in particu- ful and failed transactions. can be considered to be a type extension. instance to the select method. The prob-
lar) comes with a built-in event: the For matching, the CDI framework consid- lem is that it is impossible to instantiate
injectable javax.enterprise.event.Event. It What About Multiple Destinations? ers not only the types but also the applied an annotation. Listing 12 shows a helper
allows you to fire (distribute) any object CDI eventing is type-safe. If the “fired” qualifiers. You need to use the qualifier class for annotation instantiation.
you like to all listeners locally. If there and “observed” types match, the event only at the injection point: The class ImportanceSelector in blog
is no listener, the broadcasted payload gets delivered; otherwise, it is ignored. Listing 12 implements the Importance
just disappears. To send a message you With the current approach, you can @Inject @Importance annotation and returns its enum value
only have to inject the Event class and use a type only once. There is no way (Importance.Degree.HIGH) as well as the annotation type. The
decide which kind of payload you would to distinguish between important and Event<String> event; enum Degree is passed as a construc-
51
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 11 LISTING 12 LISTING 13 LISTING 14
tor parameter, and it can be used easily This behavior is identical to a message
@Stateless
for the selection of the desired message processed by a message-driven bean
public class MessageBroadcaster {
type (see Listing 11). bound to a javax.jms.Destination.
@Inject
Event<String> event;

JAVA IN ACTION
Synchronous or Asynchronous When Lightweight Is Not Enough public void broadcast(String message){
CDI events are delivered synchronously. Asynchronous CDI events are similar event.select(new ImportanceSelector(Importance.Degree.LOW)).fire(message);
The sender has to wait until the listener to JMS topics without the availability of }
method completes. A RuntimeException durable subscribers. Messages are stored }
inside the message body is propagated persistently for a durable subscriber while
to the message sender. If the message it is inactive. On the next sign-in, all mes-
sender is an EJB 3.1 bean (or at least in sages are redelivered to the subscriber.
the invocation call stack), the transaction A CDI event can be cached transiently

JAVA TECH
is automatically rolled back. This is con- in the thread pool’s queue, and it can get
venient in cases where the sender would lost after an application server crash or a
like to be decoupled from the listener but transaction rollback caused, for example,
perform multiple tasks in one transaction by RuntimeException. Neither CDI nor See all listings as text
consistently. Documenting the state of @Asynchronous EJB 3.1 beans offer dura-
the business process by writing audits to ble subscribers out of the box.
a database with CDI events is an example Also, event redelivery is not available replace JMS with CDI eventing, there is with the Java EE 7 specifications, espe-
of synchronous, transactional events. in CDI. In contrast to JMS, the repeti- only a small overlap between JMS and cially with CDI. Listing 14 shows a pre-

ABOUT US
Delivering events asynchronously is the tion of a failed transaction needs to be CDI. Only JMS provides you with “once view of JMS 2.0 (this could change at any
natural way of publish-subscribe com- implemented by the application, not and only once” delivery semantics. To time) that is as lightweight as CDI.
munication. The sender does not need to the infrastructure. meet the “once and only once” delivery JMS 2.0 should eliminate the plumb-
block until the event is delivered and pro- Although a JMS publish-subscribe quality you have to set up a persistent ing required to send and receive mes-
cessed. Also, JMS works asynchronously. implementation is more powerful and (backed by a database) queue. In the sages. The JMS 2.0 programming
Events can be asynchronously con- flexible, it also requires that signifi- “sending” transaction, the message is model is planned to be similar to CDI
sumed with a no-interface EJB 3.1 bean. cantly more code be written. For the persisted in the database first and deliv- (see Listing 14). Even with JMS 2.0, you
You need to declare only the message implementation of an Observer pattern, ered in subsequent transactions. Also in should not misuse messaging just to
listener as a @Stateless session bean and CDI is well suited. Events are usually a publish-subscribe scenario the mes- execute synchronous services asynchro-
an @Asynchronous method. Listing 13 transient and do not require persis- sages can be stored on the server during nously. On the other hand, CDI is per-
shows asynchronous event consumption tence or redelivery. A local CDI event the subscriber’s offline periods. fect for transient event delivery, but it is
in an EJB 3.1 bean. distribution can be implemented with a Neither use case above can be imple- really bad for messaging. Use the right
The @Asynchronous annotation also fraction of the code required for ade- mented with CDI events. CDI events are tool for the job. </article>
changes the transactional behavior. The quate JMS functionality. not persistent and would require you to
method onImportantMessage is executed implement “once and only once” deliv-
in a new, independent transaction. An Real Messaging and JMS Strikes Back ery and, thus, to reinvent the wheel. blog
exception thrown in the @Asynchronous CDI eventing with the EJB 3.1 bean The old JMS specification is planned to LEARN MORE
onImportantMessage method will not @Asynchronous combination makes be completely refurbished and shipped • LightweightPublishSubscribe project
cause the transaction initiated in the the Service Activator pattern obsolete. with Java EE 7. The main goals of JMS 2.0 • Real World Java EE Night Hacks—
MessageBroadcaster EJB bean to roll back. Although it looks tempting to entirely will be simplicity and tight integration Dissecting the Business Tier (2011)
52
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
Part 1
Clustering and High Availability
Made Simple with GlassFish

JAVA IN ACTION
JULIEN PONGE The clustering features of GlassFish provide the ability to scale applications horizontally
BIO by running a cluster comprising multiple servers.

JAVA TECH
lassFish is known for being Note: Two editions of GlassFish running in a cluster can
the reference implementa- exist: GlassFish Server Open replicate session data
tion of the Java EE specifica- Source Edition and Oracle so that a few instances
tions. It is also known for being GlassFish Server. This article is joining and leaving a
a speedy modular server that is relevant to both. cluster do not cause
particularly well suited for devel- Two orthogonal problems arise applications to become
opment tasks. The capabilities in production: providing high unavailable.
of GlassFish do not stop after availability of applications and This article is Part 1

ABOUT US
the development phase, though. absorbing traffic load. The solu- of a two-part series on
GlassFish is also a production- tion lies in scaling applications the clustering fea-
class lightweight application horizontally by running not just tures of GlassFish and
server for apps requiring the one server but a cluster compris- introduces centralized
Figure 1
most up-to-date implementa- ing multiple servers. High avail- cluster provisioning
tion of Java EE. ability is achieved when instances and management of GlassFish Web application called ClockEE
servers. The second article that provides a single page on
discusses enabling high avail- which the current time is dis-
ability of applications in played (see Figure 1).
GlassFish clusters. The application is a Maven proj-
Note: The source code for the ect whose source code is in the
examples described in this article ClockEE.zip file. The sole view is
can be downloaded here. provided using JavaServer Faces,
as shown in Listing 1.
Meet ClockEE, Our Running In turn, it requires the presence
Example of a Contexts and Dependency blog
The running example that we will Injection (CDI)–managed bean
use in this article is deliberately that provides the clock value, as
Julien Ponge provides a brief introduction to his simple to focus on the manage- shown in Listing 2.
PHOTOGRAPH BY
MATT BOSTOCK/GETTY IMAGES
GlassFish series. ment of GlassFish clusters. It is a The @Named annotation
53
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2
makes instances of this bean available bin/ directory under your global PATH
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
with CDI under the clock name, while environment variable so that the
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
the @ApplicationScoped annotation command-line tool asadmin becomes
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
ensures that a single instance will be available from anywhere. We will use <!DOCTYPE html>

JAVA IN ACTION
created for the whole application. The asadmin extensively to administer <html>
#{clock.now} expression in JavaServer GlassFish. This is not the only way to do <head>
Faces thus resolves to that bean and its so, because GlassFish also provides Web <title>Hello World!</title>
getNow() method. and Representational State Transfer </head>
<body>
(REST) interfaces that are on par with
<f:view>
Installing GlassFish and the command set of asadmin.
<p>
Deploying ClockEE The name of the default domain The current time is:
As mentioned earlier, two editions of provided with the GlassFish distribution <em>

JAVA TECH
GlassFish exist: GlassFish is domain1. The start-domain <h:outputText value="#{clock.now}"/>
Server Open Source Edition PRODUCTION READY command should be fol- </em>

The capabilities
and Oracle GlassFish Server. lowed by the name of the <a href="index.jsp">(reload)</a>
</p>
The latter is a commercial dis- domain you want to start,
tribution supported by Oracle of GlassFish but the domain name can be
</f:view>
</body>
and contains a set of exten-
sions called Oracle GlassFish
do not stop after omitted when there is only
one domain. Conversely,
</html>

Server Control that focuses the development the stop-domain command

ABOUT US
on performance, monitor-
ing, and security. The two
phase. It is also is used to stop a previously
started domain.
See all listings as text
editions share the same code a production- You can create your own
base, including clustering and class Java EE domains using the create- DAS, and its role is to act as the central Command deploy executed
centralized administration.
The Open Source Edition is no
application server.
domain command. You can
even have several of them
point for the management of a cluster.
The next sections further explain this
successfully.

lesser an edition. running on the same physical concept, but now let us get back to our You can now pick your favorite Web
GlassFish Server Open host as long as they have dif- running example. browser and point it to http://local-
Source Edition can be ferent network port settings. Deploying ClockEE to GlassFish is host:8080/clockee-1.0-SNAPSHOT/
obtained from glassfish.org On a single machine, such as a simple. From the source code folder, we faces/index.jsp to see a page similar to
as a ZIP archive. Once expanded, this machine for developing applications, need only build a WAR archive through that of Figure 1. You can also list the cur-
archive provides a fully functional appli- a domain can be seen as a GlassFish Maven, and use asadmin to perform rently deployed applications by using the
cation server. No further initial configu- server configuration with its own the deployment: following command:
ration is required, and we can start the parameters, including network ports,
default configuration straightaway: security policies, JDBC connection pools $ mvn package $ asadmin list-applications
settings, deployed applications, and so ... clockee-1.0-SNAPSHOT <web> blog
$ cd glassfish on. Such a domain is called a stand- $ asadmin deploy Command list-applications
$ bin/asadmin start-domain alone domain. However, in a clustered target/clockee-1.0-SNAPSHOT.war executed successfully.
environment, such a domain is called Application deployed with name
It is probably a good idea to put the a Domain Administration Server or clockee-1.0-SNAPSHOT. Now that we have our GlassFish
54
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 3 LISTING 4 LISTING 5 LISTING 6 LISTING 7
installation running properly, we can ensure you have a domain and, hence,
$ asadmin list-domains
undeploy ClockEE before continuing a DAS running. You can then use the
domain1 running
with the clustering facilities: create-cluster command, as shown in
Command list-domains executed successfully.
Listing 3, to create my-first-cluster. $ asadmin create-cluster my-first-cluster

JAVA IN ACTION
$ asadmin undeploy While my-first-cluster has been suc- Command create-cluster executed successfully.
clockee-1.0-SNAPSHOT cessfully declared to the domain1 DAS, $ asadmin list-clusters
Command undeploy executed it is of little use because it does not have my-first-cluster not running
successfully. any GlassFish instances: Command list-clusters executed successfully.
$ asadmin list-applications
Nothing to list. $ asadmin list-instances
Command list-applications Nothing to list.
executed successfully. Command list-instances

JAVA TECH
executed successfully.
Our First Cluster
As mentioned earlier, a GlassFish DAS Fortunately, creating instances is very
can be used to manage a cluster of easy. Let’s create two local instances
GlassFish instances. The asadmin as part of my-first-cluster, that is, two
start-domain command actually starts instances running on the very same host
a DAS. as the one that we are using for the DAS.
A DAS is able to manage several local See Listing 4.

ABOUT US
and remote instances of a GlassFish The output of this command is very
server, thus effec- instructive: each local instance has
GET SOME REST tively providing a its own set of network ports. The first
A REST Web cluster. This makes instance has its HTTP port on 28080,
service interface it possible to man-
age a cluster from
while the second one has it on 28081.
There is, consequently, no network port
is available for a single host by conflict with the default assignments.
easily integrating issuing commands Of course, you could specify your own
to asadmin and hav- port numbers if you wanted to, but in
GlassFish with third- ing them be propa- most cases you will be just fine with
party management gated automati- the default ones. We can check that our
systems. There cally to perform
application deploy-
instances are now part of my-first-cluster,
yet not running, as shown in Listing 5.
is also a Web ment, configura- Starting the cluster both makes it
See all listings as text

administration tion, and resource active and launches the instances. See
blog
console that management.
Let’s get started
Listing 6.
We can also check which nodes are
By creating a local instance, GlassFish
automatically created a local config
It is now time to deploy ClockEE to
our cluster:
provides an intuitive by creating a clus- parts of our cluster and which instances node. (We will later explore the options
graphical interface. ter on our local are attached to them, as shown in available when creating instances for $ asadmin deploy --target
machine. First off, Listing 7. remote systems.) my-first-cluster
55
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 8
target/clockee-1.0-SNAPSHOT.war Web browser to each instance HTTP
$ asadmin stop-instance local-instance-1
Application deployed with name connector, as depicted in Figure 2.
The instance, local-instance-1, is stopped.
clockee-1.0-SNAPSHOT.
Command stop-instance executed successfully.
Command deploy executed $ asadmin list-applications $ asadmin list-instances -1

JAVA IN ACTION
successfully. my-first-cluster NAME HOST PORT PID CLUSTER STATE
clockee-1.0-SNAPSHOT <web> local-instance-1 localhost 24848 -1 my-first-cluster not running
We can check that it is running, both Command list-applications local-instance-2 localhost 24849 16548 my-first-cluster running
by using asadmin and by pointing our executed successfully. Command list-instances executed successfully.
$ asadmin start-instance local-instance-1
Waiting for local-instance-1 to start ................
Creating a cluster
Successfully started the instance: local-instance-1
and deploying a simple instance Location: /usr/local/Cellar/glassfish/3.1/libexec/glassfish/nodes/local-
application with so little host-domain1/local-instance-1

JAVA TECH
effort to a server that Log File: /usr/local/Cellar/glassfish/3.1/libexec/glassfish/nodes/localhost-do-
we just downloaded main1/local-instance-1/logs/server.log
is already no small Admin Port: 24848
Command start-local-instance executed successfully.
achievement.
The instance, local-instance-1, was started on host localhost
You can, of course,
Command start-instance executed successfully.
have much more fine- $ asadmin list-instances -1
grained control over the NAME HOST PORT PID CLUSTER STATE
instances of a cluster. local-instance-1 localhost 24848 16846 my-first-cluster running

ABOUT US
For example, you can local-instance-2 localhost 24849 16548 my-first-cluster running
start and stop them Command list-instances executed successfully.
Figure 2 individually, as shown in
Listing 8. See all listings as text
Finally, we can unde-
ploy the application
from the cluster: GlassFish clustering. maintains a list of nodes taking part in a
Figure 3 shows an overview of the cluster configuration. Each node repre-
$ asadmin undeploy DAS architecture. The DAS maintains a sents a server where instances are actual
--target=my-first-cluster central repository containing deployed GlassFish servers.
clockee-1.0-SNAPSHOT applications, declared resources, and When we created the two local
Command undeploy configuration. instances earlier, GlassFish created
executed successfully. When we deployed ClockEE in the a node on our behalf on the current
previous sections, we actually deployed machine. Every instance has a cache of
GlassFish Clustering it to this central repository by using the central repository. Synchronization
Terminology asadmin. Similarly, we could have between the DAS and the node blog
Now that we have had declared a resource such as a JDBC con- instances is performed over HTTP or
an introduction, it is nection pool, and it would have been HTTPS (see the asadmin enable-secure-
time to look at the declared in the DAS central repository. admin command). As an example,
Figure 3 terminology used for When used in a cluster, the DAS declaring a new resource in the DAS
56
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 9 LISTING 10 LISTING 11 LISTING 12
is propagated to the node NODE NOTE and a confidentiality point
$ asadmin setup-ssh --sshuser
instances when synchroniza-
tion occurs.
SSH nodes can of view.
SSH nodes are preferable,
julien 192.168.56.101

Two distinct types of nodes be completely whenever possible, because


Enter SSH password for julien@192.168.56.101>
Copied keyfile /Users/julien/.ssh/id_rsa.pub to julien@192.168.56.101
managed from

JAVA IN ACTION
exist: the complete management Successfully connected to julien@192.168.56.101 using keyfile

the DAS.
■■ Config nodes need to be of a GlassFish cluster can be /Users/julien/.ssh/id_rsa
locally provisioned, con- performed from the DAS Command setup-ssh executed successfully.
figured, and administered. host machine.
They are declared to a clus- Given that SSH nodes argu-
ter from the DAS, but the DAS cannot ably provide more-interesting features,
perform any administrative com- we will focus solely on them in the
mands. Administrators are required remainder of this article. Adding Config

JAVA TECH
to log in to the machines running nodes to a cluster requires preparing
such nodes and perform the required the node hosts by installing GlassFish,
tasks. Such nodes cannot be centrally creating local Config nodes on each of
administered from the DAS. the hosts, and declaring the nodes to
■■ SSH nodes can be completely man- the DAS. As the next section shows, See all listings as text
aged from the DAS. The minimal these tasks can be fully automated in
requirement is to have an SSH server the case of SSH nodes. is running. A solid alternative that I it on the remote machine in /home/
and a Java SE runtime environment experimented with while writing this julien/glassfishv3 by performing a

ABOUT US
on such nodes. Another benefit of Remotely Provisioning and Adding article is to use a virtual machine. I used remote provisioning. See Listing 10.
SSH nodes is that communications an SSH Node Oracle VM VirtualBox to virtualize a A working GlassFish application has
between the DAS and the nodes is In this section, we are going to see Linux Ubuntu Maverick operating sys- just been provisioned remotely from a
secure, both from an authentication how to remotely provision and add a tem (see Figure 4). local image that was copied over SSH.
GlassFish instance Given that operations happen over We can now create an SSH node on the
to our cluster. It SSH, any action that requires connect- remote server:
is assumed that ing to the remote servers will require
you have a valid authentication. By default you will $ asadmin create-node-ssh
user account on a have to type your password every time, --nodehost 192.168.56.101
remote server that but you can drastically simplify this. --installdir
has, at the very Password-less SSH connections are pos- /home/julien/glassfishv3 ubuntuvm
least, a working sible by generating a public/private key Command create-node-ssh executed
Java SE 6 runtime pair locally and adding the public key successfully.
environment and fingerprint to the ~/.ssh/authorized_
an OpenSSH server. keys file on the remote servers. As shown in Listing 11, we can create
For the purpose Although you can do this manually, an instance on this SSH node, name it blog
of testing, you GlassFish can automate it, as shown vm1, and then add it to my-first-cluster.
could do this on in Listing 9. By default, the newly created instance
your local machine Let’s assume that the remote server is not running, so we can start it. See
Figure 4 as well, if OpenSSH does not have GlassFish. Let’s install Listing 12.
57
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
Conclusion
This article introduced the centralized
cluster provisioning and management
of GlassFish clusters. The ability to

JAVA IN ACTION
get a new host up and running
remotely as long as it has an SSH server
and a Java SE runtime is especially
powerful. We deployed a simple state-
less application to a cluster and played
with common administration com-
mands to check the state of our cluster
and manipulate instances.

JAVA TECH
The next article in this two-part series
Figure 5 Figure 7 shows how to enable high availability
of stateful applications deployed to our
cluster by providing transparent session
failover. </article>

LEARN MORE

ABOUT US
• GlassFish product documentation
• “Clustering in GlassFish Version 3.1”
• GlassFish videos on YouTube
• Real World Java EE Night Hacks—
Dissecting the Business Tier by Adam Bien
(press.adam-bien.com, 2011)
• Beginning Java EE 6 with GlassFish 3 by
Figure 6 Figure 8 Antonio Goncalves (Apress, 2010)
• The Java EE 6 Tutorial: Basic Concepts
We can check that ClockEE was trans- as was mentioned earlier, that is not Both are on par with the equivalent fourth edition by Eric Jendrock,
parently deployed to the vm1 instance the only option. A REST Web service asadmin shell commands. Ian Evans, Devika Gollapudi, Kim Haase,
when it was launched, provided that it interface is available for easily integrat- Figure 6, Figure 7, and Figure 8 and Chinmayee Srivathsa
had already been deployed to my-first- ing GlassFish with provide a few screen- (Prentice Hall, 2010)
cluster (see Figure 5). third-party manage- STAY TUNED shots of using the
ment systems. There The next article shows how to Web administration blog
How About the Web is also a Web admin- console to perform a
Administration Console? istration console that
enable high availability of stateful few tasks we did from
We did all administration work from provides an intuitive applications on the cluster. the command-line
the command-line using asadmin, but graphical interface. before.
58
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
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.

JOIN TODAY Go to: oracle.com/technetwork/java

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
//enterprise java /

COMMUNITY
Wake Up and Smell the Coffee

JAVA IN ACTION
The creators of jHome, a 2011 Duke’s Choice Award winner, demonstrate why Java EE 6 development is so easy.

j Home is a complete home-


automation open source API
lights from their mobile devices.
The possibilities for simplifying
jHome Devices
jHome is based on open source
■■ USB cable (the cheapest
solution)
based on GlassFish Server Open the way you control the objects in hardware and does not require ■■ Bluetooth (good for wireless

Source Edition and Java EE 6, your life are unlimited. proprietary or expensive solu- prototypes)

JAVA TECH
which enables developers to con- tions. The jHome team created ■■ ZigBee/xBee (the best

trol anything in their homes. jHome Overview the reference implementation wireless solution for real
In this article, we describe the jHome is a set of interfaces and hardware based on Arduino, an implementations)
jHome project in detail, including components based on Java EE 6 open source electronics prototyp- Relay boards are very useful
the technical context, code, and for implementing home- ing platform. The cost to control because they let you control wall
VINICIUS SENGER AND hardware details. Usage examples automation solutions. Using two lamps or wall sockets is less sockets, lamps, and any other elec-
YARA SENGER show the power and ease of use of Enterprise JavaBeans (EJB), the than US$100 using Arduino and tronic device. jHome can also read
Java EE. Timer Service, Java API for RESTful USB cables. values from sensors such as tem-

ABOUT US
BIO
Like most Java programmers, Web Services (JAX-RS), Contexts Each jHome device can com- perature, light, distance, and gas.
we are crazy for coffee. We always and Dependency Injection (CDI), municate with the jHome appli- The standard firmware for
wanted to schedule our coffee and Web components, jHome lets cation deployed on the Java EE jHome devices can control relays,
maker to turn on at a certain time, you automate your house, build container using different proto- dimmers, RGB LEDs, motors, and
so we could wake up to the smell a Web or mobile app, and control cols and different wired and wire- robots, and code for various sen-
of coffee. So we set out to develop things over the internet. less components: sors is available at the Tools Cloud
a way to do this. After all, nothing Figure 1 shows an overview of
is more fun than using the Java EE the jHome architecture.
6 Timer Service to schedule the With the simple code shown in
“real objects” of your life. Listing 1, you can inject an object
People who always lose or for- that represents a lamp in your
get their keys, for instance, might house and turn it on or off using
want to control their front door a Servlet.
through a Website or a mobile Using EJB beans to control a
application. And why not open lamp may sound strange, but
your door by sending a message the Singleton, Transactions, and blog
to a Twitter profile that is associ- Injections resources are a very
ated with your jHome application? useful way to deal with hardware
Others might want to control their communication, concurrency, and
balcony lights or swimming pool queuing requests. Figure 1
60
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2
GIT repository. Use username jhome mating control of your house. Here's how
@WebServlet(name = "Light", urlPatterns = {"/Light"})
and password: jhome. Let’s clone! the jHome team used some of the com-
public class Light extends HttpServlet {
Another interesting implementation ponents in the jHome implementation.
private static boolean on;
we made was to integrate jHome with EJB: core components. EJB beans are

JAVA IN ACTION
a heart rate transmitter and program used for all jHome core components. @EJB
jHome to do a certain task (such as open The EJB resources used in this applica- Relay light;
a Website or send a message) when the tion are the following:
user achieves a predefined maximum ■■ Singleton: Used to represent devices @Override
protected void doGet(HttpServletRequest request,
or minimum heart rate. In the Java EE and boards that cannot have more
HttpServletResponse response)
world this would be a Heart-Driven than one instance
throws ServletException, IOException {
Bean—something that brings the fun ■■ Transaction: Used to deal with hard-
if (on) {
back to development. ware concurrency light.turnOff("lamp");

JAVA TECH
■■ Web services: Very useful to expose on = false;
Understanding Arduino and functionality to any kind of client } else {
Open Source Hardware application light.turnOn("lamp");
on = true;
Arduino is an open source electronics ■■ Timer Service: Used to schedule wall
}
prototyping platform based on flexible, sockets, update sensor values, check
}
easy-to-use hardware (a printed circuit for Twitter messages, and so on }
board) and software. There are several Timer Service: scheduling the coffee
different implementations varying in maker. jHome uses the Timer Service

ABOUT US
size, price, and memory capacity. API to allow you to schedule services See all listings as text
The programming language used to such as turning lights on and off and
program the board is a C-like language, scheduling the coffee maker.
and there is a Java IDE that helps you to And because coffee is a very critical jHome architecture. jHome has three maker, and read basic sensors.
create programs and send them to the resource for Java developers, it’s impor- main modules: You must deploy the jHome Interface
board. Although the language running tant to have high availability. The Timer ■■ jHome Interface : All jHome inter- and Core modules to run the basic
on the Arduino board is not Java, the Service API delivers this: if you restart faces can be found in this module. jHome services. The jHome Web module
syntax is easy for experienced Java pro- your application server, you will not need ■■ jHome Core: This module has all the is optional, and you can create or use
grammers to learn and understand. to reschedule the coffee maker. interface’s implementation and is any other client applications such as Java
Servlet: controlling lights via the responsible for discovering the jHome ME, JavaFX, or Ginga-J to run on your TV.
Java EE 6 and jHome internet. There are a couple of Servlets devices available in the house using Sensor API. The Sensor API provides
Java EE has really evolved over the last for controlling lights. There are LED an open protocol, reading their sen- information about the physical environ-
10 years. It’s still powerful but is now strips that can control color using RGB. sors, and also helping to expose the ment, and it is implemented using the
much easier to use, affordable, and You can control the color of your swim- jHome device functionality to other Timer Service.
lightweight—in fact, our cell phones ming pool lights, aquarium lights, or any Java components. With the jHome Sensor API you can
can now run a Java EE container, such as other light. ■■ jHome Web: A Web application that feed your Java application or Website blog
GlassFish Server Open Source Edition. uses HTML5 and jQuery to control the with information from different sen-
Controlling your house with a Java EE jHome Architecture default functionalities from jHome: sors that are plugged into your jHome
application server is now a reality. All jHome is modular and uses Maven. Let’s turn a lamp on and off, control the devices. This capability provides many
Java EE components are useful for auto- look at its modules. RGB color LEDs, schedule a coffee new possibilities for designing your
61
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//enterprise java /

3 Billion

COMMUNITY
Website or Java application, might want to try it on the cloud
for instance: to further enhance their experi-
■■ Change the background color ence with the project.
of your Website based on jHome fits very well on the

JAVA IN ACTION
information from a tempera- cloud and can be provided as

Devices Run Java


ture sensor. software as a service (SaaS).
■■ Make a component turn on Our team developed a jHome
a light based on information Proxy Device, which is a very
from a light sensor. simple board with an Ethernet
■■ Give the dimensions of your connection that you can plug
house to a 3-D CAD system into your internet router. It will
using a distance sensor. receive jHome instructions from

JAVA TECH
Social network APIs. The jHome the cloud.
Computers, Printers, Routers, BlackBerry Smartphones,
Twitter API lets you control your Even if the cloud server is
home by sending tweets men- unavailable, you can access this Cell Phones, Kindle E-Readers, Parking Meters, Vehicle
tioning a specific Twitter profile device via HTTP. It’s a prototype,
and using a Twitter hash. For but it’s working, and there seems Diagnostic Systems, On-Board Computer Systems,
example, we can control our to be a good market for it. Smart Grid Meters, Lottery Systems, Airplane Systems,
office using the Twitter com-
mands shown in Listing 2. The Conclusion ATMs, Government IDs, Public Transportation Passes,

ABOUT US
bold words in the code must be jHome demonstrates that Java
included in your tweet. They are EE 6 is mature, simple, easy,
Credit Cards, VoIP Phones, Livescribe Smartpens, MRIs,
part of the syntax, used to iden- and inexpensive to maintain. CT Scanners, Robots, Home Security Systems, TVs,
tify the action. The other words Additionally, with the advent of
are optional in the tweet. open source hardware, you can Cable Boxes, PlayStation Consoles, Blu-ray Disc Players…
You can create your own create your own solutions and
extension and create a Facebook automations.
connector or implement any The jHome team is proud to
other interesting idea. have won a 2011 Duke’s Choice
Award and received community
Home Automation as a Service recognition for the jHome project.
It is impossible not to think Remember, there is life beyond
#1 Development Platform
about the relation between any database applications. </article>
new project and the cloud nowa-
days. Some people might think
that maintaining a Java EE con- blog
tainer/server in their houses to
turn lights on and off, schedule
LEARN MORE
oracle.com/goto/java
a coffee maker, and open doors/ • jHome
or call 1.800.ORACLE.1
gates can be a bit complex. They • Arduino
62
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.

ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012


//mobile and embedded /

COMMUNITY
Developing Proximity Awareness
with the Location API

JAVA IN ACTION
Using the Location API, you can access location data and incorporate that
VIKRAM GOYAL data into a game.
BIO

JAVA TECH
his article is the second Being Location-Aware criteria in the constructor of Once we have a valid loca-
article in a two-part series. Determining what is near you can the MIDlet. tion, we display that information
Part 1 described how to set up be done in several ways: Bluetooth We define a very basic set of using the getQualifiedCoordinates
the GameCanvas and deal with technology, Wi-Fi networks, cell criteria for the Location API. We method. The location is displayed
the Mobile Sensor API, JSR-256. phone tower triangulation, and, have no special requirements for to the user, and it is also broad-
We still need to add proximity of course, GPS. What might work the horizontal or vertical accura- cast to the server so that it can be
(location) awareness in one situation might cies or the response time, but we registered, as shown in Figure 1.
aspects to our loca- WHAT'S NEARBY? not work best in oth- don’t want any costs incurred in The next step is to find play-

ABOUT US
tion-based game. In ers. A combination of acquiring the location data. This ers near your own location with
this article, we add the Determine what these technologies is should suffice in even the most whom you can play the game,
location-based code. is near you perhaps the best bet basic GPS devices. as shown in Listing 3. The
For the basics of the
Location API, JSR-179,
using Bluetooth for figuring out the
location of your device.
Next, we acquire the
LocationProvider using these
getPlayersFromServer placeholder
mock method returns a list of
and the Mobile technology, Wi-Fi In this second arti- criteria. Of course, if the provider
Sensor API, see my
previous tutorials,
networks, cell cle, I concentrate on
using the Location API,
cannot be found, we cannot
proceed further and a message is
which are listed in the phone tower because it provides the displayed to the gamer.
“Learn More” section triangulation, and,easiest way of find- Our MIDlet should implement
of this article. In addi- ing people and items the LocationListener interface,
tion, the demo apps of course, GPS. that are near you. because if the provider is found,
provided with the Furthermore, you can the MIDlet can listen to the
Java ME SDK are very broadcast your own events that the provider gener-
relevant and provide location easily enough, ates. The most important event
good insight into the working of so others can find you as well. is, of course, updates on current blog
these APIs. coordinates. The locationUpdated
Note: The source code for the Using the Location API method implementation handles
PHOTOGRAPH BY game I develop in this two-part Listing 1 shows the initialization this in our code, as shown in
JONATHAN WOOD/
GETTY IMAGES series can be downloaded here. code for the Location API Listing 2. Figure 1
63
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//mobile and embedded /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5

try {

// create very basic criteria for the location provider


Criteria criteria = new Criteria();

JAVA IN ACTION
criteria.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPreferredResponseTime(Criteria.NO_REQUIREMENT);
criteria.setCostAllowed(false);

// get the provider based on the criteria


LocationProvider provider = LocationProvider.getInstance(criteria);

// provider found
Figure 2 GIVE BACK!

JAVA TECH
if (provider != null) {

players. The findPlayers command is // set this MIDlet to be the listener for location changes
provider.setLocationListener(this, -1, 0, 0);
ADOPT A JSR
handled by the command­Action method.
For the best results, make sure any
} else {
code that might take a long time to display.setCurrent(
return, such as querying the server for new Alert("Error!",
a list of players, is handled in a sepa- "Phone does not support Location Provider with the given criteria", Find your JSR here

ABOUT US
rate thread so it doesn’t block the main null, AlertType.ERROR));
program flow. The end user should be }
able to cancel the query from the server
} catch (Exception ex) {
if required, and the program should
handleError(ex);
handle that implicitly. Figure 2 displays }
a list of players.
Handling the OK button for the selec-
tion of player launches the game, as See all listings as text
shown in Listing 4.
The initiateGame mock notifies the
server and then launches the game Conclusion accessing location data and we saw
using the launchGame method, as shown In this second article, we discussed how to incorporate the data we get into
in Listing 5. how to incorporate the Location API into our game. </article>
For trivial applications, this should the gaming code that we developed in
suffice, but for production applications, the previous article. We also saw that
there are other aspects that would our core MIDlet needs to implement the
LEARN MORE blog
require attention as well, such as bet- LocationListener interface and handle • Tutorial: “Using the Location API for
ter error handling, increased sensitivity the LocationUpdated method (at the Favorite Spots”
of detection, valid response from the very least). In addition, we discussed • Tutorial: “Working with the Mobile
server, and so on. how to form very basic criteria for Sensor API”
64
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//polyglot programmer

COMMUNITY
Using Maven to Compare JVM
Scripting Languages

JAVA IN ACTION
Learn how to use Maven to quickly try your hand at Clojure, Groovy, JavaScript, JRuby, and Jython.
CASIMIR SATERNOS

M att Mullenweg, a highly suc- scripting languages: Clojure, ated Ruby with the intention of guages. Heroku supports Clojure,
BIO

JAVA TECH
cessful entrepreneur and Groovy, JavaScript, JRuby, and giving programmers joy. JavaScript, and Ruby, while the
founding developer of WordPress, Jython. Initially, a language might tar- Google App Engine utilizes Go,
recently remarked that “Scripting Note: The project was developed get a specific platform. JavaScript Java, and Python. So your choice
is the new literacy, and the ability and tested on Microsoft Windows gained popularity in Web brows- of language might well be dic-
to learn and execute on your ideas and Mac OS using the following ers. Python is used as the scripting tated by the arena of your devel-
. . . is going to be invaluable.” software versions: language for open source proj- opment efforts.
Scripting languages can ■■ Java 1.6.0_14-b08, 1.6.0_24- ects such as Blender. The Java- Using different languages
decrease time to market, improve b07-334, 1.5.0_19-b02-304 based Python implementation offers new conceptualizations

ABOUT US
efficiency, boost performance, ■■ Apache Maven 3.0.3 known as Jython is used in com- of problems. Learning Clojure
and automate previously error- (r1075438) mercial software such as Oracle increases one’s appreciation for
prone manual workflows. A new ■■ Apache Maven 3.0.2 Data Integrator. Certain cloud elegance of design and the use
programming language provides (r1056850) computing and hosting services of recursion. Developers will
a new framework to conceptual- ■■ Apache Maven 2.2.1 provide support for specific lan- never think of whitespace the
ize ideas and might offer other- (r801777)
wise inaccessible solutions. In
particular, less-structured and Language Differences
ad hoc projects can be imple- Programming languages, which
mented more effectively by are designed with different goals
choosing the right scripting in mind, vary in syntax, target
language. Specific APIs or librar- platforms, performance, and
ies that were implemented for features. Choosing a language
a given language might not be with a desirable syntax is impor-
available for other languages. tant. Some languages emphasize
This article presents a project, expressiveness and clarity, while blog
based in Apache Maven, that can others focus on conciseness.
be set up in minutes and allows Syntax concerns might not even
developers to run and compare be purely technical. Yukihiro Learning a new language gives you the power to
scripts written in five dynamic Matsumoto has said that he cre-
create better software, says Casimir Saternos.
65
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//polyglot programmer /

COMMUNITY
same way after coding in Python, where with each recent Java release. JSR-223 The output from each of these Note: You can also run the file
whitespace is syntactically significant. defined a scripting interface that was commands should indicate a Java by using the Java interpreter and
The stereotype of the lone-wolf pro- completed in Java SE 6. In Java SE 7, SDK version of 1.6. If it does not, referencing the JAR itself. The jvms
grammer locked away in a room has JSR-292 provides additional benefits download and install a Java SDK .bat script contains such a call for a

JAVA IN ACTION
faded in recent years. Team software including improved performance and (the Microsoft Windows version is Microsoft Windows environment,
development is the norm, and pair pro- additional support for dynamically jdk1.6.0_14). and the jvms.sh script contains
gramming is an accepted Agile practice. typed languages. The JVM is mature, 2. Download and install Maven, and such a call for a Mac OS environ-
Communities with different strengths widely deployed, and heavily opti- make sure it is included in your PATH ment. The remainder of this article
grow up around a lan- mized, and it includes environment variable. Then run the uses “mvn” to avoid operating-
guage. With such consider- excellent tools and allows following command: system-specific details.
RUN AND COMPARE
ations in mind, developers access to a large variety 6. To compare various languages, pass
might want to set up an The Apache Maven of libraries. mvn -version at the command line the scripts that
project presented

JAVA TECH
environment where they are to be evaluated.
can test-drive several Start Your Engines The output of this command One or more files can be passed
new languages to quickly here can be set up in Trying out Clojure, Groovy, should indicate that a recent version as arguments, and the files can
compare them. Java— minutes and allows JavaScript, JRuby, and of Maven is installed (for example, use the same or different script-
specifically the Java Virtual
Machine (JVM)—provides
developers to run Jython requires an initial
setup in order to find,
version 3.0.3).
3. Download the project itself, which
ing languages. The scripts used
in this article reside in src\main\
an excellent platform for and compare scripts download, install, and consists of a small amount of Java resources\scripts. The customary
such an exercise. written in five dynamic configure each imple- code, a few scripts, and a pom.xml “Hello World” example can be run

ABOUT US
Java and the JVM
scripting languages: mentation. The project
described here reduces
file. Extract the code, and navigate
to the directory that contains
as follows:

The Java language is not— Clojure, Groovy, the time and effort pom.xml. mvn -q exec:java -Dexec.args=
and was never intended
to be—the perfect pro-
JavaScript, JRuby, required by using Maven
to locate and download
4. Build the code, which will download
JAR files from various archives and
" hello.clj hello.js hello.groovy

gramming language for and Jython. resources from various assemble the application:
hello.rb hello.py"

every situation. The JVM public code repositories. Additional Scripts


is software constructed to Maven is also used to mvn clean install In addition to the “hello” scripts, several
execute bytecode com- build the project so other scripts (described in a bit more
piled from Java. Each JVM implemen- that a single executable JAR is created, All downloaded JAR files are detail below) are provided that can get
tation is designed to run on a specific which contains a class that can be used installed in your local Maven reposi- you started with your own experiments.
platform. The original vision was to to run scripts written in several differ- tory (by default, in your home direc- You can run these scripts and modify
allow Java to be compiled once and run ent languages. tory under .m2/repository). them to compare and contrast Clojure,
on a variety of platforms. But the JVM Setup 5. Run the application from within Groovy, JavaScript, Python, and Ruby. In
has also been leveraged in recent years To run the project, do the following: Maven (this works regardless of the some cases, the code is nearly identical,
to run bytecode created by other pro- 1. Validate your Java installation by platform in use). To see the list of but in other cases, it is radically differ- blog
gramming languages. running the following commands: available scripting languages, run ent. When you run a set of scripts, you
The JVM has accommodated other the following command: will also notice that the output shows a
languages for some time, and support javac -fullversion time in nanoseconds for each script. This
for such languages has been improved java -fullversion mvn -q exec:java allows you to create scripts in several
66
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//polyglot programmer /

COMMUNITY
languages and immediately compare that provides JSR-223 compatibility. implementations. Otherwise, it reads Rosetta Code, for example, for such
their performance. Maven plug-ins. Maven uses a plug-in the filenames passed to it as arguments comparisons. The included scripts are
to perform a unit of work. A number and attempts to locate each file. (A path relatively equivalent to allow for valid
Implementation Details of plug-ins are available that can be can be specified. The current working baseline comparisons.

JAVA IN ACTION
Maven. The convenience of build- used to build a JAR file, including the directory and src/main/resources/ ■■ fact: Outputs factorials (the product

ing a sophisticated project by run- following: scripts are searched if no path is speci- of positive numbers less than or equal
ning a simple command is almost ■■ maven-jar-plugin fied). If a file is found, the application to n) less than 100,000.
magical when first encountered. Maven ■■ maven-assembly-plugin loads a scripting engine associated with ■■ fib: Outputs the numbers in the

enables developers to build a sophis- ■■ onejar-maven-plugin the file extension, and the script is run. Fibonacci sequence under 100 (each
ticated project with a simple com- ■■ maven-shade-plugin Output generated by the script and number in the sequence is the sum of
mand through a build tool The first two plug-ins related diagnostics are displayed. the previous two).
analogous to Apache Ant BRIGHT FUTURE are standard and sufficient A single test class, JvmsTest, is used

The JVM is home

JAVA TECH
that offers a way to create for many applications. The during the build to validate that script- Conclusion
standardized builds without onejar-maven-plugin pro- ing engines can be identified for the There are many advantages to under-
significant knowledge of the to some of the top vides additional features to filenames in question. standing alternative languages for the
underlying details. All the implementations combine code and JAR files Included scripts. For each type of script JVM. The project presented in this article
project information is found
in the pom.xml file (also of new languages, into a single JAR.
The project provided with
listed below, a file with an associated
extension exists:
demonstrates how easily new languages
can be incorporated into a project using
known as the Project Object and it provides this article faced the chal- ■■ Clojure: .clj Apache Maven.
Model or POM).
an excellent lenge that various language ■■ Groovy: .groovy The JVM is home to some of the top

ABOUT US
A POM and a set of plug- implementations use dif- ■■ JavaScript: .js implementations of new languages,
ins are all that are used by infrastructure for ferent versions of APIs that ■■ Jython: .py and it provides an excellent infrastruc-
Maven to construct the proj- running them. With included different versions ■■ Ruby: .rb ture for running them. With scripting
ect provided with this article.
The repositories used in the
scripting language of classes with the exact
same name. Fortunately,
A number of scripts are included.
■■ hello: A customary “Hello World”
language support improving in each
new Java release, we can expect greater
project are listed toward support improving maven-shade-plugin can program. This is included to provide improvements and enhancements in
the end of the POM. This in each new Java be used to automatically a simple example of how to write to the future. The best-prepared profes-
enables Maven to obtain
various JAR files, in this case, release, we can rename classes to avoid
conflicts simply by specify-
standard output.
■■ loop: A loop that outputs integers 0
sionals will have a clear understanding
of the resources available and how
scripting language imple- expect greater ing a transformer imple- through 9. This demonstrates pro- they can be best leveraged to address
mentations and engines.
The dependencies sec-
improvements and mentation class.
Java class. The Java applica-
cedural techniques of repetition and
iteration. You can also use looping
the technical needs driving business
today. </article>
tion lists the specific JAR files enhancements in tion itself consists of under tests to evaluate performance.
that are included in the proj- the future. a hundred lines of Java code The other two types of scripts use
ect. Some languages require used to invoke the intended frequently implemented algorithms.
LEARN MORE
two JAR files, while others script engine based upon a They are particularly interesting in that blog
• Download Maven
require only one. This is file’s extension. they can be implemented in various
because some languages have JSR-223 If no arguments are passed to the ways that highlight differences between • JSR-223, “Scripting for the Java Platform”
support built into the language itself, application, it displays version informa- languages (using iteration, recursion, • JSR-292, “Supporting Dynamically Typed
while others require a separate engine tion and available scripting language and various optimizations). See Languages on the Java Platform”
67
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
//fix this /

COMMUNITY
Hint: Read Javadoc
carefully.

In the last issue, Arun Gupta gave readers a


piece of code and asked if the code is guaranteed to 2 THE CODE

JAVA IN ACTION
work in a multithreaded environment. Consider the following code when preparing a window:
The correct answer is #2: No. Servlets are not public class MyWindow extends JFrame {
re-entrant, and EntityManager is not threadsafe. public MyWindow() {
GridLayout layout = new GridLayout(0, 2, 4, 4);
Instead inject as setLayout(layout);
@PersistenceUnit EntityManagerFactory em; JLabel idLabel = new JLabel("ID:");

JAVA TECH
and then get EntityManager within the doGet() method. for (String d : new String[]{"USER1", "USER2", "USER3"}) {
add(idLabel);
This issue s challenge comes from Marek Piechut, a technical leader add(new JLabel(d));
}
at Transition Technologies S.A. in Lodz, Poland, who is currently }
working on a heavy Swing client for a large enterprise application. }

1 THE PROBLEM 3 WHAT S THE FIX?

ABOUT US
Java Swing is the main Java framework for heavy client 1) The first value for GridLayout is invalid and should be replaced
implementations. with the actual number of rows.
Lets create a Swing window that displays a simple table. 2) You cant add elements directly to JFrame; you should first pack
What we want displayed is all labels into JPanel and add it to JFrame.
3) You should replace a single shared instance of idLabel with a new
JLabel instance for each row.
4) You need to call layout.layoutContainer(this) in the constructor
end to lay out the window properly.
But what we get is

blog

GOT THE ANSWER?


ART BY I-HUA CHEN
Look for the answer in the next issue. Or submit your own code challenge!
68
ORACLE.COM/JAVAMAGAZINE  ///////////////////////////////////  JANUARY/FEBRUARY 2012
COMMUNITY
Learn Java 7
EDITORIAL PUBLISHING
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

JAVA IN ACTION
Cassandra Clark, Sonya Barry, Senior Manager, Audience Development
Yolande Poirier and Operations
Java in Action Editor Karin Kinnear +1.650.506.1985
Michelle Kovac ADVERTISING SALES
Technology Editors Associate Publisher
Janice Heiss, Tori Wieldt Kyle Walkenhorst +1.323.340.8585

—Oracle University—
Contributing Writer Northwest and Central U.S.
Kevin Farnham Tom Cometa +1.510.339.2403
Contributing Editors Southwest U.S. and LAD
Blair Campbell, Claire Breen, Karen Perkins Shaun Mehr +1.949.923.1660
Northeast U.S. and EMEA/APAC

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

ABOUT US
+1.888.283.0591 (U.S.)
Oracle Press Books
oraclepressbooks.com Taught by Oracle Experts
ARTICLE SUBMISSION
If you are interested in submitting an article, please e-mail the editors. 100% Student Satisfaction Program
SUBSCRIPTION INFORMATION
Subscriptions are complimentary for qualified individuals who complete the
subscription form.
MAGAZINE CUSTOMER SERVICE
java@halldata.com  Phone +1.847.763.9635
PRIVACY
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 and 2012, 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 Click for Details, Dates, and to Register
EXPRESSLY DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE
FOR ANY DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN.
The information is intended to outline our general product direction. It is intended for information purposes only, and may not
be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied blog
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
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  ///////////////////////////////////  JANUARY/FEBRUARY 2012

You might also like