Sie sind auf Seite 1von 93

//table of contents /

COMMUNITY
COMMUNITY 62
02 Enterprise Java
From the Editor Secure Java EE

JAVA IN ACTION
04 Authentication
Java Nation Implementing login authenti-
News, people, and events cation using declarative and
programmatic security
14
JCP Executive Series 68
Q&A with Credit Suisse Rich Client
EC members on the JCP Integrating Web and
Java Client Applications

JAVA TECH
JAVA TECH with Social Media
40 Johan Vos gets social.
New to Java 76
Introduction to Web Mobile and Embedded
Service Security from Getting Started with
Server to Client JSR 281
The final installment in this Bring IP Multimedia

ABOUT US
series from Max Bonbhel Subsystem services to Java-
49 enabled devices.
Java Architect 81
Demystifying Mobile and Embedded
invokedynamic Swing into Mobile
Learn how to use invoke- The Lightweight UI Toolkit
dynamic in your code.
20 26 31 36
and Nokia Series 40 phones
55 85

EMBEDDED
Java Architect Polyglot Programmer TOP 10 Java in Action Java in Action
Java Compiler Plug-ins Building Actor-Based REASONS JAVA ARRIVES THE FUTURE
in Java 8

EVERYWHERE
Systems Using the Akka TO USE JAVA ON A $25 OF MONEY
Extend the Java compiler Framework IN EMBEDDED
with new behavior. BOARD The Royal
Ted Neward wraps up this APPS The inspiration Canadian Mint
58 two-part series. Why Java is the behind the banks on Java
Terrence Barr on Java and the Internet Card for its digital
Java Architect 92 of Things
language of choice Raspberry Pi blog
currency offering.
The New javax.cache Fix This
Caching Standard Take our embedded code
The lowdown on javax.cache challenge.

COVER ART BY I-HUA CHEN, NICHOLAS PAVKOVIC


01
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//from the editor /

COMMUNITY
T

JAVA IN ACTION
FIND YOUR
JUG HERE

JAVA TECH
he age of embedded computing is here. Analysts predict that within this decade, well see tens of
billions of embedded computational devices entering our daily lives. And the possibilities for these smart My local and global JUGs
devices are literally endless: connected vehicles, appliances, utility meters, medical devices, industrial con- are great places to network
both for knowledge and work.
trollers, and even a contraption that monitors how much alcohol your local bartender pours into your cocktail.
My global JUG introduces
In this embedded-focused issue, we explore why Java is the best language choice for embedded develop- me to Java developers all
ment. In Embedded Everywhere, Oracles Terrence Barr talks about why Javas write once, run anywhere over the world.

ABOUT US
technology is perfectly positioned for the coming wave of embedded devices. He sees Java in the embedded Rgina ten Bruggencate
JDuchess
space creating an open, standardized technology infrastructure. Whats more, Java offers 9 million developers
who can apply their knowledge to embedded development. Barr talks about getting started with embedded LEARN MORE
development using a Keil board and also explores what embedded device growth will mean for big data.
In Top Ten Reasons for Using Java in Embedded Apps, Simon Ritter makes a case for Java as the go-to
language for embedded. We already have a wheel, he says. Lets not keep inventing new ones.
We also bring you two stories of embedded Java in action. In Java Arrives on a
$25 Board, we talk with Raspberry Pi Foundation Cofounder Eben Upton about //send us your feedback /

the low-cost programmable computer and Javas role. In The Future of Money, Well review all
suggestions for future
we explore the emerging world of digital currency and introduce you to the Royal
improvements.
Canadian Mints digital currency, MintChip, which runs on the Java Card platform. Depending on volume,
The embedded space presents exciting opportunities for Java developers. Its a some messages may
new year, and a really great time to be a Java developer. not get a direct reply. blog

Caroline Kvitka, Editor in Chief BIO

PHOTOGRAPH BY BOB ADLER


02
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
EDITORIAL
Editor in Chief
Caroline Kvitka
Community Editors
Cassandra Clark, Sonya Barry,
PUBLISHING
Vice President
Jeff Spicer
Publisher
Jennifer Hamilton+1.650.506.3794
Learn Java
On Demand
Yolande Poirier Audience Development and

JAVA IN ACTION
Java in Action Editor Operations Director
Michelle Kovac Karin Kinnear+1.650.506.1985
Technology Editors
Janice Heiss, Tori Wieldt ADVERTISING SALES
Associate Publisher
Contributing Writer Kyle Walkenhorst+1.323.340.8585
Kevin Farnham
Northwest and Central U.S.
Contributing Editors Tom Cometa+1.510.339.2403
Claire Breen, Blair Campbell, Karen Perkins
Southwest U.S. and LAD

Oracle University
DESIGN Shaun Mehr+1.949.923.1660
Senior Creative Director Northeast U.S. and EMEA/APAC
Francisco G Delgadillo Mark Makinney+1.805.709.4745

JAVA TECH
Senior Design Director Advertising Sales Assistant
Suemi Lam Cindy Elhaj +1.626.396.9400 x 201
Design Director Mailing-List Rentals
Richard Merchn Contact your sales representative.
Contributing Designers
Jaime Ferrand, Nicholas Pavkovic RESOURCES
Oracle Products
Production Designers +1.800.367.8674 (U.S./Canada)
Sheila Brennan, Kathy Cygnarowicz
Oracle Services
+1.888.283.0591 (U.S.) Complete Classroom Content

ABOUT US
Oracle Press Books
oraclepressbooks.com
Highest Rated Instructors
ARTICLE SUBMISSION
If you are interested in submitting an article, please e-mail the editors. Immediate Online Access
SUBSCRIPTION INFORMATION
Subscriptions are complimentary for qualified individuals who complete the
subscription form. Search, Pause & Rewind Anytime
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 2013, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwise
reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN AS IS BASIS. ORACLE 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
blog
Preview Now
incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied
upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracles
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

ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013


//java nation /

COMMUNITY
JavaOne Brazil /

Brazil) is a shining example of how to be


a positive contributor to Java, he said.

JAVA IN ACTION
Oracles Georges Saab discussed some
of the recent and upcoming changes
to Java. In addition to the incremental
improvements to Java 7, we have also
increased the set of platforms supported
by Oracle from Linux, Windows, and
Oracle Solaris to now also include Mac
OS X and Linux/ARM for ARM-based

JAVA TECH
PCs such as the Raspberry Pi and emerg-
ing ARM-based microservers.
Oracles Staffan Friberg provided an
overview of some changes coming in
Java 8, including lambda expressions,
The Java band entertains the removal of the permanent generation
Henrik Stahl crowd at the Community keynote. (PermGen) heap, improved date and

ABOUT US
time APIs, and improved security.
Oracles Judson Althoff started his talk
off with a bang. The Internet of Things

JAVAONE
is on a collision course with big data,
and this is a huge opportunity for devel-
opers, he said. Althoff noted that a car
embedded with sensors for fuel effi-

Georges Saab
LOOKS FORWARD ciency, temperature, and tire pressure
can generate a petabyte of data a day.
When a blue screen of death
appeared for the Technical keynote,
JavaOne Brazil took place in So Paulo, for Java, said Oracles Henrik Stahl in presenters gladly went on without their
Brazil, December 46. Latin America is kicking off the Java Strategy and Java slides. What followed was a collection of
an important development hub, and it Technical keynotes on the first day of the demos, including JavaFX on a tablet and
looks as though JavaOne Brazil, now in conference. He noted that the success of a look at Project Easel in NetBeans. blog
its third year, is here to stay. We con- Java depends on technological innova- Throughout the conference, attendees
tinually come back to Latin America tion, strong stewardship from Oracle, chose from dozens of sessions, more
because of the dedication the commu- and community participation. The Latin than half of which were selected by the
PHOTOGRAPHS BY LUCIANA AITH,
ORQUESTRA DE IMAGENS nity has to driving continued innovation American Java community (especially in community, and six hands-on labs.
04
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation / JavaOne Brazil /

COMMUNITY
DUKES CHOICE LAD WINNERS HONORED

JAVA IN ACTION
At JavaOne Brazil, winners of the TIVIT Softwares Central de Cesso
first regional Dukes Choice Awards
were recognized for their innovative
de Crdito (C3) project is a Java-
based high-performance scalable Geeks Ride Again
use of Java. transactional distributed system
The winners of the Dukes that intermediates and manages
Choice Awards LAD are TQTVD all credit assignment operations
Software, TIVIT Software, and CPqD between financial institutions in

JAVA TECH
Foundation. While all of the winners Brazil and tracks credit ownership. It
hail from Brazil, nominations were was developed as a result of BACEN
received from across the region. (the Central Bank of Brazil) identify-
Nominees included NeoTropics ing irregular credit assignment oper-
Kuwaiba project and Vortexbirds ations between financial institutions
Zathura Code Generator project that created a deficit of R$4.3 billion
happening in Colombia. Judges in the Brazilian banking system. Java enthusiasts donned bike

ABOUT US
included Yara and Vinicius Senger CPqD Foundations SMTVI helmets and Dukes bike jerseys
of SouJava Brazil and Alexis Lopez of (Multiplatform Services for Digital on the Saturday before JavaOne
ColombiaJUG. Interactive TV) project dramatically Brazil for a riding tour of So
improved the digital literacy of the Paulo. At this now-traditional
HERES A LOOK AT EACH WINNER: majority of the Brazilian popula- preconference ride, more than
TQTVD Softwares AstroTV project tion. This population has insufficient 20 participants enjoyed cycling
is the Brazilian middleware compli- financial resources to keep up with from Bicycle Park through down-
ant with the Ginga specification that new technological developments; town on street lanes closed off
allows full interactivity, extended TV is its only technology resource. for bicyclists. The ride was 30
content programming, and porta- The project included the creation of kilometers, but participants
bility. The Java-based Ginga specifi- interactive digital TV applications could opt to take the subway for
cation is the intermediate software in the areas of health, retirement, part of the trip.
Top: TQTVDs David Britto with Stephen layer that enables the develop- employment, chat, weather, news,
Chin (left), Bruno Souza, and Yara ment of interactive applications for e-commerce, education, and games. PHOTOGRAPH BY TORI WIELDT

Senger. Center: TIVITs Einar Saukas digital TV independently from the The use of Java technology allowed blog
and Fabiano Cury with Souza, Chin, and hardware platform of digital receiv- the design of a distributed, scalable,
Senger. Bottom: CPqD Foundations ers manufacturers (set-top boxes). and service-based architecture.
Sonia Mayumi Kutiishi and Hugo Cesar AstroTV has been embedded in
with Souza, Chin, and Senger. more than 3 million devices.
PHOTOGRAPHS BY LUCIANA AITH, ORQUESTRA DE IMAGENS 05
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
DEVOXX
attendees to like or dislike sessions. Oracles
Jasper Potts created an interactive schedule
using JavaFX for attendees convenience.

2012 Parleys, the Java e-learning Website, was


redesigned with HTML5 and GlassFish,

JAVA IN ACTION
INNOVATES
and allowed speakers to post their slides
online before their talks and then sync the
soundtracks with the slides. During the
conference, attendees participated in hands-
on workshops and enjoyed coding with their
peers in the hackergarten, which hosted
Stephen Chins NightHacking and a live cod-

JAVA TECH
ing project called Code Story.
The keynote was introduced by five danc-
ing humanoid Nao robots, setting the
stage for a talk by Oracles Nandini Ramani
about technical advances and the latest
Java embedded technologies. Java contin-
ues to drive the applications and devices

ABOUT US
that enrich our interactivity with the world
around us, she said.
Oracle technologists presented details
Devoxx, the biggest Java conference in of improvements to the Java platform. Joe
Nao robots welcomed Devoxx Europe, hosted 3,400 attendees from 40
attendees (above); Nandini Ramani Darcy and Dalibor Topic discussed the latest
talked about the future of Java. countries November 1416 in Brussels, update to JDK 7 and the upcoming features
Belgium. Through word of mouth, it sold out in JDK 8. Jasper Potts, Jonathan Giles, Jim
six weeks in advance and had hundreds of Weaver, and Michael Heinricks presented
developers on the waiting list. The confer- eight talks on effective client development
ence is for developers, by developers, and with JavaFX using its UI controls, TableView,
thats the key to its success, according to and Scene Builder. Simon Ritter, Stephen
attendees. In 200 technical sessions, 190 Chin, and Daniel Blaukopf talked about
well-known Java community experts talked programming and front-end development
about the latest products, frameworks, Java on devices with Java embedded. Shaun
language improvements, and more. Smith, Marek Potociar, Arun Gupta, Jitendra blog
Catch the sights and sounds of Devoxx Conference innovation included a room Kotamraju, and David Delabasse presented
2012. display monitor infrastructure that used the evolution of Java persistence, JSON pro-
Oracle Java SE Embedded running on a cessing, JAX-RS, and WebSocket in a series
PHOTOGRAPHS COURTESY OF DEVOXX Raspberry Pi and a rating application for of sessions over the three days.
06
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
Tridium Wins Oracle
Excellence Award

JAVA IN ACTION
Tridium, which develops solutions for connecting
devices to the enterprise, has won the 2012 Oracle
Excellence Award for Java Business Innovation. The
companys Java-based Niagara Framework integrates
diverse systems and devices, regardless of commu-
nication protocol, into a unified platform that can be

DEVOXX4KIDS
easily managed and controlled in real time over the

JAVA TECH
internet using a standard Web browser. The frame-
work facilitates remote energy metering, home auto-
Tridiums John Sublett mation, and industrial process management.
The first Devoxx4Kids one-day coding workshops took place (left) with Oracles Tridium was recognized for using Java embedded
October 13 and October 20 in Brussels, Belgium (in Flemish Judson Althoff technology and Java SE to create new possibilities
and French). One of the speakers was a Nao robot that talked for addressing how devices and systems connect
about the fun of learning programming and showed off its and interact with each other, as well as with the core enterprise platform. Its

ABOUT US
karate moves. Sixty students age 11 to 14 attended three ses- Niagara Framework has been implemented in varied application environ-
sions where they programmed Lego Mindstorm and Mars ments across many different business sectors. Tridium has applied Javas
Rover robots and coded with Scratch, a drag-and-drop pro- entire platform spectrum, from embedded to enterprise, to create a uniform
gramming interface to create interactive stories and games. software environment that integrates microdevices with each other and links
Stephan Janssen, the organizer behind the popular Devoxx them back to the enterprise applications of which they are components.
Java conference, was inspired to organize this event by his son.
My 11-year-old son wanted to learn programming, and I could
not find any content in Flemish, he said. He partnered with
Tasha Carl, who organized robotic workshops with Greenlight
NightHacking Tour
for Girls, an organization encouraging young girls to consider a Java Evangelist Stephen Chin recently wrapped up
future in science, technology, engineering, or math. his three-week NightHacking Tour across Europe on
At the Devoxx keynote in November, Janssen announced a BMW motorcycle. He went to the Devoxx and JFall
that Java user groups and developers can use his content and conferences and five Java user group events, and in-
Web infrastructure to replicate Devoxx4Kids in their regions. terviewed more than 30 NightHackers in 7 countries.
The workshops were really fun and such a rewarding experi- Highlights of the tour included hacking events in blog
ence, he said. London, England; Munich, Germany; Turin, Italy; and
Oracles Yolande Poirier
So far, Devoxx4Kids events are being organized in the Lyon and Paris, France; and a behind-the-scenes tour
chats with Stephen Chin.
Netherlands, the UK, and France. at Aldebaran Robotics. Watch all of the interviews.

PHOTOGRAPHS COURTESY OF DEVOXX; TRIDIUM BY ORANGE PHOTOGRAPHY 07


ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation / embedded /

COMMUNITY
HITACHI DEMONSTRATES SMART
M2M

JAVA IN ACTION
SENSOR INTEGRATION WITH THE CLOUD Pipelines on the Rise
Oracle commissioned a recent survey
by machine-to-machine (M2M) mar-
ket research firm Beecham Research,

JAVA TECH
which revealed that development of
automated M2M data processing pipe-
lines, in which information gathered by
remote sensors in embedded devices
is transferred to data centers for fur-
ther analysis, is rapidly increasing. The
global survey included end users, major

ABOUT US
product original-equipment manu-
facturers (OEMs), systems integrators,
mobile network operators, and M2M
platform providers.
Most survey respondents viewed
M2M data pipelines as being critically
At JavaOne 2012, Hitachis OSGi SuperJ Engine Framework was deployed to integrate data important. A full 75 percent said their
collection from smart sensors (scattered throughout the conference venue) with the cloud. M2M projects are utilized to create new
The framework applies Oracle Java SE Embedded to provide the sensors with decision-making services. However, 85 percent noted
intelligence and instrument diagnostics. The sensors collected more than 200,000 light, that the large volumes of data that are
temperature, humidity, and energy measurements in a two-day period. passed from the remote embedded
The raw measurements were preprocessed by the Java Embedded SuperJ Engine applica- devices to the data center create new
tion (which ran on a GlobalScale Technologies Mirabox device). The preprocessed results were performance issues. Efficiently filter-
transferred to a SeeControl cloud-based global data analysis application, which collated and ing and processing the data to enable
processed the data into graphic displays and made them available on the Web. its use for making timely decisions was blog
The demonstration was an illustration of the emerging machine-to-machine (M2M) cited as another difficulty.
Internet of Things that was a key focus of the very first Java Embedded @ JavaOne conference. View the complete results.

ART BY I-HUA CHEN


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

COMMUNITY
MSRP
FEATURED JAVA.NET PROJECT

JAVA IN ACTION
Java.nets Message Session Relay implements all of the requirements
Protocol (MSRP) project (RFC 4975) of an MSRP peer. Its now ready to
started out as a 2008 Google Summer be deployed in the real world, adds
of Code project. Founder Joo Antunes Uijldert.
wanted to create a library to provide Whats coming up? Uijldert lists
Jitsi, an open source Java video chat several potential enhancements,
application, with file transfer capabil- including integration with the
ity via Session Initiation Protocol (SIP, Mobicents JAIN SLEE platform, and

JAVA TECH
RFC 3261). Antunes preferred creating the development of a C# version of the
a full library rather than a Jitsi client, MSRP library. He says that the big-
so the code could be used in any Java gest challenges for this project will be
SIP application that requires file trans- the addition of secure communica-
fer capability. tion, and possible support of relaying
In 2010, Tom Uijldert, of (RFC 4976). And Uijldert is actively
ContactMakers, took over MSRP proj- seeking assistance with all this work:

ABOUT US
ect leadership duties. He is currently Anyone interested in helping out with
the primary developer, and introduced the additional functionality is hereby
ContactMakers to the features and invited to contact us, he says.
capabilities the MSRP library provides. Reflecting on open source and the
The MSRP library provides an ideal MSRP project, Antunes says, The
means for integrating VoIP [Voice over open source spirit is great! With open
IP] and chat into a single platform, source, you are making the world go
due to its SIP connectivity and forward. Plus, working on an open
standards-based programming source project is good for your rsum.
This diagram displays the MSRP concept. model, he says. As a result, Just sprinkle your code with sufficient
ContactMakers is currently integrating comments, and apply good coding
the library into its call center platform, conventions. That is the best way
and they have also become a corpo- for your project to invite third-party
rate sponsor of the MSRP project. contributions.
The project has come a long way in blog
a very short time. In late November
2012, Version 1.0.4 was released.
Antunes says, Today, the project

09
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
JAVA USER GROUP PROFILE
OptionsCity
PHILADELPHIA AREA Wins Chicago
JAVA USERS GROUP

JAVA IN ACTION
Gavin King (Hibernate), Marc Fleury
Innovation Award
(JBoss), Neal Ford (ThoughtWorks), What platform would you choose if your business required
and Eric S. Raymond (The Cathedral solving complex mathematical decision-making problems
and the Bazaar), says Fecak. within milliseconds, where the correctness of those results
Today, more than 1,300 members directly and significantly affects your customers financial

JAVA TECH
subscribe to the groups e-mail list. reserves? OptionsCity Software, which develops electronic
About eight meetings are held annu- financial market trading solutions, chose Java. In October,
ally, and these regularly draw more the companys Freeway multiasset algorithmic trading
than 100 attendees, and in the 200 platform won a Chicago Innovation Award. These awards
range for the most-popular speakers. honor innovative new products and services brought to
Looking ahead, We are currently market from the Chicago area.
transitioning from a Java language OptionsCity Director of Client Technology Freddy Guime

ABOUT US
focus to a JVM [Java Virtual Machine] calls the win a Cinderella story for Java in the financial
focus, which the membership feels will industry. The OptionsCity development team solved
The Philadelphia Area Java Users keep us current with industry trends, complex problems to achieve the performance needed for
Group (PhillyJUG) was founded in says Fecak. a submillisecond trading platform, which is necessary to
2000 by Dave Fecak, a technical Fecak has thought a great deal compete in this space, he says.
recruiter, and Dr. John Lewis, a former about the JUG leader role. I would Guime notes, Even though there were naysayers when
professor at Villanova University and encourage JUG leaders to always be we chose Java as our platform, the decision allowed us
coauthor of a popular early Java text- thinking of how to help their member- to quickly take over this space, culminating with (what
book. About 30 developers attended ship. When [vendors] approach me we consider) the first commercially viable Algo Trading
the first meeting in March 2000. about sponsoring a meeting, I always Platform. And that includes the innovation of the Algo
In 2005, the group was named to ask what I can get for my members. Store, which allows algorithm developers to be able to
Suns Top 25 program and then to Sponsors want to reach audiences, and purchase components of an algorithm.
the expanded Top 50 program. These many sponsors understand that they Within six years, OptionsCity has gone from unknown
programs recognized the leading are building corporate goodwill in the to being one of the big players in the options trading
JUGs. That recognition and some community for their brand. However, platform space in Chicago and New York. Need reliable, blog
good connections have helped us to he notes that PhillyJUG does not allow time-critical mathematical algorithm performance in your
attract some very high-profile industry pure product demonstrations or any startup product? Think Java.
names, such as Rod Johnson (Spring), sales activity.

10
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
JAVA CHAMPION PROFILE

End of Public ADAM BIEN


Updates for Adam Bien is a German thought everything to learn new things.

JAVA IN ACTION
Java SE 6 entrepreneur, architect,
programmer, author,
happened inside REM
statements. My pro-
Indeed, Java still feels
to me like the new hot
and speaker. He became grams always inter- stuff, and this keeps my
Have you updated to Java SE 7? Along with
a Java Champion in preted without error, work exciting and abso-
great features such as fork/join, NIO, and
January 2007. but nothing actually lutely not boring.
Project Coin, Java SE 7 is being updated
Java Magazine: Where happened. I wondered Java Magazine: Has
and patched regularly. Java SE 7 has been
did you grow up? about this. After getting being a Java Champion
out for more than a year and is ready to

JAVA TECH
Bien: In a small town in the basics, I was proud changed your daily life?
download.
Bavaria, Germany. to learn my first pat- Bien: As Java
The last publicly available release of
Java Magazine: How did tern: GOSUB instead of Champion, I was
JDK 6 is to be released in February
you first become inter- GOTO. and do more sports. exposed to JUG lead-
2013. After February 19, all new secu-
ested in computers and Java Magazine: What Right now I have to ers, and I learned about
rity updates, patches, and fixes for Java
programming? was your first program- catch the unchecked the wealth of worldwide
SE 6 and Java SE 5 will be available only
Bien: I was always ming job? LackOfTimeException JUG events. I regu-
through My Oracle Support and will

ABOUT US
interested in space- Bien: I had to optimize way of trying that larly speak at local JUG
thus require a commercial license with
ships, aliens, UFOs, the wire protocol of an with an empty catch events when I travel on
Oracle. Its important for developers and
robots, and black holes. early Oracle database block, unfortunately. business. It has also
systems administrators either to make
Computers were a on a VAX. I didnt have Java Magazine: What been pleasant to meet
the transition over to Java SE 7 or to work
natural progression. a VMS OS, so I used happens on your typical lots of passionate, tal-
with Oracle to get updates via the Java SE
I had my first contact Linux to compile the day off from work? ented, and opinionated
Support program.
with a computer when I C++ code. Bien: I try to spend all fellow Java Champions.
In the event that you are not ready
was eight years old. Java Magazine: What do my time with family Java Magazine: What
to migrate to Java SE 7, Oracle offers
Java Magazine: What you enjoy for fun and but there are really are you looking forward
Java SE support for continued access to
was your first computer relaxation? no days off. For free- to in the coming years?
critical bug fixes and security fixes as
and your first program- Bien: I try to enjoy lancers, the day after a Bien: Lots of interest-
well as general maintenance for JDK 6.
ming language? everything. Life is free day, youll regret it. ing things will happen
Additionally, Oracle Java SE Advanced
Bien: My first computer too short. I consider Java Magazine: What in the near future for
and Oracle Java SE Suite offer superior
was a ZX Spectrum Java programming as side effects of your Java: JavaFX, Project
diagnostics and manageability tools that
128K. I got it when I was fun and relaxation. career do you enjoy Nashorn, lambdas, Java blog
minimize the costs of deployment, moni-
12 and immediately Someday, I would the most? EE 7. And I cannot wait
toring, and maintenance of Java-based
started to program like to be able to read Bien: With Java, you get for Jigsaw. Javas future
IT environments.
in Basic. However, I more non-IT books endless opportunities is bright.

PHOTOGRAPH BY PIOTR MALECKI/GETTY IMAGES 11


ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
FEBRUARY tects pioneering Hadoop innova- CodeMotion
FOSDEM tion for two days of keynote pre- MARCH 24
FEBRUARY 23 sentations, interactive workshops, MADRID, SPAIN
BRUSSELS, BELGIUM and networking opportunities. This event, by and for technol-

JAVA IN ACTION
FOSDEM is a free, noncommer- ogy communities, gathers tech-
cial event that offers open source Mobile World Congress nicians, developers, and stu-
communities a place to meet, FEBRUARY 2528 dents. Organized by user groups
share ideas, and collaborate. BARCELONA, SPAIN for a variety of technologies,
Explore the new mobile horizon CodeMotion is a way for attendees
Jfokus 2013 at Mobile World Congress. This to step out of their comfort zones
FEBRUARY 46 industry-leading event includes and discuss innovation in coding
STOCKHOLM, SWEDEN a thought-leadership conference practices.

JAVA TECH
Jfokus is the largest annual confer- with keynotes and panel discus-
ence for everyone who works with sions, a product and technology EclipseCon North America
Java in Sweden. exhibition with 1,500 exhibitors, MARCH 2528
and an awards program. BOSTON, MASSACHUSETTS
EVENTS Java Israel
FEBRUARY 14 MARCH
This conference focuses on shar-
ing best practices, insights, case
Embedded World FEBRUARY 2628, TEL AVIV, ISRAEL QCon London studies, and innovations in the

ABOUT US
NUREMBERG, GERMANY Clojure, Grails, Groovy, Java Virtual MARCH 45 (TRAINING), Eclipse community and in soft-
Machine, JRuby, Ruby, and Scala MARCH 68 (CONFERENCE) ware development.
The Embedded World Exhibition & are all on the agenda at this one- LONDON, ENGLAND
Conference has been the gathering day Java event. QCon London is the seventh Devoxx London
place of the international embedded annual London enterprise soft- MARCH 2627
community for more than a decade. The DevNexus ware development conference LONDON, ENGLAND
event focuses on all fields of embed- FEBRUARY 1819 designed for developers, team Devoxx France
ded systems development. In addition ATLANTA, GEORGIA leads, architects, and project MARCH 2729
to discussing hardware, software, and Presented by the Atlanta Java management. PARIS, FRANCE
tools, embedded experts tackle the latest Users Group, this conference for Following the success of the
issues around embedded system design. Java developers offers seven tracks 33rd Degree Conference 11th Devoxx Java conference in
Machine-to-machine is a key theme of with three keynotes and more MARCH 1315 November, Devoxx moves to the
the event. The conference also offers an than 50 sessions. WARSAW, POLAND UK for the first time and France for
extensive exhibition hall with more This conference for Java masters the second time. The proximity of
than 800 exhibitors. Hadoop Innovation Summit features three days of Java tech- these back-to-back conferences
blog
FEBRUARY 2021 nology talks. Birds-of-a-feather allows speakers to present at both.
SAN DIEGO, CALIFORNIA and unconference sessions allow At the Paris event, 75 percent of
This event brings together data informal discussions. In-depth sessions are in French and 25 per-
PHOTOGRAPH BY GETTY IMAGES scientists, engineers, and archi- workshops are also included. cent in English.
12
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java nation /

COMMUNITY
JAVA BOOKS

JAVA IN ACTION
ORACLE
AUTHOR DISTRIBUTED, EMBEDDED CONTINUOUS ENTERPRISE DEVOPS FOR DEVELOPERS JAVA EE DEVELOPMENT
PODCASTS AND REAL-TIME JAVA SYSTEMS DEVELOPMENT IN JAVA By Michael Httermann WITH ECLIPSE

JAVA TECH
M. Teresa Higuera-Toledano and (EARLY RELEASE) Apress (September 2012) By Deepak Vohra
Our favorite Java Andy J. Wellings (Editors) By Andrew Lee Rubinger, DevOps for Developers Packt (December 2012)
authors give you the Springer (February 2012) Dan Allen, and Aslak Knutsen delivers a practical, thor- Java EE Development with
inside scoop on their This book is aimed primar- OReilly Media (September ough introduction to Eclipse is a practical guide
books. ily at researchers in real- 2012) approaches, processes, and for using the most-
time embedded systems, This practical book shows tools to foster collaboration commonly-used Java EE
particularly those who wish you how to perform con- between software devel- technologies and frame-
to understand the current tinuous development, using

ABOUT US
opment and operations. works in the Eclipse inte-
state of the art in using Java a testing platform called Efforts of agile software grated development envi-
Benjamin Evans
and Martijn Verburg in this domain. Much of the Arquillian that the authors development often end at ronment (IDE). The book
work in real-time distrib- built with the JBoss com- the transition phase from focuses on developing
discuss The Well-
uted, embedded, and real- munity. This platform acts development to operations. applications with some of
Grounded Java
time Java has focused on as the missing link between This book covers the deliv- these technologies using
Developer.
the Real-Time Specification testing and development. ery of softwarethe last the project facets in
for Java as the underlying The authors demonstrate milewith lean practices Eclipse 3.7 and its enhance-
base technology, and conse- how testing is the very for shipping the software ment Oracle Enterprise
quently many of the chap- foundation of develop- to production and making Pack for Eclipse 12c. It
Jim Weaver and mentessential for learn-
ters in this book address it available to end users, starts with a discussion of
Stephen Chin discuss ing and critical for ensuring together with the integra-
issues with, or solve prob- Enterprise JavaBeans (EJB)
Pro JavaFX 2.
lems using, this framework. that code is consumable, tion of operations with 3.0 database persistence
complete, and correct. Find earlier project phases with Oracle WebLogic
out how Arquillian helps (elaboration, construction, Server and Oracle Database, blog
you document your project and transition). Express Edition.
in the form of test cases.

13
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
JCP Executive Series

Credit Suisse
Discusses the

JAVA IN ACTION
Java Community
Process

JAVA TECH
Susanne Cech Previtali and Victor Grazi share Credit
Suisses distinctive perspective. BY JANICE J. HEISS

W
e continue our series of inter-
views with distinguished

ABOUT US
members of the Executive
Committee of the Java Community
Process (JCP) with Credit Suisse, a
financial services group of companies
with headquarters in Switzerland and
operations in more than 50 countries.
Credit Suisse is the first nontechnology
vendor on the Executive Committee of
the JCP, elected in June 2010 and re-
elected in November 2012. Credit Suisse
is what Mike Milinkovich of the Eclipse
Foundation calls a Java user company
whose focus is to improve the Java
platform in order to meet both its cus-
tomers and its own business needs. As blog
such, the company brings to the JCP a
unique and valued perspective.

PHOTOGRAPHY BY CHRIS LANE/GETTY IMAGES


14
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
JAVA IN ACTION
JAVA TECH
Victor Grazi and We met with Credit Suisses two this great and encouraging result. We in order to better meet your own and
Susanne Cech representatives on the JCP, Dr. will continue to bring in our customer your customers needs. This gives you
Previtali take a Susanne Cech Previtali and Victor view in arguing for strong, open, and a different perspective from a com-
breather on Credit Grazi. Cech Previtali, a member of stable standards that can be imple- pany that creates and sells software.
Suisses rooftop deck
in Manhattan. the Infrastructure Architecture group mented by any vendor or the open Does your perspective clash with the

ABOUT US
at Credit Suisse, is the Java platform source community for a competitive perspectives of other JCP members?
architect responsible for Credit Suisses market. We want to bring in our exper- Does it offer an opportunity for other
Java Application Platform (JAP) and tise in standardization and architec- Executive Committee members to
the related construction guidelines for ture governance and to continue our better understand how companies
the development of large-scale Java active participation in Expert Groups use Java?
EE applications. Grazi, who recently and as spec leads. We would like to aid Credit Suisse: Credit Suisse sees its role
won the annual JCP award as Best Spec in increasing university participation within the Java community in general,
Lead for his work on JSR 354, Money as spec leads and Expert Group mem- and the Executive Committee more
and Currency API, is a Java Champion bers at the faculty levelfor example, specifically, as a representative cus-
who works both in investment banking contributing to high-quality specifica- tomer interested in building mission-
architecture and as a technical consul- tions; also, we think students should critical applications on strong, open,
tant and Java evangelist. be included in making contributions at and stable standards to secure our
Java Magazine: Credit Suisse was the development levelfor example, investments. Credit Suisse previously
recently re-elected to the Executive as part of the Adopt-a-JSR initiative of contributed to the development of Java
Committee of the JCP. While your the Java user groups [JUGs]. EE specifications through participation blog
position statement is available online, Java Magazine: Credit Suisse, the first in many customer advisory boards,
would you like to offer a general sum- nontechnology vendor on the JCP, has through statements of requirements
mary of your position going forward? been characterized as a Java user com- for extensions to the core Java-related
Credit Suisse: We are very happy about pany with the goal of improving Java products in use, and through active
15
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
participation in JSRs. many of the platform-as-a-service
The JCP Executive Committee is still [PaaS] concepts in 2004 that now
dominated by vendors. Major custom- contribute to more than US$40 mil-
ers of Java technologies as the end lion of avoided costs per year. JAP fea-

JAVA IN ACTION
users were not integrated in the pro- tured one of the first large-scale SOA
cess and, as such, could not participate implementations, included the first
in guiding the development and evolu- ubiquitous PKI [public key infrastruc-
tion of Java technology. Credit Suisse ture], and reduced the server footprint
stands in close relationship with the through consolidation on shared serv-
vendors. Our experiences and feedback ers. In addition, it pioneered the adop-
with the concrete application of the tion of numerous Java EE technologies
Java technologies in, for example, our including transaction monitors, JSF As JCP representatives, Grazi and Cech Previtali offer a customer

JAVA TECH
Java Application Platform are also inter- [JavaServer Faces], and portal. view in arguing for strong, open, and stable standards.
esting and relevant for the vendors. Today, Credit Suisse invests signifi-
Java Magazine: Why did you decide to cant amounts per year in the devel-
join the JCP in 2010? How might your opment of new and maintenance for large-scale applications. These are
presence in the JCP help Credit Suisse? of existing Java EE applications, and major changes with major impact to
Credit Suisse: Oracle nominated owns more than 30 million lines of the Java platform and thus have been
Credit Suisse to run for the Executive Java code. Going forward, Credit Suisse moved from Java EE 7 to Java EE 8. The

ABOUT US
Committee seat of the Java EE/SE intends to steadily increase that current vision is common, although we CHANGE IS GOOD
Executive Committee. Credit Suisse investment as we move more workload may have differences about roadmaps The most
was elected by the JCP community with
77 percent for a ratified seat starting in
from the mainframe back end to our
Java EE platform.
and timelines.
Java Magazine: How has the JCP
important change
June 2010, and was recently confirmed Java Magazine: Does your vision of changed since Oracle acquired Sun is the JCP.next
with 85 percent. Credit Suisse was
among the first financial institutes to
Java EE differ from that of other JCP
Executive Committee members?
Microsystems?
Credit Suisse: The most important
initiative, which
embrace Web and Java technologies. Credit Suisse: Our general vision of change is the JCP.next initiative, which is a commitment
It was the first Swiss bank to provide a Java EE is focused on the support of is a commitment to greater transpar- to greater
Web-based payments solution for its
customers back in 1997, and its 1999
cloud features and modularization.
The standardization of PaaS features
ency, participation, and openness. JCP
.next.1, JSR 348, Towards a New Version
transparency,
product, YouTrade, was one of the first such as provisioning, multitenancy, of the Java Community Process, laid participation, and
client trading applications on the mar-
ket. Credit Suisse developed an inter-
elasticity, and the deployment of appli-
cations in the cloud are crucial for
the foundation for greater transpar-
ency by requiring, rather than suggest-
openness.
nal standard based on Java EE called developers and operation. The modu- ing, that all development is done on blog
the Java Application Platform [JAP], larization of the Java SE platform and open mailing lists and issue trackers.
which helped industrialize develop- the subsequent possibility of better Furthermore, the recruiting process for
ment and operations of our Java EE capturing dependencies and ver- Expert Group members will be publicly
applications. JAP also established sions across modules are important viewable, with transparent disclo-
16
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
THE CHALLENGE sure. TCK [Technology the promise of increased transparency nies to engage in the evolution of
Trying to build consensus is difficult Compatibility Kit] test-
ing process results
and openness in the JCP?
Credit Suisse: Yes. Oracle is a member
Java technology.
Java Magazine: There seems to be a
because people have individual will be investigated; of the Executive Committee and has risk that members of Expert Groups

JAVA IN ACTION
ideas about best practices. . . but
currently, the pub-
lic is rarely aware of
agreed and committed to JCP.next.1
and JCP.next.2 and collaborates on
in the JCP can be subtly influenced by
their own use cases, which suggests
uncovering all of the use cases the results of the TCK JCP.next.3. that there is a challenge in remaining
and coming up with a robust testing process. All of
these developments
Java Magazine: How could Oracle have
increased participation in the JCP?
objective about what a specification
needs and does not need. How do you
implementation is the overriding goal. are designed to result Credit Suisse: The inclusion of the filter out any biases you might have
in a more public, open, JUGs in the Executive Committee is related to the influence of your own
accessible, and trans- a great success, because it raises the use cases?

JAVA TECH
parent JCP. awareness at the right level. Credit Suisse: Trying to build consen-
JCP.next.2, JSR 355, JCP Executive Java Magazine: Are there ways that sus is difficult because people have
Committee Merge, addresses the merg- the JCP could better serve the Java individual ideas about best practices,
ing of the two Executive Committees community? which at times may conflict. There is
(Java SE/EE and Java ME) and thus lays Credit Suisse: The JCP drives the evolu- some ego involved in this, too, but
the foundation for one platform. tion of a programming language and uncovering all of the use cases and
JCP.next.3, JSR 358, A Major Revision its ecosystems and has become a very coming up with a robust implemen-

ABOUT US
of the Java Community Process, important asset for the Java commu- tation is the overriding goal.All spec
revises the JSPA [Java Specification nity. By relating the needs of the users leads have similar challenges, includ-
Participation Agreement]. This JSR with those of the technology providers, ing finding the time while still manag-
will make changes to the JSPA, the the JCP can ensure that Java contin- ing their day jobs. Also, even when you
process document, and the Executive ues to be one of the top programming find the time, it is difficult to get the
Committees standing rules with the languages. We should also not forget other members involved, because they
goals of further improving the orga- about the next generation, and make also have their own day jobs.
nizations processes, correcting prob- sure that faculty and students con- Java Magazine: Do you have any sug-
lems that have become apparent over tinue to see the value of Java. gested improvements for Java.net as it
recent years, and clarifying language to Java Magazine: What is your biggest relates to leading a JSR group?
reduce ambiguity. complaint about the JCP? Credit Suisse: Java.net is the JSR spec
Java Magazine: What structural changes Credit Suisse: The Java community is leads best friend. It provides a wiki,
would you like to see in the JCP? great and very active, but not all users source control, a mail list, archives,
Credit Suisse: Openness, transparent of Java technology are aware of the really everything you need to manage
licensing models, ease of participation, importance and impact of technology a JSR. We are very impressed with the blog
broad participation of the Java com- governance. The JSRs are developed by fast feedback that the JCP provides
munity, and awareness of the impor- the JCP community, and so perhaps we for support issues. It would be great
tance of technology governance. can do better at promoting ourselves if some performance-based incen-
Java Magazine: Has Oracle delivered on to include more people and compa- tives could be provided to the Expert
17
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
PROMOTING CHOICE
Groupsperhaps some We count on the encouraging innovation,
awards for most valuable
contributor.
standardization of does the JCP err too far in
one direction?
Java Magazine: Tell us technology because Credit Suisse: As custom-
it gives us flexibility

JAVA IN ACTION
some potential improve- ers, we count on the
ments for creators and
users of financial applica- in choosing products standardization of tech-
nology because it gives
tions that are in the works and, thus, reducing us flexibility in choosing
as a result of JSR 354. How
will their work be made
vendor lock-in. products and, thus, reduc-
ing vendor lock-in. Some
easier? people argue that there
Credit Suisse: For one should be at least two

JAVA TECH
thing, developers wont implementations avail-
need to reinvent the wheel when creat- able before the standardization. But
ing financial applications. A common what about migration paths of the
error is to use a float or double to rep- existing implementation? What about
resent financial values. However, these migration paths for the customers who
formats are not designed for accuracy, already have used that existing imple-
and can easily produce rounding errors mentation? This could result in very

ABOUT US
in the nth decimal place. Because weak standards, costly migrations, or
accountants dont appreciate rounding both. Standardizing too early is prob-
errors, a lot of thought needs to go into lematic, because immature technol-
how to make these precise. In addition, ogy does not provide enough useful
JSR 354 can help with formatting. In material. Standardizing too late
the US and Europe, most countries use is costly and probably causes major
very standard formats to express num- changes for customers who switch to
bers, but countries such as India use a standard technology. Its a delicate
lakhs and crores, which are specified balance. </article>
quite differently from anything cur-
rently available in the Java formatters.
This will improve with JSR 354.
Janice J. Heiss is the Java acquisitions
Also, rounding rules are important.
editor at Oracle and a technology editor at
In the US, its standard to round up for
Developers wont need to reinvent Java Magazine. blog
5 or more and to round down from 1 to
the wheel in creating financial 4. But different countries have more-
applications, say Cech Previtali and exotic rules for rounding. LEARN MORE
Grazi, as a result of JSR 354. Java Community Process
Java Magazine: In walking the fine line
between respecting standards and Credit Suisse
18
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
(embedded )

EMBEDDED EVERYWHERE

JAVA IN ACTION
Terrence Barr on Java and the Internet of Things BY STEVE MELOAN

JAVA TECH
ABOUT US
W
hile number estimates might
vary, its clear that within
this decade we will see tens
of billions of new embedded compu-
tational devices entering our everyday
livesincluding connected vehicles,
smart appliances, smart vending
machines, smart meters, medical
sensors, industrial controllers, and blog
more. And Javas write once, run any-
where technology is positioned for this
coming wave of diverse embedded
ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY TON HENDRIKS 20
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
SUPER VIRTUALITY

COMMUNITY
Because Java, by its nature,
is a virtual machine [VM] Java Magazine: So Java not only facili-
environment and a virtual tates development in the embedded
application platform, you can space but also acts as a catalyst toward
embedded industry growth?
start developing and testing

JAVA IN ACTION
Barr: Exactly. An Oracle technol-
large parts of your application ogy partner recently drew a parallel
between the current embedded space
on a virtual environmenton and the early cell phone space. The
the desktop, for example whole ecosystem was held back by the
before the embedded fact that there was no standard plat-
form that people could build upon.
FPO hardware is available. But as soon as fairly predictable phone

JAVA TECH
platforms became accessible, you had
this explosion of applications, accesso-
ries, hardware, and services that built
devicesoffering an underlying plat- time is spent reinventing the wheel upon the platforms. We see Java in the
form and infrastructure that include and struggling with fragmentation embedded space playing a very similar
open standards, security, reliability, rather than building solutions. role, but with even more focus on cre-
scalability, sophisticated toolsets, and Java is a platform and a technology ating an open, standardized technol-

ABOUT US
a 9-million-plus developer community. that, by design, abstracts from the ogy infrastructure.
Java Magazine sat down with underlying hardware and OS, and pro- Java Magazine: What are the time-
Terrence Barr, senior technologist and vides a rich application environment, to-market advantages of developing
product manager at Oracle, to explore from very small devices to enterprise- embedded applications via desktop
the Internet of Things, and Javas role in class servers. Java is uniquely posi- emulation?
a technology transition that some are tioned to address many of these chal- Barr: Because Java, by its nature, is a
calling a third IT revolution. lenges because, essentially, we solved virtual machine [VM] environment and
these problems 10 or 15 years ago. We a virtual application platform, you can
Java Magazine: What is the advantage solved transitions from 8- to 16- to start developing and testing large parts
of using Java in the embedded space? 32-bit that the embedded space is of your application on a virtual
Barr: The embedded space today is facing today. We have a proven and environmenton the desktop, for
very fragmented. You have to piece secure runtime environment. We have examplebefore the embedded hard-
together the entire stackthe run- infield updatability of application ware is available. So you can parallelize
time, the OS , the tools, the languages, components. And Java already has a the embedded hardware development
the protocols, and the connectivity. We technology ecosystem with 9 million and the embedded software develop- blog
strongly believe that until we have a developers. They might not currently ment, which potentially shaves many
standards-based horizontal platform, be embedded developers, but theyre months off of your development cycle.
the M2M [machine-to-machine] mar- very familiar with the programming Java Magazine: What are the issues
ket wont take off, because too much language and the toolset. regarding pushing down new logic to
21
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
embedded devicesfor Whether its util- A RICH FOUNDATION
updates and delivery of ity meters, automobiles,
new services? medical devices, or vending Delivering embedded Java as a horizontal and
Barr: Suppose you have machines, all have similar integrative solution provides 80 percent of your

JAVA IN ACTION
millions of smart meters
in the field, running the
requirementsyou need
to execute applications,
underlying infrastructure. . . . You get to market
software, collecting the and you need connectivity, much quicker and at a lower price point.
data, and sending the data security, a way to manage
to the back end. But at the device, a way to update
some point, the utility laws the device, and a way for
and regulations change, the device to connect back to the also added APIs that are specific to the
and you need to update server. Delivering embedded Java as embedded space, that allow you to

JAVA TECH
the algorithms on these a horizontal and integrative solution deliver a solution even more quickly.
meters. Its not plausible to provides 80 percent of your underlying Youre able to remotely provision and
send people into the field infrastructure. You can then build start and stop applications. You have
to manually update mil- 20 percent on top of it, adding your a logging API that allows you to log
lions of devices. Embedded particular industry value. You get to locally as well as remotely, for remote-
hardware is getting more market much quicker and at a lower monitoring purposes. And you also
and more powerful, and at price point. have the AccessPoint API, which allows

ABOUT US
the same time connectiv- Java Magazine: What are the devel- the application to intelligently switch
ity options are increasing, opment advantages of working with between multiple communications
which allows for wireless embedded Java? channels depending on data rates and
updates. Java offers the Barr: As I mentioned earlier, with tradi- bandwidth requirements.
ability to update in the tional native embedded development, And finally, you can use your same
field without affecting the you have to pick and choose the vari- familiar development tools, such as
integrity of the system. ous components, integrate them your- NetBeans and Eclipse. And you can do
Because Java is a virtual self, and deal with a range of tools and live, on-device source-level debug-
Barr shows off an application running on a environment and runs in methodologies. By comparison, the ging using these IDEs. For most Java
Keil board at Devoxx.
a sandbox model, it helps Java runtime is a complete develop- developers, thats nothing new. But for
guarantee the security and ment stack that is tested, is based on native embedded developers, this is
integrity of the system after standards, and uses standardized APIs heaven. For them, debugging and test-
the update. Also, over time, you might that youre already familiar with. So ing is typically a very painful process.
deploy, say, 20 variations of hardware its very easy to get started and write Java Magazine: What specific hardware
devices. Without Java, youd have to application and business logic. The would you recommend for develop- blog
update 20 types of native code. With new Oracle Java ME Embedded 3.2 not ers who want to get their feet wet with
Java, you write the application once, and only offers a variety of standard APIs embedded Java?
you push it to multiple devices without things like XML processing, location- Barr: If you have experience in the
concern for hardware dependency. based services, and file access. Weve embedded space, you know that there
22
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
PORT YOUR EXPERTISE ready device, we can point you to will make that process much easier
One of the big values of having Java in the embedded our partners, such as Cinterion and
Qualcomm. They will be making avail-
with similar language features, simi-
lar API features, and similar runtime
space is the ability to bring the expertise, the tools, and able various types of integrated, wire- features. To that effect, Oracle filed

JAVA IN ACTION
the code from one platform to anotherthe inherent less module devices and platforms
that come with the Oracle Java ME
two new JSRs, JSR 360 and JSR 361,
in October 2012. In 2013 and 2014,
ability to apply your expertise across this whole range of Embedded 3.2 runtime. The devices we will continue to execute on this
devices, from very small to very large. have an integrated cellular modem,
they have RAM and ROM on the
strategy to reshape the Java platform
and the Java products. The goal is
moduletheyre basically very power- that eventually developers see Java as
ful small wireless computers. So you one continuum, from the very small
are any number of permutations of pro- can also use these to get started with device up to the very large systems.

JAVA TECH
cessors, I/O, board designs, interfaces, embedded development and for your So you can apply your same skills,
and peripheralsits much more frag- actual device deployments. tools, and code across this continuum.
mented than the desktop space. So we Java Magazine: The timeline for
had to pick a specific set of hardware Oracles embedded offerings details
to start with, where we could enable a 2014 JVM [Java Virtual Machine]
developers to get a system up and convergence for Oracle Java SE
running, to experiment with some of Embedded 8 and Oracle Java ME

ABOUT US
the features that we support. So what Embedded 8. What will this mean for
we chose is the Keil MCBSTM32F200 embedded developers and partners?
(ARM Cortex-M3)a ready-to-run Barr: One of the big values of hav-
evaluation platform. You can buy it ing Java in the embedded space is the
online, and once you have it in your ability to bring the expertise, the tools,
hands, youll soon be able to down- and the code from one platform to Barr talks about embedded while
load the Oracle Java ME Embedded 3.2 anotherthe inherent ability to apply onsite at Devoxx.
runtime binary. That will come with your expertise across this whole range
instructions, and youll flash the run- of devices, from very small to very large.
time onto the board, hit the reset but- So about 12 to 18 months ago, Oracle
ton, and youll have a complete, ready- embarked on a plan to converge and
to-run Java runtime environment. make more aligned the two relevant
Youll hook up your IDENetBeans or Java platforms, Java SE and Java ME.
Eclipseand youll be ready to write Historically, Java ME was somewhat
embedded Java applications. In the the smaller sibling of Java SE. But it blog
meantime, we offer a Windows-based had different features and APIs, which
device emulation environment. made it difficult to take your code and Barr talks with Stephen Chin about
The Keil board is mainly for evaluation expertise and switch platforms. This embedded Java and demos a smart
purposes. If you want a deployment- strategy of aligning the two platforms solar tracking system.
23
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
Youll choose the runtime based on Java Magazine: Its dif-
your device properties, but from a ficult to overestimate Oracles Oracle Java SE Embedded is
based on Java SE but optimized for
developer perspective it will look very
smooth and homogeneous.
the likely billions of con-
nected smart devices in Embedded midrange to high-end embedded
Products

JAVA IN ACTION
Java Magazine: For those outside the this era of the Internet of systemsdevices having 32 MB or
embedded world, a Java ME configu- Things. At the back end, more of RAM (without graphics).
ration provides the basic set of librar- this will bring about a
Oracle Java ME Embedded Client is based on the Java
ies and VM capabilities for a range of data explosion. How is
ME Connected Device Configuration (CDC), a subset
devices, while a Java ME profile adds a Oracle positioning itself
of the Java SE platform optimized for low-to-midrange
set of APIs that enable a more specific for this data tidal wave
embedded systemsdevices having 8 MB or more of
range of use cases. How will the Java on the enterprise?
RAM (without graphics).
SE and Java ME convergence affect Barr: Its clear that these

JAVA TECH
the current CDC [Connected Device devices will be generat- Oracle Java ME Embedded 3.2 is an optimized runtime
Configuration] and CLDC [Connected ing huge amounts of stack based on the Java ME Connected Limited Device
Limited Device Configuration]? dataafter all, the data Configuration (CLDC), intended for small, headless (no
Barr: The CDC traditionally occupies is where their value is. graphics/UI) embedded devices having 130 KB or more
the midrange embedded space and If this anticipated data of RAM.
has been very successful in vertical wave is left unchecked,
product spacesfor example, every it could overwhelm the Oracle Java Embedded Suite 7.0 provides an

ABOUT US
Blu-ray player ships with a CDC run- internet infrastructure. enterprise-like suite of technologies for the Oracle Java
time. But we want to map the entire Many cellular networks SE Embedded 7 runtimeJava DB relational database;
embedded space. So CDC will basically today already might be GlassFish Servlet-based application server; and Oracles
become a configuration of Oracle Java overwhelmed in han- Jersey implementation of JSR 311, the Java API for
SE Embedded, and Oracle Java ME dling the data from RESTful Web Services (JAX-RS).
Embedded will cover everything else. smartphones, so how
As a developer, youll basically look at are we going to handle
your problem domain and your device data from billions of
requirements, and youll just say, additional connected
OK, does it fit a Java ME Embedded devices?
environment, or What you need to do is to turn large of data (and associated costs) if done
LOCAL INTELLIGENCE do I need Java SE amounts of data into small amounts on a large scale. And then on the back
What you want to do is Embedded? The
two platforms will
of valuable information. If you have a end, what do you do with that data? It
sensor thats monitoring the tempera- has almost no value.
use the intelligence of the be aligned, so from ture in a truck, you dont want that What you want to do is use the blog
local device to program-in a development device to just blindly send a tempera- intelligence of the local device to
business logic. perspective the
experience will be
ture reading to a back-end server every program-in business logic. If youre
second. Thats not useful information, transporting a certain type of product
very similar. and it generates enormous quantities that has specific temperature require-
24
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
ments, you need to send an alert only value over having different languages reaction was uniformly positive. They
if the temperature falls outside of that and different programming methodol- said, We get it. This makes sense to
range. The embedded device processes ogies spread out across your solution. us, why Java should be in the embed-
the data locally, and the back end sees Java Magazine: How does big data ded space. Now were busy fielding all

JAVA IN ACTION
a vastly reduced level of transmitted coming from embedded devices affect sorts of requests from developers and
data, in the form of actual useful infor- database product solutions? potential partners who want to open
mation such as alerts. Barr: NoSQL databases are frequently up a dialogue and understand where
But youre not just connecting those being used on these back-end sys- were going, how they can add value,
billions of embedded devices directly tems, because theyre more flexible and how they can participate. People
to the back end, because both the flow in dealing with this kind of heteroge- are excited about the possibilities out
of data and the manage- neous device data. But, there. For developers, I believe this is a
ment of these devices in many cases, you also huge opportunity. For Java, the best is

JAVA TECH
BIG DATA CHALLENGE
would be difficult to want to mesh together yet to come. </article>
handle. What you typi- Many cellular networks
relational and nonrela-
cally need is a concentra- today already might
tional data. You could
Steve Meloan is a former C/UNIX soft-
tor tier and device, which
sits between the edge be overwhelmed in
take temperature sen-
sor data and location
ware developer who has covered the Web
and the internet for such publications as
client and the back end. handling the data from
data from your devices,
Wired, Rolling Stone, Playboy, SF Weekly,
The concentrator takes
smartphones, so how
for example, and mesh
and the San Francisco Examiner. He re-

ABOUT US
the data stream from that on the back end
these devices and filters are we going to handle
with mapping data to
cently published a science-adventure
novel, The Shroud, and regularly contrib-
it, extracting in real time
the business-critical
data from billions of
create more-valuable
information.
utes to The Huffington Post.
information (called com- additional connected
Java Magazine: This year
plex event processing), devices? at JavaOne 2012, Oracle LEARN MORE
and then sends it on to presented an entire sub-
Java Embedded
the enterprise at the conference called Java
Java Embedded downloads
back end. The concentra- Embedded @ JavaOne.
tor can also act as a proxy to manage What was the takeaway experience Oracle Java ME Embedded 3.2 FAQ
devices on behalf of the back-end tier. from the conference? Terrence Barrs blog
Java brings great value to all of these Barr: Oracle is dead serious about
processing tiers. Depending on the the M2M space and embedded Java.
given solution, you can choose where Oracle recognizes that this is a huge
and how to implement filtering and opportunityfor Oracle, for Oracles blog
business logic. And with Java, its partners, and for the entire Java
always the same language, the same ecosystem.
programming model, and the same During the conference, I spoke to a
tools and expertise. Thats a huge lot of partners and developers, and the
25
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
(embedded )

TOP TEN For many years now,


weve been promised the
Internet of Thingswith

REASONS
everything from light-

JAVA IN ACTION
bulbs to cars all networked
together with built-in

FOR USING
intelligence. The com-
bination of Moores Law
and economies of scale is

JAVA IN
finally making this a real-
ity. For example, Philips

JAVA TECH
recently announced that it
would be selling internet-

EMBEDDED
enabled lightbulbs through
the Apple store. For these
networked, programmable

APPS
devices to be really useful,
they need applications to

ABOUT US
collect, process, and trans-
mit data. Traditionally,
code for embedded sys-
Learn why Java is the best language tems has been written
for the Internet of Things. in assembler or C, but
for the rapid explosion
BY SIMON RITTER
of programmable, con-
nected devices, we need
something better: Java.
What makes Java the best
language for embedded
devices? Here are ten great
reasons (with thanks to
Roger Brinkleys blog entry
for inspiration): blog

ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY BOB ADLER 26


ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
1
nication, and a ZigBee API, to name a sor and OS will change significantly
WE ALREADY HAVE A WHEEL; LETS
few. Many of these libraries are open from the previous release of the prod-
NOT KEEP INVENTING NEW ONES.
sourced and can easily be integrated uct. Migrating applications written in
into new embedded applications. assembler or C to a new platform can

JAVA IN ACTION
Java SE 7 has almost 4,000 standard be time consuming, costly, and error

2
class libraries covering everything prone. From the very beginning, Java
SEGMENTATION FAULT IS NEVER
from collections through concurrency GOOD, SO WELL JUST AVOID IT. has been write once, run anywhere.
to networking. Having this enormous Porting code in Java is a non-event. As
collection of standard APIs means long as none of the APIs used by the
significantly less time spent rewriting One of Javas strengths, and one of the application have changed, its simply
standard functionality for embedded things that has made it so popular as a a matter of redeploying the existing
applications. While smaller-footprint programming language, is how robust class or Java archive (JAR) files. When

JAVA TECH
parts of the Java platform, such as application code is. Languages such moving to a newer (and therefore
Oracle Java ME Embedded, dont have as C and C++ use explicit pointers to better-performing) version of Java, all
as many standard classes by default, reference memory. In Java, all object that is required is a simple recompile.
they still have a wealth of functional- references are implicit pointers that

4
ity available. Many of the Oracle Java cannot be manipulated by application
LET THE VIRTUAL MACHINE TAKE
ME Embedded APIs are targeted at code. This avoids potential problems, CARE OF THE MUNDANE STUFF.
the needs of embedded systems: such as buffer overruns and memory

ABOUT US
for example, the device API provides access violations, through incorrect
standardized ways of working with pointer calculations. Situations such as The Java Virtual Machine (JVM) pro-
low-level protocols such as Serial these can cause an application to stop vides a wealth of benefits to embedded
Peripheral Interface abruptly. In embedded systems, these developers that they dont get with
ONE FOR ALL (SPI) and Inter- types of errors can be much harder to natively compiled code.
Porting code in Java Integrated Circuit track down because often there is no Memory management is all handled

is a non-event. As (I2C). However,


Javas API power
device such as a screen where error
messages can be displayed.
automatically by the JVM; memory is
allocated by instantiating an object,
long as none of the doesnt stop with rather than having to use explicit calls
APIs used by the
3
the classes available to library functions such as malloc.
ONE PLATFORM RUNS
as part of the plat- Developers dont have to keep track of
application have form. Because Java
THEM ALL.
object references and explicitly de-
changed, its simply a is such a popular
language, develop- Unlike desktop machines or even serv-
allocate memory either; the garbage
collector handles all this. This substan-
matter of redeploying ers have created ers, embedded systems vary widely in tially reduces the potential for memory blog
the existing class or libraries that address terms of their architecture, resources, leaks, which can have a far greater
JAR files. almost anything you
can think of: sensors,
and OS capabilities. When embed-
ded systems are updated, theres
impact on embedded systems where
applications might need to run for very
serial port commu- also a good chance that the proces- long periods in memory-constrained
27
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
6
DONT GO NATIVE environments without pH level of part of an industrial pro-
THINGS HAVE CHANGED
Some people needing to be restarted.
Concurrency support for
cess. As such, each system will have
hardware tailored to the solution being
SINCE 1995.
wrongly think that applications is also han- developed, which gives designers far

JAVA IN ACTION
by using a VM dled by the JVM. The abil-
ity to create and synchro-
greater choice than when creating a
new desktop or laptop system.
Java was originally developed in the
early 1990s to allow applications to be
rather than native nize different threads of Many embedded chip manufactur- written for the Star7 PDA, which was an
instructions, execution has been built
in from the very begin-
ers, such as Freescale and Broadcom,
create processors and systems on a
embedded device. When Java was first
launched as a general-purpose comput-
performance will ning with Java. Even if the chip (SoCs) using architectures from ing platform in 1995, the average per-
be compromised. embedded platform on companies such as ARM. Although this sonal computer had 8 MB of RAM and
which the JVM is deployed makes certain aspects of the different a processor running at less than 200

JAVA TECH
does not support multi- processors and SoCs standard, there MHz. Even today, the full Java SE run-
threading directly (some- are often small differences in terms of time requires only a minimum of 64 MB
thing thats increasingly rare these aspects such as floating-point process- of RAM to run on Windows XP. Typical
days), its still possible to emulate the ing, bus architectures, and so on. Java low-end embedded systems now match
functionality through the concept of abstracts these differences away from or exceed these specifications.
green threads. the developers, making their lives sig- Java was developed from the very
Some people wrongly think that by nificantly easier. beginning to work in resource-

ABOUT US
using a virtual machine (VM) rather Reference implementations of the constrained environments, making it
than native instructions, performance Oracle Java Embedded Client are avail- ideally suited to the needs of embed-
will be compromised. With nearly 20 able for Intel x86 and MIPS as well as ded systems today. Oracle Java ME
years of development in the JVM, these ARM v5, v6, and v7 architectures run- Embedded will run in as little as 350
issues are no longer a significant fac- ning Linux (the most popular OS for KB of ROM and 130 KB of RAM (look
tor. In certain situations, having pre- embedded devices). Oracle Java SE carefully, thats kilobytes, not mega-
cise knowledge, which is available only Embedded is available for Intel x86 bytes), growing to 1.5 MB of ROM
as the application is running, can lead and IBM Power e500v2 and e600 with 700 KB of RAM for the full, stan-
to better performance than the perfor- systems as well as ARM v5, v6, and v7 dard configuration. Oracle Java SE
mance of natively compiled code. architectures, again running Linux. Embedded is designed for more-
This gives embedded systems design- powerful systems, but still requires

5
ers plenty of choice about which plat- only 39 MB of ROM and 32 MB of RAM.
PICK AN EMBEDDED PLATFORM
ANY EMBEDDED PLATFORM. form to use. Having to deal with lower clock
speeds also means that the Java plat-
form works well when you want to blog
Embedded systems are generally maximize the time between charges
designed to solve a specific problem, for battery-powered devices. When
whether it is how to provide in-car resources are tight, Java can still get
entertainment or how to monitor the the job done.
28
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
Java Embedded: Start Developing
7
combinations with different capabilities and modems GIVE US THE TOOLS, AND
that will provide developers one board that spans many WE WILL FINISH THE JOB.*
different device types. Included on the motherboard are
Tori Wieldt, Java Magazine technology editor, caught up
WiFi a/b/g/n, an SD card slot, four DB9 connectors, five
with Kevin Smith of Oracle Technical Business

JAVA IN ACTION
LEDs, JTAG, USIM, GPIO, SPI, and I2C. The board even Developing code requires tools; the
Developmentand got the latest on Oracle Java ME better the tools, the easier the job is
runs on the included battery. It also comes with sensors
Embedded. to finish and the more quickly it gets
for temperature and light; GPS; and a 3-D accelerometer,
Java Magazine: Whats new for partners in the Java ME done. Today, time to market is just as
so developers will be able to prototype solutions for con-
embedded space? critical as functionality for a products
tainer management, building automation, automotive,
Smith: We announced Oracle Java ME Embedded at success.
and the next wave of cool devices on the board. We also
JavaOne San Francisco 2012. Its pretty exciting because Tools for writing assembler and
have a Java ME Software Development Kit integrated
it represents a new Java platform that addresses the C code for embedded systems tend
with the NetBeans IDE that emulates the features of the

JAVA TECH
needs of the machine-to-machine [M2M] market and toward text editors and command-
board. We really think that this is going to accelerate time
the Internet of Things. We have been working closely line tool chains controlled by esoteric
to market for developers because they can get their hands
with Cinterion and Qualcomm on this. Oracle Java ME tools such as Make. These work, but
on the platforms as soon as they are available, rather
Embedded contains JSR 228, Information Module they severely limit the productivity
than waiting for OEM [original equipment manufacturer]
ProfileNext Generation. The Java ME team has been of developers. Java developers have
prototypes. Its very exciting. Additional good news for
working for many years connecting people to the internet a great deal of choice of commercial
developers: these prototype boards usually cost around
with PCs, wireless handsets, tablets, and laptops, and as well as free and open source inte-
$5,000 for a single solution, and with the Orion board

ABOUT US
Oracle Java ME Embedded represents the platform that grated development environments
they can get a scalable platform for around $500.
will connect things to the internet. Depending on which (IDEs). Tools such as NetBeans and
analyst report you read, by 2020 there will be 30 to 60 Eclipse make writing code much easier
billion things connected. Now, you can use your existing and less error prone. Features such as
Java skills to program for these many devices. automatic code completion, syntax
Java Magazine: What is the Qualcomm Orion board? checking as you type, and integrated
Smith: The Orion board is Qualcomms developer board documentation all help to get the job
for M2M and the Internet of Things. Since the inception done more quickly and make the code
of Qualcomms new M2M business unit in early 2012, we more robust. As rich client platforms
have been working with Qualcomm on Oracle Java ME (RCPs), these tools are easy to extend,
Embedded support for Orion. so they can be tailored to the needs
Java Magazine: Why does this matter to a Java of specific types of application devel-
developer? opment. Development time can be
Smith: Unlike most developer boards, Orion is different in Kevin Smith of Oracle Technical Business greatly reduced by building emulators
that the system on a chip [SoC] is attached to the board Development explains whats new for partners for the target hardware to work with a blog
via a daughter card. Qualcomm has many different SoC and Java developers in the embedded space. desktop-based IDE.

* WINSTON CHURCHILL, BBC RADIO BROADCAST, FEBRUARY 9, 1941


29
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
8
program in Java. Almost BIG TALENT POOL useful information. What is
DEVELOP ON ONE MACHINE,
DEPLOY TO ANOTHER.
all universities use Java as
a teaching language for
Because the JVM the most popular platform
for developing enterprise
object-oriented program- and the class applications? Java. Using
libraries abstract

JAVA IN ACTION
Embedded systems by their very ming fundamentals, which Java in embedded devices,
nature tend not to resemble desktop
or laptop systems. Frequently they are
means that the number of
Java developers is likely to away much of in the data center for big
data processing, and on the
what is called headless, meaning that increase. the complexity desktop for presenting and
they have no display attached. This
adds extra challenges and complex-
If you want to develop
Java code, you have a huge
of developing controlling the whole sys-
tem makes architecting a
ity to software development in terms pool of programming tal- embedded system complete solution simpler,
of how to compile the code on one ent to draw on. Because the code, you dont quicker, and cheaper.

JAVA TECH
machine and deploy it to another. JVM and the class librar- As you can see, Java
Because Java uses a VM, it doesnt ies abstract away much of need to find people offers benefits for devel-
matter where you compile your code, the complexity of devel- who have lots of oping code for embedded
so theres no need to set up complex
cross-compilation tool chains. Use
oping embedded system
code, you dont need to
experience. systems. With lower cost,
more choices of platform,
your favorite Java IDE to develop the find people who have and readily available
code in comfort on your desktop, and lots of experience in this skilled developers, theres

ABOUT US
then simply copy the class files or JAR field. For situations where nothing holding you back
files to the target device. To make more-domain-specific knowledge from helping to build the Internet of
developers lives even easier, most is required, there will still be a larger Things. </article>
IDEs support the concept of remote number of Java-capable developers to
debugging through a network connec- fill these positions.
tion. If the code is doing what you told Simon Ritter is a Java technology evan-
gelist at Oracle. He has worked in both

10
it to do, rather than what you wanted it
FROM DEVICE Java technology development and consul-
to do, simply use the debugging facili- TO DATA CENTER . . .
ties in your IDE to figure out what the tancy. He now focuses on the core Java
issues are. This will be a lot faster than platform and Java for client applications.
using print statements. For embedded systems to have real
value, they need to be networked,

9
not just to other embedded systems
NINE MILLION DEVELOPERS
but also to places where data can be
CANT BE WRONG. blog
aggregated, analyzed, and searched.
This is what data centers are good
Depending on whose survey you con- at, recording and processing huge
sult, there are up to 9 million devel- amounts of data from many different
opers in the world who know how to sources and then mining the data for
30
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
(embedded)

JAVA ARRIVES

JAVA IN ACTION
ON A $25 BOARD
Eben Upton and the Raspberry Pi
Foundation endeavor to inspire a new

JAVA TECH
generation of programmers.
BY DAVID BAUM AND ED BAUM

Y
ouve heard the phrase before:

ABOUT US
This thing is going to change
the world. People said it about
the electric lightbulb, the telephone,
and the internal combustion engine.
And they were right. But what does
it take to change the world today?
Can a single idea or innovation still
do that? For Eben Upton, cofounder
of the UK-based Raspberry Pi
Foundation, the answers to those
questions are linked to the way he
hopes to measure the success of
his project: by adding to the critical
mass of students interested in com-
puter science. blog

ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY JOHN BLYTHE 31


ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
JAVA IN ACTION
The Raspberry Pi fills the
niche need for low-cost

JAVA TECH
programmable computers,
says Raspberry Pi
Foundation Cofounder
Eben Upton.

SNAPSHOT The heart of the project is the claim that we have a full suite of puter sciences at St. Johns College,
Raspberry Pi, a tiny yet powerful mainstream development tools Cambridge, he has personally wit-

ABOUT US
RASPBERRY PI
FOUNDATION general-purpose computer priced at bundled on the device. nessed a steady decline in the num-
raspberrypi.org
US$25. The device is about the size ber of applicants for computer sci-
of a deck of playing cards and can WHERE HAVE ALL THE ences, not to mention a regression in
Headquarters: deliver 1,080p Blu-ray-quality graph- CODERS GONE? the complexity of the programming
Caldecote, ics via its HDMI port. It runs Linux With processing power sufficient to tasks those applicants can under-
Cambridgeshire,
England
kernelbased operating systems. drive a high-definition media cen- take. He says the same trend can be
Oracle is in the process of port- ter at the price of a couple of movie seen at almost any computer com-
Industry:
ing the Java Virtual Machine (JVM) tickets, its not surprising that the pany, where there are more engineers
High technology to run on the Raspberry Pis ARMv6 Raspberry Pi is on track to ship its in their 30s than in their 20s and
Employees: 700 MHz processor, expanding the millionth unit by the end of its first experienced programmers are often
3 potential uses for the minicomputer year in production. But Upton and his hired away from other companies
Java technology and making it easier than ever for colleagues consider the number of because there arent enough people
used: people to create lightweight, power- units sold to be a crude measure of entering the field out of college.
A special version ful, and reliable programs. impact. For them, success is gauged One of the main reasons for the
of Java Virtual Java is kind of the missing piece on a philanthropic scale. deterioration in computer skills in blog
Machine adapted
for the Raspberry Pi
for us, Upton says. Licensing agree- How are we going to find tomor- the upcoming generation is attribut-
computer ments are underway that will enable rows computer programmers? able to a simple fact: low-cost pro-
us to bundle Java on the Raspberry Pi. Upton asks, and with good rea- grammable computers that were
When we have that, then we can son. As director of studies in com- available when I was young arent
32
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
A CROSSOVER BOARD the intriguing little people begin to learn programming as
This intriguing little device with its impulse-buy price tag is device with its impulse-
buy price tag is also
early as age 8, apply to universities at
18, move into industry at 21, and start
also gaining momentum among adult hobbyists, tinkerers,

JAVA IN ACTION
gaining momentum their own companies at 30. Its a long-
and developers. And its raising eyebrows in industrial sectors, among adult hobbyists,
tinkerers, and devel-
range vision. Sometimes thats what it
takes to change the world.
as managers begin to perceive its potential as a low-cost opers. And its raising
alternative to domain-specific devices. eyebrows in industrial
sectors, as managers
AN ENGAGING ENVIRONMENT
FOR STUDENTS
begin to perceive its The Raspberry Pi ships without a case,
potential as a low-cost which naturally invites scrutiny and

JAVA TECH
around anymore, Upton explains. alternative to domain-specific devices. arouses curiosity. Unlike the slick,
We wanted to build a piece of hard- But Upton keeps bringing the sealed units that dominate the world
ware to fill that niche. The Raspberry Pi focus back to units of one and the of personal computing, students can
is cheap enough so that every student long-term impact of getting these see the circuit board and compo-
can have one. Some of them will be tantalizing devices into homes and nents and learn to identify their vari-
captivated by it. With Java on it, well schools where children are inspired to ous functions. The Raspberry Pi has
be able to provide an environment play with them, limited only by their a Broadcom BCM2835 system chip

ABOUT US
that is friendly enough to enable a very imaginations. In that way he hopes (which contains an ARMv6 700 MHz
young child to start programming with to begin, through his foundation, to processor and a VideoCore IV GPU),
a language that professional software refill a pipeline of talent that he says 512 MB of RAM, an HDMI port, video
engineers use. society stopped filling in the late 1990s and audio outputs, a USB port, com-
Java lets students learn how to when programmable home comput- posite video out, and an SD card slot
program without getting bogged down ers such as the Commodore 64 and the for operating systems and applica-
by the complexities of C++ and other BBC Micro were replaced by closed- tions. A US$35 model includes a sec-
languages, Upton adds. Java tells you platform gaming consoles and PCs ond USB port and an Ethernet port for
when you have done something wrong and Macs with GUIs that dont expose networking. The Raspberry Pi does not
in your coding. And it is a professional users to a programming language or a currently include wireless networking,
programming tool. Its a nice addition command screen. but users are successfully connecting
to the Raspberry Pi. Well consider the project a success USB Wi-Fi adapters (dongles).
if we eventually see more kids apply- The major hurdle during the early
SHAPING THE FUTURE ONE CHILD ing for college in computer sciences, days of the project was finding com-
AT A TIME Upton says. My hope is that we can ponents that could deliver the req- blog
The Raspberry Pi was developed pri- add 1,000 computer science students uisite performance without boosting
marily as an affordable education tool per year in the UK. That would trans- the price beyond the reach of many
to inspire the next generation of com- form the industry and the lives of those students. The breakthrough in deliver-
puter programmers. Not surprisingly, students. Upton would like to see ing high-quality graphics came from
33
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
opment community is accustomed to version of the JVM that will run on the
Get Started with If you are ready to dive into
programming on the
these kinds of limitations. When Java Raspberry Pis processor and will take

Raspberry Pi was created back in the 1990s, most advantage of the acceleration for hard

JAVA IN ACTION
Raspberry Pi, dont miss desktops had only 4 or 8 megabytes floating-point arithmetic. That should
the article Get Started of memory. yield a 10 to 15 percent improvement
with Java SE for Embedded Devices on Raspberry Pi, in Optimizing Java for the tiny com- in performance for more-compute-
the November/December 2012 issue of Java Magazine. puters ARMv6 processor requires intensive applications such as those
Authors Bill Courington and Gary Collins provide an some finesse. The challenge is related that use graphics. Were in a compre-
in-depth, step-by-step guide to getting Linux and to floating-point arithmeticthe way hensive testing cycle for the optimized
Oracle Java SE Embedded running on your Raspberry Pi the processor performs arithmetic on version of JVM for the Raspberry Pi,
in less than an hour. real, or nondecimal, numbers. Many Ritter says. That should deliver a lot of

JAVA TECH
chips based on the ARMv6 architecture benefits for users.
lack hardware floating-point units; the What else does Java bring to this
Broadcom BCM2835, however, does tiny computer? For Upton, it all comes
include ARMs virtual floating point back to educating children, the objec-
Broadcom Corporation, where Upton (VFP) coprocessor. tive at the heart of the Raspberry Pi
is employed as an SoC (system-on- A port of the JVM that uses soft Foundation. There are some high-
a-chip) architect. In 2010, he was floating point on ARM processors is quality educational applications that

ABOUT US
involved in the design and develop- currently available; it will work on run on Java that we can bring across
ment of the Broadcom BCM2835 the Raspberry Pi and is supported by with no investment, he says. Thats
multimedia applications processor. Oracle. Oracle is creating a different very important to us.
Having decent graphics perfor-
mance and multimedia features can
attract children to the platform,
Upton says. Gaming and Blu-ray-
quality movie playback are hooks to
draw young users to the device.

FINDING THE SWEET SPOT


While 512 MB of RAM may seem pro-
hibitively small for a programming
environment, Java actually fits well
within those confines. Java is a blog
language that is ideal for creating
small applications that run very por-
Simon Ritter demonstrates mind control of a Lego windmill using
tably, says Simon Ritter, technology
only his brain (and a Raspberry Pi running Java).
evangelist at Oracle. The Java devel-
34
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
Ritter concurs that the sweet spot to adapt this low-cost LOOKING AHEAD Pi Foundation. Java is
for the Raspberry Pi is in education computing platform for expected to play an
and that Java is well positioned to commercial purposes. Future enhancements important role in that pro-

JAVA IN ACTION
support that. For students and hob- Javas mature ecosystem may include Wi-Fi cess, whether in schools,
byists, Java provides better reliability
and easier debugging than many of
will facilitate that pro-
cess. GlassFish Server
plug-and-play with in industry, or in the hands
of the do-it-yourself
the other development languages that Open Source Edition firmware revisions, community.
have been ported to the Raspberry Pi,
he adds. And there are many exist-
could be put onto the
Raspberry Pi so it could
an onboard Skype Once hardware is
a given, people will be
ing libraries of frameworks for Java serve Web pages or run service, and add-on able to innovate at the
that can be used in conjunction with Java enterprise applica- expansion boards for software level, Upton

JAVA TECH
the device. It has great potential to
provide schools with a very low-cost
tions, Ritter says, citing
one example of a com- cameras. concludes. We are
very hopeful that the
platform that children can experi- mercially viable Java com- Raspberry Pi and its edu-
ment with. panion. GlassFish has cational initiatives will
Of course, ultimately these students been designed very care- refill the pipeline of tal-
will move into the business world, fully using a microkernel, so it does ented individuals who will shape the
and some of them will use their skills not require a lot of memory in its most future for all of us. </article>

ABOUT US
basic form. It only uses the parts it
needs to run the application. It is well
suited to this kind of device. Based in Santa Barbara, California, David
Upton also recognizes that his Baum and Ed Baum write about innova-
invention will soon expand beyond the tive businesses, emerging technologies,
classroom. Were going to create a lot and compelling lifestyles.
of value for people developing indus-
trial applications, he says, pointing
out that a small, affordable general-
purpose computer could ultimately
replace a wide range of specialized
devices, especially those that require
embedded microprocessors to perform
essential tasks on the shop floor, on
an assembly line, and for finely tuned blog
scientific applications.
Yet wherever this useful device may
Oracle is in the process of porting the JVM to run on the end up, fostering creativity remains
Raspberry Pis ARMv6 700 MHz processor. the driving force behind the Raspberry
35
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
THE FUTURE
(embedded )

JAVA IN ACTION
OF MONEY
With its MintChip offering, the Royal
Canadian Mint plays the Java Card
platform in the emerging world of

JAVA TECH
digital currency.
BY PHILIP J. GILL

M
inting coins is an activity as old as the
earliest human civilizations. From the
precious stones and metals that mil-

ABOUT US
lennia ago replaced the barter of cattle, sheep,
and grain, what serves as money has continued
to evolve. Today the future of money appears to
be the many forms of digital currencymoney
or scrip that is only exchanged electronically
over private and public computer networks,
including the internet.
For the Royal Canadian Mint (RCM), the sole
legal producer of all circulation coins in Canada,
the transition to digital currency represents
a major opportunity. We consider ourselves
to be quite innovative at the Royal Canadian
Mint, says Marc Brl, chief financial officer at
the RCM, which is headquartered in Ottawa, the
nations capital. blog

Royal Canadian Mint CFO Marc Brl (left)


and Dr. David Everett
ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY PATRICK FORDHAM 36
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
Brl and Everett surround themselves with coins at Royal Canadian
Mint headquarters in Ottawa.

Canada and other far have: The MintChip is the only


countries around digital currency in the world being
the world. Being researched by a sovereign govern-

JAVA IN ACTION
digital, says Brl, ment, says Kowal. Given that the
the MintChip can Canadian dollar is one of the worlds
be denominated in most widely traded currencies, that
almost any world adds substantial credibility.
currency.
We see the POCKET CHANGE
MintChip as being The RCM was founded in 1908 as a
an option to physi- branch of the UK Royal Mint and in

JAVA TECH
cal cash, says 1969 was incorporated as a for-profit
Brl. We believe commercial crown corporation. In
the MintChip can be monarchical Commonwealth countries
very cost-effective such as Canada, crown corporations
in the low-value are government-owned enterprises
transactions mar- that undertake activities on behalf of
SNAPSHOT For years we have been following ket. It offers a good value proposition their sole shareholderin the RCMs

ABOUT US
ROYAL CANADIAN the advent of electronic payments and for merchants and consumers alike case, the Canadian government.
MINT their growth, Brl continues. Three because it doesnt run across a net- While the Bank of Canada, a separate
mint.ca or four years ago, we decided to dedi- work, is highly portable, and provides crown corporation, issues all Canadian
cate some research and development chip-to-chip secure communications. banknotes, the RCM mints the pocket
Headquarters: funding to looking into electronic The MintChip is built entirely on change Canadians use every day to
Ottawa, Ontario,
payments and, more specifically, what Java Card technology, the de facto buy a cup of coffee, pay a transit fare,
Canada
needs in the marketplace werent standard platform for smartcards and or purchase a newspaper or magazine.
Industry: being fulfilled and whether there was a other small memory footprint devices. These include the Loonie, a CA$1
Government
role the Mint might play in this emerg- More than 12 billion Java Cardenabled coin so nicknamed because it bears the
Employees: ing market. devices have shipped since the plat- image of a common loon on one side,
More than 900
From that decision came a new digi- form was introduced in 1997, accord- and the CA$2 Toonie, whose nick-
in 2011
tal currency, prototypes of which were ing to Brian Kowal, Java Card business name blends the words two and loonie.
Revenue: introduced last year: the MintChip. manager at Oracle. Java Card is the Besides Canadian coins, the RCM
CA$3.2 billion
in 2011
Many forms of digital currency already worlds number one leading software also mints commemorative and col-
existfrom electronic funds trans- application platform by volume, says lector coins, bullion coins, medals blog
Java technology
fer (EFT) to direct deposit and loyalty Kowal. (See sidebar, A Pocketful of and medallions, and even coins for
used:
cardsbut the RCM sees the MintChip Java Card.) other sovereign governmentsin
Java Card
as a potential replacement for physi- Kowal says the MintChip has one any given year, the RCM contracts to
cal currency, both coins and paper, in advantage that none of its rivals thus manufacture coins for as many as a
37
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
Java Card was the obvious platform

COMMUNITY
choice for the MintChip, says Everett,
with Brl near the Ottawa River.

MONEY FOR THE MOBILE GENERATION


One of the target markets for the MintChip, at

JAVA IN ACTION
least initially, is younger mobile phone users in
developed and emerging economies worldwide
who are unbankedthat is, they do not have
regular bank checking or savings accounts and
regularly deal in cash transactions.

JAVA TECH
dozen foreign countries. We operate They are certified under the US FIPS mobile phone users in developed and

ABOUT US
like any other corporation, says Brl. 140-2 and European Common Criteria emerging economies worldwide who
We operate to make a profit, and we EAL5+ standards, used for military and are unbankedthat is, they do not
receive no government funding. government IDs and payment systems have regular bank checking or savings
In prototype form, the MintChip worldwide. What makes this interest- accounts and regularly deal in cash
is an SD, microSD, UICC (Universal ing, says Kowal, is that the MintChip transactions.
Integrated Circuit Card), or USB mem- could be embedded in an automobile, The way the MintChip works is
ory card containing an integrated cir- a smart meter, or a personal e-reader what we call an asset transfer model,
cuit that provides security. It comes or tablet and provide payment solu- explains Dr. David Everett, an indepen-
loaded with the MintChip application; tions for all a consumers personal dent consultant and the MintChips
the Java Card platform, including a connected devices. chief technical architect. The con-
Java Virtual Machine (JVM); and an Java Card hardware has unique sumer actually holds the value in their
operating system. Written in Java, the attributes to secure against physical chip. If you have a chip in your phone,
MintChip runs atop the JVM within the attacks, continues Kowal. They have for instance, the values actually in that
Java Card runtime, so theres nothing small memory footprints, are low- chip. And when you make a payment
to stop it from being deployed in the power, and have a persistent memory to somebody else, it leaves your chip blog
cloud as well, adds Brl. model that holds transactions even if and goes to another chip.
All Java Card platform chipsinclud- power is removed midway. A typical use case for the MintChip
ing those the MintChip usesare One of the target markets for the would be mass transit, Everett says.
highly secure, says Oracles Kowal. MintChip, at least initially, is younger Consumers load their MintChip
38
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
COMMUNITY
A Pocketful of Odds are, if you have a smartcard in
your pocket, its a Java Card. More than
Java Card 2 billion Java Cardenabled smart- from the chip in their card or mobile
phone to the chip in the reader, with
forms is performance. In mass tran-
sit, you need to have a very fast perfor-
cards ship every year, and to date, more
than 12 billion Java Cards have been issued since the technol- no intervening computer network or mance time, says Everett. This has
ogy platform was first introduced in 1998. back-end bank approvals. always been a challenge with a virtual

JAVA IN ACTION
The success of the Java Card platform can be traced machine like Java Card to achieve that
to several technical features, according to Tankar Ravi A NATURAL PLATFORM sort of 300-millisecond-type transac-
Ravishankar, principal engineer at Oracle. When Java Card Java Card technology is a natural plat- tion, but we believe it will stand up.
technology was first released, Ravi explains, there were many form for the RCMs digital currency Given these criteria, says Everett,
competing platforms that were proprietary and which had venture. For us, Java Card was a very Java Card came out to be an out-
long development cycles. Java Card technology enabled obvious choice because the platform standing winner.
developers to write applications in Java that could run on offered us quite a lot, says Everett. To validate the MintChip technology
cards from different vendors, could be developed using off- There are other platforms, but the and business propositions, the RCM

JAVA TECH
the-shelf tools, and were less error prone, he says. Java Card platform is ubiquitous, par- announced the MintChip Challenge,
That portability also enabled Java Card developers to move ticularly in the mobile market. Weve a competition for software developers
applications from credit cardlike smartcards to the new assumed that in general people will be to build digital currency applications
mobile phones that emerged in the early 2000s, he adds. using Java applications on Android and using the MintChip. We had decided
Because smartcards typically use persistent memory such BlackBerry phones, iOS devices, PCs, we would reach out to 500 software
as EEPROM or flash, Java Card technology includes persis- and other similar mobile devices. developers, says Brl. We werent
tent objects to meet their special needs, says Ravi. Smartcard To spark interest among developers, sure what the uptake would be, but

ABOUT US
chips also have no battery power; power is supplied to the chip he adds, we have also provided APIs it only took 72 hours to have all 500
when the card is placed in a reader device. The Java Card to the MintChip that allow developers spoken for.
platform features a transaction framework to ensure that the to use their existing platform, such as In the end, 57 qualifying applica-
application state is always consistent, says Ravi. Java on a mobile phone, which is very tions were submitted. The grand prize
The US Defense Manpower Data Center adopted Java Card popular. winner, announced in September
technology for the US military and government departments. By necessity, MintChip devices will 2012, was MintWallet, a cloud-hosted
Ravi says this has given Java Card technology a high- be highly secure, Everett adds. In addi- peer-to-peer network for sending and
security branding that has been instrumental to its growth tion to anticipated certification under receiving virtual cash. Surprisingly,
and acceptance. the Common Criteria and FIPS 140-2, MintWallet is a Windows-based Java
the MintChip assures users an extra Card application, proving that the
layer of security not available in other MintChips digital currency is as por-
electronic and digital currencies: table as the real-world pocket change
devicescredit cardlike smartcards because theres no network or approv- it could replace. </article>
or mobile phoneswith money from als involved, no personal information
a kiosk, an ATM, or across the cloud is released between the devices and no blog
from a PC or tablet. As they board a personal information travels over a net- Philip J. Gill is a San Diego, California
bus or train, they run their MintChip work. MintChip transactions can be based freelance writer and editor who has
device through a reader of some kind, completely anonymous, says Everett. been following Java technology for almost
instantly transferring the fare amount A challenge for all smartcard plat- 20 years.
39
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
Part 3
Introduction to Web Service Security
from Server to Client

JAVA IN ACTION
MAX BONBHEL Use Mutual Certificates Security to set up trusted authentication and protection that ensures the
BIO integrity and confidentiality of messages.

JAVA TECH
T his article concludes a
three-part series that
focused on ensuring the
Now we are going to use
a mechanism that allows
the client and the server to
requires a keystore file and
a truststore file for both the
client and the server sides of
Prerequisites
Download the following
software, which was used
security of Web services from mutually authenticate. an application. to develop the application
server to client. We have Note: The complete source The server certificate is described in this article:
explored how to secure Web code for the application provided to the client in NetBeans IDE 7.2 (avail-

services through the follow- designed in this article can advance of any communica- able for download here)

ABOUT US
ing mechanisms: be downloaded here. tion, so both the client and GlassFish 3.1.2.2 (available

In Part 1, we explored the server can be sure they for download here)
Username Authentication What Is the Mutual are dealing with legitimate Metro 1.3 or higher

with Symmetric Key to Certificates Security entities, as shown in Figure 1. (included in NetBeans)
generate a certificate/key Mechanism?
couple shared by the cli- Mutual certification,
ent and the server to sign also called shared certi-
and encrypt messages. We fication, is a process or
also used the username/ technology where two
password combination communicating entities
to authenticate the client authenticate mutually.
during service calls. The Mutual Certificates
In Part 2, we explored how Security (MCS) mecha-
to protect the data transit- nism provides security
ing between the client and through authentication blog
the server using Secure and message protec-
Sockets Layer (SSL) via the tion to ensure integ-
secure HTTP transport, rity and confidential-
PHOTOGRAPH BY
ALLEN MCINNIS/GETTY IMAGES HTTPS. ity. This mechanism Figure 1
40
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
Note: This article was tested using configure the keystore and the Web client that references the AuctionAppSOAPws node;
the latest version of the NetBeans truststore for the client and the Web service by specifying the then select Edit Web Service
IDE (version 7.2, at the time this server to ensure the integrity and secure Web Services Description Attributes.
article was written). confidentiality of the message. Language (WSDL) file c. Under the Quality Of Service

JAVA IN ACTION
We will perform the following Test the noncertified client tab, expand the AuctionApp
Overview of Adding MCS to the tasks: application SOAPwsPortBinding section.
Web Service Secure the Web service by add- Configure the keystore and the d. Make sure the Reliable
What we are going to do is secure ing the MCS mechanism and truststore for the client Messaging Delivery option is
both sides of the AuctionApp configuring the keystore and the Test the certified client deselected.
application by using the MCS truststore for the server application e. Select Secure Service
mechanism. Specifically, we will Create and configure a new Note: The application we are and then select Mutual
going to secure is an online auc- Certificates Security from the

JAVA TECH
tion place (like eBay) that we cre- Security Mechanism list, as
ated in a previous series of articles shown in Figure 2.
(Introduction to RESTful Web 2. Configure the keystore to
Services). Sellers post their items specify the alias identifying
in listings, and buyers bid on the the server certificate and pri-
items. A seller can post one or vate key for the AuctionApp
many items, and a buyer can bid application:

ABOUT US
on one or many items. a. Deselect Use Development
Specifically, we are going to limit Defaults if it is selected.
access to the Java API for XML Web b. Click the Keystore button,
Services (JAX-WS) Web service that and then click the Load
extrapolates the amount of a bid Aliases button and select
by multiplying by a factor (100). xws-security-server, as
shown in Figure 3.
Add MCS to the Web Service c. Click OK.
It will take less than five minutes At this point, NetBeans
to add MCS to the Web service creates a new Web Services
using NetBeans IDE 7.2. Interoperability Technologies
1. Add the MCS security mecha- (WSIT) configuration that
nism to the AuctionApp contains the security ele-
application: ments within the sc:KeyStore
a. Open the AuctionApp project tags of the wsit-com blog
in NetBeans IDE 7.2 or higher. .bonbhel.oracle.auctionApp
b. Expand the Web Service .AuctionAppSOAPws.xml
node of the AuctionApp file, as shown in Figure 4.
Figure 2 project and right-click the The file is located in the Web
41
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
Pages/WEB-INF node of the AuctionAppSOAPws?wsdl. <sp:InitiatorToken>: The initiator Create a New Web Client
AuctionApp project. The Web service presents its token refers to the public/ In this section, we are going to cre-
3. Deploy the service and WSDL file, as shown in private key-pair owned by the ate and secure a new Web service
display the WSDL file Figure 5. initiator. client that references the Web

JAVA IN ACTION
so you can inspect the The sp:AsymmetricBinding tags <sp:X509Token>: This tag speci- service that we just secured.
sp:AsymmetricBinding tags: contain all we need to encrypt fies that the X.509 certificate To do this, we will create a sam-
a. Right-click the AuctionApp and sign the SOAP message using token profile will be used. It ple Web client application by using
node and choose Deploy. asymmetric key algorithms contains the sp:IncludeToken the Web Service Client wizard pro-
b. Open your browser and type (public/private key combinations). attribute, which is responsible vided by NetBeans IDE 7.2 to gen-
the WSDL URL: http:// This tag should contain nested for adding the public key to the erate the code and everything we
localhost:8080/AuctionApp/ elements such as the following: message sent to the recipient. need for looking up a Web service.

JAVA TECH
Figure 4

ABOUT US
blog

Figure 3 Figure 5
42
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
LISTING 1
Lets code this application in five 3. Perform actions similar to
minutes. Step 2 to create the Item and @Entity
public class Seller implements Serializable {
1. Generate the initial NetBeans Bid entities.
@OneToMany(mappedBy = "seller")
project: Now we are going to add
private List<Item> items;

JAVA IN ACTION
a. From the File menu, choose properties to the entities private static final long serialVersionUID = 1L;
New Project. using the NetBeans wizard. @Id
b. From Categories, select Java 4. Open the Seller.java file, @GeneratedValue(strategy = GenerationType.AUTO)
Web. right-click anywhere in the private Long id;
c. From Projects, select Web code, and select Insert code. protected String firstName;
Application. 5. From the Generate wizard, protected String lastName;
d. Click Next. select Add property, and add protected String email;
e. Type the seller properties (String

JAVA TECH
AuctionAppWebServiceClient lastName, String firstName, public List<Item> getItems() {
for the project name and click and String email). return items;
Next. 6. Open the Item.java file and }
f. Make sure the server is speci- add the item properties
fied as GlassFish Server (or (String title, String description, public void setItems(List<Item> items) {
similar wording). Double initialPrice, and Seller this.items = items;
}
g. Click Finish. seller).

ABOUT US
2. Create the Seller entity: 7. To define the entity relation-
a. Right-click the ship, click the NetBeans Download all listings in this issue as text
AuctionAppWebServiceClient warning (lightbulb) and
project and select New; then select Create bidirectional
select Entity class. ManyToOne relationship. the Seller and item entities WebServiceClient project and
b. Type Seller in the Class Name This action creates a list of by right-clicking anywhere in select New; then select JSF
field, type com.bonbhel.oracle items in the Seller entity. the code and selecting Insert Pages from Entity Classes,
.AuctionAppWebServiceClient 8. Open the Bid.java file and add code. click Add all, and click Next.
in the Package field, and click the item properties (String 11. From the Generate wizard, b. For Session Bean Package,
Next. bidderName, Double amount, select Getter and Setter. type a name such as
c. In the Provider and Database and Item item). At this point, your Seller.java com.bonbhel.oracle
screen, select EclipseLink 9. To define the entity relation- file will look like Listing 1. . AuctionAppWebServiceClient
(JPA 2.0)(default) from the ship, click the NetBeans 12. The client implementation .facade, and for JSF Classes
Persistence Provider list. warning and select Create we are going to build con- Package, type a name such
d. From the Data Source list, bidirectional ManyToOne sists of JavaServer Faces (JSF) as com.bonbhel.oracle blog
select jdbc/sample, which is relationship. pages based on the entities .AuctionAppWebServiceClient
the datasource provided by 10. Generate the Getters and just created. Create the JSF .controller.
NetBeans. Setter, respectively, for the list pages: c. For Folder Name, type a
e. Click Finish. of items and bids created in a. Right-click the AuctionApp name such as jsfClient.
43
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
LISTING 2 LISTING 3
d. Click Finish. c. From the New Web Service
13. We are going to use the Web Client wizard, select WSDL private Double extrapolateAmountBid
(double amountBid, int factor) {
Service Client wizard to create URL, and then specify the URL
com.bonbhel.oracle.auctionapp.ws.AuctionAppSOAPws
the Web service client. We will to the Web service WSDL file
port = service.getAuctionAppSOAPwsPort();

JAVA IN ACTION
assume that the JAX-WS Web using the fully qualified host return port.extrapolateAmountBid(amountBid, factor);
service is an external service name, for example, http:// }
that resides in the application localhost:8080/AuctionApp/
tier over the network. So, we AuctionAppSOAPws?wsdl, as
will use the URL to the JAX-WS shown in Figure 6.
Web service WSDL file. Create d. Accept all other default set-
the Web service client: tings. The package name will
a. Make sure the AuctionApp be taken from the WSDL file.

JAVA TECH
project is up and running. e. Click Finish.
If it is not, right-click the 14. Add the extrapolateAmount
AuctionApp node and choose Bid operation provided by the
Deploy. JAX-WS Web service to the
Download all listings in this issue as text
b. Right-click the client classes:
WebServiceClientSecureSSL a. Open the Source
node and choose New; then Packages node of the project and double-click the source editor and choose Insert

ABOUT US
select Web Service Client. AuctionAppWebServiceClient BidController.java file located Code; then select Call Web
in the controller package Service Operation and click the
com.bonbhel.oracle extrapolateAmountBid opera-
.AuctionAppWebServiceClient tion in the Select Operation to
.controller. Invoke dialog box.
b. Put your cursor anywhere 15. We need to add some code
inside the source editor. application logic in the
c. Expand the Web Service BidController class in order to
References node of the extrapolate the amount of the
AuctionAppWebServiceClient bid (by factor, which is 100)
project and drag the when the user edits or views
extrapolateAmountBid node the bid entry. So call the
inside the source editor. extrapolateAmountBid opera-
The extrapolateAmountBid() tion to extrapolate the bid:
method appears at the end of a. Open the BidController.java file blog
the BidController class code, as in the source editor.
shown in Listing 2. b. Modify the public String
Note: Alternatively, you can prepareView() method, as shown
Figure 6 right-click anywhere in the in Listing 3.
44
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
At this point, the secured Web Test the Noncertified Client
service client is regenerated and Application
references the secured Web ser- Now its time to test the service.
vice WSDL file. We will invoke the secured Web

JAVA IN ACTION
service from the client application
before we provide the server cer-
tificate to the client.
Try to invoke the secured Web
service from the noncertified cli-
ent to display the extrapolated
amount of a bid:
1. Make sure the AuctionApp

JAVA TECH
project is up and running.
If it is not, right-click the
Figure 7 AuctionApp node and choose
Deploy.
2. Open the Web Service
References node of the
AuctionAppWebServiceClient

ABOUT US
project and right-click the
AuctionAppSOAPws node;
then select Refresh.
3. From the Confirm Client
Refresh wizard, make sure
Also replace local wsdl file
Figure 8
with original wsdl located at:
is selected; then click Yes. Figure 10
4. Right-click the
AuctionAppWebServiceClient entries, as shown in Figure 8. Configure the Keystore and
project and choose Clean and 7. Click the View link for the Truststore for the Client
Build. bidder named Vals to see the In this section, we are going to
5. Right-click the newly extrapolated amount provide the server certificate to the
AuctionAppWebServiceClient of the Vals bid, as shown in client by performing the following
project again and choose Run. Figure 9. tasks: blog
The list of all entries is dis- As you can see, the amount of Configure the keystore to

played, as shown in Figure 7. the bid changed from 12.0 to 0.0. point to the alias for the client
6. Click the Show All Bid Items This means that the client failed to certificate
Figure 9 link to display the list of bid call the secured Web service. Configure the truststore that

45
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
contains the certificate and then select Edit Web Service 2. Configure the truststore for AuctionApp node and
trusted roots of the server Attributes. the client: choose Deploy.
1. Configure the keystore for c. Under the Quality Of Service a. Click the Truststore button, 2. Right-click the
the client: tab, select the Security sec- click the Load Aliases AuctionAppWebServiceClient

JAVA IN ACTION
a. Make sure the AuctionApp tion, as shown in Figure 10. button, and select xws- project and choose Deploy.
project we opened previously d. Deselect the Use develop- security-server, as shown in 3. Right-click the
is up and running. If not, ment defaults option if it is Figure 12. AuctionAppWebServiceClient
right-click the AuctionApp selected. b. Accept all other default set- project again and choose
node and choose Deploy. e. Click the Keystore button, tings and click OK. Run.
b. Expand the Web Service click the Load Aliases button, c. Compile the applica- The list of all entries is dis-
References node of the and select xws-security- tion by right-clicking the played, as shown in Figure 13.
AuctionAppWebServiceClient client, as shown in Figure 11. AuctionAppWebServiceClient 4. Click the Show All Bid Items

JAVA TECH
project and right-click the f. Accept all other default set- node and selecting Build. link to display the list of bid
AuctionAppSOAPws node; tings and click OK. At this point, the client and entries, as shown in Figure 14.
the server are authenticated with 5. Click the View link for the
certificates. The client keystore is bidder named Vals to see the
pointing to the alias for the cli- newly extrapolated amount
ent certificate, and the of the Vals bid, as shown
truststore contains the in Figure 15.

ABOUT US
certificate and trusted SECURITY TOOL As you can see, the
roots of the server. The Mutual amount of the bid

Test the Certified


Certificates changed from 12.0 to
1200.0. This means
Client Application Security that the client suc-
Now we are ready for mechanism ceeded in calling the

Figure 11
the real test. We are
going to try to invoke ensures integrity secured Web service.
Bravo!
the secured Web ser- and confidentiality
vice from the certified
client to display the
by requiring a Conclusion
In this article, we have
extrapolated amount keystore file and a seen how easy it is to
of a bid using the MCS
mechanism:
truststore file for add a new security layer
to an existing applica-
1. Make sure the both the client and tion to protect the com- blog
AuctionApp proj- the server sides of munication between the
ect is up and run-
ning. If it is not,
an application. client and the server.
This series of articles
Figure 12 right-click the provided an overview
46
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//new to java /

COMMUNITY
of the principal aspects of Web Protecting the data transit-
services through the following ing between the client and the
mechanisms: server
Using a username/password Establishing a mutual certifi-

JAVA IN ACTION
combination to access the cate between the client and the
service server
As demonstrated, NetBeans
and GlassFish make adding
security for Web services easier
than ever. </article>

JAVA TECH
LEARN MORE
NetBeans Advanced Web Service
Figure 13 Interoperability manual
Metro User Guide
GlassFish resources

ABOUT US
Figure 14

blog

Figure 15
47
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
Your Destination for Java Expertise
Written by leading technology professionals, Oracle Press books offer
the most definitive, complete, and up-to-date coverage of Oracle
products and technologiesincluding the latest Java release.

Acclaimed
programming author
Herb Schildts books
have sold more than
3.5 million copies
worldwide

Java: The Complete Java: A Beginners Java Programming


Reference, Eighth Edition Guide, Fifth Edition Poornachandra Sarang
Herb Schildt Herb Schildt
Learn advanced skills from
A fully updated edition of the Essential Java programming an internationally renowned
definitive guide for Java programmers skills made easy Java expert

Join the Oracle Press Community at


Available in print and e-book formats
www.OraclePressBooks.com @OraclePress
//java architect /

COMMUNITY
Part 1
Demystifying invokedynamic

JAVA IN ACTION
Learn how to use invokedynamic in your code.

JULIEN PONGE
BIO T he release of Java 7
brought substantial addi-
tions to the language, such as
(JVM) bytecode instruction
called invokedynamic. It was
introduced to facilitate the
This article is a gentle
introduction to using invoke
dynamic in your own code.
as the name, and (ILjava/
lang/String;)V as the JVM
internal representation sig-
the new try-with-resources implementation of dynamic The topic in itself is fairly nature. Invoking a method

JAVA TECH
statement, multi-catch languages on top of the JVM, rich and will mostly appeal requires placing a receiver
clauses, and the diamond which is an attractive target to language and middle- objectthat is, the object on
operator. New APIs have platform with a robust adap- ware implementers. We will which the method shall be
been introduced, too, with tive runtime that, in recent only scratch the surface of invokedon the stack. The
notable examples being the years, has seen many lan- the provided APIs and pos- only exception is the case of
fork-join framework for par- guages flourish. Some are sible usages, but by the end static methods, which do not
allel algorithms and NIO.2 ports of existing languages you should have a basic have a receiver.

ABOUT US
to better deal with native file to the JVM (for example, technical understanding of The following are the four
system capabilities. Rhino, Jython, and JRuby) invokedynamic. invoke instructions:
Another much-touted while some are new (for Note: The source code for invokestatic, which is used

change is the introduction of example, Groovy, Clojure, the examples in this article for static methods.
a new Java Virtual Machine and Fantom). can be downloaded here. invokevirtual, which is used

for methods that require


Invoking Methods on dynamic dispatch, that
the JVM is, public and protected
The JVM has traditionally methods.
offered four instructions invokeinterface, which is

for invoking methods. Each similar to invokevirtual,


points out an owner class, except that the method
a name, and a signature dispatch is based on an
description. As an example, interface type.
given a static method void invokespecial, which is for blog
baz(int a, String s) in class the other types of meth-
Julien Ponge chats with Oracles Stephen foo.Bar, invoking the method ods: constructors and
Chin about invokedynamic as part of Chins requires a reference with private virtual methods.
PHOTOGRAPH BY
MATT BOSTOCK/GETTY IMAGES NightHacking Tour across Europe. foo/Bar as the owner, baz The method dispatch is
49
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
not performed based on the methods and fields from existing common language runtime classes Method Handles
receiver type but rather based on classes. Some languages even sup- and methods. Method handles are analogous
the specified owner class (this is port doing so at the instance level. In short, because there are many to the function pointers found in
how the super reference works). For all these reasons, it is necessary different execution paths with languages such as C in the sense

JAVA IN ACTION
The design of the JVM makes to defer the resolution of classes, great variance in actual types, the that they point to a target and
perfect sense because it was methods, and fields to the runtime. adaptive runtimejust-in-time can be used to invoke it. Method
originally created for a strongly It is also necessary to dynamically (JIT) compilationhas trouble handles can be obtained and
typed language, Java. In such a update the resolved entities at run- applying optimizations. Although manipulated by using the new
language, it is sufficient to check time. Also, there is often a need for dynamic language implement- java.lang.invoke API.
method invocations at compile adapting a method invocation to a ers have used clever techniques, Getting and invoking. Listing 1 is
time. Hence, it is both easy and target of a different signature. it remains true that the JVM has an example in which we obtain
natural to produce bytecode Dynamic languages on the JVM issues understanding what such a method handle to the Boolean

JAVA TECH
where invocations unambigu- have traditionally built ad hoc code does, thus hindering perfor- startsWith(String) instance method
ously specify a target. Signature runtime support on top of the JVM. mance. The bytecode emitted by of the java.lang.String class and
descriptors exactly match those This includes using wrapper type such languages lacks information then invoke it.
of the target methods. classes; building custom inline and patterns that the JVM knows We first need an object of type
caches for invoking methods; how to optimize, which are typi- MethodHandles.Lookup to search
The Case of Dynamic Languages interpreting, tracing, and generat- cally present in bytecode gener- for targets that include virtual
Things are slightly different with ing specialized bytecode; or using ated from Java. One can argue that methods, static methods, special

ABOUT US
loosely typed dynamic languages hash tables to provide dynamic this is a matter of making the JVM methods, constructors, or field
such as Groovy, JRuby, or Jython. symbol resolution. In doing so, more aware of new patterns, but accessors.
In such languages, types are most such languages generate bytecode the fact that bytecode is typed also A lookup object is dependent
often not checked at compile with entry points to the runtime gets in the way. on the invocation context of a
time. It is up to the programmer in the form of method calls using The introduction of invoke call site. As an example, a lookup
to pass a good type, and failing either of the four existing bytecode dynamic to the JVM specifica- made in a class A cannot see the
to do so results in an error at run- instructions for invocations. tion is recognition of the fact that private methods of a class B. When
time. Thus, in such languages, the dynamic languages bring value to invoking the lookup method in
closest accurate JVM type for a Here Comes invokedynamic the Java ecosystem and, as such, Listing 1, we obtain a lookup object
method argument is more often The main problem is that of per- the JVM needs to provide bet- that respects the accessibility rules
than not java.lang.Object. It easily formance. The bytecode generated ter support for them. This new from within the main method of
follows that this complicates type by dynamic languages tends to bytecode instruction is able to Sample1. The preferred way to look
analysis (which has to be done require several actual JVM method defer the invocation target resolu- up only public methods is to call
mostly at runtime) and affects invocations in order to perform tion to some runtime logic, and it MethodHandles.publicLookup.
performance. one in the dynamic language. provides support for dynamically Once this is done, we can call blog
Dynamic languages also often There is extensive use of reflection changing call site targets. It also the findVirtual method. The first
support a form of monkey- and dynamic proxies, which have has support in the JVM internals so argument is the class in which to
patching, that is, the ability to add a performance cost. Last but not that it can be better optimized by look for the method. The second
methods and fields to and remove least, such code tends to target the JIT compiler. argument is the method name,
50
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3
while the third one is an instance of handles. This is especially useful
MethodType. Here, the method that when writing dynamic applica- package sample1;
we are looking for returns a Boolean tions where you need to look up
import java.lang.invoke.MethodHandle;
and takes a string as a parameter. elements by name, but the exact
import java.lang.invoke.MethodHandles;

JAVA IN ACTION
Note that we actually pass three signatures are not known. import java.lang.invoke.MethodHandles.Lookup;
arguments to build the type: the The example in Listing 1 with
import static java.lang.invoke.MethodType.methodType;
return type followed by the argu- method handles can be equiva-
ment types. Indeed, startsWith is lently coded as shown in public class Sample1 {
a virtual method, so its first call Listing 2, in which the target public static void main(String... args) throws Throwable {
argument must be the receiver method handle is found using Lookup lookup = MethodHandles.lookup();
type, which here is a string, too. reflection.
Finally, we perform two invoca- If we were to stop our explo- MethodHandle startsWith = lookup.findVirtual(

JAVA TECH
tions by printing whether Java and rations of invokedynamic here, String.class, "startsWith",
Groovy start with J. there would not be many dif- methodType(boolean.class, String.class));
java.lang.reflect integration. Just ferences between an invocation // Prints "true"
looking at the example in Listing 1, using reflection and one using a System.out.println(startsWith.invokeWithArguments(
you could think that method han- method handle. Still, it should be "Java", "J"));
dles can be used in place of reflec- noted that every reflective invoca- // Prints "false"
System.out.println(startsWith.invokeWithArguments(
tive method invocations. Worse, tion induces verifications at the

ABOUT US
"Groovy", "J"));
you could think that java.lang JVM level. This is not the case with
}}
.invoke is a possible replacement method handles, because those
for reflection. This is far from the verifications happen only when
truth, because both APIs comple- method handles are built. Download all listings in this issue as text
ment each other. Combinators. While method
You need to know the exact handles can directly map to class
signatures of the elements to be methods, it is possible to build Lets start with a simple exam- .invoke.MethodHandles class pro-
looked up using MethodHandles more-elaborate method handles ple. In Listing 2, we obtained a vides many combinators, that is,
.Lookup. There is no way to look for by combining several of them. This method handle to the startsWith methods to derive new method
the methods, constructors, and is useful in many situations, such method of the String class. Now, handles from existing ones. In our
fields of a class just by their names as when there is a need to adapt in Listing 3, lets instead build case, we take advantage of
without knowing their precise a call site and a target of different a method handle that checks insertArguments to bind the ele-
signatures. To do that, you should types, to process arguments and whether a string given as a receiver ment at index 1. This method
simply stick to the well-known return values, or to provide con- starts with J. works as follows: it takes a method
reflective APIs in java.lang.reflect, ditional branching. In this regard, To do this, we need to perform handle, an index where arguments blog
and then use either of the unreflect guards are an especially useful a form of partial function applica- will be inserted, and a variable
methods found in MethodHandles building block for constructing tion that binds the first invocation arguments list of values to insert.
.Lookup that provide bridging more-complex call-site logic as is argument of the method to the The other combinators can
between reflection and method found in inline caches. constant value J. The java.lang remove elements; permute ele-
51
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6 LISTING 7 LISTING 8
ments; wrap arguments to or instance method, the object would
unwrap arguments from an array; be the receiver. static void printAll(String prefix, Object... values) {
for (Object value : values) {
perform type conversions; and Then, the asCollector combi-
System.out.println(prefix + value);
more. While it is beyond the scope nator wraps arguments into a
}

JAVA IN ACTION
of this article to provide a com- collecting array. Here, we bind }
plete overview of each of these, four arguments into an array of
you will discover some commonly Object instances. Using the code
used ones if you keep reading. in Listing 8, we can check that the
Example of call site and target resulting method handle is of type Download all listings in this issue as text
adaptation. You will often run into (Object,Object,Object,Object)void
the problem of adapting call sites and that invoking it with argu-
and targets when working with ments of the expected arity works. method handles are. We can now ing a way to swap out old code

JAVA TECH
invokedynamic. Suppose that you Performance-wise, you should turn to the bootstrapping side of with new code on the fly, without
have a method printAll declared as use invokeExact rather than invokedynamic. regenerating the bytecode for an
shown in Listing 4. invokeWithArguments whenever CallSite objects. Call sites need entire method.
Clearly, printAll is of type (String, you can. invokeExact requires to be bound at runtime using the The java.lang.invoke package
Object[])void. In Java, invocations the argument types to be exactly java.lang.invoke API. To do that, offers three concrete implementa-
of this method would call sites like those of the method handle each invokedynamic instruction tions of the abstract CallSite class,
such as those shown in Listing 5. type descriptor, and it dispatches refers to a bootstrap method that and you can subclass them, too:

ABOUT US
Now suppose that we have call the call much faster. In contrast, is executed the first time the call ConstantCallSite is for call sites

sites expecting something differ- invokeWithArguments performs site invocation is executed. whose target method handle
ent, such as a method that takes type checks and conversions. The bootstrap method must never changes.
a fixed number of parameters and A classic optimization for virtual return an instance of java.lang MutableCallSite has object field

no prefix string. Clearly, the signa- methods is to build inline caches .invoke.CallSite. As the name sug- semantics, which means that
tures do not match. A fix would be where the target method handle gests, such objects represent a call the target method handle can
to introduce an adaptation method is cached as long as the receiver site, and they are bound to a target be changed.
such as that shown in Listing 6. type remains stable. You should method handle, which may, in VolatileCallSite is similar to

Such an adaptation is simple to limit the cache depth in case the turn, be a chain of combinators. MutableCallSite but with volatile
perform using method handles call site happens to be mega- The CallSite can be thought reference semantics.
and combinators, as shown in morphic; otherwise, you would of as the container for the If you need a call site where the
Listing 7. create too many method handles MethodHandle. Once it has been target can be changed, choos-
First, target is a direct method arranged in a chain of guarded bound, a call site always refer- ing between MutableCallSite
handle to the printAll static tests, which further degrades the ences the same CallSite instance. and VolatileCallSite is a matter of
method. We use the bindTo com- performance figures. Although the CallSite itself will understanding the Java memory blog
binator to bind the first argument refer to the same program point model and weighing the conse-
to a value. In the case of a static Bootstrapping throughout its lifecycle, call sites quences of choosing one versus
method, this is effectively the first At this point, you should have may allow their target method the other. In multithreaded envi-
argument, while in the case of an a basic understanding of what handle to be redefined, provid- ronments, a volatile call site target
52
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 9 LISTING 10 LISTING 11 LISTING 12
change will be immediately visible Sticking to the example in
to all threads, while with ordinary Listing 8, which obtained a public static CallSite bootstrap(Lookup lookup, String name,
MethodType type) throws Throwable {
field semantics, thread caching method handle for the printAll
MethodHandle target = lookup.findStatic(
occurs and requires explicit syn- method, the code in Listing 9
Sample3.class, "printAll",

JAVA IN ACTION
chronization (see the static would be a possible call site boot- methodType(void.class, String.class, Object[].class))
syncAll method in MutableCallSite). strap method. .bindTo(">>> ")
Of course, there are performance This method returns a non- .asVarargsCollector(Object[].class)
implications, too. modifiable call site, where the pre- .asType(type);
Bootstrap methods. invokedynamic fix string is bound to ">>>" and the return new ConstantCallSite(target);
bootstrap instructions are bound remaining arguments are collected }
by invoking a static method that as variable arguments. The result-
returns a CallSite object that must ing call site is of type (Object[])

JAVA TECH
take at least three parameters: void. Note that because a string
A MethodHandles is a constant, we could
.Lookup object that is KEY FOR LAMBDAS also obtain the prefix as
bound to the classes
visible in context of
Java 8 is an extra parameter, and
the value would depend
the call site poised to take
on what is referenced
A symbolic name as a
advantage of from the call site in the

ABOUT US
string
A MethodType that
invokedynamic as
bytecode. In this case,
the bootstrap method
corresponds to the a way to support
would be as shown in
type that is expected
by the call site (this
lambdas. Listing 10.
It is easy to test the
is often useful for bootstrap method to
performing a final verify that it works as
asType() combinator invocation intended. Indeed, call sites pro-
to ensure that method handles vide a dynamicInvoker method that
match) returns a method handle. Thus,
Other parameters can be passed you can use it as weve previously
as extra arguments, with the only seen (see Listing 11).
constraint being that they must be
constant values, which means they Emitting Bytecode with
can be written to the constant pool invokedynamic Instructions blog
of a class bytecode representation. We are now ready to assemble
This is the case for primitive types, the final pieces and actually put
strings, class references, and invokedynamic into practice. While
Download all listings in this issue as text
method handles. the java.lang.invoke API can be
53
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 13 LISTING 14
used as is, it remains to be seen for the function can be anything,
how it can be leveraged directly but it is common to normal- $ java -classpath code/build/classes sample3.Caller
>>> World
from bytecode instructions. ize names and separate portions
>>> Hello
As of Java 7, there is no language using a colon, as in property:get,

JAVA IN ACTION
construct that translates into property:set, and so on.
invokedynamic instructions at the We can run this method, as
bytecode level. This might change shown in Listing 13, and see that
in Java 8 because some of the the invokedynamic instruction is
support for lambdas is likely to be correctly bound at runtime. We
implemented with invokedynamic. can also check the generated byte-
In order to bootstrap a call site code with the javap decompiler
and leverage a method handle, we that comes as part of the JDK, as

JAVA TECH
need to use a third-party library shown in Listing 14. Download all listings in this issue as text
to write bytecode. The ASM library
is our weapon of choice, because Conclusion
it helps in reading, writing, and This article introduced invoke ing Java 6 backward compatibility language? In any case, there is no
transforming bytecode. dynamic, a new instruction backed will become less of an issue. Fresh harm in trying, and who knows
Another option for simpler cases with runtime API support for facili- language implementations, such what you might come up with.
is to use a tool such as tating the implemen- as Oracles Nashorn (JavaScript), Acknowledgements. The author

ABOUT US
Indify that can replace BETTER SUPPORT tation and execution Rmi Forax PHP.reboot, or the would like to thank Marcus
some marked call sites
with an invokedynamic The introduction of dynamic languages
on top of the JVM. The
present authors yet-to-be-
released Golo language, are based
Lagergren for his very constructive
feedback. </article>
call, but leveraging ASM of invokedynamic java.lang.invoke API on invokedynamic from the get-go.
leaves no magic behind.
Lets consider the
to the JVM provides a rich set of
operations to adapt a
Java 8 is poised to take advan-
tage of invokedynamic as a way to
code in Listing 12. specification is call site to a target that efficiently implement the sup-
The code generates a recognition of the
might be of a different port of lambdas. Finally, deriva-
sample3.Caller class as
a subclass of java.lang
fact that dynamicsignature type.
Existing dynamic
tive usagessuch as the JooFlux
research project, which provides
LEARN MORE
.Object. It has a main languages bring languages for the JVM dynamic code replacement and
Bytecodes Meet Combinators:

method that loads two value to the Java(for example, Groovy aspect-oriented programming
invokedynamic on the JVM
JooFlux: Hijacking Java 7
strings and then calls a
console:print function of
ecosystem and, asand JRuby) are start-
ing to support invoke
are starting to appear.
While invokedynamic is mostly InvokeDynamic to Support Live
type (Object, Object)void such, the JVM needs
dynamic. In the long useful to language and middleware Code Modifications blog
that is bootstrapped to provide betterrun, this should reduce implementers, let nothing restrain JSR 292 Cookbook
using the static method
that we defined earlier.
support for them.the footprint of their
runtime support code
your creativity! Are you thinking of
derivative usages? Are you think-
Dynalink: Dynamic Linker
Framework for Languages on
The symbolic name because maintain- ing about creating yet another the JVM
54
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
Java Compiler Plug-ins in Java 8

JAVA IN ACTION
Use a new plug-in mechanism to extend the Java compiler with new behavior.

J ava 8 will bring a new


mechanism that allows you
of calling get() on an object
that is a subtype of Map is
Plug-ins have a simpler
interface.
to various events gener-
ated during compilation.
to write plug-ins for the Java null. In other words we are Annotation processors This is done through the
compiler (javac). A compiler looking for patterns such as are defined by a standard method addTaskListener(),

JAVA TECH
plug-in lets you add new the following, where expr is a (JSR 269). Plug-ins are which accepts an object
phases to javac without mak- subtype of java.util.Map. javac-specific. TaskListener.
ing changes to its code base. Plug-ins require the use of Listing 1 shows com.sun
New behavior can be encap- expr.get(key) == null a ServiceLoader. .source.util.Plugin, which
RAOUL-GABRIEL URMA sulated in a plug-in and uses the getName() and call()
AND distributed for other people This pattern could be con- Java Compiler Plug-in methods. Listing 2 shows
JONATHAN GIBBONS to use. For example, javac tained within a conditional Architecture some methods available in

ABOUT US
plug-ins could be used to do expression, a return state- A javac plug-in supports two com.sun.source.util.JavacTask,
BIO
the following: ment, and so on. It should be methods: and Listing 3 shows the
Add extra compile-time reported in all cases. First, a getName() method methods available in com
checks that returns the name of .sun.source.util.TaskListener.
Add code transformations How Do Plug-ins the plug-in for identifica- But there are obvious
Perform customized anal- Differ from Annotation tion purposes questions that remain unan-
ysis of source code Processors? Second, a call() method swered, for example, how do
Note: The API for creating Here are some ways that that is invoked by the javac you start writing the com-
javac plug-ins is still experi- plug-ins differ from annota- with the current environ- piler plug-in and how do you
mental for JDK 8; it is sched- tion processors: ment it is processing run it?
uled to ship in 2013. Plug-ins are more flexible. The call() method gives
In this article, we show how They can run at various access to the compiler func- Lets Build a Compiler
you can write a simple, cus- points in the compila- tionalities through a JavacTask Plug-In
tomized source code analysis tion pipeline through a object, which allows you to The first step is to download
tool so you can learn how to TaskListener. perform parsing, type check- and build the current release blog
leverage the plug-in mecha- Plug-ins do not use the ing, and compilation. In of the Java 8 compiler, which
nisms for your own applica- model of processing addition, the JavacTask object supports compiler plug-ins.
tions. We find code patterns rounds, which incurs addi- lets you add observers (which Toward this end, download
that check whether the result tional overhead. are instances of TaskListener) the latest version and fol-
55
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
low the build instructions in the Step 2: Add a TaskListener. We
README file. are looking for a code pattern that public interface Plugin {
public String getName();
Once the compiler is built, checks whether the receiver of
public void call(JavacTask task, String[] pluginArgs);
include the generated dist/lib/ the method call get() is a subtype
}

JAVA IN ACTION
classes.jar file in your project. of java.util.Map. To get the type
Alternatively, you can download of the receiver, we need informa-
a ready-made binary from tion about the types of expres-
jdk8.java.net. sions that are resolved during the
Next, there are several steps we type-checking phase. We therefore
need to follow to build our plug-in. need to insert a new phase after
Here is a summary of the steps: type checking. Toward this end,
1. Implement the com.sun we first create a TaskListener and

JAVA TECH
.source.util.Plugin interface add it to the current JavacTask, as
shown in Listing 1. shown in Listing 5.
2. Add a TaskListener to perform We now need to create the class
additional behavior after the CodePatternTaskListener, which
type-checking phase. implements a TaskListener. A
3. Create an abstract syntax tree TaskListener has two methods,
(AST) visitor to locate binary started() and finished(), which are

ABOUT US
expressions: called, respectively, before and
a. Evaluate whether the left side after certain events. These events Download all listings in this issue as text
is a method call expression are encapsulated in a TaskEvent
with a receivers object. In our case, all we
type that is a sub- JUST PLUG IN need to do is implement rent source file analyzed in a tree CompilationUnitTree:, as shown in
type of java.util.Map.
b. Evaluate whether
Plug-ins are the finished() method
and check for an event
structure. It can be accessed with
the getCompilationUnit() method.
Listing 7.
All we have left to do is to over-
the right side is a flexible, havementioning the Analyze Our code will need to traverse ride visitBinary(BinaryTree node,
null expression. a simple phase (type checking), as this tree, locate a binary node, P p) and write the logic to verify
Step 1: Implement the
com.sun.source.util interface, canshown in Listing 6.
Step 3: Create the AST
and evaluate the nodes left and
right children. This sounds like a
the code pattern. The full code
of the visitor class with inlined
.Plugin interface. The run at variousvisitor. Next, we need to visitor pattern job. The Compiler comments is provided in Listings
first step is to create the
main class, which imple-
points in the write the logic to locate
the code pattern and
Tree API provides us with a ready-
made visitor class designed for
8a8d.

ments com.sun.source compilation report it. How do we do such tasks: com.sun.source.util Lets Run Our Compiler Plug-In blog
.util.Plugin. We return the
name of our plug-in via
pipeline, and are
that? Thankfully, a task
event provides us with
.TreeScanner<R, P>. It visits all the
nodes in the AST.
We are almost finished. The final
step is to set up a file called
the getName() method, specific to javac.
a CompilationUnitTree, First, we initialize our visi- com.sun.source.util.Plugin located
as shown in Listing 4. which represents the cur- tor object and then visit the in META-INF/services/. This file
56
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 7 LISTING 8a LISTING 8b LISTING 8c LISTING 8d LISTING 9
must contain the name of our
plug-in, CodePatternPlugin, which if(taskEvent.getKind().equals(TaskEvent.Kind.ANALYZE))
{
allows javac to load the appropriate
CompilationUnitTree compilationUnit =
plug-in.
taskEvent.getCompilationUnit();

JAVA IN ACTION
Next, using your favorite IDE or new CodePatternTreeVisitor().scan(compilationUnit, null);
the command line, create a Java }
archive (JAR) file from your project
containing the META-INF directory
and compiled class files:

$ jar cvf codePatternPlugin.jar


FIND YOUR
META-INF *.class
JUG HERE

JAVA TECH
Finally, you can run the plug-in One of the most elevating things
as shown in Listing 9, where in the world is to build up a
-processorpath indicates the community where you can hang
out with your geek friends, educate
path where the plug-in JAR file
each other, create values, and
is located give experience to you members.
-Xplugin indicates the name

ABOUT US
Csaba Toth
of the plug-in to run, which is Nashville, TN Java Users' Group (NJUG)
CodePatternPlugin, in this case
LEARN MORE
Conclusion
The new plug-in mechanism pro-
vides a simple hook to javac. You
can use it to extend javac with
new behavior. In addition, you
can distribute a plug-in with-
out making modifications to the
javac code base. In this article,
we showed how you can use this
mechanism to easily write a cus-
tomized source code analysis tool
for your applications. </article> blog

LEARN MORE
Complete project and source files Download all listings in this issue as text
on github
57
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
The New javax.cache
Caching Standard

JAVA IN ACTION
Learn how to use javax.cache.
GREG LUCK
BIO ITS SUBTLE

T he javax.cache standard own service provider inter- subtleties. A cache


While caching distributed so that

JAVA TECH
being developed by face or they support just a is a place where you the work performed
JSR 107 aims to standardize few implementationsa put a copy of data seems like a by one application
the use of caching in Java.
Why? Open source caching
situation that isnt great
for anyone. Other areas of
that is intended
to be used mul-
simple topic, server gives ben-
efit to the others
projects and commercial Java, such as JDBC, the Java tiple times. Caching there are and eliminates any
caching vendors have been
available for more than a
Persistence API (JPA), and
Java Message Service (JMS),
implementations,
being in memory,
subtleties. duplicate requests
for the same data

ABOUT US
decade. The distributed kind, have solved this problem are much faster than to the underlying
which is often called a dis- through standards. the original source of resource.
tributed cache, has entered Indeed, the analyst firm the content. This means you Finally, the affordability
wide adoption. While each Gartner recently reported that get a performance benefit of servers with memory
vendor uses a very similar the lack of a standard in this from using a cache instead of capacities of 1 TB and higher,
map-like API for basic stor- area was the single biggest the original source. You also combined with vendor inno-
age and retrieval, each ven- inhibitor to mass adoption of offload the resource that the vation to utilize that memory
dor uses its own API. data grids. At the time of this original data came from. for cache storage, resulted
At present, developers will writing, JSR 107 was in Early To be effective, data needs in a new trend in which the
incur a significant coding Draft review and expected to to be used multiple times. cache has increased opera-
cost in changing from one reach final approval toward There is no value in caching tional significance. Instead
proprietary implementation the end of 2012. data that is written once and of caching just part of a
to another. It is also chal- The code listings in this never read or read only once. data set, the entire data
lenging for independent article work with the Early The efficiency of the cache set is placed in cache and
software vendors (ISVs) to Draft version of the API (0.5). can be measured by the hit is used as an authoritative blog
introduce pluggable caching ratio, which is defined as source of informationthe
to support multiple imple- About Caching cache hits/cache requests. cache, in essence, becomes
mentations. Like develop- While caching seems like To provide the maximum the operational store for
ers, ISVs either create their a simple topic, there are offload, caches need to be the application. In this use
58
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
case, the cache is often referred to tion of Cache instances that have
as a data grid. entries. The API can be thought <dependency>
<groupId>javax.cache</groupId>
Each of these areas has require- of as maplike with the following
<artifactId>cache-api</artifactId>
ments that the standard must additional features:
<version>0.5</version>

JAVA IN ACTION
deal with. Atomic operations, similar to
</dependency>
java.util.ConcurrentMap
Who Is Adopting javax.cache? Read-through caching
At the time of this writing, JSR 107 Write-through caching
is planned to be included in Java Cache event listeners
EE 7 and developed by JSR 342. Statistics Download all listings in this issue as text
Java EE 7 is due to be finalized in Transactions including all isola-
2013. In the meantime, javax.cache tion levels

JAVA TECH
will work in Java SE 6 and higher Caching annotations include the following: zero or low-cost return types. So
and in Java EE 6 environments as Generic caches that hold a storeByReference (storeByValue is while Map has V put(K key, V value),
well as with Spring and other pop- defined key and value type the default) javax.cache.Cache has void put (K
ular environments. Support for storage by reference Transactions key, V value).
The following vendors are either (applicable to on-heap caches Annotations

active members of the Expert only) and storage by value This makes it possible for an Class Loading
Group or have expressed interest implementation to support the Caches contain data shared by

ABOUT US
in implementing the specification: Optional Features specification without necessarily multiple threads, which might
Terracotta (Ehcache) Rather than split the specification supporting all the features, and it themselves be running in dif-
Oracle (Oracle Coherence) into a number of editions targeted allows end users and frameworks ferent container applications or
JBoss (Infinispan) at different user constituencies, to discover the features so they Open Services Gateway initiative
IBM (ExtremeScale) such as Java SE or Spring and can dynamically configure appro- (OSGi) bundles within one Java
SpringSource (Gemfire) Java EE, we have taken a different priate usage. Virtual Machine (JVM) and might
GridGain approach. be distributed across multiple
TMax First, for Java SEstyle caching, Good for Simple Caches to JVMs in a cluster. This makes class
Fujitsu (Interstage XTP) there are no dependencies. And Data Grids loading tricky.
Terracotta, Oracle, and JBoss are for Spring and Java EE, where you While the specification does not We have addressed this problem.
all planning releases upon finaliza- might want to use annotations and mandate a particular distributed When a CacheManager is created,
tion of the spec. In addition, Spring transactions, the dependencies will topology, it is cognizant of the fact a class loader can be specified. If
plans to support JSR 107 closer to be satisfied by those frameworks. that data storage might be distrib- none is specified, the implementa-
its final release. Second, we have a capabilities uted. We have one API that cov- tion provides a default. In either
API via ServiceProvider ers both usages but is sensitive to case, object deserialization will blog
Main Features .isSupported(OptionalFeature distributed concerns. We do not use the CacheManager instances
From a design point of view, the feature) so you can determine at have high-network-cost maplike class loader.
basic concept is a CacheManager runtime the capabilities of the methods, such as keySet() and This is a big improvement over
that holds and controls a collec- implementation.Optional features values(). And we generally prefer the approach taken by caches
59
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 7 LISTING 8 LISTING 9 LISTING 10 LISTING 11
such as Ehcache that use a fall- example, as shown in Listing 3.
back approach. With a fall-back Implementations can also sup- Cache<Integer, Date> cache = cacheManager.getCache("testCache");
approach, first, the threads con- port direct creation with new for
text class loader is used, and if that maximum flexibility, as shown in

JAVA IN ACTION
fails, another class loader is tried. Listing 4.
This can be made to work in most Or, to do the same thing without
scenarios but is a bit hit-and- adding a compile-time depen-
miss and varies considerably by dency on any particular imple-
implementation. mentation, use the code shown in
Listing 5.
Getting the Code We expect implementations to Download all listings in this issue as text
The spec is in Maven central. The have their own well-known config-

JAVA TECH
Maven snippet is shown in Listing 1. uration files, which will be used to
configure the CacheManager. The Basic cache operations. To put @CacheResultUse the cache.
A Cooks Tour of the API: name of the CacheManager can be data in a cache, use the code @CachePutPut into the cache.
Creating a CacheManager used to distinguish the configura- shown in Listing 8. To get data @CacheRemoveEntryRemove a
We support the Java 6 java.util tion file. For Ehcache, this will be from a cache, use the code shown single entry from the cache.
.ServiceLoader creational approach, the familiar ehcache.xml placed in Listing 9. To remove data from @CacheRemoveAllRemove all
which will automatically detect at the root of the classpath with a a cache, use the code shown in entries from the cache.

ABOUT US
a cache implementation in your hyphenated prefix for the name of Listing 10. When the required cache name,
classpath. You the CacheManager. So, the default key, and value can be input, they
then create a CacheManager will simply be Annotations are not required. See the Javadoc
CACHE THIS
CacheManager ehcache.xml and myCacheManager JSR 107 introduces a standardized for the details. To allow greater
The API with the code will be app1-ehcache.xml. set of caching annotations, which control, you can specify all these
supports shown in
Listing 2,
Creating a cache. The API supports
programmatic creation of caches.
perform method-level caching
interception on annotated classes
operations and more.
In the example shown in
programmatic which returns This complements the usual con- running in dependency injection Listing 11, the cacheName attribute
creation of a singleton vention of configuring caches containers. Caching annotations is specified to be domainCache,
caches. This CacheManager
called Wdefault_.
declaratively, which is left to each
vendor.
are becoming increasingly popular,
starting with Ehcache Annotations
index is specified as the key, and
domain is specified as the value.
complements the Subsequent calls To programmatically configure for Spring, which influenced The Reference Implementation
usual convention return the same
CacheManager.
a cache named testCache, which is
set for read-through, use the code
Spring 3s caching annotations.
Spring plans on supporting the
includes an implementation for
Guice, Spring, and Contexts and
of configuring CacheManager shown in Listing 6. new standard annotations in addi- Dependency Injection (CDI). CDI is blog
caches instances can Getting a reference to a cache. You tion to its own. the standardized container-driven
declaratively. have names and
class loaders
get caches from the CacheManager.
To get a cache called testCache, use
The JSR 107 annotations cover
the most-common cache opera-
injection introduced in Java EE 6.
The implementation is nicely
configured, for the code shown in Listing 7. tions, including the following: modularized for reuse and uses
60
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//java architect /

COMMUNITY
LISTING 12 LISTING 13 LISTING 14
an Apache license; therefore, we
expect several open source caches public class BlogManager {
to reuse the implementation.
@CacheResult(cacheName="blogManager")
Annotation example. The example
public Blog getBlogEntry(String title) {...}

JAVA IN ACTION
in Listing 12 shows how to use
annotations to keep a cache in @CacheRemoveEntry(cacheName="blogManager")
sync with an underlying data public void removeBlogEntry(String title) {...}
structure, in this case a blog man-
ager, and also how to use the @CacheRemoveAll(cacheName="blogManager")
cache to speed up responses, done
with @CacheResult.
public void removeAllBlogs() {...} FIND YOUR
Wiring up Spring. For Spring, the @CachePut(cacheName="blogManager")
JUG HERE

JAVA TECH
key is the configuration line shown public void createEntry(@CacheKeyParam String title,
in Listing 13, which adds the cach- @CacheValue Blog blog) {...} My local and global JUGs
ing annotation interceptors into are great places to network
the Spring context. Listing 14 @CacheResult(cacheName="blogManager") both for knowledge and work.
public Blog getEntryCached(String randomArg, My global JUG introduces
shows a full example.
@CacheKeyParam String title){...} me to Java developers all
Spring has its own caching over the world.
annotations based on earlier work

ABOUT US
} Rgina ten Bruggencate
from JSR 107 contributor Eric JDuchess
Dalquist. Those annotations and
JSR 107 will happily coexist. Download all listings in this issue as text LEARN MORE
Wiring up CDI. First, create an
implementation of javax.cache
.annotation.BeanProvider and then Java. A rich variety of commercial Java EE 6 and 7, and other frame-
instruct CDI where to find it by and open source implementa- works such as Guice and Spring,
declaring a resource named javax tions will be available, which enterprises should consider using
.cache.annotation.BeanProvider should ensure very broad adop- it for future projects. </article>
in the classpath at /META-INF/ tion. The standard accommo-
services/. dates simple in-process caches
For an example using the Weld but will also provide the primary LEARN MORE
implementation of CDI, refer to API for storage into and retrieval JSR 107 home page
the CdiBeanProvider in our CDI from data grids. JSR 107 status
test harness. Those with a need to use a cache blog
or a data grid should look to adopt
Conclusion the specification upon its release
The javax.cache specification stan- to avoid vendor lock-in. Because
dardizes a long-overdue area of the standard works with Java SE,
61
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
Secure Java EE Authentication

JAVA IN ACTION
Implement login authentication using declarative and programmatic security.

ADAM BIEN J ava EE security is easy,


powerful, extensible, and
is impossible in a single
articlethis article focuses
allows a chosen group of
people called dukes to
annotation. You could also
use an XML deployment
sufficient for the vast major- on the most-common use change the message. descriptor for this purpose.
ity of all use cases. This cases: login authentication All HTTP-GET requests The @PermitAll annotation

JAVA TECH
BIO article discusses RESTful methods with declarative of the wisdom URI should allows all users to execute an
services secured with stan- and programmatic security. be available to everyone, annotated method, and the
dard Java EE capabilities, and Note: Some relevant example whereas only members of @RolesAllowed annotation
it demonstrates a domain- code can be found here. the dukes group should be restricts access to the speci-
specific extension imple- able to execute the @POST fied roles.
mented with Contexts and Setting the Stage method shown in Listing 1.
Dependency Injection (CDI) For the purposes of this REST resource implemen- Authentication as Aspect

ABOUT US
and Enterprise JavaBeans article, we will implement a tations are usually heavily So far, the user is not going
(EJB) 3. system that, by default, dis- dependent on the JAX-RS to be authenticated. Without
Instead of covering all plays some wisdomthe API, which encourages the authentication, the current
authorization and authen- message Java Programming introduction of an explicit user is not going to be iden-
tication aspectswhich Language Rocks!and managed bean responsible tified as a Principal with its
for the message manage- configured roles member-
ment. The WindowStorage ship. In the case of GlassFish,
bean is declaratively secured a nonauthenticated user is
with @RolesAllowed annota- associated with a Principal
tions (see Listing 2). with the ANONYMOUS name.
The parameterless wisdom Fortunately, most of the
method can be executed Web frameworks, and so also
by anyone, but only a user the JAX-RS API, are Servlet-
in the dukes role is allowed based. Servlets come with an
to change wisdom by pass- easy way to authenticate a blog
ing a string as parameter. user with a single invocation
Adam Bien talks with Oracles Stephen Chin All used roles have to first of the method HttpServlet
PHOTOGRAPH BY about his current projects as part of Chins be declared on the class Request#authenticate. The
THOMAS EINBERGER/
GETTY IMAGES NightHacking Tour across Europe. level with the @DeclareRoles entire procedure can be
62
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
extracted into a reusable Web a static HTML page to perform the
filter, as shown in Listing 3. authentication. @Stateless
@Path("wisdom")
With the annotation
@Produces(" text/plain") // MediaType.TEXT_PLAIN
@WebFilter("/*"), the filter inter- What Is file?
public class WisdomResource {

JAVA IN ACTION
cepts all requests. The crux of the Within the web.xml deployment
Authenticator filter is the invoca- descriptor, a realm with the name @Inject
tion of the authenticate method. file is referenced. A realm is a user WisdomStorage storage;
repository containing the secu-
Where Annotations End and rity credentials as well as the roles @GET
XML Starts membership. A concrete realm public String wisdom() {
In the old Java EE tradition, no realization is not specified by the return storage.wisdom();
single XML line has been written Java EE specification. Usually, }

JAVA TECH
so far. Unfortunately, we will have application servers tend to support
to specify a few lines in web.xml file, database, and LDAP realms out @POST
(see Listing 4) to configure which of the box, and they support a large @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
authentication method will be number of extensions to cover a @Produces(MediaType.TEXT_HTML)
used and from which realm the wide variety of legacy resources. For public String wisdom(
authentication and authorization demo purposes, well later create @FormParam("wisdom") String wisdom) {
storage.wisdom(wisdom);
information is fetched. a file realm with the name file and

ABOUT US
return "thanks!";
The error-page section is needed a user with the name james and
}
only to display for the user a nicer membership to the dukes role. }
message than an Internal Server As an enterprise developer,
Error 500 message. Because of you cannot fully rely on concrete
its flexibility, form-based login names existing in the production
configuration is the most popular. repository. Instead of hardcoding
To pass the username and pass- volatile role names into your code,
word to the system, you only have you can use fictive role names and
to use j_security_check as a name map them to the actual ones in
of the action and j_username and the deployment descriptor.
j_password to pass the username Logical roles that come with the
and password, respectively. In our application are called groups. The
example, the form is implemented Java EE spec foresees the mapping Download all listings in this issue as text
as a static HTML page, as shown in of roles to groups in the deploy-
Listing 5. ment descriptor. Of course, such blog
Of course, you could equally a decoupling works only in cases the actual role naming in the of GlassFish, an automatic role-
well pass the information directly where roles and groups with dif- target realm, you can also con- to-group mapping can be speci-
with the POST call programmati- ferent names are semantically ventionally use the roles as groups fied directly in the security realm
cally. You are not limited to using equivalent. If you can influence and omit the mapping. In the case configuration.
63
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
LISTING 6 LISTING 7
Who Is Responsible for the ExceptionMapper implementation
401 Error? will be automatically discovered @Provider
public class AccessLocalExceptionMapper implements
The error-page section in web.xml and activated.
ExceptionMapper<AccessLocalException> {
specifies a redirect to an unau-
@Context HttpServletRequest request;

JAVA IN ACTION
thorized .html page upon any When Declarative Is
occurrence of the HTTP 401 error. Not Enough @Override
Although such a centralized re- So far, all role names were bound public Response toResponse(AccessLocalException exception) {
direct is useful and nice, the HTTP to the methods declaratively. Every try {
401 error will never happen in our declaration change requires a full request.logout();
sample code. recompilation and redeployment. } catch (ServletException ex) {
Every serious blogger would love Instead of hardcoding the role }
to change the Java Programming names in the annotations, they return Response.status(Response.Status.UNAUTHORIZED).build();

JAVA TECH
Language Rocks! wisdom to can be accessed programmatically. }
something like Java Is the New With an injected SessionContext, }
COBOL! Any attempt to do so the role membership can be
would result in error 500 with out- verified at runtime with the
put like the following, but it would SessionContext#isCallerInRole invo-
never result in error 401: cation. The Principal instance rep-
resenting the current user can be

ABOUT US
javax.servlet.ServletException: directly injected into any managed
javax.ejb.AccessLocalException: bean that allows implementation
Client not authorized for this of a finer-grained authorization, as
invocation shown in Listing 7.
In contrast to the declarative
Fortunately, JAX-RS comes with approach, the role can be chosen
a clean way to map any exceptions at runtime from the set of declared
into sensible HTTP error codes. The roles and changed without recom-
AccessLocalExceptionMapper class pilation. However, the permission
is responsible for the conversion management has to be directly
of any AccessLocalException into performed in the security realm Download all listings in this issue as text
the 401 error code. On each occur- and might be hard to implement
rence of AccessLocalException, the in the real world.
active user is also logged out (see of the unique user identification fetched from a custom realm
Listing 6). Producing More Flexibility requirement, the username can implementation, and evaluated blog
Beyond marking the on the Fly also be used as a unique identifier. at runtime. Usually, the additional
ExceptionMapper implementation The Principal name is usually a Any arbitrary information from a security information is closely
with the @Provider annotation, no username, which in turn is used custom permission store can be related to the target domain. There
further configuration is needed. An as user identification. Because associated with the username, is no significant domain complex-
64
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
LISTING 8 LISTING 9 LISTING 10 LISTING 11 LISTING 12
ity in our example, so we will use A user populated with a cus-
only generic permissions: tom set of permissions needs to @Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
be conveniently exposed to the
public class InMemoryPermissionsRealm {
public enum Permission { application code in order to be

JAVA IN ACTION
READ,WRITE,EXECUTE; useful. For the population of the private Map<String,EnumSet<Permission>> customStore;
} user instance with the externally
stored permissions, the name @PostConstruct
In the real world, you can attach of the currently active user is public void populateRealm(){
to a Principal whatever is beneficial needed. The class UserProvider this.customStore =
for the realization of your require- uses the username stored in new HashMap<String, EnumSet<Permission>>();
mentsit doesnt have to be a the injected Principal instance this.customStore.put("james",
Permission. It can be any flat or to instantiate a User with the EnumSet.allOf(Permission.class));

JAVA TECH
hierarchical data structure. Usually Permission instances from the this.customStore.put("blogger",
the custom permissions are going InMemoryPermissionsRealm (see EnumSet.noneOf(Permission.class));
to be maintained in a persistent Listing 10). }
store separately. For demonstra- Now a user instance with cus-
tion purposes, the Permission tom permissions can be conve- public EnumSet<Permission> getPermissionForPrincipal(
instances are maintained in an niently injected into any Java EE String userName){
EnumSet<Permission> configuredPermissions =
in-memory custom realm imple- component:

ABOUT US
this.customStore.get(userName);
mented as a singleton EJB bean, as
if(configuredPermissions != null) {
shown in Listing 8. public class SomeComponent {
return configuredPermissions;
In the real world, @Inject }
you could extend the User currentUser; else {
InMemoryPermissionsRealm to } return EnumSet.noneOf(Permission.class);
access the per- }
sistent store Declarative Authorization with }
KILLER USE CASE
and cache the Even More Aspects }
Authentication results. For Although a User instance popu-
and authorization reasons of con-
venience, the
lated with custom permissions
can be injected to all instances
are one of the generic set of participating in the call stack, the
Download all listings in this issue as text
few killer use Permissions is handling is still insufficiently con-
cases that can wrapped with a
more meaning-
venient. You would have to ask
the User for authorization each
that can be solved with aspects.
Instead of repeatedly asking the
The AllowedTo annotation car-
ries a Permission array and can be blog
be solved with ful class rep- time you are planning to invoke User for permission, a guarded directly applied on business meth-
aspects. resenting the
user, as shown in
a guarded method. However,
authentication and authorization
method can be denoted with a
plain annotation, as shown in
ods (see Listing 12). The actual
checks were factored out into an
Listing 9. are one of the few killer use cases Listing 11. interceptor, which compares the
65
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
LISTING 13 LISTING 14 LISTING 15
value of the Permission annotation the generic Guard to the EJB API.
with the permissions of the active An additional ExceptionMapper public class Guard {
user, as shown in Listing 13. implementation converts any
@Inject
An interceptor has access not SecurityException into an HTTP 401
Instance<User> users;

JAVA IN ACTION
only to the methods but also error code and logs out the user, as
to all parameters. In addition, shown in Listing 14. @AroundInvoke
the User is injectable to Java EE The SecurityExceptionMapper public Object validatePermissions(
components. With custom per- class is a 1:1 copy of InvocationContext ic) throws Exception{
missions and direct access to AccessLocalExceptionMapper, but Method method = ic.getMethod();
the business logic, it is still a slightly better User user = users.get();
instance-based autho- solution than introduc- if(!isAllowed(method, user)){
STRONG COMBO
rization can be eas- ing a dependency on throw new SecurityException("User " + user + " is "

JAVA TECH
ily realized. Usually, The combination
the EJB API. A JAX-RS + "not allowed to execute the method " + method);
the challenges are
not Java EE limita-
of built-in ExceptionMapper is
a great way to re-
}
return ic.proceed();
tions, but rather a deep security with duce the exception- }
understanding of the CDI and Servlet
handling plumbing
boolean isAllowed(Method method,User u) {
target domain. While
it is straightforward
API capabilities
inside the resource
classes. Alternatively,
AllowedTo annotation = method.getAnnotation(
allows a portable

ABOUT US
AllowedTo.class);
to give only specified a redirect to the unau-
if(annotation == null) {
users permission to
access particular rows
implementationthorized page could
also be specified in the
return true;

in the table, it is signifi- of custom web.xml file based on


}
Permission[] permissions = annotation.value();
cantly harder to find an authorization the exception type, not for (Permission permission : permissions) {
elegant abstraction in
practice. schemes with only
on a status code (see
Listing 15).
if(u.isAllowed(permission)){
return true;
a few lines of code. }
The Very Last Aspect Whats Left }
All attempts to access a Java EE 6 authoriza- return false;
guarded method with- tion and authentica- }
out a valid permission result in a tion comes with surprising power }
SecurityException, which will again and flexibility. The vast majority
cause an ugly Internal Server of mainstream use cases can be
Error 500 message. We could solved efficiently out of the box blog
throw an AccessLocalException to without any extensions or librar-
reuse the already implemented ies. However, third-party frame-
AccessLocalExceptionMapper, but works such as OpenAM, JBoss SSO, Download all listings in this issue as text
it would unnecessarily tighten or Apache Shiro come with custom
66
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//enterprise java /

COMMUNITY
realm implementations that offer .PolicyConfiguration (14 methods)
connectivity to a variety of stores and the abstract class javax
and APIs. The form-based authen- .security.jacc.PolicyConfiguration
tication discussed here is the most Factory (3 methods). Custom JACC

JAVA IN ACTION
popular, but it is not the only one implementations are often used to
available. Also, the insecure Basic, plug external authentication and
the slightly more secure Digest, authorization products in a por-
and the secure but harder-to- table way. </article>
deploy Certificate authentications
are available but less common
in practice. In particular, RESTful LEARN MORE
interfaces are heavily based on

JAVA TECH
Real World Java EE Patterns
URIs and can be conveniently
Rethinking Best Practices, Re-
secured by restricting accessibility
Injector and Aspect chapters
to a certain URI and method with

FIND YOUR
(press.adam-bien.com, 2012)
the web-resource-collection tag in
web.xml. Java Magazine article Who Needs
Aspect-Oriented Programming?
Conclusion Contexts and Dependency
JUG HERE

ABOUT US
The combination of built-in Injection in Java EE 6
security with CDI and Servlet API Java Magazine article Convention
CEJUG is celebrating our 10-year anniversary
capabilities allows a portable over Configuration in Java EE 6 in 2012! We follow Java technology with
implementation of custom autho- passion, share knowledge with pleasure,
rization schemes with only a few and create opportunities for students and
lines of code. Even the way the professionals with ambition.
application server resolves the Hildeberto Mendona
roles and principals and enforces The Cear Java User Group (CEJUG)

the rules is specified with the


Java Authorization Contract for LEARN MORE
Containers (JACC) specification.
JACC has been part of Java EE since
J2EE 1.4 and has to be imple-
mented by every certified applica-
tion server. blog
You could completely change
authentication and authoriza-
tion with the implementation of
the interface javax.security.jacc
67
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
Integrating Web and Java Client
Applications with Social Media

JAVA IN ACTION
Learn how to integrate your application with existing social network systems.
JOHAN VOS

T oday, many IT projects on the Web and beyond. In this article, we show User information: Appli-

JAVA TECH

BIO need to integrate with While social media often how you can easily integrate cations can benefit from
social media, for example, present themselves as your Web and Java client additional user informa-
Facebook and Twitter. easy-to-use services to the applications with existing tion that is already avail-
Buttons with text such as end user, a deep integra- social media. able in the users profile on
Log in via Twitter or Post tion at the API level requires social media. Applications
to Facebook are everywhere consideration. Social Media dont have to ask for this
There are a number of rea- informationalthough

ABOUT US
sons why a Web or client the social network will ask
application might benefit users if they want to share
from integrating with exist- this information with the
ing social media: application.
End users dont need to The level of integration
maintain additional cre- varies among applications
dentials. Instead they from easy to more challeng-
can log in using their ing and might be described
Facebook/Twitter creden- as follows:
tials. It is a big hurdle when Public information, using

people have to create yet anonymous access


another account with yet Authentication

another password for a Read

new service. Write

The viral aspect: Social blog


media is about networking. Anonymous Access
People see what their peers Most social media provide
are doing, and they might limited, anonymous access
PHOTOGRAPH BY
TON HENDRIKS Figure 1 want to do the same. to some services. As such,
68
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
LISTING 1 LISTING 2
integration with a social network is Your application
no different from integration with The end user curl
"http://api.twitter.com/1/users/lookup.json?screen_name=java"
any other external Web service. Via Authenticated access to
curl "http://graph.facebook.com/JavaChampions"
a cURL command, the informa- resources might seem more com-

JAVA IN ACTION
tion can easily be retrieved using plex, but it comes with a number
command-line requests, as shown of benefits. The application knows
in Listing 1. the end user and has access to
The first call will retrieve tweets interesting information that can be
that are tagged with java and valuable for its own purposes. To
return the result in JSON for- access user-specific information,
mat. The second call will return the social network often requires
the public part of the profile of that your application does this on

JAVA TECH
the Java Champions group on behalf of the user. Typically,
Facebook. A very basic Java pro- OAuth 1, OAuth 2, or a similar pro-
gram can be used to query Twitter tocol is used for this. It is beyond
and Facebook in order to retrieve the scope of this article to explain
information that is accessible OAuth in depth. Interested readers
without authentication, as shown can refer to the specification docu-
in Listing 2. ment for OAuth 1 and to the draft

ABOUT US
version of OAuth 2.
Authentication In general, an application is
Typically, information that is avail- allowed to make private calls only
able without a user having to log when the end user allowed it (see
in on a Website is also available Figure 1). This explains messages
via an anonymous, nonauthenti- such as this application wants to
cated API call. Thus, this informa- post on your timeline and this
tion can be retrieved easily by Java application wants to read your
applications. It should be noted, e-mail.
though, that most social media Rather than asking the user for Download all listings in this issue as text
sites impose volume restrictions. permission for every single call,
For example, you can make only the application is often granted
2,000 API calls per day or you can one user access token per user application grants sufficient access a browser application, users are
track only 10 users simultaneously. by a specific social network. All rights to the requested resource, redirected to a login page at the
Privateand often more inter- requests that the application for example, to read the social social network where they grant or blog
estinginformation is accessible makes on behalf of a specific user graph or to post tweets. deny permissions. The social net-
only by using authentication that are then signed using that token. Obtaining a user access token work and the application commu-
involves three parties: The social network then verifies is a multistep process, which is nicate via a multiphase protocol,
The social network whether the token provided by the described here for OAuth 1.0. In and the end result is the applica-
69
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
tion obtaining a user access token. DaliCore different social media. By
Users are then redirected from the DaliCore is an open source using DaliCoreSocial, an
application to the social network project that adds the concepts of application developer is
and back. Schematically, this is user, content, group, and permis- shielded from the rather

JAVA IN ACTION
shown in Figure 2. sion on top of the Java EE 6 speci- complex flow that is
Before an application can fication. The goal of DaliCore is to required for authenticat-
request that users authenticate make it easier to develop appli- ing a user with a social
themselves with social media, the cations that involve users and network.
application needs to be registered content, organize them in groups, A user of a social net-
with the social network. Every and assign and check permis- work corresponds to an
social network has its own registra- sions. A high-level overview of instance of com.lodgon
tion process, but the following are the DaliCore architecture is .dali.core.social.entity

JAVA TECH
a number of common concepts: shown in Figure 3. .OnlineAccount. A single
The application needs to provide DaliCore defines the concept of a user can be linked to zero
a callback URL that will be called user in the class com.lodgon.dali or more OnlineAccount
by the social network upon suc- .core.entity.User. Operations on the instances (for example, Figure 3
cessful authentication. user concept are defined in the an OnlineAccount for
The application is granted a stateless session bean com.lodgon Facebook and an OnlineAccount getStream

consumerKey and a consumer .dali.core.ejb.UserBean. for Twitter). postStatus

ABOUT US
Secret or a public key and a pri- The DaliCore project contains The business functionality pro- In order to couple an
vate key; terminologies tend to a module DaliCoreSocial, which is vided by DaliCoreSocial is available OnlineAccount to a User or create
vary between different social particularly useful in facilitating in the stateless session bean com a new User with an OnlineAccount,
media. This key combination is the above-mentioned process of .lodgon.dali.core.social.ejb the end user needs to connect with
used when signing requests. obtaining user access tokens for .SocialBean. This session bean a social network. As mentioned
contains functionality for finding before, an application needs to reg-
which OnlineAccount instances ister itself with each of the social
are coupled with a particular User media it wants to communicate
instance, for example: with. The registration process is
findOnlineAccount specific to each social network. For
findOnlineAccountByUser example, registering your applica-
Also, DaliCoreSocial provides tion with Twitter requires you to log
functionality that applications can in at http://dev.twitter.com and
use to retrieve information from register the application, as shown
a social network or to push infor- in Figure 4. blog
mation to a social network, for After registering successfully
example: with a social network, the applica-
getFriends tion is granted a key and a secret.
Figure 2 getStatus DaliCoreSocial requires these keys
70
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
LISTING 3

<context-param>
<param-name>dalicore.social.facebook.consumerkey</param-name>
<param-value>123460584819473</param-value>
</context-param>

JAVA IN ACTION
<context-param>
<param-name>dalicore.social.facebook.consumersecret
</param-name>
<param-value>1234bbcb1e33406cb1973e9322396e69</param-value>
</context-param>
<context-param>
<param-name>dalicore.social.twitter.consumerkey</param-name>
<param-value>abcdc9ww7iVWygvgDmxmw</param-value>

JAVA TECH
</context-param>
<context-param>
<param-name>dalicore.social.twitter.consumersecret
</param-name>
<param-value>abcdKj2k77jfZgPpwR3eyd4Sgkrm3ZnFDLaOw7VU
</param-value>
</context-param>

ABOUT US
Download all listings in this issue as text
Figure 4

to be available in the web.xml file cation, the social network wants Application Logic cessfully logging in. DaliCoreSocial
in the format shown in Listing 3. to call a callback URL, and this The demo application, called will add to the callback function
DaliCoreSocial can be used by URL should be under the control ConnectSimple, is a Maven project. a query parameter that is a com-
Web applications as well as by of the application. Fortunately, The dependency on DaliCoreSocial bination of a key (uid) and a value
JavaFX applications, as shown in DaliCoreSocial takes care of this, in the pom.xml file of the project (the user ID of the logged-in user).
Figure 5. so JavaFX developers can focus on guarantees the availability of the In case the callback value is omit-
If a Web application is required, their JavaFX client code. REST endpoint required for logging ted, the user ID for the logged-in
DaliCoreSocial can easily be We will now build a very simple in to a social network. The location user will be returned.
bundled with the specific Web application with a Web client and of this handler is /dalicoresocial/ When a user connects to a
application. If the application is a JavaFX client, which allows end connect{network}?callback={some_ social network for the first time
a Java client application, a back- users to authenticate themselves page}, where {network} can be using the above-mentioned REST blog
end component is still necessary, via Twitter or Facebook. The appli- twitter, facebook, or googleplus. endpoint, an OnlineAccount will be
because most social media require cation will subsequently show a If a value for the callback param- created. In case the user is not yet
a static callback URL to be avail- list of friends on a Web page or in eter is specified, the user will be known, a User instance will auto-
able. Upon successful authenti- the JavaFX application. redirected to this page after suc- matically be created as well. The
71
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
connect/twitter?callback=BASE/
rest/demo/callback
BASE/rest/dalicoresocial/
connect/googleplus?callback=

JAVA IN ACTION
BASE/rest/demo/callback
The whole authentication flow
(including retrieval of a user access
token) is done by DaliCoreSocial.
When the user is authenticated
and the social network allows our
application to access the user
information, an OnlineAccount is

JAVA TECH
created and the user is redirected
to BASE/rest/demo/callback.
Our application contains a REST
handler class named Handler.java,
which is annotated with the
@Path annotation to indicate that
it listens to REST requests that

ABOUT US
start with demo:

Figure 5 @Path("/demo")
@ManagedBean
user corresponding to a specific Our demo application contains Web Example public class Handler {
user ID can be obtained by calling two REST handlers: The Web application contains a
the following: Handler.java is used by the Web home.jsp file that contains three }
example. The responses of the images: a Facebook image, a
UserBean.getByUid( method calls are Jersey Viewable Twitter image, and a Google+ Note that the class is also anno-
String uid); instances, which create HTML image. Clicking one of those tated with @ManagedBean in order
pages. images will direct the user to the to easily use the stateless session
The friends of a specific user can API.java is used by the JavaFX start of the login flow at one of the beans UserBean and SocialBean:
be retrieved by calling the follow- example. The responses of the following, which will then direct
ing method, which will return the method calls are in XML or JSON the user to the specific social net- @Inject
friends of the user for a specific format and can be processed work login page: SocialBean socialBean; blog
network: by any client capable of doing BASE/rest/dalicoresocial/ @Inject
XML/JSON processing. connect/facebook?callback= UserBean userBean;
SocialBean.getFriends( The functionality provided by BASE/rest/demo/callback
String uid, String network); both REST handlers is similar. BASE/rest/dalicoresocial/ The callback method is anno-
72
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
LISTING 4 LISTING 5 LISTING 6
tated with the @Path ("callback") JavaFX Example
annotation and will be called We will now show how a JavaFX List<OnlineAccount> onlineAccounts =
socialBean.findOnlineAccountsByUser(user.getId());
when the user is redirected to application can access informa-
BASE/rest/demo/callback. This tion in social media, leveraging

JAVA IN ACTION
method is called by DaliCoreSocial the same principles as in the case
after the social network redirects of a Web application. Our JavaFX
the user back to our application. example contains five classes:
DaliCoreSocial adds to the callback ExternalNetworkFX is the main

a query parameter, uid, which con- class. This class, which also con-
tains the unique identifier for the tains the functionality for com-
created user. The callback method municating with the back end
will retrieve the user linked to the using REST, contains the current

JAVA TECH
unique identifier by using the fol- state of the application (for Download all listings in this issue as text
lowing code: example, logged-in user and list
of friends). In typical business
User user = userBean.getByUid(uid); applications, this functionality JavaFX comes with a WebView where network is either facebook,
belongs to separate classes. For component. We can use a twitter, or googleplus, depend-
The OnlineAccount instances simplicity, we combined most WebView for the Web-based user ing on which framework we want
associated with the user are of the controller and the model authentication to a social network. to connect. In our code, this is

ABOUT US
obtained by calling the code parts into a single class. Once the user is authenticated, achieved for the Facebook button
shown in Listing 4. ProfilePane is the class that we want to use instances of the using the code in Listing 6.
Both the user and the list of describes the layout of the pane plain JavaFX Node in order to ren- For the Twitter button and the
OnlineAccount instances are put that is shown once the user has der information, for example, a Google+ button, a similar snip-
in a Model class, which is a POJO been successfully authenticated. list of the users friends. As a con- pet applies. The WebView will now
that holds a user and the list of UserDetail is the class describing sequence, information about the point to the Facebook login page,
OnlineAccount instances. Next, a the layout for a single user. logged-in user needs to be trans- as shown in Figure 6.
Jersey Viewable instance is created User and Friend are two classes ferred from the WebView to the After the user grants the per-
by calling new Viewable("/accounts that hold data for the current other JavaFX components. We will missions, the social network will
.jsp", model); and this Viewable user and the list of friends. build an application that allows make a call to the DaliCoreSocial
is returned. This will cause the The typical flow in social this. The code for the application back end. DaliCoreSocial will
accounts.jsp Web page to be dis- networkbased authentication can be downloaded here. continue with the OAuth flow,
played, and the information avail- leverages Web components. The First, we add three image but- and a user access token will be
able in the Model instance can application redirects the end tons that have the Facebook, obtained. DaliCoreSocial then
be rendered in the Web page, as user to the login page of a social Twitter, and Google+ icons. checks whether the logged-in blog
shown in Listing 5. network, and upon successful Clicking any of those buttons cre- user already exists in the applica-
The full code for this example is authentication, the social network ates a WebView, and the location tion and, if not, an OnlineAccount
downloadable here and can also redirects the end user back to of the WebEngine is set to SERVER/ is created and coupled to a newly
be viewed online. the application. dalicoresocial/connect/{network}, created User entity.
73
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
LISTING 7 LISTING 8 LISTING 9

Node item = webEngine.getDocument().getChildNodes().item(0);


String uid = item.getTextContent();

JAVA IN ACTION
JAVA TECH
Download all listings in this issue as text
Figure 6

Again, note that in case the put the UUID of the user in the example, the Twitter or Facebook The RestRequestBuilder will cre-

ABOUT US
authentication flow begins with a response object. We can read this account. DaliCoreSocial keeps track ate a NetworkSource that makes
call to [SERVERBASE+"/connect/ UUID by parsing the Document of the OnlineAccount instances (for a request to the back end and
facebook/{uid}"], the created Object Model (DOM) in the result example, a Twitter or Facebook calls the method associated with
OnlineAccount will be coupled to page, as shown in Listing 7. account) that are coupled to this the rest/api/friends/{uid} path.
the existing user with the cor- The obtained uid is an identifier user. As described earlier in the The ObjectDataSourceBuilder cre-
responding uid, which is a UUID. for the logged-in user, Application Logic sec- ates an ObjectDataSource that
Because no callback was specified and we can now start EASY, OR NOT tion, the rest request will will parse the result of the REST
in the initial call, DaliCoreSocial working with it. For exam- The level of return all the friends that call. We assume the informa-
will respond to the client with the
UUID of the logged-in user.
ple, the friends of a user
can be obtained by mak-
integration are on all this users cou-
pled networks. The code
tion will be available in XML, and
the different entities are tagged
In the JavaFX application, we ing a call to the following between an snippet in Listing 8 shows with the name friend. The enti-
want to be notified when the loca- REST endpoint: application and how to obtain the friends. ties are converted to instances of
tion of the WebEngine starts with
the callback URL of our applica- GET /api/friends/{uid}
social media We used the DataFX
framework for making a
the Friend class and added to the
ObservableList<Friend> friends.
tion. After successful authen- varies from call to a REST endpoint Visualizing the list of friends blog
tication, the social network will
redirect our WebView to call the
Note that the uid that
has to be provided is the
easy to more and to parse the results.
DataFX was described in
is done in the ProfilePane class.
The code in Listing 9 shows how
callback URL of DaliCoreSocial and, UUID of the user, and it challenging. a previous issue of Java we listen for changes in the list of
in our case, DaliCoreSocial will is not the identifier of, for Magazine. friends. We loop over all the new
74
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//rich client /

COMMUNITY
JAVA IN ACTION
JAVA TECH
FIND YOUR
JUG HERE

ABOUT US
Figure 7
I have met so many amazing people
through the London Java Community
friends and create a UserDetail integrate social network users and friends, mentors, new colleagues
node for them. This node is added functionality into your applica- and through it I have achieved much
to a FlowPane. The result of this tions. It is important to note that more than I could have on my own.
application is shown in Figure 7. the same approach works for Java Trisha Gee
EE applications (including Web London Java Community (LJC)

Conclusion clients) as well as for Java desktop


In this article, we showed how applications or a combination of LEARN MORE
your application can integrate the two. </article>
with large, existing social network
systems. Authentication, privacy,
and permissions are important
concepts for all social media. The blog
DaliCoreSocial module deals with LEARN MORE
these concepts, and provides Java Johan Vos blog
developers with an easy-to-use Johan Vos YouTube screencast on
framework that can be used to DaliCoreSocial
75
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
IMS Services APIGetting Started
with JSR 281

JAVA IN ACTION
Learn how to bring IP Multimedia Subsystem services to Java-enabled devices.
VIKRAM GOYAL
BIO

T he IP Multimedia provides an implementation via pipes that provide for pre-existing criteria

JAVA TECH
Subsystem (IMS) of this API. simultaneous transfer of the and contracts.
involves the evolution of very Lets get started. data. Therefore, instead of an Identity on an IMS net-
basic telephone and data old-style telephone exchange work is established using SIP
exchanges into a modern What Is the IMS? system, which provides for (RFC 3261essentially, your
exchange system, powered The IMS is an architectural only one kind of media trans- e-mail address) or a tel URI
by a plethora of high-capacity framework that helps with fer (voice), the IMS can easily (RFC 3966essentially, your
devices and networking lines. delivering multimedia ser- handle multiple media trans- phone number). An end user

ABOUT US
Driven by the recent explo- vices that use the Internet fers simultaneously. or service may have multiple
sion in internet and high- Protocol (IP). It was origi- This exchange of data can such identities, and the user
end devices, Java ME, which nally defined by the 3GPP take place between services can be reached on one, some,
is installed on billions of (3rd Generation Partnership without a human element or all of these identities, at the
devices worldwide, is strate- Project) as a standardized way present, as in video or audio same time. This is the beauty
gically placed to take advan- for wireless mobile devices to streaming where an end of an IMS-based system.
tage of this. distribute internet-based ser- user consumes the data I have used the example
Here, I offer a brief intro- vices. However, it is broader without needing to have of telephony so far, which
duction to IMS technology, now and covers multiple net- a physical entity present would be the most common
followed by a discussion of work and media types. at the other end. The end use. However, the structure
JSR 281, the IMS Services The architecture defines a user is dialing into a service of IMS precludes no par-
API, which attempts to bring centralized exchange-type of that would have advertised ticular data and is, therefore,
the IMS to Java-enabled system that advertises its ser- itself previously with its own media agnostic. You could
devices. Finally, I will pro- vices. End users can connect unique identity. Business- easily use movies delivered
vide some simple code using their devices to this central- to-business transactions over this architecture to illus- blog
the latest Java ME SDK for ized service and gain indi- are also possible, as long as trate its usage.
mobile phones (version 3.2) vidual identities. Multimedia- individual identities have A commercial IMS system
PHOTOGRAPH BY and the LG Session Initiation based messages and data been established and a con- would control the function-
JONATHAN WOOD/
GETTY IMAGES Protocol (SIP) server, which are sent to these identities nection is possible based on ality of the whole network
76
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
and provide the basic structure Java ME and the IMS IMS application identifier define this registry by writing
to get the system going. Thus, it Java is present on a plethora of (AppId), which is a string that the capabilities within the Java
would seamlessly integrate all devices (not just mobile phones, identifies your application Application Descriptor (JAD) or
available networks and provide but set-top boxes as well), so it (potentially from among other Java archive (JAR) manifest file.

JAVA IN ACTION
authentication and authorization. is ideally suited to use the IMS. IMS applications on the same This is the static method of install-
Further, it could actually look up JSR 281, a step in this direction, device) ing an IMS application on an IMS-
new networks and services and defines an API that can be used to The MIDlet, which handles the capable device. JSR 281 also allows
provide them to the end user create an IMS-ready application application logic andin JSR developers to dynamically register
for use. A recent example of this that can sit on any Java-enabled 281 lingois said to be the their application from within the
service is the Push-To-Talk feature device that implements this API. owning Java application MIDlet by using the classes in the
that has been tried successfully by A device that implements The IMS engine stores these javax.microedition.ims package.
several telecommunications com- JSR 281 provides the IMS engine properties in the registry within The capabilities are defined in

JAVA TECH
panies. Each IMS system should an execution environment that the IMS device. This registry is the registry by using at least one
be able to advertise its services (or an IMS-ready application can used to identify the properties that of the properties described in
capabilities) when new subscrib- interface with. The application define the capabilities of the IMS Table 1: StreamMedia, BasicMedia,
ers connect to it. itself is defined with the following application. FramedMedia, Event, or
If an IMS device provides new parameters: Application developers need to CoreService. The capability declara-
capabilities, these need to be sepa-
rately identified. For each service

ABOUT US
that is standard, the 3GPP defines PROPERTY NAME PROPERTY MEANING EXAMPLE PROPERTY VALUES SAMPLE DECLARATION
a standardized identifier called StreamMedia MEANS THAT YOUR APPLICATION CAN STREAM AUDIO, Audio OR Video OR Audio Video MicroEdition-IMS-1-Stream: Audio
the IMS Communication Service VIDEO, OR BOTH. Video
Identifier (ICSI). For services that BasicMedia image/png, text/plain, MicroEdition-IMS-1-Basic: image/png
MEANS THAT YOUR APPLICATION CAN TRANSFER
are new or localized to your applica- OR HANDLE MEDIA OF THE TYPES DEFINED BY THIS application/myApp
tion, the IMS Application Reference PROPERTY VALUE.
Identifier (IARI) is recommended.
FramedMedia SPECIFIES THAT THE APPLICATION CAN TRANSFER text/plain image/png, 4096 MicroEdition-IMS-1-Framed: text/
One final point to note about plain image/png, 4096
APPLICATION DATA-LIKE MESSAGES AND FILES. YOU
the IMS is that it doesnt matter NEED TO DEFINE THE CONTENT TYPES AND THE SIZE.
how a user connects to an IMS
network; it always provides the Event SPECIFIES THAT YOUR APPLICATION USES THE presence MicroEdition-IMS-1-Event
same services to the end user. So PUBLICATION AND SUBSCRIPTION CLASSES TO
DECLARE EVENTS RELEVANT TO AN IMS APPLICATION.
a user could connect to a local IMS
network via Wi-Fi at home, to a 3G CoreService DECLARES THE CORE SERVICES THAT THE urn:URN-3gpp:org.3gpp MicroEdition-IMS-1-CoreService-1
or 4G network while traveling, and APPLICATION SUPPORTS AND DEFINES ANY .icsi;require;explicit FOR ICSI blog
to a fixed-line network when at COMPOSITE PROPERTIES AND SERVICES THAT ARE AND
SUPPORTED. urn:IMSAPI:com.myCompany
the office. At each place, the user
.iari.myApp FOR IARI
experience within the IMS will be
the same. Table 1
77
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
LISTING 1
tion must add at least one of these connected, this class allows devel-
properties to identify the capabili- opers to find any identities on the service = (CoreService) Connector.open("imscore://myApp;
userId=Vikram sip:vikram@myemail.net serviceId=chat");
ties of the IMS application. network. Related to this class is the
The API itself is divided into ConnectionStateListener interface,

JAVA IN ACTION
three packages. implementations of which can Download all listings in this issue as text
As mentioned previously, the be used to retrieve notifications
main javax.microedition.ims pack- about changes in the state of the
age is used to define, configure, connection. Finally, this package create and provide the IMS ser- Each implemented interface
and install an IMS application. also defines the Service interface, vices (in other words, the capa- of the ServiceMethod interface
The Configuration class provides which is the base interface for all bilities). At the heart of this is the has a related listener inter-
methods such as setRegistry() and types of IMS services, including CoreService interface, which pro- face attached. Thus, for the
removeRegistry to dynamically CoreService, which is an interface vides methods for calling remote Capabilities interface, you can

JAVA TECH
install applications (as opposed defined in the javax.microedition peers over the IMS network. The use the CapabilitiesListener; for
to the static method just dis- .ims.core package. CoreServiceListener implementa- PageMessage, you can use the
cussed). The ConnectionState class The second package, javax tion of this interface is also used to PageMessageListener; and so on.
is used to monitor whether the .microedition.ims.core, contains listen for incoming connections. The final package, javax.micro
application is connected to the the interfaces and a single class An example usage of this interface edition.ims.core.media, is used
IMS network and, if the network is that enable the application to in shown in Listing 1. to help with the transmission of
The CoreService is what media (BasicMedia, FramedMedia,

ABOUT US
enables connections and ses- and so on). Consequently, it pro-
sions within an IMS network, vides the BasicReliableMedia,
but it is the ServiceMethod inter- BasicUnreliableMedia,
face and its implemented inter- FramedMedia, and StreamMedia
facesCapabilities, PageMessage, interfaces. As the names sug-
Publication, Reference, Session, gest, BasicReliableMedia is used
and Subscriptionthat are used to transmit media over TCP,
to inspect and manipulate the BasicUnreliableMedia is used
messages that are transmitted to transmit media over UDP,
within each session. The messages FramedMedia is used to transmit
themselves are represented using data that is delivered in packets,
the Message interface, but any and StreamMedia is used for media
manipulation of messages should that can be streamed in real time.
be left for advanced IMS applica-
tions only. The MessageBodyPart A Simple IMS Application blog
interface allows an IMS applica- In this section, I will walk through
tion to create ad hoc body parts a simple IMS application for regis-
to attach to each message that is tering new users to an IMS server.
Figure 1 transmitted. More-detailed applications can be
78
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
LISTING 2 LISTING 3
built on top of this application. tor environment. To do this, run
Setting up. To get started, down- the installation folder\bin\ MicroEdition-IMS-1-Identity: com.oracle.test, IMSLaunchMIDlet
load the LG Java Mobile SDK, ktoolbar.exe file, and then select
because we will use the emula- File -> Utilities -> Start SIP Server,

JAVA IN ACTION
tion platform provided by it for the as shown in Figure 1.
development of this MIDlet. It also The LG SDK also provides the
provides a SIP server to test our means to specify the location of the Download all listings in this issue as text
MIDlet against. SIP server using the imsserver.ini
Once you have the LG SDK file. This file is located in the
downloaded, add it to NetBeans installation folder\LGJP_SDK_12\ purposes of this simple example). server is difficult to do because not
as another emulator platform. appdb directory. Open the file and Next, there are three basic steps many full-fledged IMS servers are
(NetBeans should auto-detect set the named variable com.lge.ims involved in creating a useful IMS publicly available. For testing pur-

JAVA TECH
whether you are in the right sec- .ims_uri to the location of your SIP application: poses, I used the SIP server bun-
tion.) Make sure you select IMS server (which is likely to be just Registering your application dled with the LG SDK. There are
Services API 1.1 from the optional the name of your machine; I tried with your device some online SIP servers, but they
packages list. using a local IP address, but that Networking with an IMS server are not reliable. (See this listing of
Start the SIP server provided by didnt work). You can leave the rest and declaring your identity public SIP servers.)
the LG SDK by running the emula- of the entries as is (at least for the Connecting a call and applying To start, use the code shown in
any media data, if applicable Listing 3 to declare your intentions

ABOUT US
Registering your application. To to the IMS server.
register your application, you can Notice the connection string.
either use the JAD manifest way It starts with imscore and then is
or the dynamic way (as I men- followed by the predictable HTTP-
tioned earlier). In this example, I like characters ://. Then, the next
have chosen to declare and reg- thing is actually the application ID
ister my application via the JAD that we declared in the previous
manifest file. section. Separated from this by a
The most important manifest semicolon is the user who is mak-
entry that you need to provide is ing this request; this has a familiar
the MicroEdition-IMS-1-Identity e-mail syntax, preceded by sip.
property. This property should The effect of this code is to reg-
be set to the ID of your applica- ister the user using the ID vikram@
tion and the fully qualified MIDlet oracle.com with the IMS server
name. See Listing 2 for what I used defined in the previous section. blog
for this application. Figure 2 shows the response on
Networking with an IMS server and the SIP server side.
declaring your identity. In the test- Connecting a call and applying any
Figure 2 ing world, networking with an IMS media data, if applicable. Next, we
79
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
LISTING 4 LISTING 5

Session mySession =
myCoreService.createSession(
"sip:vikram@oracle.com", "sip:lisa@oracle.com");
mySession.setListener(this);

JAVA IN ACTION
Download all listings in this issue as text

need to create a session to initi- internet-capable devices to deliver


ate a conversation or interaction. multimedia content seamlessly
This is typically done by using the and reliably. Java ME takes full

JAVA TECH
Session class, as shown in Listing 4. advantage of this by providing an
This code assumes that the user implementation via JSR 281.
on the other end (lisa@oracle.com) In this article, I introduced you
has accepted your session initia-
tion request.
Once created, the session can
to JSR 281 and how it fits within
the whole IMS ecosystem. I
started with an introduction to
FIND YOUR
be used to transfer any sort of data the IMS and then showed how
JUG HERE

ABOUT US
that the two end users and their JSR 281 implements the IMS
devices are capable of, and all data architecture and enables devel-
One of the most elevating things in the
can be transferred simultaneously. opers to create applications world is to build up a community where
For example, the two users could based on this platform. Finally, you can hang out with your geek friends,
initiate a chat application; have a I showed the steps required for educate each other, create values, and
text-based chat; and then during creating a session within a give experience to you members.
the same session, send data in the MIDlet with this API. </article> Csaba Toth
form of framed media (such as Nashville, TN Java Users' Group (NJUG)

pictures or videos). See Listing 5.


Once the media type has been LEARN MORE LEARN MORE
set, the session can be started. The IMS specification
actual creation of media is left for
the developer of the application.
For that, the developer can use the
Mobile Media API (JSR 135). blog

Conclusion
The IP Multimedia Subsystem is
a useful technology for leveraging
80
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
Swing into Mobile

JAVA IN ACTION
Use the Lightweight UI Toolkit on Nokia Series 40 phones.

NIRMAL
KIZHAKKEVEETIL, Y ouve probably used
Swing to create UIs for
advertising, as well as inte-
grated operator billing pro-
simplifies many of the typi-
cal challenges you might
you will be able to build a
single UI that runs across
PRAKASH your desktop applications. vided by the Nokia Store, the face when creating apps for multiple UI styles in different
RAMACHANDRAN, The rich simplicity of Swing tools are there to monetize mobile phones. These com- screen orientations and sizes

JAVA TECH
REHA CHAKROBORTY, inspired the development of your apps. ponents mean that with less and on devices with a range
the Lightweight UI Toolkit In this article, you will dis- effort, you can create apps of form factors. And you can
AND ANNA ZHUANG (LWUIT), and this technology cover how to take advantage that have compelling user see this demonstrated in
BIO is now ready to use on the of the demand for Series 40 experiences. Another advan- several LWUIT for Series 40
worlds most popular mobile apps by leveraging LWUIT tage is that LWUIT comes example applications on the
phone platform, Series 40. through smart develop- with built-in support for Nokia Developer Website.
With smartphone-like ment tools and distribution touch- and keypad-based

ABOUT US
features at a budget price, through the Nokia Store. UIs, as well as multiple LWUIT Comes to Series 40
Series 40 powers the latest screen resolutions. With Nokia has a long tradition of
Nokia Asha Touch phones, LWUIT: Simplifying good designby separating supporting Java in its plat-
such as the Nokia Asha 311 Mobile Apps the UI from the app logic forms and creating robust
and the Nokia Asha 308, If you have flirted with mobile
shown in Figure 1. Series apps development, you might
40s capabilities are driving have been put off by not hav-
demand for Asha phones, ing a modern UI framework,
and with that demand has needing to code everything
come ever greater interest yourself to the canvas, and
from users for smart apps, having to build your own UI
driving record downloads framework and controls for
from the Nokia Store. anything interesting or use-
With an estimated 675 ful. Why cant I just use
million Series 40 phones in Swing? you might have won- blog
active use every day, there is dered. You were not alone,
a huge potential market for and so LWUIT was born.
your apps. With support for By providing a set of rich
in-app purchase and in-app UI components, LWUIT Figure 1
81
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
LISTING 1
and easy-to-use tools for develop- able UI components, LWUIT for
ers. Adding LWUIT to the Series 40 Series 40 adds built-in support Form form = new Form();
GestureHandler
platform was a natural extension for dynamic orientation change in
handler = new GestureHandler() {
of this tradition. The first goal was full-touch phones.
public void gestureAction(GestureEvent e) {

JAVA IN ACTION
to ensure that LWUIT was avail- The touch UI is one of the key switch(e.getType()) {
able for all the UI styles found on features of Nokia Asha mobile case GestureInteractiveZone
Series 40 phones: the full-touch phones, and it provides support .GESTURE_TAP:
UI, the touch-and-type UI (a for a wide variety of gestures. //handle tap
unique hybrid of touchscreen and Therefore, Nokia optimized and break;
ITU or QWERTY keyboards), and tightly integrated LWUIT for Series case GestureInteractiveZone.GESTURE_LONG_PRESS:
the nontouch UI. 40 with the native touch UI using //handle long press
Next, LWUIT for Series 40 had a simple yet elegant solution: the break;

JAVA TECH
to offer users the same look and GestureHandler helper class (part case GestureInteractiveZone.GESTURE_FLICK:
feel as the underlying UI. In Series of the com.nokia.lwuit package), //handle flick
40, Nokia has already created a which can be used in your LWUIT- break;
set of UI styles that provides users based apps, as shown in Listing 1. }
with a great Another key aspect of the }
user experience LWUIT port to Series 40 is };
A SINGLE UI //set handler to receive gesture events only when the
By separating on phones that memory consumption and per-

ABOUT US
// form is visible. Every form can have its own handler.
have relatively formance. Several key compo-
the UI from the small screens. nentssuch as Form, List, and
GestureHandler.setFormGestureHandler(form, handler);
//Creating another handler
app logic, you Therefore,
Nokia optimized
HTMLComponenthave been
improved. In addition, UI widgets
GestureHandler g = new GestureHandler() {
can build a single LWUIT so it usability has been improved for
public void gestureAction(GestureEvent e) {
//handle event
UI that runs better matched
the platform UI
Series 40. }
across multiple styles. For exam- Designing with LWUIT
};
//if you want to always catch gestures, set the handler
UI styles in ple, the LWUIT The three UIs used in Series 40 // as a global handler. There can be only one global handler.
different screen text area and
text field were
phones have their own unique
characteristics. While there is
GestureHandler.setGlobalGestureHandler(g);

orientations tightly integrated much in common among the Download all listings in this issue as text
and sizes and with the native
Series 40 text
different UI styles there are differ-
ences, most notably between the
on devices with editor found in full-touch UI (shown in Figure 2) For example, all the Series 40 lower right of the screen and in the blog
a range of form more-recent and the two UIs where a keyboard UIs employ a drill-down approach; Options menu, but the Options
factors. phones.
To benefit fully
or keypad is present: the touch-
and-type UI and the nontouch UI
back-stepping is hierarchical
(not historical). By default, all the
menu is repositioned in the full-
touch UI. The primary action
from the scal- (shown in Figure 3). UIs have the back function in the (called the default command in
82
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
LWUIT) is automatically mapped 40 application layout displays title Building Your LWUIT Apps for LWUIT is included in the 2.0
to the action button in the header and softkeys (or actions), but the Series 40 SDK. To use LWUIT in your apps,
bar of the full-touch UI and to the application can be set explicitly to Get the right tools. You build apps you simply add its Java archive
middle softkey in the other UIs. full-screen mode to provide more for the latest version of the Series (JAR) file to your apps build path

JAVA IN ACTION
By default, the LWUIT for Series space for content. 40 platform using the Nokia SDK and start adding LWUIT compo-
All the familiar LWUIT features 2.0 for Java. The SDK can be inte- nents, as shown in Figures 4 and 5.
are available, to enable the easy grated with NetBeans or Eclipse, Beyond that, the development
creation of impressive user inter- but the best experience will come process will be pretty much as you
faces. You can, for example, define from using the Nokia IDE for Java would expect for a desktop app.
application layout as a grid instead ME (Eclipse), which is installed by The differences come when you
of the ordinary one-column layout. the SDK. start testing.
You can also use subtle anima- The Nokia IDE has a number of Test your app. To test your apps,

JAVA TECH
tions (for single components) or Nokia-specific features, such as a you run them in a PC-based emu-
transitions (for application views). tool to help you locate the Series lator. With the emulator, you are
Note, however, that excessive use 40 SDKs you need and an editor able to test virtually all aspects of
of the effects is not encouraged, for the Nokia-specific attributes your application, including loca-
to ensure that application perfor- in your apps Java Application tion features or accelerometer
mance is good on all possible tar- Descriptor (JAD) files. sensors. You will want to test your
get phones. This is the area where

ABOUT US
developers may wish to consider
feature variation based on phone
Figure 2 capabilities; that is, build in more
eye candy for more-capable
phones such as the Nokia Asha 311.
One of LWUITs unique benefits
is the ability it provides for you
to easily create custom themes
using the LWUIT Resource Editor
tool. Using the tool, its possible to
customize the LWUIT for Series 40
themes for a branded look and feel
while maintaining a consistent UI.
The Designing for Series 40
section of the Nokia Developer blog
Design and User Experience Library
provides much more detail on this
subject and is well worth visiting
Figure 3 before you start design work. Figure 4
83
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//mobile and embedded /

COMMUNITY
running on a Series 40 phone.
There is also a lively community
forum in the Nokia Developer Java
Tools discussion board, where

JAVA IN ACTION
you can post questions and join
fellow developers in technical
discussions.

A Final Word
With the introduction of LWUIT,
you will be able to create apps with
a rich UI quickly. Then, with good

JAVA TECH
design, apps can run unchanged
over the range of Series 40 phones
to cover the full-touch, touch-and-
type, and nontouch UIs.
Because Series 40 phone users
are beginning to demand more
Figure 5 and more apps, now is a great

ABOUT US
time to start creating apps using
apps on a phone, too, but the reduce this overhead to below the LWUIT library for Series 40 if
emulator makes initial testing 350 KB, depending on the com- you want to give your Java apps
faster. Figure 6 shows the Nokia plexity of the app (that is, how more reach. </article>
SDK 2.0 for Java emulator running many LWUIT classes it uses).
a LWUIT demo app.
And when it comes to testing on Getting Started and Where to Figure 6
a phone, dont worry about getting Get More Information LEARN MORE
access to Series 40 phonesyou You can find more information on download the tools. Another rec- LWUIT Javadoc
can access a range of Series 40 creating Java apps for Series 40 ommended resource is the video Binary package
phones over the internet using the on the Nokia Developer Website. introduction Get Started with
Working with Lightweight User
Nokia Developer Remote Device In addition to the SDK and design LWUIT for Series 40, which you can
Interface Toolkit (LWUIT) 1.4
Access service. library, check out the videos and watch on the YouTube channel
Obfuscate your code. It is essential Webinars in the Learning section (which includes many other vid- Rich Applications for Billions of
to obfuscate your code, because and the Java Developers Library. eos about developing with Java for Devices: Whats New in LWUIT? blog
you include the LWUIT JAR in each Getting started with LWUIT is Series 40). In the LWUIT video, Using Styles, Themes, and
application you build, and it adds just as easy. You can start from the you will see how to set up the Painters with LWUIT
up to 800 KB to each apps distri- LWUIT for Series 40 project home tools, code your app, test your app LWUIT for Series 40 example
bution file. By obfuscating, you can page, where you can learn and in the emulator, and get your app applications
84
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
Part 2
Building Actor-Based Systems
Using the Akka Framework

JAVA IN ACTION
TED NEWARD Learn how to use the Akka library to do more than create simple actors.
BIO

I n Part 1 of this two-part within it, and weve already embraces a Let it fail con- the console, this isnt a prob-

JAVA TECH
series, we discussed the seen the actor as a container cept rather than the Keep it lemthe user can always
difficulties in building reli- for behavior, because actors from failing, ever strategy just rerun the command that
able, distributed, concur- contain code. That code, espoused by most traditional launched the system. But
rent systems, and we briefly however, doesnt execute in J2EE/Java EE stacks. in a system thats supposed
explored the concept of an response to method calls, But lets take this one step to possess even a modest
actor for building such sys- but in response to messages at a time. degree of reliability, this isnt
tems. We explored an imple- sent to the actor via the so good.

ABOUT US
mentation of actors on the actors mailbox. This helps Minions! Where Are My Imagine, for a moment,
Java Virtual Machine (JVM) actors avoid blocking on one Minions? that instead of simply print-
called Akka, which is part of another, which is a major Weve already seen a bit of ing to the console, our actors
the Typesafe Stack that also source of concurrency bugs. how an actors-based system are engaging in some risky
includes Scala and the Play The last two parts of an is designed in the earlier behavior, which in this case
framework. We illustrated actorchildren and super- Hello and the Pi calcula- consists of doing anything
some simple examples, but visory strategiesbecome tor examples, but these that might throw an excep-
space constraints prohibited important when actors work examples had one tiny flaw: tion. We can mimic this
a deeper look. together to accom- If something went by creating a case within
I simplified the actor story plish some larger wrong inside the HelloActor from our earlier
HUNG UP
a bit to help put the basics in task, which is actor, the entire examples that, in a semi-
place: The Akka documenta- most of the time. An unbounded system (trivial random fashion, throws an
tion describes an actor as a
container for State, Behavior,
The supervisory
strategy will be a
wait is essentially though it was)
would come crash-
exception when used (see
Listing 1).
a Mailbox, Children and a large part of how a deadlock or a ing to the floor This is obviously a con- blog
Supervisor Strategy. Weve we follow Akkas production hang and worse, never trived example, but it does
already seen the actor as a
container for state, in that we
ideas for building
robust systems,
waiting to happen. get up again.
In a trivial sys-
create for us a failure
scenarioone that allows for
PHOTOGRAPH BY
PHIL SALTONSTALL saw an actor can hold state which, if you recall, tem that runs in at least a certain amount of
85
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 1 LISTING 2 LISTING 3 LISTING 4
recoveryin this case, to just keep strophic failure and we need to
trying over and over again until we create a new one to do message class HelloActor extends Actor {
def messageOut(msg: String) = {
finally get messages out. processing).
if ((System.currentTimeMillis() % 10) == 0)
But we need to refactor the Stop this actor.
throw new RuntimeException("NOOO! Even time! The horror!")

JAVA IN ACTION
HelloActor design a little: HelloActor Escalate the issue to this actors
else
cant do everything on its own, own supervisor (which, in System.out.println(msg)
because if the exception is thrown the case of HelloActor, will be }
so that it escapes HelloActor, the the Akka system runtime) by
actor dies. What we need is to rethrowing the exception to it. def receive = {
establish a new actor that will do For example, by default, a case Start =>
the risky operation, and then use RuntimeException maps to the messageOut("Hello, Akka")
that actor from within HelloActor, restart option, which tells Akka to case incoming : RepeatMessage =>

JAVA TECH
as shown in Listing 2. restart the failed actor. We know for (it <- 0 to incoming.num)
When the code in Listing 2 is this by examining the type of the messageOut("Repeat: " + incoming.message)
run, an interesting thing hap- exception in the pattern match case incoming : Message =>
pens: If the time happens to be inside of the actor (see Listing 3). messageOut("Message: " + incoming.message)
lucky (or, I suppose, in this case, In cases where we want entirely case Stop =>
unlucky) enough to end in a zero, new behavior, we need to override context.system.shutdown()
}
the exception is triggered, but the supervisorStrategy value. The

ABOUT US
}
the program doesnt terminate. canonical way to do this is within
Since the exception is thrown the actor subtype itself, as shown
from a child actor (one that was in Listing 4.
created from within HelloActor), Theres more to the
the actors supervisory strategy SupervisorStrategy constructor, but
which is a OneForOneStrategy by the parameters maxNrOfRetries
defaultlooks at the exception and withinTimeRange are fairly
thrown from within the child self-explanatory, are described in Download all listings in this issue as text
actor. Depending on the strategys the Scaladocs for Akka, and have
directive (a mapping of excep- some generally useful defaults.
tion types to a directive type), a number of methods that pro- actors of this given actor.
the supervisory strategy decides Context Matters vide interesting information and parent: This is the parent of this
which of the following to do: Notice that the code in Listing 4 behavior for an actor to use: actor.
Resume the failed actors mes- uses the context value, which is actorOf: This method is used in self: This is a reference to the
sage processing (meaning the a bound value built in to every Listing 4 to create another actor actor itselfthis is a little dif- blog
actor didnt suffer a catastrophic actor that provides a reference that will be a child of this actor ferent from the this reference,
failure and we can keep using it). to the actor system in which it (the one doing the actorOf call). because the self reference is
Restart the failed actor (mean- executes. This is a reference to children: This returns an Iterable to the ActorRef that wraps the
ing the actor suffered a cata- an ActorContext object that has of references to all the child actor, rather than to the raw
86
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 5a LISTING 5b LISTING 6 LISTING 7 LISTING 8
object, and in most cases, self is erate omission on my part: The
the more appropriate of the two system as a whole functions a case class RichMan(val kind : String)
case object Sheriff
to use. lot more quickly and smoothly if
stop: This method shuts this
case class Rob(val whom : String)
we design it so that all message-
case class Hide(val where : String)

JAVA IN ACTION
actor down. sends are considered one-way, case class JobComplete(val msg : String)
dispatcher: This returns the asynchronous communications.
MessageDispatcher used for this No blocking means no opportuni- class RobinHoodActor extends Actor {
actor. The MessageDispatcher is ties for deadlock. val rightHandMan = context.actorOf(Props[LittleJohnActor])
the strategy by which messages Its important to realize that an def receive = {
are delivered to the actor and actor can always send a one-way case rm : RichMan => {
largely describes the relation- message back to the sender of the println(
ship of actors to threads. (For message by using the sender refer- "Robin Hood says, 'Ho, ho! Rob the " + rm.kind + "!'")

JAVA TECH
example, does each actor have ence within the actor. So its always rightHandMan ! Rob(rm.kind)
its own thread? Or do all the possible to do something like you }
actors operate on one thread?) can see in Listings 5a and 5b. case Sheriff => {
system: This is the reference to But the problem with this println("Robin Hood says, 'The Sheriff! Hide, men!")
the ActorSystem to which the approach is that if we fire mes- rightHandMan ! Hide("forest")
actor belongs. sages at a RobinHoodActor using }
sender: This is the actor from
case j : JobComplete =>
the traditional ! syntax, as shown

ABOUT US
println("Robin Hood says, 'My men report '" + j.msg + "''")
which the currently processing in Listing 6, what were going to
}
message came. get (see Listing 7) is not quite what }
Almost any nontrivial actor will wed expect or, most likely, want.
use context at some point during Because the messages are asyn-
its execution, as we see in Listing 4. chronous, Robins messages to his Download all listings in this issue as text
There are a few other methods on men appear to arrive in an out-of-
ActorContext, two of which we will order fashion, and certainly the
examine later, but for the most results returned to Robin are not and work. Even then, Akka wont dealing with how long the system
part, these are well documented in quite in the order a leader usually give us an unbounded block- should wait for a response.
the Scaladocs for Akka. expects (a response as soon as an ing request/response method. To begin with, assume that we
order is given and before the next Instead, it will asynchronously have a simple echoing actor, as
Dont Just Stand There! Say order is given). send the message and hand back a shown in Listing 8. Its annoying,
Something! In this case, its possible to write Future object, which will (at some but it works. In the sender, once
In Part 1, we showed that actors request/response messages, point) receive the result. the actor is created, the mes-
can send messages to another but that approach intentionally To start with, sending a request/ sage is sent using the ? method, blog
actor using the ! method, but requires a lot more work because, response message uses the ask which will work only if an implicit
nothing was said about how actors as already mentioned, blocking methodor its shorthand equiva- Timeout object has been created
could engage in a round-trip is playing with fire and should, by lent, ?but a couple of things beforehand. (Otherwise, there
request/reply. This was a delib- definition, require more thought have to be established first, mostly will be a compile error. The ask
87
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 9 LISTING 10 LISTING 11
method, on the other hand, is nor the ? method appears on the
less syntactically short but takes Actor API. Failing to use these val ma = system.actorOf(Props[MockingActor])
implicit val timeout = Timeout(5 seconds)
the timeout parameter explicitly, import statements will result in
val future = (ma ? "Hello").mapTo[String]
which is sometimes a little easier some truly misleading compiler
val result = Await.result(future, 5 seconds)

JAVA IN ACTION
to read.) messages. println("Received result: " + result)
Once thats done, the returned Needless to say, Akka is making
object from the ? call is mapped to it a lot easier to use one-way mes-
a particular future-result type. (In sages, and despite the additional
this case, because were expecting a work, building redundant and
string back, it needs to be mapped fault-tolerant systems fares better
back to a Future[String] type.) Then, when doing exactly that. Download all listings in this issue as text
finally, as shown in Listing 9, we

JAVA TECH
need to establish how long were Get This to Phil in Accounting!
willing to wait for that Future object Seeing these messages flying something the developer wants or NotifyAccountActor, and so on).
to be populated with the result from one actor to another might needs to deal with. And for some of these, linear
before the Akka API will allow us to lead some readers to wonder if However, there are interesting sequences of steps through each
actually harvest that result. this isnt a replacement for Java parallels between the two kinds (for example, A to B to C to D) will
Why all the fuss? Michael Message Service (JMS) or some of systems. One parallel is that of work, in which case, we can sim-
Nygard, in his book Release It!, other kind of messaging-oriented creating a workflow or pipeline ply pass the next actor in to the

ABOUT US
describes in great detail why middleware system. On the sur- of actors that can work together previous one. But for others, some
unbounded waits are a bane to face, yes, there appear to be some to accomplish a common goal. It of the steps will be processed
production-quality code. So I similarities, particularly when might sound retro, but build- in parallel or in some combina-
wont get into the details here, but routing messages (our next topic), ing large systems out of small tion or hybrid thereof. This entire
in summation, an unbounded wait but similarities end there on the piecesfor example, by using subject is called routing in Akka,
is essentially a deadlock or a pro- surface, really. A messaging- UNIX command-line tools such and while theres no way we can
duction hang waiting to happen. oriented middleware system is as grep, sed, awk, and moreis exhaustively cover all the different
The repeated use of timeout values generally about making the mes- by far a more resilient and robust possibilities, we can explore a few
here tells Akka exactly how long to sages and their delivery a top- way to achieve long-term success simple scenarios.
wait for each potentially hanging level concern as something the than by building monolithic large Consider creating an actor spe-
operation before recovering and developer wants to see and deal chunks of code. cifically for printing to the con-
continuing execution (giving you with, usually for reasons of dura- In some cases, these sole, as shown in Listing 11. In this
the chance to recover from the lost bility, persistence, and so on. In chunks of code will be distinct particular example, we want to
message or response). an actor-based system, the mes- and separate actor types (a have five different instances of the
Note, though, that certain sages are almost an implementa- PrintlnActor, a FibonacciActor, a PrintlnActor (which well be able blog
import statements (see Listing 10) tion detail; they are used solely to FactorialActor, orif we want to verify by seeing the created!
must appear prior to the code in help break the blocking nature of to get out of the mathematics message printed when each one
Listing 9 for the code to compile, a method call and (in the case of domaina ProcessRequestActor, is instantiated). More importantly,
because neither the ask method the mailboxes themselves) are not a TransferMoneyActor, a when we send 10 messages, we
88
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 12 LISTING 13 LISTING 14
want the messages to be routed to one has the smallest mailbox
each actor in a round-robin fash- (meaning the least work being object Main {
def main(args: Array[String]): Unit = {
ion, as shown in Listing 12. processed). Note that any
val system = ActorSystem()
When we run the code, what we remote actors will be selected

JAVA IN ACTION
see is that, indeed, five actors are last, since Akka cant see the val roundRobinRouter =
created, and each one receives two mailbox state for actors running system.actorOf(Props[PrintlnActor].
messages in order, as shown in in remote processes. withRouter(RoundRobinRouter(5)), "router")
Listing 13. The BroadcastRouter will hand
1 to 10 foreach {
The key to this is in the creation the message to all the actors i => roundRobinRouter ! i
of the roundRobinRouter, an actor underneath it in a broadcast }
that essentially fronts the collec- fashion. }
tion of five PrintlnActors such that The ScatterGatherFirstCompleted }

JAVA TECH
to the client (main), it appears that Router is a BroadcastRouter but
theres just one actor, while in fact, with a hitch. It will dispatch the
the work is being split across five message to each actor, but it will
different instances, as we can see accept only the results of the
from the output. first actor to return; it will throw
Akka offers several differ- away the rest of the results. This
ent routers, each with different is essentially an implementation

ABOUT US
semantics: of the Scatter-Gather Download all listings in this issue as text
The RoundRobinRouter pattern commonly seen
WORTH THE WORK
will pass messages to
each actor in a round-
Akka makes it in messaging systems.
Although we didnt but instead of taking the first for doing this for actors by allow-
robin, ring-like fash- a lot easier to
do it, its possible to result, it would take the first two ing an actor to change the code
ion, as weve already
seen.
use one-way create routers that
fluctuate in the num-
results and compare them to
make sure theyre both identical,
that responds to the incoming
messages. This capability hides
The RandomRouter messages, ber of actors by creat- as they should be. The Akka man- behind the innocuously named
will, as its name and despite the
ing a DynamicResizer ual has an example of one, if you become method, and at its heart,
implies, hand mes-
sages to a randomly
additional work,
and passing it in
as a resizer argu-
find the need. its a simple mechanism: Each
time become is called, a different
selected actor with no building redundant
ment when creating a You Must Become . . . method becomes the method that
other consideration.
The SmallestMailbox
and fault-tolerant
router. Another option
is to create a custom
Something Else
Of course, one of the most com-
is executed when a message is
delivered to the actor for process-
Router will examine systems fares router, for example, mon things that we do when ing. Consider Listing 14. blog
the mailboxes of all better when doing
a RedundancyRouter building systems is managing We can send the code in
the actors under it,
and hand the mes- exactly that. that would be similar
to the ScatterGather
objects internal state as clients
use them in a progressive fashion.
Listing 14 some messages (the
exact type of message is irrelevant
sage to whichever FirstCompletedRouter, Akka offers a powerful capability to our example here, so well just
89
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 15 LISTING 16 LISTING 17
borrow the Start message from for this is simple: The program-
Part 1): mers approach to remote actors akka {
actor {
is, essentially, exactly the same
provider = "akka.remote.RemoteActorRefProvider"
val pp = system.actorOf( as that for local actors, which is
}

JAVA IN ACTION
Props[PingPongActor]) simply sending messages. The remote {
pp ! Start only things that are different are transport = "akka.remote.netty.NettyRemoteTransport"
pp ! Start establishing a configuration that netty {
pp ! Start allows for remote communication hostname = "127.0.0.1"
(which consists of the right entries port = 2552
What emerges at the console is in a custom text file format that }
this: Akka can find when running your }
code) and specifying how to find }

JAVA TECH
It begins! (or create) the actor on the remote
PING system. Neither of these tasks
PONG substantively changes the nature
of your interaction with the actor
If this leads you to conclude nor the design of the actor-based
that we could build finite state system as a whole.
machine (FSM) behavior explicitly Configuration-wise, Akka will

ABOUT US
into the actors, youre spot-on. need an akka.conf file containing
As a matter of fact, Akka provides the entries shown in Listing 15. The
some even more explicit support actor section says that instead of
for describing an FSM in an actor, using local actors, we now want
and the Akka manual describes the actors that can receive messages
FSM module in more detail. (The from across the network, and the
become functionality is great for remote section specifies what
lightweight state transitions, but communication transport and
for very complex state machines, various TCP/IPlevel details (such
a more rigorous description of the as the host name and port) to use.
states and their transitions will be In order to keep the external
necessary, and this is the support requirements to a minimum, Im Download all listings in this issue as text
provided by the FSM module.) going to embed the configuration
in the code and read it directly
We Need to Shoot a Scene in a using a ConfigFactory (which, by for production code. The actor in Next, we need to establish the blog
Place Far, Far Away the way, is not technically part question is shown in Listing 16, server on the remote machine, as
It might come as a surprise that, of Scala; the Scaladoc is on the which is, again, kept deliberately shown in Listing 17. (Again, this
as of yet, theres been no mention Typesafe Website). This approach simple to allow us to focus on the will be the same machine were
of remote actors. The main reason is obviously not recommended important parts. running on to keep things simple.)
90
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//polyglot programmer /

COMMUNITY
LISTING 18
Aside from the configuration on a few more .jar files, notably the
passed in to the ActorSystem, the akka-remote JAR and the external object Client {
def main(args: Array[String]): Unit = {
server code is fairly standard Akka dependencies netty-3.5.3.Final.
val config = """
code. It creates the actor using jar and protobuf-java-2.4.1.jar
akka {

JAVA IN ACTION
actorOf, except this time, we give it (from the akka-2.0.3 release), all actor {
a name in order to be able to find of which are already found in the provider = "akka.remote.RemoteActorRefProvider"
this actor from the client. We then Akka distribution but will likely }
block on an incoming keystroke need to be referenced somewhere remote {
(using System.in) just to keep the in your build path or the project transport = "akka.remote.netty.NettyRemoteTransport"
process up and running. (Again, settings of your integrated devel- netty {
this is not really recommended for opment environment. hostname = "127.0.0.1"
production code.) port = 2553

JAVA TECH
The client, then, is also almost Conclusion }
just as deceptively simple (see Akka is not, by any stretch of the }
Listing 18). The only thing thats imagination, a trivial system to }
new is that the method actorFor master. The concepts are straight- """
is used instead of actorOf, and the forwardmessage passing in a
parameter to it is a URI describ- shared-nothing environment val system = ActorSystem("client",
ConfigFactory.parseString(config))
ing where to find the remote actor. but making the transition to

ABOUT US
The format of the URI is fairly building actor-oriented systems
val actor =
self-describing, as most URIs can be tricky. Just keep an eye on system.actorFor(
are, and most of the informa- sending one-way messages, avoid "akka://server@127.0.0.1:2552/user/actorName")
tion was contained in the servers blocking, and remember to let it println("We have an actor: " + actor)
configuration: fail! </article> actor ! "HELLO!!"
The scheme (akka)
println("Message sent")
The servers ActorSystem name
}
(server) }
The servers host name (in LEARN MORE
this case, the raw IP address Akka Website
127.0.0.1) Java Champion Jonas Bonr
The servers port (2552)
Explains the Akka Platform
The actors path (/user/actor

Name, where actorName was the


string passed in when the actor blog
was created using actorOf on
the server)
When building the code, note Download all listings in this issue as text
that the system will now depend
91
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013
//fix this /

COMMUNITY
Hint: Think about
how data structures
are reused.

In the November/December 2012 issue, Oracle Java ME Embedded Client,


Jason Hunter and Boris Shukhat gave us a code and CLDC forms the basis of

JAVA IN ACTION
challenge around porting JDBC code to use the Java Oracle Java ME Embedded.
Persistence API (JPA). They gave us code from a
In the following example, we use a DatagramConnection to set up a server
program that was redesigned to use JPA.
that listens and processes messages from clients. The messages are of
The correct answer is # 4. JPA commit() does a database variable length, but never more than 256 bytes. When the application runs,
rollback itself if it fails and then it closes the transaction. The some messages require multiple reads to get the whole message.
correct code looks like this:
2HowTHE

JAVA TECH
entityTransaction.begin();
try {entityManager.createNativeQuery(
CODE
sqlInsertStatement).executeUpdate(); should this code be modified so all messages are read in a single
entityTransaction.commit();}
catch(RollbackException e) {log.info(
getData() call?
"Transaction failed and was rolled back");} datagram = connection.newDatagram(256);
catch(RuntimeException e) {
if (entityTransaction.isActive()) {entityTransaction

ABOUT US
while (notDone) {
.rollback();log.error( connection.receive(datagram);
"Transaction ended abnormally and was rolled back");} data = datagram.getData();
} bytesReceived = datagram.getLength();
// process datagram ...
This issue s code challenge comes from Simon Ritter, a Java }
evangelist at Oracle, who presents us with an embedded problem.
3 WHAT S THE FIX?
1 THE PROBLEM 1) E nsure that the type of the connection is UDPDatagramConnection.
2) Move the call to connection.newDatagram inside the while loop.
Both the Connected Device Configuration (CDC) and the
Connected Limited Device Configuration (CLDC) use the 3) Add a call to datagram.reset() before the call to connection.receive().
Connector framework to support generic input and output 4) Add a call to datagram.setLength(256) before the call to
through a minimal-footprint API. CDC forms the basis of connection.receive(). blog

GOT THE ANSWER?


PHOTOGRAPH BY BOB ADLER,
ART BY I-HUA CHEN Look for the answer in the next issue. Or submit your own code challenge!
92
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////// JANUARY/FEBRUARY 2013

Das könnte Ihnen auch gefallen