• Save
Javamagazine Mayo Junio 2013
Upcoming SlideShare
Loading in...5
×
 

Javamagazine Mayo Junio 2013

on

  • 1,320 views

Revista Java

Revista Java

Statistics

Views

Total Views
1,320
Views on SlideShare
1,320
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Javamagazine Mayo Junio 2013 Javamagazine Mayo Junio 2013 Presentation Transcript

  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013ABOUTUS01JAVATECHJAVAINACTIONCOMMUNITYblog//table of contents /COMMUNITY03From the Editor05Java NationNews, people, and events14JCP Executive SeriesQ&A with Mark LittleRed Hat’s vice president ofengineering talks about theJCP and Java EE 7.JAVAINACTION18Slam DunkJava takes ESPN.com to thewinner’s circle.22Banking on JavaA Java EE–based systembrings stability to Brazil’scomplex financial market.JAVATECH34Java ArchitectThe Advanced JavaCompiler APIBuild a full graphical codeanalysis tool.41Java ArchitectDemystifyinginvokedynamicJulien Ponge continues hisinvokedynamic series.47Java ArchitectAdvanced Operationswith LambdasBen Evans and MartijnVerburg conclude their series.51Java ArchitectWhat’s Driving theCloud for Developers?A cloud primer74Rich ClientIntegrating JavaFXScene Builder intoEnterprise ApplicationsAdam Bien on Scene Builder82Polyglot ProgrammerJython 101Josh Juneau continues hisseries on Java and Jython.89Mobile and EmbeddedBuild a CommunicationsNetworkUse standards-based APIs forcommunications services.95Mobile and EmbeddedBuild an InstagramJava ME ApplicationVikram Goyal shows you how.99Fix ThisTake our code challenge!COVER ART BY I-HUA CHEN26New to JavaEXPLOREJAVA EE 7Max Bonbhel showsyou how to use thenew APIs in Java EE 7.55JAVAEE7ARRIVESOracle’s Anil Gaur discussesthe evolution of Java EE.61Enterprise JavaBOOSTINGDEVELOPERPRODUCTIVITYIncrease your produc-tivity with updatedspecs and new APIs inJava EE 7.66Enterprise JavaEMBRACINGHTML5Discover new featuresin Java EE 7 for creat-ing next-generationWeb apps.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH02COMMUNITYJAVAINACTIONABOUTUSblogEDITORIALEditor in ChiefCaroline KvitkaCommunity EditorsCassandra Clark, Sonya Barry,Yolande PoirierJava in Action EditorMichelle KovacTechnology EditorsJanice Heiss, Tori WieldtContributing WriterKevin FarnhamContributing EditorsClaire Breen, Blair Campbell, Karen PerkinsDESIGNSenior Creative DirectorFrancisco G DelgadilloSenior Design DirectorSuemi LamDesign DirectorRichard MerchánContributing DesignersJaime Ferrand, Nicholas PavkovicProduction DesignersSheila Brennan, Kathy CygnarowiczPUBLISHINGVice PresidentJeff SpicerPublisherJennifer Hamilton +1.650.506.3794Audience Development andOperations DirectorKarin Kinnear +1.650.506.1985ADVERTISING SALESAssociate PublisherKyle Walkenhorst +1.323.340.8585Northwest and Central U.S.Tom Cometa +1.510.339.2403Southwest U.S. and LADShaun Mehr +1.949.923.1660Northeast U.S. and EMEA/APACMark Makinney +1.805.709.4745Advertising Sales AssistantCindy Elhaj +1.626.396.9400 x 201Mailing-List RentalsContact your sales representative.RESOURCESOracle Products+1.800.367.8674 (U.S./Canada)Oracle Services+1.888.283.0591 (U.S.)Oracle Press Booksoraclepressbooks.comARTICLE SUBMISSIONIf you are interested in submitting an article, please e-mail the editors.SUBSCRIPTION INFORMATIONSubscriptions are complimentary for qualified individuals who complete thesubscription form.MAGAZINE CUSTOMER SERVICEjava@halldata.com  Phone +1.847.763.9635PRIVACYOracle Publishing allows sharing of its mailing list with selected third parties. If you preferthat your mailing address or e-mail address not be included in this program, contactCustomer Service.Copyright © 2013, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwisereproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLYDISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANYDAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. Theinformation is intended to outline our general product direction. It is intended for information purposes only, and may not beincorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be reliedupon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’sproducts remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respective owners.Java Magazine is published bimonthly with a free subscription price byOracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600.Digital Publishing by TexterityGet Java EEExpertise—Oracle University—New Java EE 7 TrainingEngineering-Developed CoursesAligned with Java EE CertificationsExperienced Java InstructorsRegister Now
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY03JAVATECHABOUTUSJAVAINACTIONblog//from the editor / ou’ve been waiting, and now it’s here. Java EE 7 has arrived, with lots of new tools designed to makeyou more productive and let you add new capabilities to your Web applications. If you’re like me, when some-thing new arrives at your doorstep, you want to open it up and start using it right away. And inthis issue of Java Magazine, we help you do that with Java EE 7. So roll up your sleeves and dive in.(Look for our Java EE 7: License to Code icon for all of the Java EE 7–related content in this issue.)First, Anil Gaur, vice president of software development at Oracle, brings you up to speed onwhat’s new and notable in Java EE 7—including HTML5 support, WebSocket, JAX-RS, JSON Processing, batchprocessing, concurrency, and more—in our interview. Then Max Bonbhel explores the new APIs in Java EE 7.This is a big subject, so Max will continue with this topic in the coming issues. Next, Johan Vos digs into theproductivity enhancements in the new release and shows you how Java EE 7 simplifies the default develop-ment and configuration. And finally, Eduardo Moranchel and Edgar Martinez, Java curriculum developers atOracle, tackle the new features in Java EE 7 that allow you to create next-generation internet applications—WebSocket, HTML5, and JSON.We also have stories of Java EE in action—from bringing sports fans up-to-the-instant information at ESPN to solving complex banking challenges in Brazil.Do you have a story to tell about how you use Java or how your Java user groupis thriving? Want to share your coding wizardry in our back-page Fix This column?Have other feedback? Send it our way.Enjoy Java EE 7!Caroline Kvitka, Editor in Chief BIO//send us your feedback /We’ll review allsuggestions for futureimprovements.Depending on volume,some messages maynot get a direct reply.YPHOTOGRAPH BY BOB ADLEROne of the most elevating thingsin the world is to build up acommunity where you can hangout with your geek friends, educateeach other, create values, andgive experience to you members.CsabaTothNashville,TN Java Users Group (NJUG)FINDYOURJUG HERELEARN MORE
  • What’s in Your Code?case study / s p o n s o r e d b y P a l a m i d aQ: Why do developers useopen-source software?A: Software developers are constantly facedwith the choice of taking the time to write codethemselves, or searching the Internet for codethat does what they’re looking for. For ten years,that is what’s been going on under the radar in theworld of software development. They are under thegun, they’ve got tight schedules, and they decideit is more productive to find an element of codealready out there on an open-source site, downloadit, put it in the code that they are developing fortheir company, and move on. And so what wefind in today’s world is that well over half of thecode commercial companies ship is code that theydidn’t write. Our typical customer either has noknowledge of the open-source code that they’reusing—even though they’re using hundreds ofpieces—or they know just one percent of it.Q: What are the issues around this?A: There are three issues: number one is intellectualproperty compliance and copyright infringement—respecting the rights of the authors as expressedin the open-source license that they have chosento govern the use of their software. Number two ismaintaining visibility and traceability so that issuessuch as security vulnerabilities can be identified andfixed. Number three is traceability for compliancewith export control regulations.Q: How can Palamida help?A: Palamida’s special-purpose search engine allowscompanies to scan and discover what makes uptheir code. We will tell you what components andversions you’re using and then supply informationsuch as license, known security issues, and whetheror not the open-source components containcryptography, which would make it subjectto export controls. Palamida offers twosolutions to match your business needs: asoftware product licensed as a subscription forcustomers who prefer to scan code and reporton results on their own, and a professionalservices product in which one of ourexperienced professionals scans the code anddelivers a complete analysis to the customer.Q: Why choose Palamida?A: As a seven-year-old company, we have aproven track record in this area. The averageduration of time our professionals have beenwith the company is over five years, so youknow you’re getting the best talent out there.Also, our search engine tracks over 800,000different open-source components. With our patentedsearch techniques, we search for and index the world’sopen-source software continuously, and every daywe add somewhere between three to five gigabytesof new material to our library. We are confident thatwe can deliver superior search results and give ourcustomers the information they need to effectivelymanage and secure their use of open source and otherthird-party content. zFor more information visit palamida.comPalamida’s CEO Mark Tolliver discusses how companies can ensure their software is compliant and secure.Mark Tolliver, CEO, Palamida
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY05JAVATECHABOUTUSJAVAINACTIONblogOn March 17, 2013, 10 kids gathered at the home of OracleJava Evangelist Arun Gupta to learn to program in Java usingMinecraft. This wildly popular game among elementary andmiddle schoolers allows players to build constructions oftextured cubes in a 3-D world. The game is written in Javaand can be extended by writing “mods,” or modifications.After spending a recent school break writing a few mods withhis son, Gupta decided to invite some other young Minecraftenthusiasts to a coding workshop. The attendees ranged inage from 10 to 14, and most had no programming experience,let alone Java experience. The group did, however, possessa lot of Minecraft experience. Gupta leveraged their passionfor the game and introduced them to Java programming.Using easily understandable concepts about cars and fruit,he introduced the core concepts of class, property, method,interface, and exception. Asked for a one-word description ofbuilding and running their first Hello World application usingNetBeans, workshop attendees responded: “Fun,” “Easy,”“Quick,” “Awesome,” “Short,” and “Intuitive.” By the end ofthe session, the group had worked out an entire frameworkfor making a mod. The mod built in the workshop added anew server-side command and printed a trivial message. Butthe joy on attendees’ faces was priceless. Want to host yourown Minecraft workshop? Get the details.PHOTOGRAPHS BY FRED WORLEYAND MENKA GUPTALeft: Young Minecraftaficionados listen toinstructions; right:Arun Gupta introducesJava programmingusing car and fruitanalogies.TEACH JAVA WITH MINECRAFT//javanation/Aditya Gupta shares his thoughtson the workshop.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY06JAVATECHABOUTUSJAVAINACTIONblog//java nation /The iJUG Association of JavaUser Groups, an umbrella groupfor Java user groups (JUGs) inGermany, Switzerland, andAustria, was formed in November2011 and has been growing eversince. iJUG cofounder MarkusEisele spoke with Java Magazine.Java Magazine: Who were theoriginal iJUG founders?Eisele: iJUG was founded byGerman Oracle User Group(DOAG), Java User GroupDeutschland, Java User GroupMunich, Java User GroupErlangen-Nürnberg, Java UserGroup Stuttgart, JUG SaxonyDresden, and JUG Köln.Java Magazine: How manysmaller, local JUGs coordinatetheir efforts with iJUG?Eisele: Twelve JUGs aremembers.Java Magazine: How many devel-opers in total are part of iJUG?Eisele: The 12 associated JUGsrepresent around 20,000 mem-bers and prospects.Java Magazine: What are thebenefits for the smaller JUGs?Eisele: iJUG’s focus is on foster-ing communication among thedifferent members, and differentactivities help to achieve this.First of all, Java Aktuell, a Java-centered, German print maga-zine and corresponding monthlydigital newsletter, is sent to themembers. We also cooperatewith the biggest IT publishinghouse in Germany, heise online,to get news items out. Goingthrough iJUG allows individualsto join the JCP [Java CommunityProcess] without having to sign apersonal JSPA [Java SpecificationParticipation Agreement].Java Magazine: What else wouldyou like to say about iJUG, orabout JUGs and community?Eisele: The biggest benefit iJUGis able to deliver is indepen-dence for individual members.Working locally within the exist-ing organization is augmentedby the umbrella with the powerof roughly 9,000 active indi-viduals. In line with the saying“Think globally, act locally,” iJUGcan funnel and communicatethe feedback from its individualmembers effectively and helpgrow the local JUGs by settingthem in the spotlight.German-speaking developerscan find out more at the iJUGWebsite.iJUGJAVA USER GROUP PROFILEDolphin BridgesJava Enterprise andJava DesktopDolphin, a free opensource library from CanooEngineering that protectsbusiness applications from the uncer-tainties of changing visualization tech-nologies, was released in April 2013.Dolphin, which is available for JavaFXand Swing, strictly separates businesslogic from visualization; has pluggableremoting, which keeps business logicon the server; and offers easy migrationbetween client technologies.In addition, visualization coderesides on the client (View), domainmodels and controllers remain on theserver, presentation models are sharedbetween client and server, and a servermay “push” commands to the clientby means of a long poll.See Dolphin in action.The overflow in the JavaFX abacus
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY07JAVATECHABOUTUSJAVAINACTIONblog//java nation /Antonio Goncalvesis a senior softwarearchitect, author,cofounder of theParis Java UserGroup and DevoxxFrance, and anactive member ofthe Java CommunityProcess (JCP), wherehe is an ExpertGroup member formany Java EE JSRs.He became a JavaChampion inJune 2009.Java Magazine:Where did yougrow up?Goncalves: In Paris,but I’m Portuguese,so I’ve spent my lifebetween two coun-tries, two cultures,two languages.Java Magazine:When did you firstbecome interestedin computers andprogramming?Goncalves: At schoolwhen I was 12. Wehad Thomson TO7and MO5 comput-ers (Motorola 6809processor–based)with some BASICcourses.Java Magazine:What was yourfirst computerand programminglanguage?Goncalves:Commodore 64with BASIC andassembly lan-guage. It was a timewhen CommodoreMagazine had doz-ens of pages withcode to developgames. So I literallyspent weeks writingcode, saving it ontoa tape, and runningand debugging it. Atthe time, GOTO wasa fantastic keyword.Java Magazine:What was your firstprofessional pro-gramming job?Goncalves: Writingbatches in COBOL.I wish I had kepton programminggames with myCommodore 64,but COBOL was thelanguage to know ifyou had to work andpay your bills. ThenC++, Smalltalk,some Visual Basic,and Java in 1998.Java Magazine:What do you enjoyfor relaxation?Goncalves: I stud-ied art history fortwo years, and I livein Paris. So I useand abuse all of itscultural resources.I’m always at jazzconcerts and artexhibitions.Java Magazine:What happens onyour typical day off?Goncalves: I writecode, blog, or dogeeky stuff. Mydaughter is eightyears old, so wego to concerts andexhibitions and takecycling day trips.Java Magazine:What side effects ofyour career do youenjoy the most?Goncalves: I havea very isolated job.Physically meet-ing people is veryrefreshing.Java Magazine:Has being a JavaChampion changedanything in yourdaily life?Goncalves: It helpsin meeting smartpeople.Java Magazine: JavaEE 7 is coming outsoon. What is mostsignificant aboutthis new release?Goncalves: Despitethe updates inJMS [Java MessageService] 2.0, JTA[Java TransactionAPI] 1.2, and JAX-RS2.0, the signifi-cant move aboutthis release is theintegration withCDI [Contextsand DependencyInjection]. More andmore Java EE 7specifications arestarting to embraceCDI, and this willbring cohesion tothe platform.Java Magazine:What are you look-ing forward to?Goncalves: To besurprised. My careerhas changed a lot.These changeshappened thanksto what I aimedfor, but also dueto unpredictablesurprises. As JohnLennon wrote, “Lifeis what happensto you while you’rebusy making otherplans.”Find more atAntonioGoncalves.org or on twitter.JAVA CHAMPION PROFILEANTONIO GONCALVESOpenJDKGoverning BoardElects At-LargeMembersThe OpenJDKGoverningBoard, which oversees thestructure and operation of theOpenJDK community, has electedtwo at-large members: AndrewHaley and Doug Lea. Both werepreviously serving as at-largemembers and began new one-year terms on April 1.Haley, of Red Hat, wrote in hiscandidate statement that hisgoal is to “stand up for freedomand steer the governing boardtoward helping people who crankout code to get their job done.”Lea, of SUNY Oswego, wrotethat he hoped “to continue myrole as an advocate for continu-ing improvements in OpenJDKprocesses and mechanisms,especially as they impact the aca-demic, research, and individualcontributor communities.”
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY08JAVATECHABOUTUSJAVAINACTIONblog//java nation /A pair of Devoxx conferences took place March 26–29 inLondon, England, and Paris, France. These developer con-ferences were all about Java, with topics including Java-related technologies and platforms, methodologies, cloud,infrastructure, and the future of Java, to name a few. Therewas a packed schedule of presentations by internationaland local speakers, three-hour-long hands-on labs, birds-of-a-feather discussions, and plenty of space to codein the Hackergarden. Altogether, the two conferencesattracted 2,000 developers from around Europe.Oracle was a European Partner for Devoxx. Oracle tech-nical staff presented sessions about the new featuresin upcoming Java EE 7, Java SE 8, the JavaScript engineNashorn, JavaFX, Raspberry PI, the Java CommunityProcess, Adopt-a-JSR, and more. The upcoming JavaEE 7 generated a lot of interest, especially sessions aboutWebSocket and standardized batch processing. Organized by the London Java Community, the firstDevoxx UK was full of humor, and matched the atmo-sphere of creativity and passion that developers sharefor their work. Kevlin Henney’s keynote, titled “TheProgrammer,” presented useful insights into who pro-grammers are and tips to increase programmer pro-ductivity. Watch the replay on Parleys. Martijn Verburg,cofounder of Devoxx UK, said the conference provided“quality content that will help developers in their day jobsand in their careers and support them in the passion theyhave for computing as a whole.”For its second anniversary, Devoxx France added a CTOtrack, a day on DevOps methodology, coding days, andcompetitions. Programatoo, a programming workshopfor 6- to 14-year-olds, ran for a day. According to NicolasMartignole, cofounder of Devoxx France, Programatoo wasDevoxx’ best investment for the future.DEVOXX UK AND DEVOXX FRANCEDid you miss JavaOnein 2012? Catch up onmany of the sessions,including conferencepresentations, birds-of-a-feather events,and tutorials. Morethan 450 videos, sortedin playlists by sessiontracks, are availableon Oracle LearningLibrary’s YouTubeChannel.JavaOne,WheneverYou Want ItLeft: the expo floor at Devoxx France;right: the Devoxx UK team
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY09JAVATECHABOUTUSJAVAINACTIONblog//java nation /In a recent Java.net poll,the Java developer com-munity overwhelminglyselected HTML5 sup-port as being the mostimportant enhance-ment in Java EE 7. Atotal of 1,631 votes werecast during the two-week survey. The finalvoting shares wereJAVA.NET POLLWHAT’S THEMOST IMPORTANTENHANCEMENTIN JAVA EE 7?Golo Language forJVM DemoedGolo, a simple, dynamic weaklytyped open source language forthe Java Virtual Machine (JVM),was unveiled at Devoxx France 2013. Developers canpick up this language, which favors the explicit overthe implicit, in a matter of hours, not days. The lan-guage was developed by the DynaMid research projectmembers of the CITI Laboratory at INSA-Lyon.Built from day 1 with invokedynamic, and currentlyin beta, Golo takes advantage of the latest advances ofthe JVM. It is also a showcase on how to build a lan-guage runtime with invokedynamic.Golo founder Julien Ponge says there were two rea-sons why he decided to create a new language, despiteso many languages being available for the JVM.“I am working in a small team whose focus is arounddynamic middleware and applications. As such, I amdeveloping my research expertise on everything thatsits between a dynamic application and its runtimeenvironment,” he explains. “Another good justificationis that the only way to develop expertise in an area issimply to make all the possible mistakes you can.”90%HTML5support,includingWebSocket(JSR 356)and JSONProcessing(JSR 353)3%JavaServerFaces 2.2(JSR 344)2%JAX-RS 2.0(the JavaAPI forRESTfulWebServices,JSR 339)2%ExpressionLanguage3.0(JSR 341)1%JavaMessageService 2.0(JSR 343)2%Somethingelse90%3% 2%2% 1%2%
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY10JAVATECHABOUTUSJAVAINACTIONblog//java nation /The final push to release Java EE 7 has been given a boost by Java user groups(JUGs) from around the world. Java enterprise developers have created theAdopt-a-JSR for Java EE 7 initiative specifically for JSRs related to Java EE 7.To participate, a JUG first selects one or more Java EE 7 JSRs that the memberswould like to support. Then, the JUG must join the Adopt-a-JSR program, reviewthe specifications for the selected JSRs, and contact the specification lead orExpert Group. JSR support tasks available to JUGs include building and testingReference Implementation (RI) builds, reporting bugs and other issues, helpingmoderate mailing lists, and helping build the Technology Compatibility Kit.At press time, 19 JUGs across five continents were participating in the Adopt-a-JSR for Java EE 7 initiative: BeJUG, Campinas JUG, CeJUG, JUG Chennai, CologneJUG, Congo JUG, FasoJUG, Houston JUG, Hyderabad JUG, Indonesia JUG, Jozi JUG,London Java Community, Madrid JUG, Mbale JUG, Morocco JUG, Peru JUG, SiliconValley JUG, SouJava, and Toronto JUG.Mobile World Congress used to justbe about mobile phones and theindustry around mobile networks.Judging from this year’s conference,held February 25–28 in Barcelona,Spain, it’s clear that mobile hasredefined itself and is about sensorseverywhere: cars, scooters, buildings,people, and more. The machine-to-machine or Internet of Things revolu-tion is here, with mobile phones asjust one of the many components thatcreate an intelligent, connected world.As the mobile industry moves itsfocus from voice to data, developersnow have the entire world as a poten-tial for apps.All this opportunity requires thatdecisions be made. Today’s develop-ers have a wide range of choices forwhat device to use and how to controlit. The device and the platform youchoose are key components for a suc-cessful implementation. Java enablesdevices to be intelligent, scalable,and supportable. Want to update adevice remotely? Done. Want it to beheadless? Done. Want a remote sen-sor on your grandmother that callsthe hospital if she falls, and also letsthe paramedics open the door to herhouse? Done.A Java-powered remote sensor can savethe life of an elderly person who falls.MobileWorldCongress:RedefiningMobileJUGS ADOPT A JSR FOR JAVA EE 7See how Java makes it easy to getstarted in mHealth.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY11JAVATECHABOUTUSJAVAINACTIONblogEVENTSJavaOne Shanghai JULY 22–25SHANGHAI, CHINAJavaOne Shanghai returns with four content-packed days ofkeynotes, technical sessions, hands-on labs, and demos.Topics include constructing modern applications using Java SE;creating rich and immersive client-side solutions using JavaFX;building mobile and embedded Java applications targeting next-generation smart devices; composing sophisticated Java EE–based enterprise solutions; and building and deploying businessapplications in the cloud securely and seamlessly.JUNENo Fluff Just Stuff (NFJS)JUNE 7–9, COLUMBUS, OHIOJUNE 13–14, SANTA CLARA, CALIFORNIAJUNE 21–22, SALT LAKE CITY, UTAHJUNE 28–30, AUSTIN, TEXASNo Fluff Just Stuff focuses on the latesttechnologies and best practices emergingin the enterprise software developmentspace. The speakers are authors, consul-tants, open source developers, and rec-ognized industry experts. Topics includeenterprise Java, agility, Hibernate, Spring,Groovy/Grails, Ajax, JavaServer Faces,and more.JULYFISLJULY 3–6PORTO ALEGRE, BRAZILThe International Free Software Forum(FISL) includes lectures, workshops,demos, and presentations about freesoftware.Java Forum Stuttgart 2013JULY 4STUTTGART, GERMANYJava Forum, organized by Java UserGroup Stuttgart, includes presentations,workshops, demos, and birds-of-a-feather sessions about Java.The Developer’s Conference (TDC)JULY 10–14SÃO PAULO, BRAZILOne of Brazil’s largest conferences fordevelopers, IT professionals, and stu-dents, TDC offers 21 tracks. Java-focusedcontent includes introductory sessionsin the Java University track, advancedand intermediate sessions in the JavaEE track, and mobile and embeddedsessions in the new mobile and embed-ded tracks. Other tracks include SOA,business process management, testing,architecture, and cloud computing.ÜberConf 2013JULY 16–19DENVER, COLORADOPart of the No Fluff Just Stuff SoftwareSymposium Series, ÜberConf exploresthe ever-evolving ecosystem of the Javaplatform. This event offers 160 techni-cally focused sessions including 25-plushands-on workshops centered aroundarchitecture, cloud, security, enter-prise Java, languages on the Java VirtualMachine, build/test, mobility, and agility.OSCONJULY 22–26PORTLAND, OREGONOpen source pioneers, experts, and inno-vators have gathered at OSCON over thepast 15 years. With a dozen tracks andhundreds of sessions, the conferenceoffers tutorials, keynotes, and a wealthof information on open source languagesand platforms. Get a 20 percent discounton registration with the code JAVAMAG.PHOTOGRAPH BY GETTY IMAGES//java nation /[art: Shanghia photo – please source]
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY12JAVATECHABOUTUSJAVAINACTIONblog//java nation /JAVA BOOKSCORE JAVA VOLUME I –FUNDAMENTALS,NINTH EDITIONBy Cay S. Horstmann andGary CornellInformIT (November 2012)Designed for seriousprogrammers, this no-nonsense tutorial illumi-nates key Java languageand library features withthoroughly tested codeexamples. As in previouseditions, all code is easyto understand, reflectsmodern best practices,and is specifically designedto help jump-start yourprojects. Volume I quicklybrings you up to speed onJava SE 7 core languageenhancements, includ-ing the diamond operator,improved resource han-dling, and catching of mul-tiple exceptions.BEGINNING JAVA EE,THIRD EDITIONBy Antonio GoncalvesApress (May 2013)This step-by-step andeasy-to-follow bookdescribes many ofthe Java EE specifica-tions and ReferenceImplementations, andshows them in action usingpractical examples. Thisbook uses the latest ver-sion of GlassFish to deployand administer the codeexamples.Written by an expertmember of the Java EEspecification requestand review board in theJava Community Process,Beginning Java EE, ThirdEdition offers an expert’sperspective on enterpriseJava technologies.LEARNING JAVA,FOURTH EDITIONBy Patrick Niemeyer andDaniel LeuckO’Reilly (June 2013)Java is the preferred lan-guage for many of today’sleading-edge technolo-gies—everything fromsmartphones and gameconsoles to robots, mas-sive enterprise systems, andsupercomputers. If you’renew to Java, the fourthedition of this best-sellingguide provides an example-driven introduction to thelatest language features andAPIs in Java 6 and Java 7.Advanced Java develop-ers will be able to take adeep dive into areas suchas concurrency and JavaVirtual Machine enhance-ments. You’ll also learn newways to manage resourcesand exceptions in yourapplications.Akure 2013Inspires YouthMore than 1,000 students attended the Akure2013 conference February 11–16 in Akure, Nigeria.This conference was the 15th annual nationalconvention organized by the Nigerian Associationof Computer Science Students (NACOSS), whichspans more than 125 educational institutionsand boasts 200,000 members. The conferencetheme, “Youth Relevance to Sustainable NationalDevelopment through Information Technology,”was inspired by NACOSS’ passion to addressthe leadership challenges faced by young andupcoming leaders in Nigeria. Subthemes includedleadership, the power of information and com-munications technology (ICT), ICT trends, and theimportance of industry-academia cooperation.Oracle Country Manager Layo Ajay gave a ses-sion on leadership and entrepreneurship, andOracle Java Evangelist Simon Ritter followed with a“Welcome to the Petabyte Age” session that high-lighted the growth in data and the “device to datacenter” approach of Java.With a GDP growing at a rate of 7 percent and thecountry being called one of the “Next 11,” Nigeriapresents an opportunity for software startups.
  • #1 Development Platform3 BillionDevices Run JavaComputers, Printers, Routers, BlackBerry Smartphones,Cell Phones, Kindle E-Readers, Parking Meters, VehicleDiagnostic Systems, On-Board Computer Systems,Smart Grid Meters, Lottery Systems, Airplane Systems,ATMs, Government IDs, Public Transportation Passes,Credit Cards, VoIP Phones, Livescribe Smartpens, MRIs,CT Scanners, Robots, Home Security Systems, TVs,Cable Boxes, PlayStation Consoles, Blu-ray Disc Players…Copyright © 2013, Oracle and/or its affiliates. All rights reserved. Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.oracle.com/goto/javaFonts: Univers LT Std. 75 Black, 65 Bold, 55 Roman, 45 Light,67 Bold Condensed, 57 CondensedPRODUCTION NOTESPUB NOTE: Please use center marks to align page.Please examine these publication materials carefully.Any questions regarding the materials,please contact Darci Terlizzi (650) 506-9775READER01LASER% Released5/152013Print Ad Resize85p4 x 64p0Java Magazine(Full Page Ad)Job #:Ref #:Headline:Date:Project:Type:Live:Trim:Bleed:413M_CRP_Java3BDev_rev_Jmag112M_CRP_Java3BDev_rev3 Billion Devices Run Java05/15/2013NAS/Global Regional FulfillmentMagazineNA85p4 x 64p0NA
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201314blogCOMMUNITYJAVATECHABOUTUSJAVAINACTIONContinuing our series of interviewswith distinguished members of theExecutive Committee of the JavaCommunity Process (JCP), we turn toMark Little, vice president of engineeringat Red Hat. Initially known for its EnterpriseLinux OS, Red Hat acquired JBoss in 2006and added enterprisemiddleware to its roster oftechnology offerings. RedHat participated heavily inthe development of boththe Java EE 6 specification and the just-released Java EE 7 specification.JCP Executive SeriesAConversationwithMarkLittleRed Hat’s vice president of engineering discusses Java EE 7 and the JCP.BY STEVE MELOANPHOTOGRAPHY BY JOHN BLYTHEMark Little, vice president of engineering atRed Hat, overlooks a clean room cooling and airfiltration system in the Newcastle Universitybuilding where the Red Hat offices are locatedin northeast England.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201315blogCOMMUNITYJAVATECHABOUTUSJAVAINACTIONJava Magazine: Red Hathas been very involved inthe evolution of Java EE 7.Can you comment onleading the specificationsfor CDI [Contexts andDependency Injection] 1.1,and Bean Validation, andparticipating in the devel-opment of a number ofother JSRs?Little: We led the CDI andBean Validation updates,because we were alreadyleading those in Java EE 6.And as you indicated,we’ve been very activeon a number of otherJSRs—including JTA[Java Transaction API],JCA [Java EE ConnectorArchitecture], and JMS[Java Message Service]updates.We’ve tried to be activelyinvolved, in one way or another, withall of the JSRs that have been updatedin Java EE 7. Even if we’re not leadingthem, it’s still important that we bringthe perspective of Red Hat customersand our wider open source communityto how Java EE is being adopted.Java Magazine: Can you comment onthe importance of these JSRs withinJava EE 7, and your experiences duringtheir refinement and evolution?Little: We think that CDI is probablythe most important addition to thewhole Java EE architecture that we’veseen in a number of years. And I don’tjust say that because Red Hat led theeffort, because it was really a groupeffort. I say it because we were hearingfrom many vendors that it was hard attimes to develop applications using thestandard Java EE stack. CDI has triedto greatly simplify that. So annotationsare a great addition to the language,and we’re now seeing them being usedin lots of different areas.Since Java EE 6 was released, we’veseen the momentum around it build-ing. We’re seeing a lot more peoplewho didn’t consider Java EE 6 on theirradar screen but who are now reallytaking a look at it as a means of sim-plifying the development of enter-prise applications. And they mentionCDI time and time again. So it waspretty obvious to us that we wantedto lead the update to CDI in Java EE 7,because there were some things thatwe couldn’t do in the version that wentinto Java EE 6. And there was also feed-back that we’d gotten from users whenJava EE 6 was finalized that we wantedto take into account.In terms of the process, we’vedone pretty much the same this timearound as we did with Java EE 6. All ofour processes are open—so we havean open mailing list, all the partici-pants see what everybody else is talk-ing about, and we have open issuetracking. The drafts go through a verywide revision process.Java Magazine: How has the WebProfile of Java EE 6 affected Red Hattechnologies, and how will that furtherchange for Java EE 7—in terms of newAPIs like WebSocket and JSON-P?Little: The growth and complexity ofthe Java EE stack is really not unique. Ifyou look at CORBA and DCE and otherstandards, you see a similar phenom-enon. Java EE 6 recognized that factand introduced the concept of a WebProfile, which is essentially a stripped-down version of the full profile.In terms of the impact that it had onRed Hat, we’d been delivering our ownversion of profiles to our communitiesfor some time. There was no standardthat we could present, but we couldoffer the ability to streamline the stack.If a customer didn’t want Web services,for instance, we could provide that.So I think the Web Profile was a reallygood thing to introduce as a standard.And the feedback that we’ve gottenhas been extremely positive. We see alot of people who might not have con-sidered Java EE 6, who are now lookingat the Web Profile, and then eventuallyupgrading to the full profile becausesome of the things that they wantaren’t in the Web Profile. So I think it’sa really good way to on-board moreusers, and from a company perspec-tive, to gain new customers.We saw a lot of new APIs in Java EE 6,including JAX-RS and CDI, which havereceived a lot of attention for the bene-fits they’ve brought to developers. WithLIttle conferswith a colleague.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201316blogCOMMUNITYJAVATECHABOUTUSJAVAINACTIONJava EE 7, we’re seeing theAPIs extend yet again withadditions such as JSON-Pand WebSocket, both ofwhich are vital for keepingthe enterprise Java stack atthe forefront of waves suchas cloud and mobile.Java Magazine: A varietyof cloud-related featuresoriginally intended for JavaEE 7 have been deferredto Java EE 8. Can you com-ment on this change, how Java EE isused in cloud environments today, andhow the technology will evolve in post–Java EE 7 releases?Little: From discussions with our com-munities and our customers, whatthey wanted was the ability to offloadapplications from their own infra-structure onto somebody else’s, butwithout having to reimplement. Andthe obvious way to do that is to ensurethat the platform you’ve been run-ning with your own hardware is on thecloud. From very early on, we’ve beenworking to ensure that our implemen-tations will run on an infrastructure asa service, and therefore form a plat-form as a service.When Java EE 6 came along, it actu-ally offered us an easier route to dothat, because with the profiles intro-duced in Java EE 6, it became easierfor us to offer a standard Web Profileand a standard full-profile platformto customers who want to run theirapplications in the cloud.We announced our ownplatform as a service backin 2011, which was initiallybased on a pre-release ofour Java EE 6–compliantapplication server. Andthen we released EAP6,which is our full imple-mentation, where we madethe announcement ofOpenShift, our platform-as-a-service offering.When we were originally working onJava EE 7, there were quite a lot of newJSRs that were going to be focused onmaking Java EE more cloud-aware. Butas I said, Java EE 6 is pretty darn goodin the cloud today. There are certainareas where it can be improved—interms of modularity and multi-tenancy. But I agree with the defer-ment move on these features, so thatwe could get Java EE 7 out on sched-ule. Those features will be in the nextrelease, and therefore Java EE 8 will beeven better for evolving clouds.Java Magazine: How will the JBossDeveloper Studio IDE reflect/utilizethe new offerings found in Java EE 7?Little: We try to keep JDBS at the van-guard of getting things in front of theactual developers, so we can deter-mine pretty quickly where the prob-lems are. If a change in CDI isn’t reallyright, for example, then we’ll get a lotof feedback from developers throughJDBS. So it’s important to us that weget these features into the IDE asquickly as we possibly can, so we canget people to kick the tires.Java Magazine: Java EE 7 has pruned anumber of older features (JSR 77,JSR 88, JSR 93, JSR 101, and so on). Howwill this be addressed in Red Hat’sJava EE 7 offerings?Little: This isn’t the first time that JSRshave been pruned. What we tend todo, and what I expect we will do withthese JSRs, is if they’re no longer in theJava EE 7 spec, then we will removethem from our Java EE 7–compliantimplementation.But we’ve got the Java EE 6 imple-mentation—AS7 [JBoss ApplicationServer 7] is the community version, andEAP6 [JBoss Enterprise Application 6]is the product version. And EAP6 issupported for seven years. So custom-BIG SPEC“WethinkthatCDIisprobablythemostimportantadditiontothewholeJavaEEarchitecturethatwe’veseeninanumberofyears.”Little says that opensource communities“drive everything wedo at Red Hat.”
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201317blogCOMMUNITYJAVATECHABOUTUSJAVAINACTIONers who really need those featurescan have them in a supported way foranother five or six years. For JSRs thatbecome optional, we will typically sup-port them in one way or another. Wewon’t remove them until they’re offi-cially removed from the Java EE stack.Java Magazine: In the big-picturesense of JCP involvement, how do youresolve and reconcile diverse interestswhen working with other membercompanies?Little: Everyone understands that Javaand Java EE are very important to ahuge part of our industry. So we have aduty to work together in its evolution.It’s really no different than working inOASIS or W3C or any of the other stan-dards groups. Issues may come up, andyou won’t always get everything thatyou want, but you have to compromise.Java Magazine: What are the issuesand balances between preserving cur-rent standards and promoting futureinnovation?Little: A big danger is standardizingtoo early—because all of the goodstandards are based on experience. Ifyou standardize too early, you end upwith APIs or data formats that are notfit for the purpose, and then nobodyuses them.But it’s a trade-off—if you wait toolong to standardize, then you can endup with vendor lock-in, or with mul-tiple different ways of doing the samething. One of the things that we’re try-ing to do in the Executive Committee isto encourage innovation in upstream,open source communities, aroundthings that we might want to see inJava EE 8 and Java EE 9.Java Magazine: How do you think theJCP can better serve the Java commu-nity, and how would you suggest pro-moting greater participation?Little: The work that the various Javauser groups have been doing, likeAdopt-a-JSR, is great. Everything wedo at Red Hat is driven by open sourcecommunities—we get a lot of feedbackon things that we’re going to propose inthe various JSRs long before we mightactually include it in a document. So wetry and bring our communities into theExecutive Committee in that way.Java Magazine: At last year’s JavaOne,you and Cameron Purdy gave a sessionexploring non-Java languages runningon the JVM [Java Virtual Machine]—how a Ruby developer, for example,can leverage the Java EE stack, uti-lizing features such as JMS or EJBs[Enterprise JavaBeans]. Can you dis-cuss this trend, in terms of an expand-ing Java community/ecosystem?Little: Over the last several years, we’veseen a growing adoption of languageslike JRuby and Clojure and Scala thatrun on the JVM. And we’re developingour own language, called Ceylon. Whatwe’ve been trying to do with these com-munities is encourage developers whomight have needs for high-performancemessaging, or transactions, or data-bases not to reinvent the wheel whenthere’s already a perfectly good set ofsolutions in terms of the Java EE stack.So we’ve tried to find out what theyexpect from a given API, say for mes-saging, write something with the widerdeveloper community, and then layerour stack, or at least part of our stack,underneath that. So Ruby developersare defining the API, and we’re provid-ing a binding of that API to our JMSimplementation.The last thing we want with thesenew language communities is for themto reinvent the same bugs that we had20 years ago. It’s far better for them touse what we’ve already got and improveupon it. And we have some very suc-cessful projects—like the Ruby project,called TorqueBox. Ultimately, the devel-opers don’t even need to know thatthey’re running on top of an applicationserver, or that they’re using a Java EEstack beneath the covers. </article>LEARN MORE• Java Community Process• Red HatSteve Meloan is a former C/UNIX soft-ware developer who has covered the Weband the internet for such publications asWired, Rolling Stone, Playboy, SF Weekly,and the San Francisco Examiner. He re-cently published a science-adventurenovel, The Shroud, and regularly contrib-utes to The Huffington Post.INNOVATION’S ROLE“Oneofthethingsthatwe’retryingtodointheExecutiveCommitteeistoencourageinnovationinupstream,opensourcecommunities,aroundthingsthatwemightwanttoseeinJavaEE8andJavaEE9.”
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201318COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogPHOTOGRAPHY BY STAN GODLEWSKI/GETTY IMAGESSLAM DUNK Java takes ESPN.comto the winner’s circle.BY DAVID BAUMManny Pelarinos (left), seniordirector of engineering, and SeanComerford, director of engineering,ESPN Technology, toss a ballaround at the office.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201319COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogIt was a quintessential Kobe Bryantmoment, and one that Los AngelesLakers fans will never forget. Duringthe final seconds of an ESPN night-time game against the Miami Heat, theLakers were down by two as they tookpossession of the ball for a final play.Ron Artest quickly passed the ball toBryant, but Dwyane Wade’s aggressivedefense wouldn’t give him the oppor-tunity for a shot. As the clock tickeddown to almost zero, Bryant fakedright, dodged left, and finally leapedbackward to launch a long three-pointjump shot over Wade’s outstretchedarms. The ball found the glass andbanked into the hoop, beating thebuzzer to send the LosAngeles Lakers to theireighth straight victoryover the Miami Heat.The stadium erupted,and Lakers fans every-where let out a collectivecry of victory. Thanks tothe work of engineersat ESPN Technology,millions of people hadan up-to-the-instantaccount of the actionthrough free mobile appson their smartphones,laptops, and tablets.As the leading providerof sports on the internet, ESPN.comprovides fans with late-breakingnews, game statis-tics, schedules, playerupdates, Fantasy games,and video throughWatchESPN, in additionto instantaneous scoresfrom live events like thisone. National BasketballAssociation (NBA) gamesare among the thou-sands of events thatESPN covers. Millionsof sports enthusiaststune into the site to fol-low football, baseball, hockey, soccer,NASCAR racing, and many other typesof matches, races, tournaments, andgames. During major sporting extrava-ganzas such as the FIFA World Cupsoccer championship, ESPN handlesmore than 100,000 hits per second.With help from Java, ESPN’s consumer-facing Websites have been architectedto handle this crushing load.“We build and enhance systemsthat must scale to meet the needs ofmillions and millions of fans,” saysManny Pelarinos, senior director ofengineering at ESPN Technology, adivision charged with creating, design-ing, investigating, implementing,and maintaining technologies usedat ESPN. “One of our most importanttasks from an engineering standpointhas been building our systems so thatthey perform extraordinarily well andscale horizontally. Java has always beenin our DNA. Right from the get-go, webuilt the site using Java.In fact, ESPN has beenusing Java since beforethe servlet specificationwas even created.”Click over to ESPN.comto check out the action.You’ll find scoreboardsfor your favorite teams,game highlights, andprofiles of all the players.You can tune into currentnews, watch replays fromrecent sporting events,Pelarinos and Comerford inthe pantheon of athletes atESPN headquartersINSTANT ACCESSEngineersatESPNTechnologygavemillionsofpeopleanup-to-the-instantaccountofthequintessentialKobeBryantmomentthroughfreemobileapps.SNAPSHOTESPN, INC.espn.go.comESPN.com is theofficial Website ofESPN and a divisionof ESPN, Inc.Headquarters:Bristol, ConnecticutIndustry:Media, news, andpublishingRevenue:US$8.2 billionEmployees:6,500 worldwideJava technologiesused:Java SE 1.6 and 1.7,Java EE 6
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201320COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogand learn about everything from pokertournaments to tennis matches.What appears to be a few simpleWeb pages is actually the front end ofa massive digital infrastructure com-prised of dozens of databases andapplications spread across hundredsof servers. Pelarinos and his team useservlets to dynamically generate Webpages that can be interleaved withstatic Web markup content. The result-ing pages are compiled and executedon ESPN’s server farm via a Java VirtualMachine runtime environment.ESTABLISHED POSITIONThese fundamental Java technologieshave been the foundation of ESPN’spopular Website since its launch in1997, along with a content manage-ment system that hosts importantinformation such as sports headlines,news stories, and configuration dataabout how to lay out the content onthe site. This nimble Java infrastructuredelivers current news along with results,game highlights, and stats to ESPN’smobile experiences and Websites. Itbreaks down the information by sport,team, player, and columnist, andinfuses it with personalized contentbased on consumer preferences.“The content management systemis the lifeblood of our Website,” saysPelarinos. “All the textual data thatcomes from our editors is housed inthat platform.”“We have deals with the NBA to con-sume data right from their systems,”Pelarinos continues. “The data takesthe form of a feed that gets put into aJava Message Service [JMS] queue. Wehave message-driven beans that mar-shal these feeds into our Java domainobject model.”The data is persisted into anotherESPN data store optimized for digitalconsumption using Java PersistenceAPI (JPA), a framework for manag-ing relational data in Java SE and JavaEE applications. Moments later, itupdates all the caches in the ESPNapplication tier to send updates tomillions of eager sports fans. All theentities are updated in near real time.Another system polls a specialized APIonce or twice every second and pushesupdates to fans.“Fans get score updates almostimmediately, and their renditionof the ticking clock represents theactual game clock in real time,” saysPelarinos. “The updates happen so fastthat it gives you the impression thatyou are right there at the stadium.”TECH MVPTo achieve this level of speed, scalabil-ity, and reliability, ESPN.com relies ona caching architecture and JPA.“Our JPA object model allows usto push data to Web applicationsor mobile services powering apps,”explains Sean Comerford, director ofengineering at ESPN Technology.Another important part of the archi-tecture is JMS, a message-orientedmiddleware API for sending andreceiving information betweenESPN.com’s many servers and appli-cations. JMS controls how Javaapplications create, send, receive,and read messages. It allows thecommunication between differentcomponents of a distributed applica-tion to be loosely coupled, reliable,and asynchronous. These are essen-tial attributes for a site that dependson constant communication amonga constantly expanding user base.Subscribers can click on updates todiscover additional information aboutthe event in question or drill intoESPN’s extensive databases of con-tent. They can sort sports informationby city if they want to read local newsor find out about upcoming events,games, and matches in their area.ON JAVA EE 7“WiththeintroductionofJavaEE7anditsease-of-useimprovementsinJMS,wewillhaveanopportunitytosimplifyourcodegoingforwardandbringnewdevelopersuptospeedmorequicklyonthiscriticalareaofourarchitecture.”
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201321COMMUNITYJAVAINACTIONJAVATECHABOUTUSblog“We’re heavily utilizing Java mes-saging,” states Comerford. “Over thelast five years, we’ve adopted JMS as astandard interface for asynchronousmessaging. It works reliably and solvesmany of the challenges around guar-anteeing a message is processed onceand only once.”Another major benefit of JMS isthe publish/subscribe model, whichpermits ESPN to share informationwith internal systems and add newsystems without changes to the pub-lisher. Content about sports, teams,and players, along with news storiesand updates, flows through ESPN’sJMS hub and is consumed by a myriadof consumers who can take action onthat content. In addition, that sameJMS hub is responsible for replicatingcontent in real time to other environ-ments, such as development and QA.“This approach is truly service-oriented, as it cleanly decouples theapplications that publish content fromthose that consume it,” Comerfordadds. “In fact, with the introduc-tion of Java EE 7 and its ease-of-useimprovements in JMS, we will have anopportunity to simplify our code goingforward and bring new developers upto speed more quickly on this criticalarea of our architecture.”JPA has enabled ESPN.com toachieve this same level of abstractionin the database tier. “The JPA codeis easier to read, understand, andmaintain,” says Comerford. “Anotherbenefit of this architecture is platformindependence; we can fairly easilychange our underlying data store if weneed to.”FAST BREAK TO THE FUTUREESPN Technology is on the cusp ofinnovation as it continues to enhanceone of the world’s most viewedWebsites.“We’re able to use the performanceand reliability of Java to continue topower our extremely high-scale sys-tems,” says Pelarinos. “Digital media ison the leading edge to begin with, andhere at ESPN.com we are always exper-imenting with new ideas and tech-nologies. It keeps our work continuallyfresh and interesting.”“At the end of the day, our goal isto serve sports fans,” Pelarinos con-cludes. “We continue to invest innew technologies to ensure that thishappens.” </article>Based in Santa Barbara, California,David Baum writes about innovativebusinesses, emerging technologies, andcompelling lifestyles.My local and global JUGsare great places to networkboth for knowledge and work.My global JUG introducesme to Java developers allover the world.Régina ten BruggencateJDuchessFINDYOURJUG HERELEARN MORE
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201322COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogPHOTOGRAPHY BY PAULO FRIDMANBankingon JavaA new system built on JavaEE brings stability andtransparency to the complexworld of trading financialcredit assignments in Brazil.BY PHILIP J. GILLFrom left: Cláudio Silveira, Einar Saukas, andFabiano Marques outside TIVIT headquartersin São Paulo, Brazil
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201323COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogMarques, Saukas, and Silveira collaboratein the TIVIT offices.Brazil has one of the world’s larg-est and most dynamic econo-mies—but in 2010 the country’sdecade-long economic success storywas threatened not by the global eco-nomic slowdown, but by a surprisingdiscovery made by the country’s cen-tral bank, the Banco Central do Brasil.Some Brazilian banks were resellingcredit assignments—essentially loancontracts arising from consumer,financing, and leasing transactions—more than once. Such double-dealing,the central bank realized, had createda R$4.2 billion hole in the Brazilianbanking system and the potential for anationwide financial crisis.“Apart from being obviously illegal,the actions of these banks createdinstability in the Brazilian financialsystem,” says Einar Saukas, a principalarchitect at Java specialty firm SummaTechnologies do Brasil and a consul-tant to TIVIT, an IT services company,both based in São Paulo. “The bankslost confidence in their ability to buythose credits, and to compensate forthat, they raised interest rates to coverthe increased risk,” explains Saukas.In turn, Saukas adds, “thisdecreased business turnover, slowedoverall economic growth, and raisedinterest rates for millions of consum-ers and businesses.”To quell the uncertainty and returnstability to the Brazilian economy,the central bank—which performsthe same functions in Brazil as the USFederal Reserve—set out to ensurethat such double-dealing could neveragain threaten the Brazilian bankingsystem and economy.Enter the Central de Cessão deCrédito (C3)—in English, Central CreditAssignment. C3 is a scalable, high-performance, distributed transactionsystem that now monitors the integrityof all credit assignment transactions.Written in Java, C3 was implementedin less than a year and quickly returnedstability to the Brazilian banking sys-tem, says Saukas, who adds that it“reduced risk, restored confidence,lowered interest rates, and helped theeconomy to grow again.” C3 also wonone of the first Duke’s Choice AwardsLatin America—a special honor forSaukas, who has worked on two otherDuke’s Choice Award–winning projects.For C3, the central bank contractedTIVIT, which chose to build the sys-tem on Java EE. “The Java EE platformwas a natural choice for C3,” explainsCláudio Silveira, TIVIT’s operationsdirector for applications. “In Brazil,Java has become a standard for bank-ing applications.”CONSUMER CULTUREWorldwide demand for Brazil’s natu-ral resources, agricultural products,manufactured goods, and businessservices has resulted in annual GDPgrowth exceeding 5 percent in mostyears since 1999 and has transformedSouth America’s largest country intothe world’s sixth-largest economy as of2011, surpassing the UK.That growth also lifted 31 mil-lion Brazilians into the middle class,which now comprises nearly half thecountry’s 193 million citizens. As inother thriving economies, growth ofthe middle class has been fueled byand has led to a boom in demand forconsumer loans for cars, mortgages,and leases. Today about a third of allBrazilians have some kind of con-sumer debt.To keep their coffers flush with cashfor new loans, Brazilian banks—likebanks in the US and elsewhere—resellSNAPSHOTTIVITtivit.com.brHeadquarters:São Paulo, BrazilIndustry:IT servicesEmployees:28,000Revenue:R$1.5 billion(2012 estimate)Java technology used:Java EE 6
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201324COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogtheir loan contracts to other banksand financial institutions as long-terminvestments. “When a person goes tothe bank to get a loan to buy a new car,for instance, they sign a contract to getthe loan,” explains Saukas, who con-sulted with TIVIT on the developmentof C3. “Since these institutions special-ize in making loans, they need moremoney fast to make new loans to otherpeople, so they resell these contractsto other banks.”In its first stage, C3—which oper-ates under the supervision of thecentral bank—was designed to moni-tor all credit assignment operationsbetween participating banks and torecord whenever one bank sold a creditto another financial institution. “Thatnegotiation has to be registered withC3, which detects instantly if someoneis trying to sell the same credit to twodifferent banks,” says Saukas.In the second stage, installed in2012, additional functions were addedthat allow C3 to negotiate and controlthe actual sale through the centralbank’s payment system, known asCETIP. “Through C3, thebuyer and seller negotiatethe sale of those creditsand the buyer is able toconfirm all the informa-tion from the other side,”says Saukas. “The systemcontrols the ownership,and payment for the cred-its is actually controlled byCETIP and the central bank.C3 transfers the ownershipfrom one bank to another,so the system is now fullyautomated.”PIPELINE ARCHITECTURETIVIT’s choice of Java EE,the Java platform for scal-able, high-performance,transaction-oriented appli-cations that are also highlysecure and reliable, wasa straightforward one. Inaddition to its widespreadpopularity in Brazilian bank-ing circles, Java EE was theonly platform that integratesthe comprehensive set ofAPIs needed for a system ascomplex as C3; these include the JavaMessage Service (JMS) and Java OpenTransaction Manager (JOTM).In addition, Java EE has wide-spread support from the open sourcecommunity; open source technolo-gies and development tools used todevelop C3 include XA distributedtransaction protocol, theSpring Framework, JBossSerialization, ApacheCommons, dom4j,XStream, Hudson, Sonar,Nexus, JUnit, Mockito,Maven, and Eclipse.The platform was alsochosen because TIVIT haddeveloped an earlier sys-tem with similar high-volume require-ments using Java EE: the Débito DiretoAutorizado (DDA), or Authorized DirectDebit, a real-time electronic billingand payment system. DDA, also writ-ten in Java, exchanges payment databetween participating Brazilian banksand allows Brazilians to both receiveand pay bills electronically. The sys-tem began operating in October 2009and currently has more than 8.6 mil-lion registered bank customers andmore than 729 million registered bills,processing 10 percent of the paymentvolume in Brazil.The C3 system was developed andput into production in less than a year,because TIVIT was able to reuse DDA’sMarques readies apresentation whileSaukas and Silveiradiscuss projects.MODERN ICONBrazil’sfederalcapital,Brasília,isconsideredaniconicmasterpieceofmodernarchitecture.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201325COMMUNITYJAVAINACTIONJAVATECHABOUTUSblogunderlying software infrastructure.“Using the same software infrastruc-ture lower layer as DDA reduced thedevelopment effort considerably,”says Fabiano Marques, TIVIT’s chiefJava architect. “Because of this, theentire C3 project, from initial conceptto production, could be done in thesame year. Most of the developmentfor the initial phase of C3 was executedin under two months.”That software infra-structure layer includesa unique “pipeline”architecture specificallydesigned to accommodatethe high volume of trans-actions and large amountsof data; this architectureconnects to a back-endDB2 database and a hier-archical storage manage-ment system.“To allow the flexibility needed bythe complex Brazilian banking system,the C3 system is structured as trans-actional Enterprise JavaBeans [EJBs]connected through JMS queues,”explains Saukas. “Requests are pro-cessed by a sequence of EJBs workingas a ‘pipeline,’ in which each beanreads from an internal JMS queue,performs a certain task or tasks, andforwards the results to the next bean.The EJBs use JOTM to guaranteetransactional consistency and integ-rity between JMS and DB2 operationsthrough XA.”“Integration through JMS queues,”Saukas continues, “also ensures auto-mated load balance and fault toler-ance—since multiple bean instances,from different servers, processrequests from each JMS queue as theybecome available, without the need fora centralized distribution logic.”To date, C3 has managed more than700 million credit installments worthmore than R$127 billion.More importantly, C3has helped return stabil-ity and certainty to theBrazilian financial system.“The Brazilian NationalBanks Federation and thecentral bank both creditthe system for decreasingoperational risks in creditassignments and allow-ing financial institutionsto lower interest rates onloans, financing, and leasing opera-tions,” says Saukas, noting that thishas had a definite positive impact onordinary Brazilians as well. “The lowerrates directly benefit the 61 millionBrazilian citizens who currently haveconsumer loans.” </article>JavainBrazil Besides being one of the world’s largesteconomies, Brazil also boasts one of theworld’s largest Java communities—it’s home to more than142,000 Java developers, according to Java.net.In fact, Brazil is home to the world’s largest and second-largest Java user groups (JUGs), each with more than40,000 members. The largest is SouJava, based in SãoPaulo, the country’s largest city and an international businessand financial center. The second largest is DFJUG, based inBrasília, the modernist federal capital district in the country’scentral highlands.Einar Saukas, a principal architect at São Paulo–basedSumma Technologies do Brasil, is a founder of SouJava andhas worked on three Duke’s Choice Award–winning proj-ects, including the Central de Cessãode Crédito (C3) distributed transactionsystem. Saukas explains that Java’spopularity is due in part to the Braziliangovernment’s encouragement. “A fewyears back, the Brazilian governmentrealized it had millions of documents ina proprietary format, Microsoft Word,”Saukas says. “The government did not want to risk vendorlock-in, so officials encouraged the country’s technology sec-tor to embrace open standards such as Java.”In addition to C3, Saukas has helped develop two othermajor Java applications that have won Duke’s ChoiceAwards—the Unified Health System for the Brazilian federalgovernment in 2003 and the City of São Paulo IntegratedPatient Scheduling System in 2005.Philip J. Gill is a San Diego, California–based freelance writer and editor who hasfollowed Java technology for 20 years.BIG MONEYBrazilwastheworld’ssixth-largesteconomyin2011,surpassingtheUnitedKingdom.Einar Saukas
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH26COMMUNITYJAVAINACTIONABOUTUSblog//new to java /This article is the first partof a three-part series, andit will demonstrate how touse Java EE 7 improvementsand newer Web standardssuch as HTML5, WebSocket,and JSON processing tobuild modern enterpriseapplications.In this part, we will see indetail how to use NetBeansIDE 7.3 and GlassFish 4 tobuild a complete three-tierend-to-end application usingthe following technologies,which are built into Java EE 7:■■ Java Persistence API (JPA)2.1 (JSR 338)■■ JavaServer Faces (JSF) 2.2(JSR 344)■■ Contexts and DependencyInjection (CDI) 1.1 (JSR 346)Note: The complete sourcecode for the applicationdesigned in this article canbe downloaded here.What Is Java EE?Java Platform, EnterpriseEdition (Java EE) is a dedi-cated Java platform fordeveloping and runningenterprise applications. JavaEE provides all you need tocreate large-scale, multi-tiered, scalable, reliable, andsecure network applicationsfor business.PrerequisitesEnough explanation is pro-vided in this guide to getyou started with the sampleapplication; however, thisarticle is not a comprehen-sive Java EE tutorial. Readersare expected to know aboutbasic Java EE concepts, suchas Enterprise JavaBeans(EJB), JPA, and CDI. The JavaEE 6 Tutorial is a good placeto learn all these concepts.Download and install thefollowing software, which wasused to develop the applica-tion described in this article:■■ JDK 7■■ NetBeans IDE 7.3 or higher“All” or “Java EE” version■■ GlassFish 4.0 b80Note: This article wastested using the latestversion of NetBeans IDE(version 7.3, at the time thisarticle was written).It is based on work createdand shared by Arun Gupta,Java evangelist at Oracle.Create a Real-LifeEnterprise Applicationwith NetBeans IDE 7.3In this practical section, wewill build a real-life Java EE 7enterprise application stepby step so that you can learnquickly the basics about thenew and important APIsLearn how to use the new and important APIs added to Java EE 7.MAXBONBHELBIOPart1Three Hundred Sixty–DegreeExploration of Java EE 7UserInterfaceDatabaseShowBookingAdd/DeleteMovieTicketSalesMoviePointsChatRoomPart2Part2Part3Part3Figure 1PHOTOGRAPH BYALLEN MCINNIS/GETTY IMAGES
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH27COMMUNITYJAVAINACTIONABOUTUSblog//new to java /improved in Java EE 7, such as JPA2.1, JSF 2.2, and CDI 1.1.What we are going to do is cre-ate a typical three-tier Java EE 7Web application that allows cus-tomers to view the show timesfor a movie showing at a seven-theater Cineplex and then to makereservations.Figure 1 shows the features thatwill be added and explained in thisarticle and the upcoming Part 2and Part 3.Table 1 details the componentsdesigned in this article and theselected technology used in eachcomponent’s implementation.Specifically, we will perform thefollowing tasks:■■ Install and configure GlassFishand NetBeans IDE 7.3.■■ Load a sample Maven applica-tion by following the instruc-tions and guidance.■■ Review the configured data-source and generate databaseartifacts, such as tables.■■ Create the Web pages that allowa user to book a particular movieshow in a theater.■■ Add and update existing code inorder to demonstrate the usageof different technology stacks inthe Java EE 7 platform.■■ Run and test the sampleapplication.Install and Configure NetBeansIDE 7.3 and GlassFish 4Let’s establish our developmentenvironment by downloading andinstalling the latest version ofNetBeans IDE and GlassFish.1. Download and install thelatest version of NetBeansIDE:a. Download the All or Java EEversion of NetBeans IDE 7.3or higher.b. Follow the installationinstructions here.2. Download the GlassFishserver and configure it inNetBeans IDE. To be sure weuse GlassFish as our applica-tion server, we are going tospecify it in NetBeans IDE:a. Download GlassFish 4.0.b. Unzip the compressed file inthe location where you wantthe glassfish4 folder to beplaced.c. Open NetBeans IDE and clickthe Services tab.d. Right-click Servers and thenchoose Add Server, as shownin Figure 2.e. Select GlassFish Server 3+ inthe Add Server Instance wiz-ard, as shown in Figure 3.f. Type GlassFish4.0b80 in theName field, and click Next.g. Click Browse, browse to thelocation where you unzippedthe GlassFish files, and selectthe glassfish4 folder.h. Click Finish.Bravo! Now your environment isready for fun.Walk Through the SampleApplicationIn this section, we will downloadthe sample application. Then wewill walk through the applicationFigure 2Figure 3Table 1FLOW DESCRIPTIONUSERINTERFACE WRITTENENTIRELYINJSF■■ SHOWBOOKING■■ SHOWTIMEFORTHESELECTEDMOVIEANDALLMOVIES■■ CONFIRMTHESELECTIONUSESLIGHTWEIGHTEJBBEANSTOCOMMUNICATEWITHTHEDATABASEUSINGJPAFigure 4
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH28COMMUNITYJAVAINACTIONABOUTUSblog//new to java /so we get an understanding of theapplication architecture.1. Download the initialNetBeans project:a. Download the sample appli-cation here.b. Unzip the compressed file inthe location where you wantthe movieplex7 folder to beplaced.c. Open NetBeans IDE and fromthe File menu, choose OpenProject.d. Select the unzipped directory,and click Open Project. Theproject structure is shown inFigure 4.e. Opening the project willprompt you to create a con-figuration file to configurethe base URI of the RESTresources bundled in theapplication, as shown inFigure 5. The applicationalready contains a sourcefile that provides the neededconfiguration, so click Cancelto dismiss this dialog box.2. Take a look at the Mavenconfiguration:a. Open the Project Files nodeof the movieplex7 project anddouble-click the pom.xml file.b. In the pom.xml file, you cansee that the javaee-api isspecified as a project depen-dency, as shown in Figure 6.This will ensure that Java EE 7APIs are retrieved fromMaven. Notice that a par-ticular version number isspecified and this must beused with the downloadedGlassFish 4.0 build.Review the Datasource andGenerate the Database SchemaIn this section, we will see in detailhow the components of the appli-cation are using JPA to communi-cate with the database.1. Configure the datasource:a. Open the Other Sources nodeof the movieplex7 project andthen expand the src/main/resources node.b. Open the META-INF node,Figure 5Figure 7Figure 6
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH29COMMUNITYJAVAINACTIONABOUTUSblog//new to java /and double-click persistence.xml. By default, NetBeansopens the file in Design View.c. Click the Source tab to viewthe XML source file, which isshown in Figure 7.Notice that <jta-data-source> is commented out;that is, no datasource ele-ment is specified. This ele-ment identifies the JDBCresource to connect to in theruntime environment of theunderlying application server.The Java EE 7 platformdefines a new default data-source that must be providedby the runtime. This precon-figured datasource is acces-sible under the JNDI namejava:comp/DefaultDataSource.The JPA 2.1 specifica-tion says that if neither thejta-data-source elementnor the non-jta-data-sourceelement is specified, thedeployer must specify a JavaTransaction API (JTA) data-source or the default JTAdatasource must be providedby the container.d. For GlassFish 4, the defaultdatasource is bound to theJDBC resource jdbc/___default.Clicking back and forthbetween the Design viewand the Source view mightprompt the warning shownin Figure 8. This will getresolved when we run theapplication. Click OK to dis-miss the dialog box.2. Generate the databaseschema. The scripts to gener-ate the schema are locatedin the META-INF directory.Because the location of thesescripts is specified as a URL,the scripts can be loaded fromoutside the WAR file as well.a. Open the Other Sources nodeof the movieplex7 project andthen expand the src/main/resources node.b. Open the META-INF nodeand execute the create.sql script to generate thedatabase schema shown inFigure 9.Figure 8Figure 9
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH30COMMUNITYJAVAINACTIONABOUTUSblog//new to java /JPA 2.1 introduces a new rangeof javax.persistence.schema-generation.* properties that canbe used to generate databaseartifacts such as tables, indexes,and constraints in a databaseschema. This feature allows yourJPA domain object model to bedirectly generated in a database.The generated schema mightneed to be tuned for the produc-tion environment. The proper-ties, their meanings, and possiblevalues are explained in Table 2.Create the Web Pages to Allow aUser to Book a MovieIn this section, we will create Webpages that allow a user to book aparticular movie show in a theater.We are going to use a new featureintroduced with version 2.2 of JSF.JSF 2.2 introduces Faces Flow,which provides an encapsula-tion of related views/pages withapplication-defined entry andexit points. Faces Flow borrowscore concepts from Oracle ADFtask flows, Spring Web Flow, andApache MyFaces CODI.Our application will build a flowthat allows the user to make amovie reservation. The flow willcontain four pages whose purposeis the following:■■ Booking page: Displays the listof movies■■ Show Times page: Displays thelist of available show times forthe selected movie■■ Confirmation page: Allows auser to create a reservation for aselected movie, show time, andtheater■■ Print page (ReservationConfirmed): Shows the reserva-tion informationWe will also use the WEB-INF/template.xhtml file to define thetemplate of the Web page with aheader, a left navigation bar, anda main content section. The fileis located in the WEB-INF direc-tory so that the template is acces-sible only from the pages that arebundled with the application. Ifthe template were bundled withthe rest of the pages, it would beaccessible outside the applicationand, thus, other external pagescould use it as well.1. Create the Booking page:a. In NetBeans IDE, right-clickthe Web Pages node of themovieplex7 project and selectNew and then Folder.b. Type booking in the FolderName field, and click Finish.c. Right-click the newly createdfolder, and select New andthen Other.d. In the dialog box, selectJavaServer Faces in theCategories section andFacelets Template Clientin the File Types section, asshown in Figure 10. Thenclick Next.e. Type booking in the File Namefield.f. Click Browse next to Templateand then select the template.xhtml file under the WEB-INF node.g. Click Finish.2. Edit and modify the booking.xhtml file:a. Change the <ui:define> sec-tion, so it looks like thatshown in Listing 1.The code in Listing 1 buildsan HTML form that displaysthe list of movies as radiobuttons. The chosen movie isbound to #{booking.movieId},which will be defined as aflow-scoped bean. The valueof the action attribute oncommandButton refers to thenext view in the flow, which,in our case, is showtimes.xhtml in the same directory.b. Click the hint (denoted witha yellow lightbulb) and clickthe suggestion to add anamespace prefix. Do thesame for the c: and f: prefix,as shown in Figure 11.Table 2PROPERTY MEANING VALUESjavax.persistence.schema-generation.database.actionSPECIFIESTHEACTIONTOBETAKENBYTHEPERSISTENCEPROVIDERWITHREGARDTOTHEDATABASEARTIFACTSnone, create,drop-and-create, dropjavax.persistence.schema-generation.create-sourceSPECIFIESWHETHERTHECREATIONOFDATABASEARTIFACTSISTOOCCURONTHEBASISOFTHEOBJECT/RELATIONALMAPPINGMETADATA,ADATADEFINITIONLANGUAGE(DDL)SCRIPT,ORACOMBINATIONOFTHETWOmetadata, script,metadata-then-script,script-then-metadataFigure 10
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH31COMMUNITYJAVAINACTIONABOUTUSblog//new to java /3. Create a booking Java beanand define it as a flow:a. Right-click the SourcePackages node of the movie-plex7 project and select Newand then Java Class.b. Type Booking in the Namefield and enter org.glassfish.movieplex7.booking in thePackage Name field.c. Add the @Named class-levelannotation to make theclass Expression Language(EL)–injectable.d. Add @FlowScoped("booking")to define the scope of beanas the flow. The bean isautomatically activated orpassivated as the flow isentered or exited.Add the following propertyin the Booking.java file:int movieId.e. Generate getters/setters byright-clicking anywhere in theedited source code.f. Select Insert Code, thenselect Getter and Setter, andselect the field.g. Add the public StringgetMovieName() method,as shown in Listing 2. Thismethod will return themovie name based upon theselected movie.h. Inject EntityManager in thisclass by adding the followingcode:Alternatively, a movie ID andname can be passed fromthe selected radio button andparsed in the backing bean.This will prevent an extra tripto the database.4. Create the Show Times page:a. Repeat Steps 1 and 2 tochange the content of the<ui:define> section, as shownin Listing 3The code in Listing 3 buildsan HTML form that displaysthe chosen movie’s nameand all the show times.#{timeslotFacadeREST.all}returns the list of all themovies and iterates overthem using a c:forEach loop.The ID and start time of theselected show are bound to#{booking.startTime}. The(value="Back") command but-ton allows the user to go backto the previous page, and the(value="Confirm") commandbutton takes the user to thenext view in the flow, which isconfirm.xhtml, in our case.Typically, a user will expectto see only the show timesfor the selected movie, butall the show times are shownhere. This allows us todemonstrate going backand forth within a flow if anincorrect show time for amovie is chosen.5. Modify the Booking.java file:a. Add the properties and meth-ods that will parse the valuesreceived from the form, asshown in Listing 4.b. Add another method that willfind the first theater avail-able for the chosen movieand show time, as shown inListing 5.6. Create the Confirmation page:a. Repeat Steps 1 and 2 to changethe content of the <ui:define>section, as shown in Listing 6.@PersistenceContextEntityManager em;Figure 11Download all listings in this issue as text<ui:define name="content"><h2>Pick a movie</h2><h:form prependId="false"><h:selectOneRadio value="#{booking.movieId}"layout="pageDirection" required="true"><c:forEach items="#{movieFacadeREST.all}" var="m"><f:selectItem itemValue="#{m.id}" itemLabel="#{m.name}"/></c:forEach></h:selectOneRadio><h:commandButton id="shows" value="Pick a time"action="showtimes" />}"/></h:form></ui:define>LISTING 1 LISTING 2 LISTING 3 LISTING 4
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH32COMMUNITYJAVAINACTIONABOUTUSblog//new to java /The code in Listing 6 dis-plays the selected movie, theshow time, and the theater, ifavailable. The reservation canproceed if all three are avail-able. print.xhtml, identifiedby the action of the commandButton with the Book value,is the last page, which showsthe confirmed reservation.actionListener can be addedto the commandButton toinvoke the business logic formaking the reservation.7. Create the Print page(Reservation Confirmed):a. Repeat Steps 1 and 2 tochange the content of the<ui:define> section, as shownin Listing 7.The code in Listing 7 dis-plays the movie name, theshow times, and the selectedtheater. The commandButtonis an exit point from the flowand takes the user back to thehome page of the application.8. Configure the flow:Since all the pages (booking.xhtml, showtimes.xhtml,confirm.xhtml, andprint.xhtml) are in the samedirectory, the runtime needsto be informed that theviews in this directory are tobe treated as view nodes ina flow.a. Right-click the Web Pages/booking folder, and selectNew and then Other.b. Select XML and then XMLDocument.c. Type booking-flow in theName field and click Finish.d. Modify the generated XMLfile booking-flow.xml so itlooks like Listing 8.9. Invoke the flow in the tem-plate.xhtml file. To do this,edit the WEB-INF/template.xhtml file and change thecommandLink from the codeshown in Listing 9 to the codeshown in Listing 10.commandLink renders an HTMLanchor tag that behaves like aform submit button. The actionattribute points to the directorywhere all views for the flow arestored. This directory already con-tains booking-flow.xml, whichdefines the flow of the pages.Test Our Sample ApplicationNow it’s time to test our moviereservation application. We willinvoke all the pages we created.1. Run the project by right-clicking the movieplex7node and then selectingRun. The browser shows theupdated output, as shown inFigure 12.2. Click Book a movie to see theBooking page, as shown inFigure 13.Download all listings in this issue as textpublic String getTheater() {// for a movie and showtry {// Always return the first theaterList<ShowTiming> list =em.createNamedQuery("ShowTiming.findByMovieAndTimingId",ShowTiming.class).setParameter("movieId", movieId).setParameter("timingId", startTimeId).getResultList();if (list.isEmpty())return "none";return list.get(0).getTheaterId().getId().toString();} catch (NoResultException e) {return "none";}}LISTING 5 LISTING 6 LISTING 7 LISTING 8 LISTING 9 LISTING 10Figure 12
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH33COMMUNITYJAVAINACTIONABOUTUSblog//new to java /3. Select a movie, for example,The Shining, and click Pick atime to see the Show Timespage, which is shown inFigure 14.4. Pick a time, for example,04:00, and click Confirm tosee the Confirmation page, asshown in Figure 15.5. Click Book to confirm thereservation and see theReservation Confirmed page,which is shown in Figure 16.Bravo!ConclusionJava EE 7 includes a number ofinteresting new features. In thisarticle, we created a three-tierWeb application using the follow-ing technology, which is part ofJava EE 7:■■ Java Persistence API 2.1 (JSR 338)■■ JavaServer Faces 2.2 (JSR 344)■■ Contexts and DependencyInjection 1.1 (JSR 346)Our sample movieplex7 Webapplication was designed so thateach of the new APIs matchesa specific need, for example,JavaServer Faces was used toimplement the user interfaceand Enterprise JavaBeans and theJava Persistence API were used toimplement the “show booking”functionality.In the next articles in this series,we will improve the movieplex7Web application by adding threenew functionalities—Add/DeleteMovie, ticket sales, movie points,and chat room—using impor-tant components and APIs pro-vided by Java EE 7, such as BatchApplications for the Java Platform1.0 (JSR 352), Java API for JSONProcessing 1.0 (JSR 353), Java APIfor WebSocket 1.0 (JSR 356), JavaTransaction API 1.2 (JSR 907), andJAX-RS 2.0 (JSR 339). </article>Figure 13Figure 14Figure 15Figure 16LEARN MORE• GlassFish resources• “Java EE 7—Introduction”• “Java EE 7 Hands-on Lab”• Java EE Platform specification
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH34COMMUNITYJAVAINACTIONABOUTUSblog//java architect /Part 1 of this series intro-duced the Java CompilerAPI and showed how toperform basic code parsing.Here, in Part 2, we will usewhat we’ve learned to builda full graphical code analysistool that goes beyond thepublic API and can actuallyunderstand Java code at thestatement level.Because the compiler APIsare some of the most under-documented parts of theJDK, what I will demonstratehere might not work in allcircumstances. We will onlyuse public APIs, but we willstress them to the limit.We will build a full codeanalysis tool that will dis-play a parsed codebase in athree-paned view. Each panehas a list: one for packages,one for classes, and one formethods and constructors.Using this browser, you cannavigate through the entiresource tree.When a package isselected, the class list isupdated to show only theclasses in that package. Themethod list behaves thesame way for the selectedclass. When you select amethod, the source of thatmethod is displayed in themain text area below thethree panes. To the rightis a smaller text area fornotes. On the bottom is aconsole area to show statusand errors. The finished GUIlooks like Figure 1.Note: Because this article isabout the Java Compiler API,not Swing, I will skip the codefor the GUI. It is standardGridBagLayout Swing codethat I built with the IntelliJIDEA GUI Builder. If you wantto see the full source code,download this file.The Code ModelThis is a big project, so let’sstart small. Everything in thetool works on an abstrac-tion of the source codebase,so we need to build a coremodel. The actual tree struc-tures provided by the JavaCompiler API contain all theinformation we need, butthey are not in a convenientpackage, so we will build ourown wrapper classes.First is the MethodModel,which represents every-thing we know about asingle method. A methodhas a name, the body (theactual statements inside themethod), and a list of param-eter variables and their types.The definition looks likeListing 1. I’ve also includedtwo longs for start and endas well as a reference to theCompilationUnitTree. I willexplain these later.Next is the class model,which represents a singleclass in the codebase. It hasBuild a full graphical code analysis tool that can understand Java code at the statement level.PHOTOGRAPH BYCHRIS PIETSCH/GETTY IMAGESPart2The Advanced Java Compiler APIFigure 1JOSHMARINACCIBIO
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH35COMMUNITYJAVAINACTIONABOUTUSblog//java architect /a class name and two collectionsof MethodModel representing themethods within this class. I amusing both a list and a methodmap because I need the meth-ods to be ordered (which the listprovides) and also addressable byname (which the map provides).Next is the ClassModel defini-tion (see Listing 2). There arealso accessor and util-ity methods for gettinga particular method byname or index and forsorting the methods.These accessors arenot shown. See the fullsource for details.The methodMap alsoensures that the meth-ods are unique. Javaallows two methods tohave the same name,so we can’t use just thename as the key for thehash map. We needsomething unique. To fix this,MethodModel.getUniqueName()will return a unique key based onthe method name as well as thenames of the parameters, whichmust be unique.The PackageModel andCodebaseModel classes look verysimilar to the ClassModel; they arejust higher levels (see Listing 3).PackageModel represents a singlepackage. The CodebaseModel rep-resents the entire codebase full ofpackages. Again, utility and acces-sor methods are not shown.Full Code ProcessingIn the previous article, we usedan annotation processor to ana-lyze the codebase. We will againuse an annotation processor, butthis time we need to add an extraAPI. The AnnotationProcessing API goesdown only to the methodlevel. To go inside themethods, we needan optional (but sup-ported) API called theJava Compiler Tree API.This API provides a treestructure that representsevery language con-struct in Java, includingif statements, for loops,and try blocks. It also hasutility classes to assistwith parsing tasks.To start, we will build a new pro-cessor called a FullCodeProcessor,as shown in Listing 4. As before, itis annotated as a processor for alltypes. I have overridden the initfunction to create an instance ofthe Trees class. This class will con-vert objects between the standardjavax.lang.model API and the com.sun.source.tree API.As before, we implement theprocess method. This time, wewill create a TreePathScannerinstead of an ElementVisitor6. ATreePathScanner is similar to theother visitor classes, but it workswith the Java Compiler Tree API. Italso keeps track of where we are inthe tree, so at any time, we can getthe path back to the root. The codein Listing 5 starts the processing.For each root element (pack-TO THE COREEverythinginthetoolworksonanabstractionofthesourcecodebase,soweneedtobuildacoremodel.Download all listings in this issue as textpublic class MethodModel implements Comparable<MethodModel> {public String name = "";public String body = "";public CompilationUnitTree compUnit;public long start;public long end;private List<String> varTypes = new ArrayList<String>();private List<String> varNames = new ArrayList<String>();LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH36COMMUNITYJAVAINACTIONABOUTUSblog//java architect /age), we add a new package modelto the codebase and then get thematching tree path. Then we callthe scanner on the tree path. Oncescanning is complete, we sort theclasses in each package and themethods in each class. Our imple-mentation of TreePathScanner(CodeScanner) does the real scan-ning work (see Listing 6). First, itoverrides visitClass to keep track ofwhich class we are inside as well asadd to the codebase model.Next, it overrides visitMethod tocreate a model for each method(see Listing 7). Inside, it loopsover all the method’s parametersto add a name and type for each.The type could be either a primi-tive or an identifier. An identifieris a reference to some real class,whereas a primitive is just one ofthe standard Java primitives (int,float, boolean, and so on). For eachcase, it calculates a type string.visitMethod also calculates thesource position to pull out themethod body. Let’s back up for asecond. A codebase is composedof CompilationUnit instances,which usually map to the actual.java files on disk. Each .java fileis just a big array of characters.The source positions are theoffsets into this character arraywhere a particular method startsand ends. By knowing these off-sets, we can pull out the actualsource code that defines eachmethod. The Java Compiler TreeAPI defines a SourcePositions classfor getting these values, whichare obtained from Trees. The codein Listing 8 gets the current treepath, finds the start and end off-sets, and then saves the methodbody into the model.Hooking Up the GUINow the FullCodeProcessor iscomplete. It is run in the callbackmethod for the Open button. Thecode in Listing 9 looks very similarto what we did last time, but it hasa few very important differences.Let’s walk through it.First, it creates a ConsoleHandler,which will report any errors.We will look at the code forConsoleHandler in a moment.Then, it gets the default com-piler and file manager. Noticethat the ConsoleHandler is passedinto the getStandardFileManagermethod. This will let the file man-ager report any file errors to thehandler. Next, it sets the outputdirectory for compiled classes to/tmp and it sets the source pathto a project I already have on mycomputer. (You would change thisto the path of the source code youwant to analyze.)To actually load the code, weneed a list of all the source filesusing filemanager.list(). Thekinds variable contains a Set ofJavaFileObject.Kind attributes. Thistells the file manager which kindsof files to list.Finally, we create the actualcompiler task. Notice thatthis time, the task is cast to aJavacTask. JavacTask is a subclass ofCompilerTask provided by the JavaCompiler Tree API. It does every-thing the CompilationTask does,plus a few extra things. Ratherthan invoking the compiler asa whole, you can separately callthe parse, analyze, and generatephases of the compiler, as shownin Listing 10. This task is specific toOracle’s implementation of javac,so it will not work with other com-pilers, such as Jikes.Now that we have a CompilerTask,we can set the processor, addthe ConsoleHandler to captureerrors, and then parse and ana-Download all listings in this issue as textprivate class CodeScanner extends TreePathScanner<Void, Void> {public Void visitClass(ClassTree classTree, Void aVoid) {String clsName = classTree.getSimpleName().toString();currrentClass = new ClassModel();currrentClass.name = clsName;currentPackage.add(currrentClass);return super.visitClass(classTree, aVoid);}LISTING 6 LISTING 7 LISTING 8 LISTING 9 LISTING 10
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH37COMMUNITYJAVAINACTIONABOUTUSblog//java architect /lyze the code. Once the codebaseis fully processed, we call a SwingRunnable to update the GUI.Notice in Listing 10 that we callparse before analyze. The parse()method just goes through all theJava code looking at the structure.It will check for basic syntax errors.Then analyze() performs a secondcompiler pass to see whether thecode actually makes sense. In thisphase, it will determine the typesof variables and class references.To understand the difference, con-sider this piece of code:After the parsing phase, wewould know that this code containstwo assignment statements result-ing in two variables named foo andbar. We know that the type of foo isString. We also know that the typeof bar is a class called Ensign, butwe don’t know anything else aboutit. We don’t know where Ensignis defined, what methods it has,or if it even exists. Only when theanalyze phase is complete will weknow this information. Actually,this is true for the String type aswell, because the developer couldhave overridden String with a dif-ferent import statement. We don’tknow anything about any typesuntil the analysis has been done.If we run the project at thispoint, we can load up a codebaseand browse by package, class, andmethod. The GUI will look likeFigure 2. Any parsing errors will beshown in the bottom console area.Converting Text into TreesNow that we can browse the code,let’s do something more useful.When we move the cursor aroundthe code, it would be nice if theGUI could show us the source forthe method under the cursor. Todo this, we need to first convertfrom the position in the text win-dow to the element in the treethat represents that same partof code. Then, if the cursor is in amethod call, we must match themethod call with the real methodand show the source in the notesarea on the right.The code in Listing 11 defines anevent handler that is called when-ever the cursor moves in the mainString foo = new String("foo");Ensign bar = new Ensign("bar");Figure 2private class CaretMoveHandler implements CaretListener {public void caretUpdate(CaretEvent caretEvent) {if(currentMethod == null) return;int dot = caretEvent.getDot(); //cursor positionin charactersCurrentMethodScanner scanner = new CurrentMethodScanner(dot,currentMethod,trees,Main.this);//scan every ASTfor(CompilationUnitTree ast : ASTs) {scanner.scan(ast,(Void)null);}locationLabel.setText(scanner.getDeepestPath());if(scanner.getInvokedMethod() != null) {notesArea.setText(scanner.getInvokedMethod().body);} else {notesArea.setText("");}}}LISTING 11Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH38COMMUNITYJAVAINACTIONABOUTUSblog//java architect /editing text area. It will be calledupon mouse clicks and arrowkeystrokes.The caretEvent has a propertycalled dot. This is the position ofthe cursor in characters from thestart of the text area. The eventhandler creates a new scannercalled CurrentMethodScanner,which will look for the elementthat matches dot. Once the scan-ner has finished going through theentire codebase (abstract syntaxtrees), it will set the location labelto the deepest path that the scan-ner found. This will let you knowwhere you are inside the codebase.If you are inside a method invoca-tion, the body of that method isshown in the notes area.Now, let’s look into the methodscanner (see Listing 12). It is asubclass of TreePathScanner. Lasttime, we overrode one of the visit*methods. This time, we will justoverride scan(), which is called forall elements in the tree. For eachelement in the tree, we will checkwhether the element contains thecursor position we are looking for.If it does, we will save the loca-tion. The real magic happens incontainsPosition().containsPosition gets the currenttree path and the current compila-tion unit. The unit will tell us theactual source file we are lookingat. If it is the right source file, thenthe code gets the start and endingpositions of the current element.The position of an element meansthe offset (in bytes) of that ele-ment within the actual source file.These positions are nested.For example, in the codeString bar = new String("bar"),the constructor invocation newString("bar") is inside the assign-ment statement, which containsthe entire line. This statementmight itself be inside a block,which could be inside a methodand inside a class.Positions always nest strictly.If the start and end position ofthe element contain the cursorposition, then we can say the cur-sor is currently inside this ele-ment. Notice that we have to addthe start position of the currentmethod. This is because the com-pilation unit counts from the startof the text file, whereas our textarea counts only from the start ofthe method. Adding the methodoffset accounts for this.The saveLocation() methodsaves the path to the current cur-sor location (see Listing 13). If theelement is a method invocationor a member select, then it callsfindMemberSelect() to find the realmethod. The findMemberSelect()method first looks at a memberselect tree to find the real methodit calls. First, it needs to knowthe real class, so we need to diginto findClassModel(), as shown inListing 14.Here, the code gets really tricky,so we need some background.The JDK uses two separate mod-els. First, we have a tree API thatrepresents the source code parsedinto a tree. Then, we have theElement API, which represents theactual classes and methods alongwith their relationships (who callswhom, who extends whom, andso on). These two APIs are sepa-rate, but we can convert from oneto another using the Trees utilityclass, which has a method calledgetTypeMirror() that will convert atree object into a type mirror. Fromthere, we can get the real element.First, the code checks whetherthe kind of tree is an IDENTIFIERand returns null if it is not. Then, ituses Trees to get the type mirror forthe identifier. It rejects types thatare not declared types (they almostalways are). From there, it can getthe underlying TypeElement.public class CurrentMethodScanner extends TreePathScanner<Void,Void> {private boolean containsPosition(Tree tree, long pos) {TreePath pth = getCurrentPath();if(pth == null) return false;CompilationUnitTree unit = pth.getCompilationUnit();if(unit.getSourceFile().equals(currentMethod.compUnit.getSourceFile())) {SourcePositions sp = trees.getSourcePositions();long realpos = pos + currentMethod.start;long start = sp.getStartPosition(unit,tree);long end = sp.getEndPosition(unit,tree);if(realpos >= start && realpos < end) {return true;}}return false;}LISTING 12 LISTING 13 LISTING 14Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH39COMMUNITYJAVAINACTIONABOUTUSblog//java architect /With the element in hand, wecan now fetch our class modelusing the class and package name(code not shown). The code justpaws through our class modelmap. Now we can return to thefindMemberSelect method shownin Listing 15.Now that we have theClassModel, we can get the methodelement using the same process.We use trees.getTypeMirror() togo from the tree path to a mirror,then we get the element, and thenwe look up the method modelfrom the ClassModel.If we run the code now, we willsee that the method location isupdated as we navigate throughthe source. Whenever the cursoris over a method invocation, thetarget method body will be shownin the notes area.Notice that some methodinvocations don’t show source.Instead, the notes area is empty.This is because the compilercouldn’t find that method. Thecompiler can analyze only thesource to which it has access. Ifyour code calls other libraries thatthe compiler doesn’t have thesource for, the method body can’tbe shown. This is especially true ofcode that calls Java runtime envi-ronment (JRE) methods.For example, if you run the toolon code that calls Document.getChildNodes(), the compiler willnever find the body ofgetChildNodes() because that ispart of the org.w3c.dom.Documentclass, not my XMLLib. The onlyway to fix this would be to addthe source to the JRE and to thesource path when you set up thecompiler.Finishing Touches andNext StepsFor the finishing touches, weneed to add a few more things.Remember the ConsoleHandlerclass? Listing 16 shows the source.Download all listings in this issue as textprivate void findMemberSelect(MemberSelectTree memberSelectTree) {ClassModel clazz = findClassModel(memberSelectTree);if(clazz != null) {TreePath curr = getCurrentPath();TreePath pth =TreePath.getPath(curr.getCompilationUnit(),memberSelectTree);TypeMirror mirror = trees.getTypeMirror(pth);if(mirror.getKind() != TypeKind.EXECUTABLE) return;ExecutableType ex = (ExecutableType) mirror;String methName =calculateMethodName(ex,memberSelectTree.getIdentifier());MethodModel methodModel = clazz.getMethod(methName);if(methodModel != null) {invokedMethod = methodModel;}}}LISTING 15 LISTING 16Figure 3
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH40COMMUNITYJAVAINACTIONABOUTUSblog//java architect /It implements bothDiagnosticListener andTaskListener so that itcan print messagesand event informationfor both the JavacTaskand the file manager.All the messages andevents are added to theconsole text area at thebottom of the screen.I’ve also addeda Compile button,which will simply callJavacTask.generate() togenerate real class filesfrom the parsed code-base. The class files willgo into whatever wasset as the CLASS_OUTPUT location.Figure 3 shows what the finalapplication looks like.From here, there is a lot morewe could do. First, some of thecode is not as efficient as it couldbe. The CurrentMethodScannerscans the entire codebase. Itcould be improved to scan onlythe compilation unit of themethod you are currently view-ing. It also handles only some treecases. It can look up methods butnot constructors (which are tech-nically different than methods inthe Java language).We could also add some simplesyntax highlighting, because ourscanners can now go down tothe statement level. Ifyou really want to getfancy, you could makethe editor live, mean-ing each time you editcode, the compilergenerates and runsnew class files. Nowthat we have the abilityto process full sourcecode, there are endlesspossibilities.ConclusionThis two-part articleintroduced you tomany parts of the JavaCompiler API, includingannotation processing,the language model, the com-piler tree, and the javac internalAPI. We typically think of onlydynamic languages as targets forcode manipulation, but with theJava Compiler API, we can per-form many of these same dynamictricks with plain old, superfast,mature Java code. </article>LEARN MORE• “The Advanced Java Compiler API:Part 1”COOL TOOLWewillbuildafullcodeanalysistoolthatwilldisplayaparsedcodebaseinathree-panedview.Usingthisbrowser,youcannavigatethroughtheentiresourcetree.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH41COMMUNITYJAVAINACTIONABOUTUSblog//java architect /Part 1 of this series servedas a gentle introductionto invokedynamic. It showedhow to obtain method han-dles, bind them to call sites atruntime, and then emit JavaVirtual Machine (JVM) byte-code with actual invokedynamic instructions. Part 1introduced you to invokedynamic, but the finer detailsof the java.lang.invoke APIremain to be explored.In particular, the methodhandle combinator chainsthat we built in Part 1remained fairly linear.Indeed, we had a methodhandle to a target method,and we sometimes per-formed arity and type con-versions to adapt a call siteand a target of differenttypes, for example, adapt-ing a call site of type (Object,Object)Object to a methodhandle of type (int, int[])int.This article shows thatmore-elaborate logic canbe put into method handlechains. We will see thatvalues can be filtered, con-ditional branching can bedone, and exceptions canbe caught. A very importantpoint is that you can create alot of programming logic bycombining method handles.In effect, correctly used, theMethodHandle API is versatileenough to abstract us awayfrom ever explicitly havingto use bytecode. This is verypowerful. We will presenteach of the correspondingcombinators through simpleexamples and explain howthey could be used in thecontext of real dynamic lan-guage implementations.Dancing with the TypesThe need to do type conver-sions quickly arises whenimplementing a language onthe JVM, especially for Javainteroperability purposes.Fortunately, doing conver-sions is often a simple matterof using filtering combinators.Suppose that we have theRichInt class shown inListing 1. It wraps a primitiveint type and adds a squaremethod. A full implementa-tion of an “improved inte-ger” in a language would, ofcourse, provide more thanthe square method, but thisimplementation shows thebasic idea.We can obtain a methodhandle to square and invokeit as long as we are passingan instance of RichInt as thereceiver, as shown in Listing 2.Wouldn’t it be convenientto pass int values instead,invoke square on them, andget back an int value?This kind of conversion canbe performed using thefilterArguments and filterReturnValue combinators ofthe MethodHandles class.filterArguments takes a posi-tion in the arguments list,followed by a variable num-ber of method handles. Eachmethod handle filters anargument starting from thatposition. filterReturnValueworks similarly, albeit with asingle method handle.We perform the methodhandle invocation usinginvokeExact, which requiresthat the arguments andreturn value types exactlymatch those of the methodhandle. This is not alwayspossible (that is, known atcompile time), in which casesinvoke and invokeWithArguments can be usedinstead. The difference isthat those methods need toperform type conversions,such as boxing and unboxingprimitive types. It is prefera-ble to use invokeExact when-ever possible, because it hasbetter performance.Creating a new instanceof RichInt does the conver-sion from an int to a RichInt.Calling the intValue virtualmethod of RichInt does theopposite. The code in Listing 3illustrates how it is done. ByLearn how to master the details of invokedynamic.JULIENPONGEBIOPHOTOGRAPH BYMATT BOSTOCK/GETTY IMAGESPart2Demystifying invokedynamic
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH42COMMUNITYJAVAINACTIONABOUTUSblog//java architect /doing so, we can treat int like aRichInt, call its square method, andreturn an int.Branching with guardWithTestDynamic language implementersfrequently need to map if/then/else conditional branching at acall site, for instance, to dispatcha method invocation to differenttargets based on the receiver typeor depending on some argumentvalue. The previous article showedonly linear combinator chains, butfortunately, it doesn’t have to bethat way.The MethodHandles class has amethod called guardWithTest thatis used to create a combinatorwith conditional branching. To doso, it takes three method handlesas its input:■■ A predicate method handle thatimplements the guard conditionand returns a Boolean■■ A method handle that is executedwhen the guard returns true■■ A method handle that is executedwhen the guard returns falseWhile the guard method handleconsumes the arguments that arebeing passed on the combinatorchain, it might not consume all ofthem. For instance, it might evalu-ate its condition based only onthe first parameter. The true andfalse branch method handles needto process all arguments, eitherdirectly or through further combi-nator-based adaptation.Let’s build an example in a classcalled Guards. We want to create achain of method handle combina-tors for a call site with an (Object)String signature, where we pass anobject and obtain a string repre-sentation for it. We expect special-ized representations for Integerand String arguments along witha general-purpose representationfor any other type. To do that, weprovide three static methods (seeListing 4).We will take advantage of guardWithTest to create a branchingstructure so that the target is anyof these three methods dependingon the argument class. Becausethere are three cases, we need twoguard methods, which are shownin Listing 5.Note that we suppose that thevalue won’t be null. We could haveused the instanceof operator, but itmight be slow with deep type hier-archies, so comparing referencesagainst getClass() (and maybe null,too) is the best bet in all caseswhere an instanceof check can beavoided. Our test method is shownin Listing 6.We first obtain a lookup object,and then we get method handlesfor the target and guard methods.Because the target methods havedifferent signatures, we need toDownload all listings in this issue as textpublic class RichInt {private final int value;public RichInt(int value) {this.value = value;}public int intValue() {return value;}public RichInt square() {return new RichInt(value * value);}@Overridepublic String toString() {return "RichInt{" + "value=" + value + "}";}}LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH43COMMUNITYJAVAINACTIONABOUTUSblog//java architect /adapt each to the call site type,which is (Object)String, using theasType combinator. This worksbecause it is obviously possible todeal with an Integer or a String asan Object.Remember that method handlechains are type-checked whenbuilt: failing to adapt the signa-tures with asType would raise anexception at runtime. Last but notleast, never forget that boxing andunboxing primitive types are costlyoperations that, as of yet, cannotalways be eliminated by the JavaHotSpot VM.Finally, we build a branchingmethod handle using a first guardWithTest. If the object type is anInteger, the intDisplay branch istaken; otherwise, the code fallsback to a second guardWithTestconstruct that looks for a String. Ittakes the stringDisplay branch orfalls back to the general-purposeobjectDisplay.Running this example yields thefollowing console output:In real dynamic languages,guardWithTest is often used tobuild inline caches with self-modifying mutable or volatile callsites. This idea comes from thedays of Smalltalk. Briefly, theidea is to cache the targetmethod handle when doingmethod invocations, as long asthe receiver objects encounteredat a call site remain of the sametype. Doing this yields dramati-cally better performance thanperforming a method handlelookup for each invocation.Inline caches can also be usedin adaptive runtimes, such asJVMs. The just-in-time (JIT)compiler generates native codeoutside of the interpreter thatmakes speculative assumptionsabout the code being executed,such as a receiver type being of acertain type or locks never beingused in a multithreaded context.Because such assumptions mightbe invalidated, generated native-code blocks (the “fast” path) haveguards to fall back to previouslyoptimized code or the interpreter(the “slow” path).Showing an example of aninline cache in this article wouldbe too lengthy, and many detailsof an inline cache’s implementa-tion depend on the target lan-guage’s runtime specificities.Instead, you are encouragedto look at the example by RémiForax in the JSR 292 Cookbookproject and then experiment withan adaptation for your own lan-guage’s runtime.Switch PointsThe SwitchPoint class is anotheruseful addition to the languageimplementer toolbox when itcomes to branching, especiallywhen a target should be executedas long as “some condition” ismet, forever reverting to a fallbacktarget as long as the condition nolonger holds.A typical case would be adynamic language in which meth-ods in object instances can bereplaced at runtime. A switch pointholds for as long as the method isstable, and then it gets invalidatedonce it is replaced. It is equivalentto a guardWithTest-based con-struction, albeit sometimes morestraightforward to use when manycall sites depend on the same con-dition not changing.Listing 7 is an example of a run-ner thread that takes two methodInteger = 1String = fooObject = truestatic class Runner extends Thread {final MethodHandle runHandle;final MethodHandle waitHandle;Runner(MethodHandle runHandle, MethodHandle waitHandle) {super();this.runHandle = runHandle;this.waitHandle = waitHandle;}@Overridepublic void run() {while (true) {try {System.out.println((String) runHandle.invokeExact());waitHandle.invokeExact();} catch (Throwable e) {throw new RuntimeException(e);}}}};LISTING 7Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH44COMMUNITYJAVAINACTIONABOUTUSblog//java architect /handles. The code is an infiniteloop in which runHandle is amethod handle of type ()String. Ityields a string value whenever it iscalled. waitHandle is of type ()voidand is supposed to put the threadto sleep for some arbitrary time.Our test method will exercise thethread in two phases:■■ runHandle will return “a” every500 milliseconds for about5 seconds.■■ Then runHandle will return“b” every 1,200 millisecondsafterward.To do that, we first define thestatic methods in Listing 8, whichwill later be used as methodhandle targets. Our test method isshown in Listing 9.As usual, we first constructmethod handles to our targetmethods. We then instantiate twoswitch points: one for the run­ner target and one for the waitingtarget.A SwitchPoint gives us a methodhandle by invoking the guardWithTest method. It is very similarto directly using a guardWithTestcombinator, as we previouslydid, except that it takes only twomethod handles. The first will beexecuted as long as the switchpoint is valid; the second is exe­cuted as soon as the switch pointis no longer valid.No explicit guard code is exe­cuted each time the SwitchPoint iscalled. The same semantics couldbe achieved using guardWithTestwith a guard that evaluatesagainst some reference object orexpression.We can then start the thread,passing it the method handlesfor the switch point targets. Thethread is then put to sleep for fiveseconds, after which we invalidatethe two switch points using theinvalidateAll static method of theSwitchPoint class. At this point,“a” gets printed every 1,200 milli­seconds until the application isterminated.Invalidating a set of switchpoints causes all of them toswitch their target branches.This is immediately reflectedacross concurrent threads withvolatile semantics. While this isa potentially costly operation, itcan be more effective to use aSwitchPoint in combination witha MutableCallSite than to rely on aVolatileCallSite just to ensure thatchanges get propagated as soon asthe invalidation happens. Again,the choice is best made based onperformance analysis against theinvalidation rate of your call sites.The choice of a SwitchPoint ver­sus a guardWithTest constructalso depends on how invalidationis done. In situations in whichthe invalidation depends only onthe receiver type or arguments,a guardWithTest is a good choice.Invalidation is a local call-timedecision and applies for, say, inlinecache constructs.Now, consider the case of adynamic language in which meth­ods can be modified not juston class definitions but also onobjects. A good example is theRuby programming language, inwhich you can define a class asfollows:class Foodef bar"bar"endendfoo = Foo.newputs foo.bar # prints barstatic String a() {return "a";}static String b() {return "b";}static void slow() {try {Thread.sleep(1200);} catch (InterruptedException e) {throw new RuntimeException(e);}}static void fast() {try {Thread.sleep(500);} catch (InterruptedException e) {throw new RuntimeException(e);}}LISTING 8 LISTING 9Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH45COMMUNITYJAVAINACTIONABOUTUSblog//java architect /This calls method bar on objectfoo, which is an instance of classFoo. Ruby also allows you to rede-fine bar on the foo instance:In such cases, there are many callsites that can depend on a givenmethod to remain valid, such ascalls to bar in the previous exam-ple. Invalidation happens when theinstance method is changed. Thiscould be done with guardWithTestand an instance-wide condition asa guard, but SwitchPoint is muchbetter. Indeed, all call sites can beinvalidated at once under volatilesemantics and, more interestingly,the overhead of a SwitchPoint isvirtually zero for as long as it doesnot need to be invalidated.Not So Exceptional ExceptionsMethod handle targets can throwexceptions, just like any Javamethod. Because call sites aredynamically bound at runtime, itis likely that you will find yourselfin a situation in which the tar-get raises an exception, but thebytecode surrounding the invokedynamic instructions makes noassumption about that exceptionto be thrown.The MethodHandles class pro-vides a combinator called catchException that can mimic a try/catch construction at the method-handle level. It takes a methodhandle that is the regular target,an exception class, and a methodhandle to be invoked as a catchblock equivalent. Similarly, thereis a throwException combinator inthe MethodHandles class that canbe used to throw exceptions at acall site.Our example is inspired by thesafe navigation operator (?.) foundin the Groovy programming lan-guage, which can be used to avoidthe infamous NullPointerExceptionwhen chaining method calls.Indeed, if a method in the middleof the chain returns null, the nextcall raises a NullPointerException.Placed as a method invocationoperator, the safe navigation oper-ator avoids this issue and returnsnull instead:If friends is null, or if there is no“mrbean” entry, mrbeanPhone isnull. The same code with just “.”could raise a NullPointerExceptionin such cases.Let’s build runtime support fora similar construction in whichwe return a value when the regu-lar target throws an exception.Consider the target method shownin Listing 10.Obviously, passing null asthe obj parameter will raiseNullPointerException. In suchcases, we would like to return adifferent representation using thetarget method handle shown inListing 11, which works with anycall site signature as long as thearguments are being wrapped intoan array. We can leverage catchException as shown in Listing 12.The method handle tostringAndHashCode is straight-forward. The one to npeHandlerrequires two adaptations usingintermediate combinators: one tocollect all arguments into an arrayof two arguments (asCollector) andthen a call site type adaptation.Once this is done, catchExceptionyields to us a method handle thatproperly routes a method calldispatch to stringAndHashCode,def foo.bar"[bar]"endputs foo.bar # prints [bar]def mrbeanPhone =person?.friends["mrbean"]?.phonestatic String stringAndHashCode(String prefix, Object obj) {return new StringBuilder(prefix).append(obj.toString()).append(" #").append(obj.hashCode()).toString();}LISTING 10 LISTING 11 LISTING 12Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH46COMMUNITYJAVAINACTIONABOUTUSblog//java architect /unless a NullPointerException israised. Executing the programgives the following output:The interesting point is thatexception handling and throwingcan be done using combinators.This does not require the cor-responding bytecode-level sup-port, which is, incidentally, morecomplicated, because you needto delimit a try lock and specifyan exception type and a jump to acatch block. Multiple catch clausesrequire suchconstructs tobe nested inbytecode. Bycontrast, a com-binator-basedsolution comesup with simplebytecode and acomposition offunctions.The questionof performanceis worth raising.Why not use aguardWithTest tocheck for a nullvalue instead ofwaiting for anexception to be thrown? As usual,your mileage varies depending onhow often you expect exceptionsto be raised. As their name sug-gests, exceptions should be rare.In such cases, you can gamble on afast dispatch to the target methodhandle and a slower dispatch inthe rare cases in which an excep-tion happens to be thrown. Alwaysbenchmark your solutions.ConclusionThis article concludes a series oninvokedynamic. We covered por-tions of the java.lang.invoke APIsthat allow more-elaborate logicto be made out of method han-dles. You should now be ready toexplore more of invokedynamic byyourself. This is a fairly low-levelAPI, but it comes with everythingyou need for supporting latebinding while not confusing theJVM when it comes to adaptiveoptimizations.Last but not least, higher-levellibraries, such as the Dynalinklinker, can greatly help by pro-viding some common runtimeplumbing logic. Indeed, develop-ing runtime support for a dynamiclanguage using the java.lang.invokeAPI is anything but trivial. Dynalinkprovides ready-to-use buildingblocks such as ready-made andefficient guarded invocations, typeconversions, overloaded methodresolution, variable argumentshandling, and more. Dynalink alsooffers a metaobject protocol librarythat can greatly facilitate theinteroperability between Java andDynalink-powered JVM languagessuch as Oracle’s Nashorn.Will you contribute to theinvokedynamic support of an exist-ing dynamic language for the JVM?Will you design your own lan-guage? Will you make fun hackswith invokedynamic? March on—the rest is history.Acknowledgements. The authorwould like to thank MarcusLagergren for his thoughtful andpositive feedback during thereview process. </article>>>> 666 #666>>> Hey! #2245797[null] -> [>>> , null][null] -> [null, null]LEARN MORE• John R. Rose, “Bytecodes MeetCombinators: invokedynamic onthe JVM”• “JooFlux: Hijacking Java 7InvokeDynamic to Support LiveCode Modifications” by JulienPonge and Frédéric Le Mouël• “JSR 292 Cookbook,” a collectionof common invokedynamicpatterns by Rémi Forax• Dynalink: Dynamic LinkerFramework on the JVM byAttila SzegediHANDLING LOGICElaboratelogiccanbeputintomethodhandlechains;forexample,valuescanbefiltered,conditionalbranchingcanbedone,andexceptionscanbecaught.One of the most elevating thingsin the world is to build up acommunity where you can hangout with your geek friends, educateeach other, create values, andgive experience to you members.CsabaTothNashville,TN Java Users Group (NJUG)FINDYOURJUG HERELEARN MORE
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH47COMMUNITYJAVAINACTIONABOUTUSblog//java architect /In this article, we will buildon the discussion startedin Part 1 and Part 2 of thisseries about lambda expres-sions. If you are not familiarwith the basic syntax ofJava 8 lambda expressions orthe streams approach, youshould read those articlesfirst to familiarize yourselfwith those concepts.Note: It is important torealize that lambda expres-sions are still a moving tar-get. This means that thecode examples from earlierbuilds of lambdas mightnot always work with more-recent beta builds. In par-ticular, the code in this articleuses the latest code from theOpenJDK Project Lambda.This represents an evolutionof the API, which is aheadof the Oracle Early Accessreleases but which is likelyto be much closer to the APIthat ultimately ships withJava 8.The Limits of CollectionsJava collections have servedthe Java language extremelywell. However, they are basedupon the idea that all theelements of a collection existand are represented some-where in memory. This meansthat they are not capable ofrepresenting more-generaldata, such as infinite sets.Consider, for example, theset of all prime numbers.This cannot be modeledas Set<Integer> becausewe don’t know what all theprime numbers are, and wecertainly don’t have enoughheap space to representthem all. In Java 7 and ear-lier versions, the only way tomodel the set would be towork with an Iterator repre-senting the set instead.It is possible to constructa view of data that worksprimarily with iterators andrelegates the underlying col-lections to a supporting role.However, this requires dis-cipline and is not an imme-diately obvious approach toworking with the Java collec-tions. With Java 7 and earlierversions, if you wanted touse this type of approach,you would typically dependupon an external library thatprovided better support forthis functionality.The upcoming release ofJava 8 addresses this use caseby introducing the Streaminterface as an abstractionthat is better suited to deal-ing with more-general datastructures than basic, finitecollections. This means thata Stream can be thought of asmore general than an Iteratoror a Collection.However, a Stream isnot really a data structure;instead, it’s an abstractionfor handling data.What does this distinctionmean? It means a Streamdoes not manage the stor-age for elements nor does itprovide a way to access indi-vidual elements directly fromthe Stream.Lazy and Eager EvaluationLet’s dig a little deeper intothe consequences of mod-eling an infinite sequenceof numbers. Some con-sequences include thefollowing:■■ We can’t materializethe whole stream to aCollection, so methodssuch as collect() won’t bepossible.■■ We must operate by pull-ing the elements out ofthe Stream.BENEVANSANDMARTIJNVERBURGBIOLazy evaluation and parallel operations enable optimizations that were not available before.Part3AdvancedOperationsUsingJava8Lambda ExpressionsPHOTOGRAPHS BYJOHN BLYTHE AND BOB ADLER
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH48COMMUNITYJAVAINACTIONABOUTUSblog//java architect /■■ We need a bit of code thatreturns the next element as weneed it.This approach also means thatthe values of expressions are notcomputed until they are needed. Itmight not seem so, but this simplestatement actually represents ahuge step for Java.Before Java 8, the value of anexpression was always computedas soon as it was bound to a vari-able or passed into a function.This is called eager evaluation andit is, of course, thedefault behavior forexpression evalua-tion in most main-stream programminglanguages.With Java 8, a newprogramming para-digm is being intro-duced for Java: Streamuses lazy evaluation.This is an extremelypowerful new feature,and it takes a bit ofgetting used to.Let’s look at a map/filter pipe-line, such as the one we discussedin the last article (see Listing 1).The stream() method returnsa Stream object. The map() andfilter() methods (like almost all theoperations on Stream) are lazy. Atthe other end of the pipeline, wehave a collect() operation, whichmaterializes the entire Streamback into a Collection. This methodis eager, so the complete pipelinelooks like Listing 2.This means that, apart fromthe materialization back into theCollection, the platform has com-plete control over how much of theStream to evaluate, which opensthe door to a range of optimiza-tions that are not available in Java 7and earlier versions.Lazy evaluation requires morecare from the programmer, butthis burden largelyfalls upon the librarywriter. The aim oflambda expressionsin Java 8 is to simplifylife for the ordinaryprogrammer, even ifthat requires extracomplexity in theplatform.Handling PrimitivesOne important aspectof the Stream API thatwe have glossed overuntil now is how to handle primi-tive types. Java generics do notallow a primitive type to be usedas a type parameter, so we cannotwrite Stream<int>.However, the eagle-eyed readermight have noticed that in the lastarticle, we had a bit of code likethe code in Listing 3 for finding theaverage age of some otters.This code actually uses primitivetypes over most of the pipeline,so let’s unpack this a bit and seehow the primitive types are used incode like this.First off, don’t be confused bythe cast to double, which is justto ensure that Java does a properaverage instead of performinginteger division.The argument to map() is alambda expression that takes in anOtter and returns an int. If we couldwrite the code using Java gener-ics, the lambda expression wouldbe converted to an object thatimplements Function<Otter, int>.However, because Java generics donot allow this, we need to encodethe fact that the return type is intin a different way—by putting it inthe name of the type.So the type that is actuallyinferred is ToIntFunction<Otter>.This type is known as a primitivespecialization of the function type,and it is used to avoid boxing andunboxing between int and Integer.This saves unnecessary genera-tion of objects and allows us touse function types that are spe-cific to the primitive type that’sbeing used.Let’s break down the averagecalculation a little more. To getthe age of each otter, we use thisexpression:Let’s look at the definition ofthe map() method that is beingcalled:From this we can see that weare using the special function typeToIntFunction, and we’re also usinga specialized form of Stream torepresent the stream of ints.ots.stream().map(o -> o.getAge())IntStreammap(ToIntFunction<? super T> f);PARALLEL SUPPORTThelazyevaluationapproachforstreamsallowsthelambdaexpressionframeworktoprovidesupportforparalleloperations.Download all listings in this issue as textstream() filter() map() collect()Collection -> Stream -> Stream -> Stream -> CollectionLISTING 1 LISTING 2 LISTING 3
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH49COMMUNITYJAVAINACTIONABOUTUSblog//java architect /After this, we pass to reduce(),which is defined as follows:This, too, is a specialized formthat also operates purely on intsand takes a two-argument lambda(both arguments are ints) to per-form the reduction.reduce() is a collecting opera-tion (and, therefore, eager), so thepipeline is evaluated at that pointand returns a single value, whichis then cast to a double and turnedinto the overall average.If you missed all of this detailabout primitives last issue, don’tworry. One of the good thingsabout type inferencing is thatsome of these differences can behidden from the developer mostof the time.We’ve talked about why theStream<T> abstraction is poten-tially more general than Java 7collections, so let’s turn to oneof the most important use cases:parallelism.Parallel OperationsOne of the primary goals for ProjectLambda was to upgrade Java sup-port for collections to allow effi-cient use of multicore processors.for loops are serial. In Java 7 andearlier versions, all operations oncollections are serial. This meansthat no matter how large the col-lection that is being operated onis, only one core will be used toexecute the operation. As data setsget larger, this is not appropriate.The lazy evaluation approach forstreams allows the lambda expres-sion framework to provide supportfor parallel operations.The primaryassumption in theStream API is thatcreating a Stream(whether from aCollection or by someother means) shouldbe cheap, but theremight be operationsin the pipeline thatare expensive. Thisassumption allows usto characterize a paral-lel pipeline like this:The single method parallel() con-verts a Stream that was previouslyserial so it is parallel. This capabil-ity allows ordinary developers torely on parallel() as the entry pointto parallelism, and it places theburden of providing parallel sup-port on the library writer.To finish, let’s look under thehood to see how the platformimplements parallelism by rely-ing on a new concept called aSpliterator.SpliteratorsIn order to parallelize, we startwith a single Stream and end upwith multiple streams(which might need tobe recombined at theend). This requires anabstraction that canboth iterate and splititself into multipleparts. This abstrac-tion is represented bya new interface typecalled java.util.Spliterator, whichhas two methods—tryAdvance() andtrySplit()—that repre-sent the iterative andsplitting natures ofthe Spliterator.The task of writinga library that can automaticallyparallelize a Stream is not straight-forward, so any special proper-ties an individual Stream has thatcan help should be exploited. Inthe Spliterator interface, this ishandled by declaring any usefulcharacteristics as a set of flags. Thefollowing are some of the mostcommon flags:■■ DISTINCT indicates that all ele-ments coming from the sourceare different from each other.■■ SORTED indicates that the ele-ments are produced in a sortedorder.■■ SIZED indicates that there are aknown and finite number of ele-ments in the stream.■■ NONNULL indicates that no ele-ments coming from the sourceare null■■ IMMUTABLE indicates that thesequence of elements cannotbe modified after the source hasbeen created.The standard library has sup-port for spliterators at a numberof levels.One of the simplest ways touse a Spliterator is to start with anIterator and use a factory methodin the java.util.Spliterators class toproduce a Spliterator. From this, aStream can be easily constructedfrom one of the factory methods injava.util.stream.Streams.Spliterators, like the rest of theStream API, also contain primi-tive specializations of the classesto support using primitive typesin places where this would notbe allowed by the rules of Javagenerics.ConclusionJava 8 introduces the Stream API,which enables developers to workIntStreammap(ToIntFunction<? super T> f);s.stream().parallel().streamOps().collect();THE POWER OF LAZYWithJava8,anewprogrammingparadigmisbeingintroducedforJava:Streamuseslazyevaluation.Thisisanextremelypowerfulnewfeature,andittakesabitofgettingusedto.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH50COMMUNITYJAVAINACTIONABOUTUSblog//java architect /with datasources that are moregeneral than basic, finite collec-tions. For example, a Stream canrepresent an infinite set.The Stream API is lazily evalu-ated and makes heavy use oflambda expressions, which meansthe platform has complete con-trol over how much of a Streamto evaluate. Lazy evaluation andthe lambda expression frame-work open the door to a range ofoptimizations that were not avail-able in Java 7 and earlier versions,for example, support for paralleloperations.Automatic parallelism isachieved through the use of theparallel() method, which convertsa Stream that was previously serialso it is parallel. Under the hood, anew abstraction called a Spliteratoris responsible for implementingthe parallelization functional-ity. Spliterators, like the rest ofthe Stream API, contain primitivespecializations of classes to sup-port using primitive types in placeswhere this would not be allowedby the rules of Java generics.In this series of three articles,we have explored the lambdaexpressions feature coming inJava 8. We looked at the syntax,and discussed automatic con-version, type inference, and theupgrades to the collections librar-ies (including default methods).We talked about the new Streamabstraction, lazy evaluation, andprimitive specialization. Finally,we introduced automatic parallel-ism and the mechanism known asSpliterators, which provide muchof this functionality.It seems certain that withthe release of Java 8, lambdaexpressions and their associ-ated upgrades will become a veryvaluable part of the Java devel-oper’s toolbox. Their introductionbreathes new life into the plat-form’s capabilities, and will have amajor impact on almost every Javacodebase and project. </article>LEARN MORE• For help with lambda expressionsor to join our global hack days, jointhe Adopt OpenJDK project.LEARN MOREI have met so many amazing peoplethrough the London Java Community—friends, mentors, new colleagues—and through it I have achieved muchmore than I could have on my own.Trisha GeeLondon Java Community (LJC)FINDYOURJUG HERE
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH51COMMUNITYJAVAINACTIONABOUTUSblog//java architect /With every passing year,we draw closer andcloser to achieving the visionof the ubiquitously con-nected global village. Thenumber of internet userstoday exceeds 2 billionworldwide, with global inter-net penetration estimated togrow from 34.3 percent at theend of 2012 to 45 percent ofthe world’s projected popu-lation by the end of 2016. Forthe world of software devel-opment, this offers uniqueopportunities to lower devel-opment costs and improveproductivity and through-put by utilizing geographi-cally dispersed teams andprocesses.Data production isexpected to be 44 timesgreater in 2020 than it wasin 2009, reaching a world-wide total of 7.9 zettabytes(or eight trillion gigabytes) by2015. Developers are underpressure to use that datato create more-compellingapplications. Also, companiesare searching for solutionsthat will provide unprec-edented capacity, scalability,and speed to keep pace withthat explosive growth.There’s another trendaffecting developers: mobil-ity is untethering individualsfrom the need to be at anyparticular place in order tobe productive. In 2011, 420million smartphones and66 million tablets were sold.In 2016, those numbers areprojected to balloon to 1.2billion smartphones and tab-lets being sold. Project teamsare global, sharing code andcollaborating from anywherein the world as seamlesslyas possible. They need infra-structure that allows them todo that.Social platform adoption issuch an integral part of ourlives that 90 percent of allinternet users now have anaccount on at least one socialservice, and there are morethan 13 million businesspages on Facebook alone. Associal behaviors continue toincrease, modern develop-ment environments mustkeep pace and offer similarlevels of seamless and fre-quent interaction.Due to the need forcutting-edge infrastructures,enterprises are facing pres-sure to modernize to achievethe flexibility, scalability, andresponsiveness that will helpthem remain competitive.But companies can rarelyafford to rip out and replacetheir entire infrastructure orretrain their staffs. Adoptinga standards-based cloudinfrastructure enables com-panies to modernize at agradual pace.As a result of these trends,application needs are grow-ing exponentially. In addition,the pace and competitivenessof development put enor-mous pressure on productiv-ity, throughput, and quality.But development resourcescontinue to grow as linearlyas ever, resulting in a grow-ing “development gap” (seeFigure 1). It’s the ability to fillin this development gap thathas made the cloud such avaluable force in the devel-oper world.According to Gartner, thepublic cloud services mar-ket is forecast to grow 18.5percent in 2013 to totalUS$131 billion worldwide,up from US$111 billion in2012. Market dynamics varysubstantially when consider-ing cloud services’ marketWhat’s Driving the Cloudfor Developers?A cloud primer for Java developers.DIBYMALAKARBIO
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH52COMMUNITYJAVAINACTIONABOUTUSblog//java architect /size and market growth acrossthe different regions of the world.According to Gartner, the emerg-ing markets in Asia Pacific, LatinAmerica, Eastern Europe, theMiddle East, and North Africa showthe highest growth rates whilerepresenting the smallest overallmarkets. China is the exception,being both a large and growingmarket. The mature markets ofNorth America, Western Europe,Japan, and the mature Asia Pacificcountries constitute the larger, butslower-growth, markets.Fundamental Models ofCloud ComputingCloud computing providers offertheir services according to threefundamental models: infrastruc-ture as a service (IaaS), platformas a service (PaaS), and softwareas a service (SaaS), where IaaS isthe most basic model and eachhigher model abstracts from thedetails of the lower models. Thedistinctions are as follows.IaaS. In the most basic cloud-service model, providers of IaaSoffer computers—physical or(more often) virtual machines—and other resources. To deploytheir applications, cloud usersinstall operating system imagesand their application software onthe cloud infrastructure. In thismodel, the cloud user patches andmaintains the operating systemsand the application software.PaaS. In the PaaS model, cloudproviders deliver a computingplatform that typically includesan operating system, a program-ming language execution envi-ronment, a database, and a Webserver. Application developers candevelop and run their softwaresolutions on such a cloud platformwithout the cost and complexity ofbuying and managing the underly-ing hardware and software layers.SaaS. In the SaaS model, cloudproviders install and operate appli-cation software in the cloud andcloud users access the softwarefrom cloud clients. The cloud usersdo not manage the cloud infra-structure or the platform on whichthe applications are running. Thiseliminates the need to install andrun the applications on the cloudSPOTLIGHT:OracleJavaCloudServiceOracle Java Cloud Service provides an enterprise-gradeplatform to develop and deploy business applications inthe cloud. It uses Oracle WebLogic Server in the cloudand offers choice, an open environment, security, andease of use. Oracle Java Cloud Service supports Javastandards and offers flexibility, portability, and deployment options.Choice. Developers have a choice when it comes to the IDE, application devel-opment and deployment, service integration, and monitoring and managementservices. Starting with the IDE, Oracle Java Cloud Service supports variousplatforms—from Eclipse and Oracle JDeveloper to NetBeans. At the click ofa button, you can deploy your applications onto Oracle Java Cloud Service. Ifyour development cycle involves team development, you can easily deploy yourapplications from your key development environment onto Oracle Java CloudService or other standards-based environments. There are also choices forservice integration, including Web services, SOAP, and REST APIs. For manag-ing and monitoring services, there is a command-line interface with plug-insfor Maven and Ant.Open. Create Java EE applications within the Oracle cloud and deploy them instandard WAR (Web Application Archive) or EAR (Enterprise Archive) format.Beyond the standard Java EE specifications, Oracle Java Cloud Service sup-ports the deployment of applications using Oracle WebLogic Server–specificextensions as well as Oracle Application Development Framework constructs.Secure. Applications are secured at multiple layers, because the Oracle JavaCloud Service instance itself is isolated. The service includes dedicated virtualmachines (VMs) and schemas that sit on top of Oracle Exalogic Elastic Cloud.The VMs then map to a corresponding database schema on an Oracle ExadataDatabase Machine. The security is not limited to applications deployed toOracle Java Cloud Service. If you’re using another service in Oracle Cloud—suchas Oracle Fusion Applications—and building custom extensions in Oracle JavaCloud Service, the identity information and user profiles can be securely popu-lated from Oracle Fusion Applications onto Oracle Java Cloud Service using theIdentity Service in Oracle Cloud’s common infrastructure.Easy to use. The entire service lifecycle—from subscription to service use,to monitoring and management—can be done through a single, easy-to-useWeb-based interface.Oracle also offers a comprehensive set of platform services to build richapplications, including Oracle Database Cloud Service, Oracle Developer CloudService, Oracle Storage Cloud Service, and Oracle Messaging Cloud Service.Figure 1
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH53COMMUNITYJAVAINACTIONABOUTUSblog//java architect /user’s own comput-ers, simplifying main-tenance and support.IaaS cloud solu-tions offer the abilityto deploy compute,network, and stor-age resources withminimal effort. Whilethose abilities aredefinitely very ben-eficial, from a devel-oper’s perspective,the advantage of thecloud does not stopthere. In fact, greatervalue lies beyond the provisioningof the infrastructure layer wheredevelopers devote more than80 percent of their time and effort.This is where PaaS provides tre-mendous benefits for applicationdevelopment, testing, deploy-ment, and management.With on-demand infrastructure,automated provisioning, flexibledevelopment and runtime tools,and management automation,IaaS and PaaS cloud services arepoised to have a profound impacton the developer experience.What to Look for in aCloud OfferingWhen evaluating cloud optionsfor developers, you should con-sider standards, choice, breadth,depth, self-service capability,and data integrityand portability.Support for stan-dards. Are the cloudservices built on stan-dards, such as SQL,Java, and HTML5?Building on standardshas a lot of benefits.One of the mostimmediate benefits isthat you can run yourapplications in thecloud more transpar-ently, which meansyou can port an appli-cation to your local on-premisesenvironment without having toalter any code. Conversely, if you’rerunning an on-premises applica-tion built on open standards andwould like to move it to the cloud,you will be further along in theprocess to make that change.Choice. Your vendor’s cloud offer-ings should span public and pri-vate clouds and, if applicable, itsproduct portfolio. Does your ven-dor provide comprehensive prod-ucts for cloud providers to buildand manage private clouds, andmanaged cloud services to helpcustomers fully manage and/orhost their clouds? Private cloudsenable organizations to have com-plete control and visibility oversecurity, regulatory compliance,service levels, and functionality.Breadth. One of the big advan-tages of cloud computing is thatit breaks down silos across yourorganization. Your cloud solutionshould help you avoid the frag-mentation of data and businessprocesses that occurs when usingmultiple, siloed public clouds. Ifyour vendor offers multiple typesof cloud services, this gives youmaximum flexibility. The plat-form services must enable thedeveloper community to build anddeploy applications. The applica-tion services should enablebusiness users to start usingpackaged functionality rightaway. For example, are packagedapplications—such as enterpriseresource planning, customerrelationship management, andhuman capital management—available on a subscription basis?Are social services integrated withthe applications or tacked on?Depth. Look for services that arenot only rich in functionality but,more importantly, integrated towork together seamlessly. Theservices should run on proveninfrastructure, offering you thereliability and performance of anenterprise-grade solution.Self-service capabilities. Can youdevelop, deploy, and manageyour applications or platform withminimal involvement of the ven-dor or your IT staff?Data integrity and portability.Does your vendor commingle yourdata with other customers’ data?Surprisingly, this is pretty commonin a public cloud environment. Youshould consider asking whetherthe vendor can provide data iso-lation. Also, how portable is yourdata? Don’t let your vendor holdyour data hostage. Make sure itis easy and straightforward to getall your data out of the cloud in aformat you can use.ConclusionDevelopers can leverage thecloud to address the “develop-ment gap” that results from theincreasing pressure to createand deploy applications faster,lower the cost of innovation, anddramatically reduce risk. A goodcloud vendor will provide youwith a comprehensive suite oftechnologies and applicationsthat are based on open standardsand integrated to work togetherseamlessly. </article>LEARN MORE• Oracle Java Cloud Service tutorials• “Deploying an Application toOracle Java Cloud Service” tutorial• “Securing a Web Application onOracle Java Cloud Service” tutorial• Oracle Java Cloud Service 30-dayfree trialMIND THE GAPApplicationneedsaregrowingexponentially,butdevelopmentresourcescontinuetogrowaslinearlyasever,resultinginagrowing“developmentgap.”
  • JAVA EE 7ARRIVESAnil Gaur on the evolution of Java EEBY STEVE MELOANORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201355blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSAs the industry standard forenterprise Java computing,Java Platform, EnterpriseEdition, has constantlyevolved to keep pace withthe emerging usages, patterns, frameworks,and technologies of the enterprise space.Java EE 7 is now here, with essential supportfor modern-era Web applications—includ-ing HTML5, WebSocket, Java API for RESTfulWeb Services (JAX-RS), JSON Processing(JSON-P), and more.Java Magazine sat down with Anil Gaur,vice president of software developmentat Oracle, to explore the new features andtechnologies of the just-released Java EE 7PHOTOGRAPHY BY PHIL SALTONSTALLAnil Gaur (center), vice president of softwaredevelopment at Oracle, chats with Java EE 7Platform Specification Leads Bill Shannonand Linda DeMichiel.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201356blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSplatform and examine what it means toenterprise developers and customers.Java Magazine: What’s new and nota-ble in Java EE 7?Gaur: The Java EE platform is at a criti-cal point right now, in that we haveto rapidly move forward to keep pacewith emerging Java usages and pat-terns. These changes are being greatlydriven by modern Web applications.Over the past few years, many otherframeworks have evolved, and we alsowanted to align the platform withthose changes.So the main theme of Java EE 7 isproductivity and HTML5 support. TheHTML5 enhancement comes fromWebSocket, Java Servlet 3.1, the NIO[non-blocking I/O] feature, Server-Sent Events [SSE], JAX-RS, and JSON-P.In addition, several enhancementshave been made throughout the plat-form to improve productivity, becausethat’s another pain point, and itdirectly reflects on the cost of develop-ment and maintaining applications.With Java EE 7, developers will haveto write less boiler­plate code, and theplatform will also offer richer function-ality through various new specifica-tions, such as batch processing andconcurrency.What’s more, the JMS [Java MessageService] spec has gone through majorenhancements in JMS 2.0, wherewe’ve introduced some of the conceptsalready available in the Servlet andEJB [Enterprise JavaBeans] specs. Andthe Expression Language specificationhas also been enhanced in version 3.0,which will benefit many other tech-nologies within the platform.The various specs that have gonethrough changes are JPA 2.1 [JavaPersistence API], Java Servlet 3.1,EJB 3.2, Bean Validation 1.1, and CDI[Contexts and Dependency Injection forthe Java EE platform], which was addedin Java EE 6 and was one of the mostpopular and widely used specs there.Java Magazine: How will Java EE 7provide developer simplificationwhile also offering richer applicationpossibilities?Gaur: We’ve particularly focused onsimplification in terms of introducingthe concept of profiles. We’ve heardmany times that the platform has beengrowing into a monolithic bundle thatwas sometimes difficult for very spe-cific, targeted usages. And we took thatvery seriously. So we invested heavilyin the Java EE 6 platform, where weintroduced the Web Profile, a runtimestack of standard APIs specificallytargeted to Web application develop-ment. And that profile has allowed usto put in place a basic framework thatwe can use toward defining futureprofiles. Developer simplification alsooccurs by providing more defaults andby using CDI, which reduces the use ofXML coding.We’ve seen great demand for the newspecs that we’ve added in Java EE 7.People were already using technolo-gies such as WebSocket and JSON,but prior to Java EE 7, there were nostandard APIs. Now, developers nolonger need to package their ownJSON libraries in the applications. TheGaur discusses Java EE 7capabilities with ArunGupta (dark shirt), Javaevangelist at Oracle, andShreedhar Ganapathy,engineering managerat Oracle.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201357blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSsupport is in the base platform. Andthey can invoke WebSocket endpointsdirectly from Java clients. So that alsomakes for significant developmentsimplification, while helping to mini-mize the size of the applications thatare deployed.Batch processing is another addi-tion to the platform, which has beenregularly requested by customers. Thisprovides a standardized programmingmodel to implement batch applica-tions. The JSR defines the domain area,batch job, application executor, andjob manager. And in addition to thesupport in Java EE, some of the fea-tures will also be included in Java SE.But Java EE is a superset of Java SE,so it inherently provides a richer fea-ture set. JTA [Java Transaction API], forexample, is only found in Java EE.We’ve also added concurrency to theplatform, which had similarly beenrequested by developers. This allowsapplication-level work to be performedconcurrently, using different threads ofexecution. Prior to this release, vari-ous application servers had their ownproprietary implementations, but thatreduced application portability. Theirinclusion in Java EE 7 provides a stan-dard API available to all EE vendors,customers, and developers.And, as I indicated earlier, the JMS2.0 spec has been revised and simpli-fied in a variety of ways that had beenrequested by the community. JMS 2.0will make greater use of annotations,as did the EJB and Servlet specs inprior versions of the platform. JMSconnection factory will also leverageDependency Injection [DI]; in addition,the API is being cleaned up so thatinterim objects are not required, andthen there are AutoCloseable resources.These changes should be very attrac-tive to developers and allow them tostart using JMS more extensively.So, yes, we’ve added more APIs tothe platform, but most of the addi-tions have been based on communityrequests and what was needed to solvethe issues we’ve seen for developingenterprise applications.Java Magazine: What’s been prunedfrom the release, what does thatachieve, and how does it poten-tially affect application backwardcompatibility?Gaur: While we’ve added many newfeatures to Java EE 7, we have alsomade certain APIs optional. So theplatform has grown in terms of func-tionality, but there has also been somecleanup of older features—which willnot only help reduce the platform foot-print, but free developers from havingto deal with obsolete specifications.This process began in Java EE 6,where we marked several tech-nologies as optional, and targetedthem for eventual pruning—Java EEManagement [JSR 77]; ApplicationDeployment [JSR 88]; JAXR, for interfac-ing with UDDI registries [JSR 93]; JAX-RPC, for XML-based RPC [JSR 101]; andEJB 2.x Container Managed Persistence,which is effectively replaced by the JavaPersistence API [JSR 317].Since these were marked for prun-ing in the Java EE 6 release, it makes itpossible for us to remove them in thisrelease. But that’s optional, of course.It’s up to each vendor to make thatdecision for the release. If they’re see-ing continued demand, if their cus-tomer base is still using these specs,they can keep them in the platform.But we will remove them in the nextrelease [Java EE 8]. And I expect mostvendors will follow that same strategy.Java Magazine: What does the WebProfile stack for Java EE 7 bring tothe release and to Web applicationdevelopers?Gaur: The Web Profile was introducedin Java EE 6 and became very popular,because it offered a subset of the fullplatform, providing standard APIs thatare specifically targeted to meet theRESPONDING TO FEEDBACKWe’veheardmanytimesthattheplatformhasbeengrowingintoamonolithicbundlethatwassometimesdifficultforveryspecific,targetedusages.Andwetookthatveryseriously.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201358blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSneeds of the majority of Web appli-cations. Not every developer needsall the Java EE APIs, so this offers areduced runtime memory footprint,simplified installation, and enhancedresponsiveness.So as with Java EE 6, the Java EE 7release includes a Web Profile. Butthere are new specs being added—WebSocket and JSON-P. And theJAX-RS 2.0 enhancement, the cli-ent APIs, is another notable addition.These specifications are, of course, notrestricted to just the Web Profile.But more and more developers areusing JavaScript and HTML5 in theirapplications, and WebSocket andJSON-P are two specs very well alignedwith that programming model. So thatmakes it very attractive and suitablefor next-generation Web applicationdevelopment.Java Magazine: Can you discuss thedecision to defer some cloud-relatedfeatures originally intended for Java EE 7to Java EE 8 and the features involved?Gaur: This was a tough decision, butI think we made the right call. Andwe consulted with our communitymembers, Expert Groups, and vendorsbefore making the final decision.This decision occurred partly due tolack of maturity in the cloud space—specifically, in provisioning, multi-tenancy, and elasticity. We cameto realize that fact when we werealready well into the implementation.Ultimately, we wanted to avoid addingAPIs or functionalities that were eithernot fully realized or not ideally suitedto the intended goal.So we chose a more conservativeapproach—to make sure that we reachour goal in a way that can maximallybenefit the industry and develop-ers. After consulting with communitymembers, and conducting a survey, wedecided to shift the focus of Java EE 7toward HTML5 and productivity. Thisshift in scope allowed us to betterretain our focus on enhancements,simplification, and usability—and tostill deliver the release on schedule. Inthe end, we didn’t want to hold up fea-tures that were ready to go for some-thing that’s not fully realized.Java Magazine: What specific JSRs weredeferred?Gaur: There were no specific JSRs, assuch. The cloud requirements werecross-cutting, impacting many dif-ferent specs. So no actual specs weredropped in the process. But featureswithin several specs, including theJava EE 7 platform spec, were affected.Java Magazine: In the interim period,what facilities exist for running Java EEapplications in the cloud?Gaur: If you look at many of the ven-dors out there, in most cases, theircloud platforms are built on Java, whichis great news for us. And Java EE 6 isalready compatible with those environ-ments. So the container-based modelthat we have in Java EE, along withsecurity isolation, makes it very suitablefor writing PaaS [platform as a service]–enabled applications. And JAX-RS, theAPI for RESTful Web Services, is alsowell tailored for cloud applications. Sogiven all this, it’s still a good platformfor building cloud solutions.Java Magazine: How has the Java com-munity been involved in the evolutionand refinement of Java EE 7, particu-larly with the recent cloud-relateddecisions?Gaur: We have been developing theJava EE Reference Implementation asan open source project since Java EE 5,under Project GlassFish. And withJava EE 7, we decided to go even fur-ther, such that all the Java EE specs arenow developed with participation froma broader community in addition tothe Expert Groups and Java EE vendors.So over the last two or three years,the spec development process hasGaur and Java EE 7team leads share alighthearted moment.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201359blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSbecome more and more transparent.And that’s not by accident. Oracle andthe community had a strong desireto engage more community mem-bers—and earlier in the process—sothat the community could review andprovide feedback as we developed thespecifications.We filed JSR 348 to define the rulesby which a JSR needs to be run—in atransparent manner. All the Oracle-ledJSRs are now following that process.The Expert Groups have open e-mailaliases for technical discussions, theinterim drafts of specifications are vis-ible on the project page, and we useJIRA, which contains a list of all thefeatures that we target for each of theJSRs. So everyone who is interestedcan now file a JIRA request if they wantcertain features to be added or if theyhave feedback on features that arealready planned. Each JSR has a dash-board for JIRA requests.This has allowed a much broadercommunity to provide their ongo-ing feedback. And, as a result, wecan deliver a superior technology at afaster pace. In addition, we engaged19 Java user groups [JUGs] who par-ticipated in a program called Adopt-a-JSR, in which developers can volunteertheir time to review what’s being pro-posed and how it might impact tech-nologies in the platform. JUGs havealso developed several small applica-tions to try out what’s being proposed.The feedback provided by these JUGshelped iron out issues long before theplatform was finalized.Java Magazine: What features are nowplanned for Java EE 8, and what are thetarget dates?Gaur: After the release of Java EE 7,Oracle and other vendors will beginworking on Java EE 8. The focus ofthe release will be a standards-basedcloud programming model—deferredfrom Java EE 7—in which we will addsupport for multi-tenancy and elasticity.You can also expect to see modular-ity based on Jigsaw in Java EE 8. Thereis also strong interest in some sort ofNoSQL support in the Java EE plat-form, so we will evaluate that as well.But in the meantime, the platform willcontinue to evolve. It’s not as if, afterJava EE 7, the only time you’ll get to seesomething new is in Java EE 8. We’d liketo have new JSRs, such as JCache andJSON-B [JSON Binding], finalized wellbefore Java EE 8. So there will be incre-mental progress in the platform, whereour customers will be able to see andexperiment with those new APIs beforeJava EE 8 is ultimately released.In terms of a formal release date forJava EE 8, the community will helpdefine the scope and the features of therelease, and that will ultimately deter-mine the dates. The Expert Groups willplay a major role in coming up with afinal feature set and the release dates.Java Magazine: At JavaOne 2012, HasanRizvi pointed out that the ongoing suc-cess of Java is based on a triad of tech-nology innovation, community par-ticipation, and Oracle’s stewardship.Do you have any thoughts on furtherenhancing the partnership betweenGaur talks withteam membersRajiv Mordani (left)and Nazrul Islam atOracle’s Santa Clara,California, offices.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 201360blogJAVATECHCOMMUNITYJAVAINACTIONABOUTUSOracle and the Javacommunity?Gaur: I’m pleasedto say that the rela-tionship with theJava community hasstrengthened quitesignificantly underOracle’s stewardship.And that has beendemonstrated in sev-eral different ways.The community isvery actively engagedin defining the next-generation plat-form, and I expect that to continue.And we will continue to run theExpert Groups in an open fashion,which will enable more people to par-ticipate without requiring them to jointhe JCP or adhere to any heavyweightprocess. We will also continue todevelop Reference Implementationsas open source, and that will helpus gather feedback quickly and, ulti-mately, develop a platform that isappealing to both enterprise custom-ers and developers.As evidence of this open approach,the Java EE 6 release was adoptedmore quickly than any previousrelease. I attribute that to the fact thatwe’ve been engaging the communityat earlier stages, and I expect that we’llcontinue on that path with similarpositive results.Java Magazine: How can developersaccess Java EE 7?Gaur: The Java EE SDKis our most popu-lar bundle, whichdevelopers can useto learn the newtechnologies in theplatform. That is nowavailable on OracleTechnology Network.The SDK bundle con-sists of GlassFishServer Open SourceEdition 4.0, which isalso the ReferenceImplementation for Java EE 7. It con-tains a comprehensive tutorial that cov-ers the new APIs, and there are manysample programs that will help devel-opers understand each of the specifica-tions and get up to speed faster.I should also touch upon IDE sup-port. The NetBeans IDE will be the firstIDE to support the Java EE 7 APIs. Weworked very closely with the NetBeansfolks as we developed the platform, sothat enables us to have a much tighterintegration between the NetBeansIDE and GlassFish and a superior out-of-the-box experience. And I expectEclipse and IntelliJ will be next in linewith support for the Java EE 7 platform.Java Magazine: What can the GlassFishcommunity expect with GlassFish 4.0,which is being released in conjunctionwith Java EE 7?Gaur: As with Java EE 5 and Java EE 6,the Reference Implementation of JavaEE 7 is derived from Project GlassFish.Being the Reference Implementation,GlassFish is always up to date with thelatest Java EE specifications. So whenwe ship the Java EE 7 platform, thecommunity will have GlassFish ServerOpen Source Edition 4.0. It will offersupport for all the Java EE 7 APIs, butthe clustering and high availability fea-tures are there for evaluation purposesonly. Those production deployment–centric features will be made availablein the subsequent release, 4.1.GlassFish 4.0 will be available fordownload in two different flavors. Thefirst distribution contains support for allthe APIs in Java EE 7, while the secondcontains a subset of APIs defined by theJava EE 7 Web Profile specification. Sodevelopers will have a choice—they canstart with the SDK bundle that containsthe open source bits of GlassFish 4.0,or they can download the GlassFish bitsseparately from Java.net. </article>LEARN MORE• Download Java EE 7• GlassFish 4.0• NetBeans IDESteve Meloan is a former C/UNIX soft-ware developer who has covered the Weband the internet for such publications asWired, Rolling Stone, Playboy, SF Weekly,and the San Francisco Examiner. He re-cently published a science-adventurenovel, The Shroud, and regularly contrib-utes to The Huffington Post.LISTENING TO THE COMMUNITYWe’veaddedmoreAPIstotheplatform,butmostoftheadditionshavebeenbasedoncommunityrequestsandwhatwasneededtosolvetheissueswe’veseenfordevelopingenterpriseapplications.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH61COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /Java EE 7 is the long-awaited major overhaul ofJava EE 6. With each releaseof Java EE, new features areadded and existing specifica-tions are enhanced. Java EE 7builds on top of the successof Java EE 6 and continues tofocus on increasing devel-oper productivity.The Java EE umbrella con-tains a number of specifica-tions. JSR 342 describes theoverall container require-ments, and it lists the tech-nologies that should be sup-ported in a JavaEE platform. TheJava EE PlatformSpecificationproject also hasa dedicated wiki.The Java EE speci-fication docu-ment explicitlymentions ease ofdevelopment asone of the key goals:“Java EE 7 also continuesthe ‘ease of development’focus of Java EE 5 andJava EE 6. Most notably,Java EE 7 includes arevised and greatlysimplified JMS 2.0 API.Ease of developmentencompasses ease ofconfiguration as well.”The early versions of theJava EE specification wereoften criticized as beingvery complex for develop-ers to work with. The bal-ance betweencomplexity andsimplicity wasclearly more inthe direction ofcomplexity.With Java EE 5,focus shiftedtoward ease ofdevelopment. Byleveraging anno-tations and by providingdefault behavior and defaultconfiguration, it enableda drastic reduction in linesof code and lines of XMLconfiguration.The Java EE 5 requirementsfor simplicity are twofold:■■ Defaults should be appli-cable to most applica-tions and useful for mostdevelopers.■■ It should always be possi-ble to change the defaults(by providing annotationsor descriptors).By meeting these require-ments, the Java EE speci-fication adhered to theconvention-over-configu-ration design paradigm. Forbehavior that follows theconvention, no additionalcode or XML should berequired. If developers wantnonconventional behav-ior, they should be able toachieve that by writing codeor declaring XML. This clearlylowered the barrier to Java EEdevelopment.The Java EE 6 specificationmade reasonable progress inthe same direction and addeda number of new APIs (forexample, JAX-RS, describingthe Java REST APIs).Java EE 7 simplifies thedefault development andconfiguration even more. Thelist of changes in the tech-nologies that were alreadypart of Java EE 6 is huge, butthis article highlights a fewchanges in existing specifica-tions that will help developersincrease their productivity:■■ JPA 2.1 (JSR 338) standard-izes schema generation.Developers can rely on JPAto create tables, indexes,generators, and so on.■■ JPA 2.1 also adds supportfor stored procedures.Increase your productivity using the updated specifications and the new APIs in Java EE 7.JOHANVOSJavaEE7Boosting Developer Productivitywith Java EE 7BIOPHOTOGRAPH BYTON HENDRIKSMAKING IT SIMPLERJavaEE7simplifiesthedefaultdevelopmentandconfigurationevenmore.Listen toauthorJohan Vosdiscuss theproductivitygains offeredin Java EE 7.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH62COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /■■ JPA 2.1 requires containers toprovide a default datasource.■■ Servlets 3.1 (JSR 340) allowsfor asynchronous I/O based onNIO2.■■ JavaServer Faces (JSF) 2.2(JSR 344) adds support forHTML5.■■ JSF 2.2 now contains a fileupload component.■■ Bean Validation 1.1 (JSR 349)allows for method-levelconstraints.■■ Contexts and DependencyInjection (CDI) 1.1 (JSR 346)allows developers to specify theorders of the interceptors. Inaddition, by using the @Vetoedannotation, types or packagescan be prevented from beingconsidered by CDI.■■ Expression Language (EL) 3.0(JSR 341) supports lambdaexpressions.But Java EE 7 is more than amaintenance release. It also addsa few additional APIs, includingthe following:■■ JSR 352: Batch processing■■ JSR 353: Java API for JSONprocessing■■ JSR 356: WebSocket■■ JSR 236: ConcurrencyThe new JSRs were added to theplatform because they are relevantto today’s Java EE developers. Thelandscape in enterprise comput-ing is always evolving, and the JavaEE standard should evolve as well.More specifically, the Java EE speci-fications should allow enterprisedevelopers to take advantage of thelatest and greatest technologies,without having to write lots of boil-erplate code and without runninginto potential vendor locks—hencethe need for standardization.Without exception, the new JSRstarget real developer needs, andthey allow developers to boosttheir productivity and focus ontheir core business.Batch ProcessingMany real-world business applica-tions have a need for some meansof batch processing. Occasionallyor periodically, data has to be pro-cessed in a noninteractive way,and the processing can take a longtime. A typical example is a job thatruns once a day and calculates aninventory and generates reports.It was already possible to achievethis in the Java EE world, but devel-opers had to come up with theirown code, or they had to use exist-ing third-party (nonstandardized)frameworks. JSR 352 now describesthe involved entities and their rela-tions. The terminology and con-cepts are very familiar to users ofexisting batch frameworks.Using JSR 352, Java EE develop-ers can define a job using XML.Listing 1 shows how a job is com-posed of steps containing chunks.The typical job execution is aprocess that reads data, processesdata, and writes results. Javaclasses are used to read, process,and write data. In the XML exam-ple in Listing 1, three Java classesare involved, which are shown inListing 2.By using JSR 352, developersdon’t have to worry about theinfrastructure required for batchprocessing. They can focus on theirdomain-specific issues instead.JSONMany Web services use the JSONformat for receiving requests andsending responses. Also, a largenumber of Web frameworks (Javaand non-Java) rely on the JSONformat. As a consequence, manyDownload all listings in this issue as text<job id="myJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee"><step id="myStep" ><chunk item-count="3"><reader ref="myItemReader"></reader><processor ref="myItemProcessor"></processor><writer ref="myItemWriter"></writer></chunk></step></job>LISTING 1 LISTING 2
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH63COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /Java EE applications need to beable to parse or generate JSONcode. A number of JSON parsersand generators are available, butusing them implies that develop-ers have to create hard dependen-cies on nonstandard interfaces.JSR 353 standardizes the con-cepts of JSON parsing. UsingJSR 353 APIs, developers can usestandardized APIs in the packagejavax.json (and in the subpackagesjavax.json.spi and javax.json.stream)rather than using proprietary APIs.The underlying implementationis shieldedfrom the devel-oper, and it isexpected thatsuppliers ofJSON parserswill implementthe standardAPIs.The JSONprocessingAPIs havesome simi-larities withthe XML pro-cessing APIs.This is impor-tant, becausemany appli-cations haveto deal withboth XML andJSON. Having asimilar approach for both formatsmakes developers’ lives easier.Similar to XML processing, thereare two ways to process JSON data:stream-based processing anddocument-based processing.Using the stream-basedapproach, a JSON documentis read and processed event byevent, as shown in Listing 3. Thedocument-based approach allowsdevelopers to browse through thewhole JSON document—similar tousing the Document Object Model(DOM) for browsing XML docu-ments (see Listing 4).WebSocketJava EE developers are increasinglyconfronted with Web clients or cli-ent applications that require full-duplex bidirectional communica-tion. This request is often drivenby HTML5–based Websites thatwant to leverage the WebSocketprotocol, as described in the IETFRFC 6455. Also, applications thatare not Web–based (for example,JavaFX applications) often benefitfrom the advantages provided bythe WebSocket protocol.As part of the Java EE 7 platform,developers are able to use JSR 356,Java API for WebSocket. This JSRprovides Java EE developers withan easy-to-use annotations-based framework for managingWebSockets. Without this JSR,developers would need to writelots of boilerplate code in orderto register a WebSocket endpointor make a connection to anotherWebSocket endpoint.All the internal details aboutthe WebSocket protocol are pro-vided by implementations ofJSR 356. This saves a huge amountof time. Registering a WebSocketendpoint and accepting incomingmessages can be done as shownin Listing 5.From the code in Listing 5, itshould be clear that the bulk ofthe work—including the lifecyclemanagement of the WebSockets—is done by the implementationprovided by the Java EE platform.When a client makes a connectionto a WebSocket annotated with@ServerEndpoint("/myEndpoint"),the method annotated with@OnOpen is called and a Sessionobject is passed.Each time a message is received,the method annotated with@OnMessage is called. Whenthe connection gets closed, themethod annotated with @OnCloseis called.For developers, using theWebSocket API is almost as simpleas implementing the application-specific logic and annotating themethods with the correct annota-tions. More WebSocket examplescan be found here.JsonParserFactory factory = Json.createParserFactory();JsonParser parser = factory.createParser(...);while (parser.hasNext()) {Event event = parser.next();}LISTING 3 LISTING 4 LISTING 5Download all listings in this issue as textCOMPLEXITY WONTheearlyversionsoftheJavaEEspecificationwereoftencriticizedasbeingverycomplexfordeveloperstoworkwith.Thebalancebetweencomplexityandsimplicitywasclearlymoreinthedirectionofcomplexity.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH64COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /ConcurrencyA complaint often heard beforeJava EE 7 was that the concur-rency tools developed for Java SEcannot be used in Java EE imple-mentations. In the Java EE world,all resources are managed bycontainers. Threads and execu-tors, as in the java.util.concurrentpackage, are not man-aged by containers. It is,therefore, dangerous oreven forbidden to usethem in an enterpriseapplication.This situation madelife for the average Javadeveloper pretty dif-ficult, because a devel-oper is used to workingwith the concurrencytools when develop-ing a Java SE applica-tion, but can’t use thesame concepts when developinga Java EE application. JSR 236 nowprovides the infrastructure forusing the traditional concurrencyconcepts in a container-managedenvironment.Building on the java.util.concurrent.ExecutorService, theManagedExecutorService pro-vides a container-managedExecutorService, which is safeto use in Java EE applications. AManagedExecutorService imple-mentation can be obtained usingJNDI and easily inserted, as shownin Listing 6.Other Upgrades in Java EE 7Apart from the new JSRs, a num-ber of existing specifications got amajor upgrade in Java EE 7. Mostnotably, the specification for JavaMessage Service (JMS) has beenchanged from 1.1 to 2.0.The JAX-RS specifica-tion, which was intro-duced in Java EE 6, wasalso updated to version2.0 and is now includedin Web Profile.JMS. The Java EE 5 andJava EE 6 specificationsmade it much easierto use most of theenterprise resources,including EnterpriseJavaBeans (EJB) andpersistence resources.The messaging component, how-ever, had not changed since 2003,when version 1.1 was released.Compared to other Java EE 6 tech-nologies, using JMS 1.1 requiredlots of boilerplate code andconfiguration.JMS 2.0 now provides the samesimplifications provided for theother components. By default,sending a message or processinga message requires less code andless configuration. But more-flexible and more-complex con-figurations are still possible usingeither annotations or descriptors.Basically, JMS is about sendingmessages from one softwarecomponent to another. This isnontrivial, and it requires a num-ber of intermediate steps pro-vided by different actors. In JMS1.1, most of these steps had to beimplemented by the Java devel-oper. In JMS 2.0, most of thesteps are implemented by theJMS implementation.A typical usage of JMS 1.1 wouldinject a ConnectionFactory anda ConnectionQueue and cre-ate a Connection, a Session, aMessageProducer, and a Message.In JMS 2.0, this becomes muchsimpler by default. A JMSContext iscreated, and this context is usedto send messages, as shown inListing 7.JAX-RS. The Java API for RESTfulWeb Services is one of the fastest-evolving APIs in the Java EE land-scape. This is, of course, due to themassive adoption of REST-basedWeb services and the increasingnumber of applications that con-sume those services.JAX-RS 2.0 fine-tunes the server-side specifications for REST APIsand adds a client part. Today’senterprise applications often maketheir services available via RESTAPIs, but they also need to con-sume other (external) Web ser-vices. In order to do this with JavaEE 6, developers needed to eithercreate their own boilerplate code oruse a proprietary framework.Download all listings in this issue as textManagedExecutorService mes = (ManagedExecutorService)ctx.lookup("java:comp/env/concurrent/ThreadPool");LISTING 6 LISTING 7 LISTING 8EVER EVOLVINGThelandscapeinenterprisecomputingisalwaysevolving,andtheJavaEEstandardshouldevolveaswell.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH65COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /JAX-RS specifies a javax.ws.rs.client package that can easily beused for querying external Webservices. A POST request to a fictiveserver called my.server.com can bedone as shown in Listing 8.Note the use of method chain-ing, which is very convenient andproductive when a (potentially)large number of methods have tobe called.The JAX-RS 2.0 specificationalso allows the result of a clientrequest to be java.util.concurrent.Future, thereby enabling asyn-chronous requests. This can sim-ply be done by adding the async()method call on the Target instance.Asynchronous processing is alsopossible on the server side by add-ing the @Suspended Asyncresponsesignature in the processingmethod.ConclusionThe Java EE specifications need tostrike a difficult balance betweenbusiness needs and developer pro-ductivity. Starting with Java EE 5,developer productivity becamemore of a priority and changes tosupport increased productivitywere done without jeopardizingbusiness needs.Java EE 7 follows this path byproviding some new features thatare very important in today’s busi-ness environments and by sim-plifying some existing specifica-tions. The Java EE 7 specifications,thereby, achieve two goals:■■ It is very easy to use the defaultbehavior with very few lines ofcode.■■ If the default behavior is notwhat is needed, it is still possibleto configure the behavior.The majority of existing appli-cation servers will likely imple-ment the Java EE 7 specifications.The GlassFish project serves as aReference Implementation for thevarious specifications. </article>LEARN MORE• Java EE 7 specification• “Batch Applications in Java EE 7—Understanding JSR 352 Concepts”• “JSON-P: Java API for JSONProcessing”• “JMS 2.0 Early Draft—SimplifiedAPI Sample Code”• JMS 2.0 blogCopyright © 2013, Oracle and/or its affiliates.All rights reserved.REGISTER NOWSave $400 by July 19thSEPT. 22 - 26, 2013 | SAN FRANCISCORegister at oracle.com/javaone
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH66COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /Java EE 7 supports new andevolving standard tech-nologies such as WebSocket,HTML5, and JSON, providingan API for each one.This article first pres-ents some background onWebSocket and then offersa Web application to dem-onstrate the new platformfeatures.Note: The source code forthe example described inthis article can be down-loaded as a Maven projecthere.WebSocket BackgroundModern Web applicationshave grown in interactivity,demanding greater com-munication between thebrowser and the Web server.At first, constant communi-cation was achieved by serv-lets with long polling in thebrowser, but problems in theserver appeared because thethreading model of the Webcontainer demanded thatevery request be handled bya thread until the response iswritten. Then, asynchronousservlets came with Java EE 6providing a more efficientapproach that allowedrequests to be processedasynchronously.The Polling, long pooling,and Comet/Ajax approachessimulate a full-duplex com-munication between theserver and the browser.WebSocket is a full-duplexand bidirectional API, whichnot only involves the serverbut the Web browser, too.WebSocket changes theway the Web server reactsto client requests: insteadof closing the connection, itsends a 101 status and leavesthe connection open, expect-ing messages to be writtenon the stream and to be ableto write messages, as well.The client also expects mes-sages to be written and isalso able to write messagesat its end of the stream. Thisallows both ends to read andwrite to the stream and com-municate in real time.Before Java EE 7, imple-menting a WebSocket wasWeb container–dependent:you could write a WebSocketfor Tomcat, but if you wantedto migrate to Jetty, you hadto reimplement it for thenew server.Note: As with every newtechnology, WebSocket isbeing adopted by differentWeb browsers at differenttimes. You can check thispage for more informationabout browser compatibility.Overview of the StickerStory ApplicationLet’s start with a simpleexample to see how thethings we have discussed sofar work.This article showcases asticker story Web applicationthat children can use to cre-ate a story collaboratively bydragging stickers into a bookor canvas. At the instant asticker is placed into a child’sExplore new features for creating next-generation internet applications.EDUARDOMORANCHELANDEDGARMARTINEZBIOThis video provides a demo of the stickerstory application.JavaEE7Embracing HTML5
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH67COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /book, the sticker is drawn withinother children’s books. Watchthe video to see the applicationin action.Figure 1 shows the home pagefor the sticker story Web appli-cation. When you drag a stickerfrom the sidebar on the left to thecanvas and drop it, the sticker isrendered into all the Web brows-ers that are open at that time, asshown in the video.Obtaining and Running theSticker Story Application1. Download GlassFish v4promoted build 79 (glassfish-4.0-b79.zip). GlassFish canbe obtained here as a ziparchive.2. Unzip GlassFish into a direc-tory of your choice.3. Download and installNetBeans. The version usedin this article is NetBeans 7.3.4. Download the sticker storyMaven project link to sticker-story.zip.5. Expand the project into adirectory of your choice.6. Start NetBeans, and on theServices tab, right-click theServers node, and then clickAdd Server.7. From the Server list, selectGlassFish Server 3+, and thenclick Next.8. In the Server Location field,enter the path to the directorywhere you unzipped GlassFishv4, and then click Finish.9. Select File -> Open Project.10. From the Open Project dialogbox, open the sticker storyMaven project.11. Right-click the project andselect Run. Select the recentlyinstalled GlassFish server(GlassFish Server 3+) whenprompted.You can now point your Webbrowser to http://localhost:8080/sticker-story to see a page simi-lar to that of Figure 1. Make sureyour browser is compatible withWebSocket by checking this page.Application ContentsThe application contains the fol-lowing files and Java classes:■■ index.html is the home pageand contains JavaServer Faces(JSF) 2.2 and HTML5 code.■■ The org.sticker.jsf.StickerSheetclass is the managed bean usedby the home page to display allthe available stickers.■■ story-page.js contains theJavaScript code for theWebSocket client and the drag-and-drop functionality.■■ The org.sticker.websocket.Stickerclass is the object being sentand received by the WebSocket.■■ The org.sticker.websocket.StickerEncoder and org.sticker.websocket.StickerDecoderclasses transform the data sentby a WebSocket into objects.■■ The org.sticker.websocket.StoryWebSocket class is theWebSocket handler. It alsostores the stickers in the currentstory book.Combining HTML5 with theJSF 2.2–Friendly HTML MarkupJust as Ed Burns, spec lead ofJSF 2.2 (JSR 344), mentionedin his blog, JSF 2.2 allows pageauthors to have complete controlof the HTML rendering by usingthe Friendly Markup feature ofJSF 2.2. It also facilitates theseparation of markup and busi-ness logic.Let’s see an example. The viewof the sticker story applicationis provided using HTML5 andJSF. Listing 1 shows the contentof the index.xhtml file, whichis mostly HTML5; JSF is used torender the sticker images in thesidebar of the browser using the<h:graphicImage> tag.■■ JSF 2.2 lets you pass throughHTML attributes. There aretwo ways to do this: with thenamespace for the pass-throughattributes, which is http://java.sun.com/jsf/passthrough, orby using the child TagHandlerf:passThroughAttribute (orf:passThroughAttributes for mul-tiple attributes). In our example,we use the former.Figure 1
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH68COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /In Listing 1, notice the<h:graphicImage>tag. Thereare three attributes (draggable,ondragstart, and data-sticker) inour graphicImage tag that are notpart of the attributes forgraphicImage but that we need inorder to make our stickers work.Therefore, we use the prefix p: sothat JSF pass-through adds thesethree attributes. Note: BecausegraphicImage is a JSF markup,we have used the namespacehttp://java.sun.com/jsf/passthrough. If youwant to pass throughelements into a non-JSF-aware markup, usethe name­space http://java.sun.com/jsf. Lookfor some examples inListing 1, such as head orscript tags.Listing 2 shows themanaged bean, whichprovides the names ofthe stickers. The@Named annotationexposes the bean to JSF, and laterthe bean method is called usingthe #{stickerSheet.allStickers}expression as the value in the JSFui:repeat tag in the index.xhtml fileshown in Listing 1.Writing Drag-and-Drop CodeIn HTML5, drag-and-dropfunctionality is simplified andrequires specific events that arehandled using JavaScript codethat is divided into two parts: thedragged-object events and thereceiving-object events.The dragged object (that is, thesticker) must define theondragstart event (see Listing 1)and handle it using JavaScript. Aswe discussed earlier, in JSF 2.2,you can use the pass-throughparameters to add this event.The JavaScript code in Listing 3specifies what will beexecuted when thedrag starts.In drag-and-dropinteractions, you mighthave to use an inter-mediate object to storethe data being trans-ferred between com-ponents. In JavaScript,you do this by storingthe data inside the dragevent.dataTransfer prop-erty. Because this prop-erty allows only stringsto be stored, the easiest way tostore data is using JSON.The JavaScript code for the dragevent creates the sticker repre-sentation, gets from the screenthe coordinates of the locationto which the sticker was dragged,and—using another HTML5 fea-ture—gets the sticker image file-name from the tag’s data-stickerDownload all listings in this issue as text<?xml version=’1.0’ encoding=’UTF-8’ ?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"xmlns:jsf="http://java.sun.com/jsf"xmlns:ui="http://java.sun.com/jsf/facelets"xmlns:h="http://java.sun.com/jsf/html"xmlns:p=" http://java.sun.com/jsf/passthrough"><head jsf:id="head"><title>Sticker Story</title><script jsf:target="body" jsf:name="story-page.js"/><link jsf:name="styles.css" rel="stylesheet" type="text/css" /></head><body jsf:id="body"><header><h1>Sticker Story Book</h1></header><nav>Drag stickers from the left bar to the canvas.</nav><aside><h2>Stickers</h2><div id="stickerContainer"><ui:repeat var="imgName"value="#{stickerSheet.allStickers}"><h:graphicImage library="stickers" name="#{imgName}"style="float:left" p:draggable="true"p:ondragstart="drag(event)" p:data-sticker="#{imgName}" /></ui:repeat></div></aside>…</body></html>LISTING 1 LISTING 2 LISTING 3DID YOU KNOW?WebSocketisafull-duplexandbidirectionalAPI,whichnotonlyinvolvestheserverbuttheWebbrowser,too.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH69COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /attribute. In HTML5, you can usecustom attributes to store appli-cation-specific data by adding thedata- prefix to the attribute; inJSF 2.2, you use the pass-throughattributes to add such attributes.For the drop action, the droptarget object (that is, the receiv-ing end) must define two eventhandlers.One is the ondragover eventhandler, which must handle thedrag-over (hover action) of themouse to determine whether adrag is valid. To allow drops withfurther validation, the code justcalls ev.preventDefault(), since thedefault behavior is to deny drops.The second event handler isondrop, which handles the dropevent when the mouse buttonis released while something isbeing dragged. The JavaScriptcode that handles this event (seeListing 4) begins by preventingthe default behavior (denyingthe drop) and then gets the datafrom dataTransfer. Because weare transferring text, we have toconvert it to an object using theJSON.parse method, which is astandard JavaScript method. Next,we convert the dragged object tothe actual object that we are goingto send to the server. The dropmethod in Listing 4 also calculatesthe coordinate for the position ofthe upper left corner of the stickeron the canvas and adds the nameof the sticker to the object. Theobject then is converted to a JSONstring and finally sent using theWebSocket.send method.A WebSocket Clientwith JavaScriptUsing WebSocket, the sticker storyapplication sends data to the serverwhen a drag-and-drop actionoccurs. So how is a WebSocketconnection established? Let’s see.After the page loads, theinitialize method is called (seeListing 3), and the first thing thismethod does is draw the back-ground for the application usingthe HTML5 canvas. Next, it opensthe WebSocket connection byusing the statement socket = newWebSocket("ws://localhost:8080/sticker-story/story/notifications")to establish and open the com-munication. Note that it uses theWebSocket protocol instead ofHTTP and the path is absolute.Note: If you are running the Webserver in a different port, you willneed to change this line to useyour server’s port.The next line in Listing 3 defineswhat the client will call when theserver pushes a message to thebrowser.Now, take a look at theonSocketMessage method inListing 4. This method will handlefunction drop(ev) {ev.preventDefault();var bounds = document.getElementById("board").getBoundingClientRect();var draggedText = ev.dataTransfer.getData("text");var draggedSticker = JSON.parse(draggedText);var stickerToSend = {action: "add",x: ev.clientX - draggedSticker.offsetX - bounds.left,y: ev.clientY - draggedSticker.offsetY - bounds.top,sticker: draggedSticker.sticker};socket.send(JSON.stringify(stickerToSend));log("Sending Object " + JSON.stringify(stickerToSend));}// Web socket on message received:function onSocketMessage(event) {if (event.data) {var receivedSticker = JSON.parse(event.data);log("Received Object: " + JSON.stringify(receivedSticker));if (receivedSticker.action === "add") {var imageObj = new Image();imageObj.onload = function() {var canvas = document.getElementById("board");var context = canvas.getContext("2d");context.drawImage(imageObj,receivedSticker.x, receivedSticker.y);};imageObj.src ="resources/stickers/" + receivedSticker.sticker;}}LISTING 4Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH70COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /WebSocket messages from theserver side.The sticker story applicationsends JSON objects as text usingthe WebSocket connection.Therefore, when a message isreceived, it is transformed toa Sticker object and theonSocketMessage method doesthe following:■■ Transforms the data■■ Gets the image for the sticker■■ Draws the image on the canvasusing the coordinates from thestickerAnd because the connectionis open at this time, sending amessage to the server is doneusing the send method in theWebSocket JavaScript object. It’sjust that simple.WebSocket for Real-TimeCommunicationCreating a WebSocket in Java EE 7is very easy. You just need to createa couple of annotations and yourWebSocket will be configured.In the sticker story applica-tion, the class configured as aWebSocket is the StoryWebSocketclass (see Listings 5a and 5b).Notice the @ServerEndpointannotation at the top of the classdeclaration. Just as with servlets,you have to define a mapping. Fora WebSocket, the value of the@ServerEndpoint defines themapping of the WebSocket. Thismeans that you can declare aWebSocket just by using thefollowing and the server willwait for connections at the/websocketMapping URL toconnect to the WebSocket:For now, skip the encoders anddecoders attributes and head overto the methods of the class. Todefine the methods that will han-dle the WebSocket events, you useannotations as well.The @OnOpen, @OnClose, and@OnError annotations are relatedto the lifecycle of the WebSocketconnection. You can annotate amethod with any of them and themethod will be called when a con-nection opens or closes or whenthere is an error in the connection(an exception was not handled).Our application uses the@OnOpen annotation to push thestickers to the connected user.This way, a newly connecteduser receives all the stickers pre-viously posted on the canvas byother users.The @OnMessage annotation isthe core of the WebSocket imple-mentation. The annotated methodwill be called whenever the clientsends a message; in the appli-@ServerEndpoint("/websocketMapping")package org.sticker.websocket;import java.io.IOException;import java.util.*;import java.util.logging.*;import javax.websocket.EncodeException;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;import javax.websocket.OnMessage;import javax.websocket.OnOpen;@ServerEndpoint(value = "/story/notifications",encoders = {StickerEncoder.class},decoders = {StickerDecoder.class})public class StoryWebSocket {private static final List<Sticker> stickers =Collections.synchronizedList(new LinkedList<Sticker>());@OnOpenpublic void onOpen(Session session) {synchronized (stickers) {for (Sticker sticker : stickers) {try {session.getBasicRemote().sendObject(sticker);} catch (IOException | EncodeException ex) {Logger.getLogger(StoryWebSocket.class.getName()).log(Level.SEVERE, null, ex);}}}}LISTING 5a LISTING 5bDownload all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH71COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /cation, the client sends stickersand then the WebSocket storesthe added sticker and pushes thesticker to all the connected peers.Notice that the @onMessagemethod receives a Sticker object(see Listing 6) and a Sticker objectis written to the other peers usingthe following method:We discussed the fact thatWebSocket sends and receivestext. So, why do the methodsreceive a Sticker object, and whyare we writing Sticker objects to thesessions? The answer lies in the@ServerEndpoint declaration, spe-cifically in the encodersand decoders attributes.A WebSocket may usea decoder to transformthe text message into anobject and then handle itin the matching@OnMessage method,and whenever an objectis written to the session,a WebSocket may use anencoder to convert theobject to text and send itto the client.URL path parameters.You can set URL pathparameters by add-­ing them to the@ServerEndpoint mapping. Do soby enclosing the parameter nameinside brackets:To use it, add a string parameterto any annotated method and addthe @PathParam("parameterName")annotation to the method param-eter. In the example in Listings 5aand 5b, you would add the@PathParam("parameter1") stringparameter. You can add as manyparameters as you need.And while we are at it, for themethods annotated using anyWebSocket–related annotation,you can receive the WebSocketsession as a parameter.In the application, weadd it as a parameter,but it is not neededand it can be omittedcompletely.The @OnMessageannotation applies to amethod that can havean extra parameter. Thisparameter is the mes-sage being received andcan take the form of anyobject decoded using thedeclared decoders in the@ServerEndpoint anno-tation or String, if nodecoders are specified.session.getBasicRemote().sendObject()/pathToWebSocket/{parameter1}Download all listings in this issue as textpackage org.sticker.websocket;public class Sticker {private int x;private int y;private String image;public Sticker() {}public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public String getImage() {return image;}public void setImage(String image) {this.image = image;}}LISTING 6EASY AS 1, 2, 3CreatingaWebSocketinJavaEE7isveryeasy.YoujustneedtocreateacoupleofannotationsandyourWebSocketwillbeconfigured.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH72COMMUNITYJAVAINACTIONABOUTUSblog//enterprise java /Using the New JSON APIwith WebSocketThe new Java API for JSONProcessing (JSR 353) is part ofJava EE 7, and we are using it inour example.The sticker story applicationcommunicates with the client andthe WebSocket server by usinga JSON string representation ofobjects. The WebSocket usesdecoders and encoders to trans-parently convert the text sent tothe WebSocket into a Sticker objectand to convert Sticker objects sentto the client into text.In the StickerDecoder andStickerEncoder classes (Listing 7and Listing 8), the application usesthe JSON API for the following:■■ Reading from the socket streamto get objects■■ Transforming objects into JSONstring representation and writ-ing them to the socketYou can create appropriatedecoders depending on the formatin which you want to read the datafrom the WebSocket. Similarly, youcan create encoders depending onhow you want to write the data tothe socket.As shown in Listing 7, a decodermust implement any interfaceinside the parent Decoder inter-face. There are several types ofdecoders and encoders, and theyvary in the parameters that thedecode and encode methods take.The StickerDecoder class inListing 7 uses the Decoder.TextStream interface, which allowsyou to read the data from thesocket using a Reader. To converta string into a JsonObject you usea JsonReader, which convenientlytakes a Reader to be constructed.Note: The JsonReader objectshould not be created; instead,use the JsonProvider class to createreaders and writers.Listing 8 shows the StickerEncoderclass that writes the object to theWebSocket stream.ConclusionWebSocket technology, JSF’sHTML5 pass-through parameters,and JSON object serialization arepowerful additions to Java EE 7that greatly simplify the develop-ment of applications that requireconstant communication betweenthe browser and the Web server.In this article, we’ve built aWeb application to show howto combine HTML5 with theJSF 2.2–friendly HTML markup.We also wrote a WebSocket clientand drag-and-drop functionalityfor the application with JavaScript.Lastly, we built a WebSocket serverby using the new Java APIs forWebSocket and JSON processing.The example shown in this articlebarely touches on their potential.Acknowledgements. The authorswould like to thank Marco Velasco,a young Mexican artist, for theillustration of the sticker storyapplication. </article>LEARN MORE• JSF 2.2 JSR• Java API for WebSocket JSR• Java API for JSON Processing JSR• Arun Gupta’s video about Java EE 7and the WebSocket APIpackage org.sticker.websocket;import java.io.IOException;import java.io.Reader;import javax.json.JsonObject;import javax.json.JsonReader;import javax.json.spi.JsonProvider;import javax.websocket.DecodeException;import javax.websocket.Decoder;public class StickerDecoder implementsDecoder.TextStream<Sticker> {@Overridepublic Sticker decode(Reader reader) throws DecodeException,IOException {JsonProvider provider = JsonProvider.provider();JsonReader jsonReader = provider.createReader(reader);JsonObject jsonSticker = jsonReader.readObject();Sticker sticker = new Sticker();sticker.setX(jsonSticker.getInt("x"));sticker.setY(jsonSticker.getInt("y"));sticker.setImage(jsonSticker.getString("sticker"));return sticker;}}LISTING 7 LISTING 8Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH74COMMUNITYJAVAINACTIONABOUTUSblog//rich client /Listen toauthorAdam Biendiscuss theoutcomes ofusing JavaFXScene Builder.What-You-See-Is-What-You-Get (WYSIWYG)Java editors have promisedrapid development andhigher productivity since themid-’90s. Usually the UIconstruction was based oncode generation and pro-tected regions. The developerhad to blindly rely on thecorrectness of the generatedcode—any modeling mis-takes often led to corruptedUIs and some frustration.Without a clear strategy forthe separation of the gen-erated code, WYSIWYG-driven development quicklybecomes unmaintainableand heavily dependent on aproprietary Java editor.JavaFX 2 comes with SceneBuilder—a tool for the visualconstruction of user inter-faces. This article covers apragmatic integration ofScene Builder’s output intomultiview enterprise appli-cations using a create, read,update, and delete (CRUD)example.The sample CRUD appli-cation—AirHacks Control(shown in Figure 1)—isintended to enable a user toquickly maintain informa-tion about attendees whoare attending a multidayevent. Depending on theirregistration day, attendeesappear in a particular tab.Existing attendees can bemaintained in the table aswell as in the input area. Thedata is persisted in a localApache Derby database, butit could be moved to theserver easily without affect-ing the overall design.Note: The source code forthe AirHacks Control applica-tion can be downloaded here.What Does EnterpriseMean?Although the boundarybetween consumer andenterprise applications hasbegun to blur, enterpriseapplications are still drivenby a different set of require-ments and processes. Asuccessful consumer appli-cation tends to focus on asingle problem and solvesthat problem as elegantly aspossible. Branding, pixel-perfect positioning, andeven nice-looking dock iconssignificantly contribute tothe commercial success of aconsumer application.Enterprise applications donot have to be ugly—how-ever, slickness is not theirprimary goal. ParamountPragmatically integrate JavaFX Scene Builder output into multiview enterprise applications.PHOTOGRAPH BYTHOMAS EINBERGER/GETTY IMAGESPart1Integrating JavaFX Scene Builderinto Enterprise ApplicationsFigure 1ADAMBIENBIO
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH75COMMUNITYJAVAINACTIONABOUTUSblog//rich client /are long-term maintainability andviews (screens) that directly reflecta use case or user story.Also, the entire business logic ofan enterprise application sits onthe server exposed via REST, SOAP,IIOP, or other proprietary proto-cols. Consumer applications tendto contain more business logicand communicate less frequentlywith the back end, which is oftenrepresented by differentcloud providers.The UI of a successfulconsumer applicationis highly influenced bydesigners and usabilityexperts, whereas the UIof an enterprise applica-tion is usually a directreflection of requestsfor enhancement(RFEs) from the domainexperts and users.This article focuses on enter-prise applications, which typicallyrequire larger development teamsand, therefore, a clearer and more-obvious structure.Scene Builder’s XML RootsThe Don’t Repeat Yourself (DRY)principle made XML disappearfrom pragmatic Java EE applica-tions. Java EE became extremelyproductive by eliminating the repe-tition and maintaining the requiredmetadata with annotations directlyon the affected classes. To getstarted with Java EE, you need toknow only a few annotations.Scene Builder is highly based onXML. The UI definition is main-tained in an XML dialect calledFXML. Although it uses XML, thereis no repetition. In fact, the gener-ated FXML is the “single truth”and so it is still DRY. Also, the maindifference between an averageJava EE applicationand a typical UI is theamount of configurationand metadata required.Because fewer conven-tions are available for atypical UI, even a simpleview requires the con-figuration of colors,layout, positioning, andsize, so it vastly exceedsthe configuration of anyJava EE application.An FXML file is actually onlya configuration of the javafx.fxml.FXMLLoader factory. TheFXMLLoader consumes anFXML file and creates the rootnode (javafx.scene.Parent) withsome interesting extensions forDependency Injection (DI) frame-works, which are covered later.Instead of creating a Parent man-ually, you can use the FXMLLoaderfor this purpose. The entire con-figuration of the FXMLLoader isprovided by Scene Builder withMAKE A SCENEJavaFX2comeswithSceneBuilder—atoolforthevisualconstructionofuserinterfaces.Download all listings in this issue as text<?xml version="1.0" encoding="UTF-8"?><?import java.lang.*?><?import java.net.*?><?import java.util.*?><?import javafx.scene.*?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><AnchorPane id="AnchorPane" prefHeight="243.0" prefWidth="600.0"styleClass="mainFxmlClass" xmlns:fx="http://javafx.com/fxml"fx:controller="..."><children><VBox id="VBox" fx:id="inputBox" alignment="CENTER"layoutX="100.0" layoutY="33.0" prefWidth="343.0" spacing="5.0"><children><TextField fx:id="firstName" prefWidth="200.0"promptText="First Name" /><CheckBox fx:id="paid" mnemonicParsing="false"prefWidth="103.0" text="Paid" /></children></VBox><Button fx:id="saveButton" defaultButton="true"disable="true" layoutX="98.0" layoutY="192.0" onAction="#save"prefHeight="22" prefWidth="57.0" text="Save" /><HBox id="HBox" alignment="CENTER" layoutX="100.0"layoutY="149.0" spacing="5.0"><children><!-- .... --></children></HBox></children><stylesheets><URL value="@attendeeinput.css" /></stylesheets></AnchorPane>LISTING 1
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH76COMMUNITYJAVAINACTIONABOUTUSblog//rich client /the FXML file. Nodes in JavaFX areorganized hierarchically; FXMLexactly mirrors the structure of theview and it is even readable, as youcan see in Listing 1.FXML is not only readable, butcomplete. You could even generateJava code from an FXML file.The Challenge and Inversionof ControlWith Scene Builder, we get aninstantiated tip of a node treeentirely constructed from FXML.Usually, FXML does not containany business logic. Script eventhandlers are optional and not“mainstream.” But, what is thelink between logic implementedwith Java and FXML?FXML comes with a simplebut great idea: any POJO (witha default constructor) can beloaded and created by theFXMLLoader and then bounddeclaratively to UI events, asshown in Listing 2. Methods ofthe loaded class can be associ-ated with UI events within SceneBuilder, as shown in Listing 3.The name of the method hasto correspond with the value ofthe attribute in the FXML file. AllUI components can be optionallyinjected into the POJO by denotingthem with the @FXML annotation,as shown in Listing 4.Also, in this case, the name ofthe injected component has tocorrespond with the value of thefx:id attribute in the FXML file.WYSIWYG builders gener-ated complete view code, whichwas supposed to be integratedwith the remaining presentationlogic. Scene Builder follows theInversion of Control approachand instantiates the presentationlogic from the generated XML file.In addition, the bindings to themanually created code are gener-ated, which makes Scene Builderalmost transparent.With Scene Builder, the manu-ally created code is not dependenton generated artifacts; rather it isthe reverse. FXML contains bind-ings to the manually created code.The relation is based on namingconventions.Convention over ConfigurationThe remaining difference betweenconsumer and enterprise applica-tions is the number of developersand roles involved in the process.Consumer applications are some-times built with surprisingly fewresources; the head count for anaverage enterprise application canbe orders of magnitude higher.Having more developers requiresmore structure and convention.Easy and self-explanatory ruleslead to higher productivity andmaintainability. In optimal cases,there is a recurring recipe for thecreation of each view or form.Let’s introduce a convention forour AirHacks Control application: aview with the name AttendeeInputresides in a package with the samename (attendeeinput) and containsthe following artifacts:■■ AttendeeInputPresenter: Themanually created presenter classloaded by FXMLLoader. The pre-senter contains all the presen-tation logic and is independentfrom the generated artifacts.■■ AttendeeInputView: A class wrap-ping the FXMLLoader for con-venience. AttendeeInputViewinherits from FXMLView, but itis not dependent on any gener-ated artifact.■■ attendeeinput.css: An (initially)empty stylesheet for maintain-ing the look and feel.■■ attendeeinput.fxml: The con-figuration generated by SceneBuilder, which contains bind-Download all listings in this issue as text<AnchorPane (...) fx:controller="com.(...).AttendeeInputPresenter">LISTING 2 LISTING 3 LISTING 4Adam Bien walks you through the AirHacksControl application.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH77COMMUNITYJAVAINACTIONABOUTUSblog//rich client /ings to the manually createdAttendeeInputPresenter.Creating subclass javafx.scene.Parent with FXMLLoader from anFXML descriptor is simple butrepetitive. The class FXMLView notonly encapsulates the view con-struction, but it also implementsthe aforementioned conventions(see Listings 5a and 5b).FXMLView provides access to theParent and the presenter POJO, andit also loads all the required files.If you can live with the conven-tion, a typical view can be leftempty, as shown in Listing 6. Thesubclass is necessary—all thementioned conventions are derivedfrom the class name, and theCascading Style Sheets and FXMLfiles are loaded from the package.Now the view can be instantiatedand the presenter obtained usingthree lines of code (see Listing 7).The AttendeeInputView user is fullydecoupled from the FXML, theCSS, and Scene Builder.A Bit More Juice with GuiceSo far, no logic has been imple-mented in the view, and theFXML-instantiated POJO shouldcontain only presentation logic.No matter what kind of enterpriseservices need to be accessed by thePOJO (aka the presenter), the ser-vice wrapper—or even the actualbusiness logic implementation—needs to be instantiated, initial-ized, and passed to the presenter.A singleton is the obvious choiceas a service wrapper but comeswith its own shortcoming. A sin-gleton instantiated once is hard to“uninitialize,” and so it is difficultto test. Unit tests usually rely on aclearly defined initial state.In our CRUD example, theJavaFX application directlyaccesses the Java Persistence API(JPA) 2 EntityManager, which needsto be instantiated and cachedbetween invocations. The entireCRUD functionality is imple-mented within a single class—theRegistrationService (see Listing 8,which increases usability throughan EntityManager wrapper).The RegistrationService isimplemented as a simple POJO,not a singleton. During unittests, the invocation of themethod RegistrationService#initcan be omitted and boththe EntityManager andEntityManagerFactory mockedout for test purposes. However, itwould be even nicer to mock outthe entire RegistrationService andtest the UI with a mock back end.With mockable business logic, youcould even prerecord the expectedbehavior and omit the entire back-end conversation.Fortunately, JavaFX 2 introduceda callback for DI frameworks. TheDownload all listings in this issue as textpublic abstract class FXMLView {public static final String DEFAULT_ENDING = "view";protected FXMLLoader loader;public FXMLView() {this.init(getClass(), getFXMLName());}private void init(Class clazz, String conventionalName) {final URL resource = clazz.getResource(conventionalName);this.loader = new FXMLLoader(resource);this.loader.setControllerFactory(new Callback<Class<?>,Object>() {@Overridepublic Object call(Class<?> p) {return InjectorProvider.get().getInstance(p);}});try {loader.load();} catch (Exception ex) {throw new IllegalStateException("Cannot load " + conventionalName, ex);}}public Parent getView() {Parent parent = this.loader.getRoot();addCSSIfAvailable(parent);return parent;}LISTING 5a LISTING 5b LISTING 6 LISTING 7 LISTING 8
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH78COMMUNITYJAVAINACTIONABOUTUSblog//rich client /FXMLLoader passes a class, andthe DI frameworks are expectedto return an instance and performthe injection magic. The creation ofviews and presenters is performedby FXMLLoader and encapsulatedwithin the abstract FXMLView.FXMLView is also the natural placefor the FXMLLoader instrumenta-tion. Listing 9 shows enabling DIwith the ControllerFactory.The InjectorProvider utility shownin Listing 10 is a lean wrapperaround the Guice Injector.Guice DI injection is imple-mented in a type-safe mannerwith classes implementing thecom.google.inject.Module inter-face. The PersistenceModule classshown in Listing 11 cares about theinstantiation and lifecycle of theRegistrationService.The PersistenceModuleinstantiates and initializes theRegistrationService. Becausethe RegistrationService.class isbound to the created instance,RegistrationService effectivelybecomes a singleton without sac-rificing any testability.Now the RegistrationService canbe injected with the standard@javax.inject.Inject into any pre-senter and it becomes available inthe Initializable#initialize method.Listing 12 shows the injection ofthe business logic.Guice was chosen only becauseat the moment it is the sim-plest and leanest—but stilltype-safe—implementation ofthe JSR 330 DI standard. Guiceimplementation was encapsu-lated within the InjectorProviderand can be easily replaced withany other DI framework, such asWeld or OpenWebBeans, withoutaffecting the existing presenterimplementation. A DI frame-work replacement would onlyaffect the InjectorProvider utilityand make the PersistenceModulesuperfluous.Single Page, but Many ViewsIn rich clients, the flow is imple-mented by substituting smallerview portions (for example, tabs),rather than by using a coarserpage flow as in JavaServer Faces(JSF). A single view is representedas a package. Navigation betweenviews needs to be implemented bya superordinate presenter. Also,the application frame needs to beprovided by a main view and it iscreated with Scene Builder provid-ing the skeleton.There is no difference to thestructure already described, exceptthe naming (see Figure 2). Thepackage of the main view is namedafter the application, not after theview’s responsibility. Hence, theapplication view’s main responsi-bility is controlling the navigationbetween views and provisioningcommon functionality, such assaving and loading the applicationfolder, which may contain addi-tional supporting classes.In fact, the InjectorProvider aswell as the PersistenceModuleclasses are located within themain application package. Theapplication package (“airhacks,”in our case) resides at the samelevel as the view-specific packagesinside the presentation package.The AirhacksPresenter createsand coordinates the subordinatethis.loader.setControllerFactory(new Callback<Class<?>, Object>() {@Overridepublic Object call(Class<?> p) {return InjectorProvider.get().getInstance(p);}});LISTING 9 LISTING 10 LISTING 11 LISTING 12Download all listings in this issue as textFigure 2
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH79COMMUNITYJAVAINACTIONABOUTUSblog//rich client /views and adds them to the skel-eton layout, as shown in Listings13a and 13b.The WorkshopsView encap-sulates and manages the tabsand makes the entire lower areareplaceable. More precisely, thesubordinates views are managedby the WorkshopsPresenter initial-ized by the FXMLLoader encapsu-lated within the WorkshopsView.Neither javafx.scene.control.TabPane nor the javafx.scene.control.Tab instances are injectedinto the WorkshopsPresenter. Onlythe javafx.scene.control.Tab con-tent, the javafx.scene.control.AnchorPane, is directly injectedinto the WorkshopsPresenter. SeeListings 14a and 14b.Scene Builder allows the injec-tion of the leaf views (AnchorPaneinstead of TabPane,as shown in Figure 3),which makes the codesignificantly leaner.Our CRUD use casecan be solved withoutany reference to thejavafx.scene.control.TabPane class. Ifwe had to react totab alternation, theTabPane could be alsoinjected. Only the fx:idneeds to be set withinScene Builder and afield with the samename and type as TabPane needsto be declared in the presenter.An Emerging View-Presenter-View (VPV) PatternA single utility class, FXMLView,allows us to fully decouple from theFXML file and, thus, from any arti-facts generated by Scene Builder.With that, a recurring patternemerges: the developer instanti-ates an FXMLView subclass, whichinitiates the instantiation of thecorresponding presenter. With theimplementation of the javafx.util.Callback passed to the methodFXMLLoader#setControllerFactory,the initialization process is del-egated to a JSR 330 implementa-tion, which, in our example, isGoogle’s Guice. Guice not onlyinstantiates the presenter, but italso performs the injec-tion of pre­configuredcomponents and caresabout the scoping.For our use case, it isessential to have onlya single instance ofthe RegistrationServiceavailable. With theintegration of a DIframework, any ser-vices or service wrap-pers (such as theBusiness Delegatepattern) can be trans-parently injected toDownload all listings in this issue as textpublic class AirhacksPresenter implements Initializable {@FXMLAnchorPane input;@FXMLAnchorPane overview;AttendeeInputPresenter attendeeInputPresenter;WorkshopsPresenter workshopsPresenter;@InjectRegistrationService rs;@Overridepublic void initialize(URL url, ResourceBundle rb) {AttendeeInputView inputView = new AttendeeInputView();this.attendeeInputPresenter =(AttendeeInputPresenter) inputView.getPresenter();this.attendeeInputPresenter.newAttendeeProperty().addListener(new ChangeListener<Attendee>() {@Overridepublic void changed(ObservableValue<? extendsAttendee> ov, Attendee old, Attendee newAttendee) {if (newAttendee != null) {workshopsPresenter.newAttendeeProperty().set(newAttendee);}}});WorkshopsView workshopsView = new WorkshopsView();this.workshopsPresenter =(WorkshopsPresenter) workshopsView.getPresenter();this.attendeeInputPresenter.selectedAttendeeProperty().bind(workshopsPresenter.selectedAttendeeProperty());input.getChildren().add(inputView.getView());overview.getChildren().add(workshopsView.getView());}LISTING 13a LISTING 13b LISTING 14a LISTING 14bTHE XML FACTORSceneBuilderishighlybasedonXML.TheUIdefinitionismaintainedinanXMLdialectcalledFXML,andalthoughitusesXML,thereisnorepetition.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH80COMMUNITYJAVAINACTIONABOUTUSblog//rich client /presenters and instantiated by theDI framework.The presenter is only looselycoupled to the FXML frameworkor Scene Builder. Only optional@FXML and @Inject annotationsare marking the injection points,so there is no other dependency.An ordinary non-FMXL presenteralso instantiates views. SeeFigure 4.All in all, the VPV patterns allowus to seamlessly include gener-ated Scene Builder code (there isno significant difference betweenXML and Java code) into a manu-ally crafted application. With VPV,the component hierarchy wasfactored out from the view into aconfigurable factory (FXMLLoader)instrumented with an FXML file.At any time, you could replace theFXML file with a manually codedlayout and also manually instanti-ate the presenter.The Model-View-Presenter(MVP) PatternThe classic MVP pattern wasretired by Martin Fowler in 2006.More precisely, the MVP pat-tern was split into the PassiveView, Supervising Controller, andPresentation Model patterns.Although Fowler’s patterns tookdata binding into account, thereis no mention of the integration ofWYSIWYG editors. JavaFX enablesDI with WYSIWYG by inverting therelations between generated codeand manually created code. TheVPV pattern introduced here is inthe purest form, and it is adequatefor the Passive View pattern, whichis defined by Fowler as follows:“A screen and componentswith all application spe-cific behavior extractedinto a controller so thatthe widgets have theirstate controlled entirelyby controller.”However, you could also bindthe view components directly todomain objects or the model, andthen this approach would be simi-lar to the intentions defined in theFigure 3Figure 4
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH81COMMUNITYJAVAINACTIONABOUTUSblog//rich client /Supervising Controller pattern,which is defined by Fowleras follows:“Factor the UI into a viewand controller where theview handles simple map-ping to the underlyingmodel and the controllerhandles input responseand complex view logic.”Strictly speaking, the separa-tion between the presenter andJavaFX specifics is not very strict.The presenter is still dependentupon JavaFX-specific events andcontrols. With the introduction ofan additional class, all clean pre-sentation logic couldbe factored out into aJavaFX-independentPOJO. The presenterwould transform alllow-level JavaFX eventsinto higher-level appli-cation events.In this case, the pre-senter would also haveto expose all injectedJavaFX widgets asJava primitives. The“pure” POJO presenterwould not be coupledto any UI frameworkand could potentiallybe reused acrossframeworks such asSwing, JSF 2, Wicket,or Vaadin. Becausethe JavaFX-dependent presenter,as well as the back-end services,could be easily mocked out, sucha plain POJO presenter would alsoincrease testability even further.This pattern is available under thename Presentation Model, whichis defined by Fowler as follows:“Represent the state andbehavior of the presenta-tion independently of theGUI controls used in theinterface.”However, there are too manypresenters in the descrip-tion. This is also the reason whythe Presentation Model pat-tern is often calledthe Model-View-ViewModel (MVVM)pattern: the View (sub-class of the FXMLView)contains specific GUIcontrols and definesthe appearance; theViewModel (presenter)represents the stateand behavior of thepresentation; and theModel is the domainobject (Attendee JPAentity). The MVVMpattern also introducesa controller (the super-presenter, for example,AirhacksPresenter),which implements theworkflow and medi-ates between the views.On the other side, an additionalclass would drastically decreasedeveloper productivity and intro-duce code duplication. Views withcomplex presentation logic couldbenefit from a pure presenter, butit is not a good idea to maintain anadditional class for simplistic views.ConclusionThe inverted relation betweenthe generated and manuallycrafted code introduces interest-ing opportunities for rapid appli-cation development. The com-bination with Convention overConfiguration boosts productivityand maintainability at the sametime. Scene Builder can be usedwithout any negative impact oncode clarity and so maintainability.The next article in this series willfocus more closely on the interac-tions between the views and pre-senters by combining JavaFX databinding with Scene Builder, FXML,and the Supervising Controllerpattern. </article>LEARN MORE• Scene Builder• Source code for AirHacks Controlapplication• The ideas extracted from AirHacksControl as “framework”• afterburner.fxIN A BINDWithSceneBuilder,themanuallycreatedcodeisnotdependentongeneratedartifacts;ratheritisthereverse.FXMLcontainsbindingstothemanuallycreatedcode.Therelationisbasedonnamingconventions.My local and global JUGsare great places to networkboth for knowledge and work.My global JUG introducesme to Java developers allover the world.Régina ten BruggencateJDuchessFINDYOURJUG HERELEARN MORE
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH82COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /Jython is an implementa-tion of the Python languagefor the Java Virtual Machine(JVM). As the name implies,it allows developers to usethe Python language syntaxand the standard library,plus apply coding patternsthat are used with CPython,the canonical implementa-tion of Python written in theC language. Jython is also anold-timer when it comes todynamic languages for theJVM. As such, it isa great option fordeveloping solu-tions for the JVM ina productive anddynamic manner.This is the secondarticle in a series onJython. In the firstarticle, we took anintroductory lookat using Jython andsome of the ben-efits that Jython can add toa developer toolset. In thisarticle, we will discuss one ofthe most beneficial featuresof Jython: its ability to inte-grate with Java.Using Java from JythonAs developers for the JVM, wehave numerous libraries atour disposal that can be usedto help build robust appli-cations. That said, Jythondevelopers can access anincreased toolsetby combining theproductivity of thePython program-ming languagewith the ability touse existing Javalibraries.Any library thatis part of the JVMcan also be usedwith Jython, whichmeans that Jythondevelopers have both Pythonand Java libraries available.That is, pure Python libraries(not those implemented inC++) are available for usevia Jython.Many third-party Javalibraries, or libraries writ-ten in other JVM languages,can also be used via Jython.Simply adding third-partylibraries to the CLASSPATHmakes the libraries available.By default, nearly all librariesthat are available on the JVMare inherently available foruse by Jython.To utilize Java code fromwithin Jython, it mustfirst be imported into thenamespace. A standardPython import statement canbe used to import any Javaclass. It is important to notethat if a name conflict occurs,the most recent import over-rides any other modules orJava classes by the samename. Therefore, it some-times is necessary to use theimport as syntax when work-ing with imports. Not onlydoes this import syntax pro-vide an alias for the code thatis imported, but it can alsobe a matter of convenience ifyou use a shorter name.Let’s begin by looking ata couple of examples usingthe Java Logging API. Tobegin working with it, sim-ply import the necessaryJava classes. Java classes areimported using the standardPython import statement,as follows:In Listing 1, a log file iscreated and messages arewritten to it to demon-strate the use of a standardPython import statement.from java.pkg import JavaClassLearn how to integrate Jython with Java.JOSHJUNEAUBIOPart2Jython 101—A RefreshingLook at a Mature AlternativeIT’S DYNAMICJythonisagreatoptionfordevelopingsolutionsfortheJVMinaproductiveanddynamicway.Listen toauthorJosh Juneauintroduce thetopic of inte-grating Jythonwith Java.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH83COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /The example in Listing 2 changesthe first example just a bit andutilizes the import as syntax,rather than the standard import,as follows:As mentioned previously, it isalso possible to include external orthird-party Java libraries in Jythonapplications. In order to do so,ensure that the JAR file containingthe Java library is contained withinyour CLASSPATH, and then importas you would normally. To add aJAR file to the CLASSPATH, use oneof the following techniques:For a UNIX-based OS, use this:For Microsoft Windows, use this:To demonstrate the use of externalor third-party Java code, a JAR filenamed JythonArticleExamples.jarhas been provided with the sourcecode for this article. A class namedJavaExample accepts two int valuesas input and then returns eitherthe sum or product of those twonumbers, depending on the meth-od that is called.The code for the JavaExampleclass can be seen in Listing 3.To use the example class fromJython, add the JAR file containingthe class to the CLASSPATH, andthen import, as demonstrated inListing 4.When a Java class is broughtinto use from Jython, type coer-cion occurs on any Java typesthat are present. Java types arecoerced into the Python typesthat equate most closely to theirnative types. To see a list of theJava types and what Pythontypes they are coerced into,see Table 10-1 in The DefinitiveGuide to Jython.In Java, interfaces play a keyrole in object-oriented develop-ment. Jython developers can useinterfaces as well, and Jythonclasses can also subclass Javaclasses. To demonstrate thisconcept, the Java interface inListing 5 (Pool) has been written todefine a type of swimming pool,and the Jython class in Listing 6implements the Pool interface,as you can see from the followingclass declaration:The ability for Jython classes toimplement Java interfaces is key tousing Jython modules from Java,as you will see next.From java.pkg import MyCls as Aexport CLASSPATH=$CLASSPATH:/jarset CLASSPATH=C:.jar%CLASSPATH%class VolumeCalculator(Pool):Download all listings in this issue as text>>> from java.util.logging import FileHandler>>> from java.util.logging import Logger>>> handler = FileHandler("/java_dev/my_log.log")>>> log = Logger.getLogger("app_log")>>> log.addHandler(handler)>>> log.info("This is an informational message")Nov 22, 2012 00:00:00 AM org.python.core.PyReflectedFunction__call__INFO: This is an informational message>>> log.warning("This is a warning message")Nov 22, 2012 00:00:00 AM org.python.core.PyReflectedFunction__call__WARNING: This is a warning message>>> log.severe("This is a severe message, take caution!")Nov 22, 2012 00:00:00 AM org.python.core.PyReflectedFunction__call__SEVERE: This is a severe message, take caution!>>> handler.close()LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH84COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /Using Jython from JavaThere are many use cases forusing Jython in a Java applica-tion. For example, Jython has aless-verbose syntax than that ofJava, and in some cases, code canbe more productive or more effi-ciently implemented in Jythonthan in Java. Whatever the case,there are a couple of different waysin which Jython can be used fromJava code. In most cases, the useof a technique referred to as objectfactories is the most efficient wayto work with Jython from Java (asof version 2.5.x or prior). If you areusing Jython 2.7.x or later, thereare some even more-efficient waysof working with Jython via Java.Object Factories—ManualObject CoercionThe concept behind an objectfactory is to call upon a proxy thatperforms the conversion of Jythoninto compiled Java source. Thecode conversion involves perform-ing a series of steps to prepare aspecified Jython module and thencoding an object factory class thatis responsible for making theconversion. The most time-consuming task is the implemen-tation of the object factory foreach Jython module that you wishto use, but there are ways to avoidcoding a factory manually, whichwe will look at later.It is important to understand theconcept behind the object fac-tory, so this section shows how tocode one manually, although mostdevelopers should not choose touse this option.Note: To work with Jythonfrom within a Java application,the Jython-required depen-dencies must reside within theCLASSPATH. The easiest way toensure that all dependencies arein the CLASSPATH is to packagethe standalone jython.jar withyour application. To learn moreabout using the CLASSPATH withJython, refer to Appendix B of TheDefinitive Guide to Jython.To create a Jython module thatcan be coerced, you must write aJava interface that includes thedefinitions for any methods thatyou wish to invoke within theJython module. The Jython mod-ule must then implement the Javainterface, and once the modulehas been converted into Java, theinterface is called upon in order tomake the method calls.Let’s look at an example of thistechnique by making some modi-fications to the volume calculatorprogram that we’ve previouslydemonstrated. In Listing 7, a Javainterface named org.javamagazine.interfaces.PoolCalculator containsa number of method and variabledeclarations. A Jython modulepublic interface PoolCalculator {public static final double circularCoefficient = 5.9;public static final double rectangularCoefficient = 7.5;public double calculateVolume();public void setDepth(double shallowDepth, double deepDepth);public void setLength(double length);public void setWidth(double width);public void setDiameter(double diameter);}LISTING 7 LISTING 8Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH85COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /named JyVolumeCalculator.py(Listing 8) implements this Javainterface, and the module isresponsible for performing all thevolume calculation tasks. Notethat in this example, setter meth-ods are specifically implementedto allow for error handling whenusing the calculator.The final (and most impor-tant) piece of the puzzle is theobject factory implementation.The object factory is respon-sible for coercing the Jythonmodule into a Java class via theuse of a Jython utility knownas the PythonInterpreter. ThePythonInterpreter comes bundledwith Jython, and it is an entry pointinto the Jython runtime that canbe used for embedding Jython,thereby compiling Jython into Java.First, obtain a new instance of thePythonInterpreter, as follows:Before the PythonInterpretercan be used to compile a Jythonmodule, it must obtain a ref-erence to the module that wewish to use and store it in a localPyObject wrapper for the module.This can be done in the construc-tor for the object factory class. Theinterpreter can execute the Jythoncode responsible for importing themodule for use. After the modulehas been imported, a call to theinterpreter.get() method can bemade, passing the string-basedname of the module that is beinginterpreted. The interpreter.get()method will return the wrappedPyObject, as shown below.All of this code can be placedinto the constructor so that it isexecuted when the object factoryis initialized. The object factorymust also contain a method thatis responsible for performing theactual coercion of the PyObjectinto a Java class, and this creationmethod is called against the objectfactory when using the Jython codefrom Java.In our example, the methodthat is named create() makes acall to the __call__special methodof PyObject, which returns a newPyObject. If any parameters needto be passed to the underly-ing Jython module, they can bepassed into the __call__method asPython objects.For instance, if you want topass a parameter with a type ofJava String, wrap it in a PyStringobject before passing to __call__.For an entire listing of Pythonobjects that can be used for pass-ing parameters, see the Jythondocumentation.Once a true PyObject has beengenerated by the __call__method, itcan be coerced into Java by callingits __tojava__special method, andpassing the Java interface that theJython module implements as aparameter. The __tojava__methodreturns a Java object that is of thesame type as the Java interface.This resulting Java class is thenreturned to the caller of thecreate() method and can be usedto work with the Jython object. Thecomplete listing for an object fac-tory is shown in Listing 9.The excerpt from Listing 10below demonstrates how to per-form the method calls from theJava code. As you can see, theobject factory implementation ishidden from the developer whois making the calls against theJython module.Behind the scenes, an objectfactory compiles the Jython codeinto Java. Since the Jython moduleimplements a Java interface, themethods and variables are acces-sible to code against. Such animplementation would be impos-sible if there were no Java inter-face, because the actual Jythonfunction names are mangled atcompile time.Object Factories Without Allthe CodingAs mentioned previously, you canuse Jython from Java without allthe object factory coding. A projecttitled PlyJy focuses on abstractingaway the worries of object factorycoding, allowing the developermore time to work with applicationcode rather than internal details.It is possible to implement anobject factory that can be usedwith any Jython module, ratherthan creating a one-to-one design.In this case, the object factory isnot hardcoded to accommodatespecified object parameters, butinstead it is implemented generi-cally so that any Jython modulewill work with it.Listing 11 shows the implemen-tation of a loosely coupled object Create PythonInterpreterPythonInterpreter interpreter =new PythonInterpreter(); Obtain reference to moduleString j="JyVolumeCalculator";interpreter.exec("from JyVolumeCalculator " +"import JyVolumeCalculator"); Return the PyObjectpoolCalcClazz = interpreter.get(j);// Create the factoryPoolCalculator volumeCalc =factory.create();// Invoke the Jython methodsvolumeCalc.setLength(32);volumeCalc.setWidth(16);volumeCalc.setDepth(3, 8);// Call to perform calculationvolumeCalc.calculateVolume();
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH86COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /factory such as the one described.Note that the factory is a single-ton, so it is instantiated only onceper application. A method namedcreateObject() accepts the Javainterface that is implemented bythe Jython module to be coerced,along with the string-based nameof the module. The createObject()method is responsible for creatingthe PyObject that is used to coercethe Jython module into Java usingthe call __tojava__.Using a loosely coupled objectfactory, such as those availablefor use from the PlyJy project, isvery similar to using a one-to-oneobject factory, such as the onedescribed in the previous section.Any Jython module that is tobe used from within Java mustimplement a Java interface, whichincludes definitions for thosemethods and variables that will beused from the Java code. Becausea loosely coupled factory containsno specific customizations for anyJython module, you must definethe setter methods for setting anyvariable values within the Javainterface so that the setters areexposed for use.As such, instantiation of aloosely coupled factory containsno arguments, and all values mustbe explicitly set by calling the set-ter methods. The createObject()method accepts the Java interfacethat is implemented by theJython module, along with thestring-based name of the moduleitself. Listing 11 demonstratesthis technique.Yet another technique thatmakes use of the object fac-tory strategy involves work-ing with the org.python.core.PySystemState class rather thanthe PythonInterpreter. It is nor-mally a fairly time-consuming taskto instantiate a PythonInterpreter,and if an application requiresseveral new instances of aPythonInterpreter, it makes senseto reduce the overhead.It is possible to get aroundworking with PythonInterpreter ifPySystemState is used to obtaina reference to the importer. Forbrevity, we will not go into the fulldetails for using the PySystemStateobject factory. Instead, Listing 12demonstrates how to use thetechnique. If you are interested inlearning more about it, refer toThe Definitive Guide to Jython.Using JSR 223 to EmbedJython ScriptsThere are a couple of differentways to embed Jython in Java.You can either make use of aPythonInterpreter to invoke Jythonstatements and expressions oruse a Jython engine along withJSR 223. We introduced theNote: The following listing has been excerpted for space. The full code listing isavailable by downloading the code listings for this issue.import org.javamagazine.interfaces.PoolCalculator;import org.python.core.PyObject;import org.python.util.PythonInterpreter;public class VolumeCalculatorFactory {private PyObject poolCalcClazz;public VolumeCalculatorFactory() {PythonInterpreter interpreter = new PythonInterpreter();interpreter.exec("from JyVolumeCalculator import JyVolumeCalculator");poolCalcClazz = interpreter.get("JyVolumeCalculator");}public PoolCalculator create () { The __call__function also accepts other Python objects as parameters to be passed to the underlying module, if neededPyObject poolCalcObj = poolCalcClazz.__call__();return (PoolCalculator)poolCalcObj.__tojava__(PoolCalculator.class);}}LISTING 9 LISTING 10 LISTING 11 LISTING 12Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH87COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /PythonInterpreter class previouslywhen discussing the use of objectfactories.The PythonInterpreter does as itsname implies—it accepts Jythoncode and interprets it into Java. Aninstance of a PythonInterpreter canbe used to execute multiple linesof Jython code by calling its exec()method, thereby embedding theJython in Java.The following lines of code dem-onstrate how to execute Jythoncode using PythonInterpreterwithin Java:Listing 13 demonstrates howto use the PythonInterpreter toperform imports and how to usea multiline string to contain yourJython code.JSR 223 was introduced into theJava language to bring the use ofscripting languages into Java. Thisenabled developers to embed linesof code that were written in differ-ent JVM languages, such as Jython,into Java programs. For instance,to execute a line of Jython codefrom within a Java application, youcan include the JSR 223 enginefor Jython in your CLASSPATH, andthen use lines such as those inListing 14 to invoke the engine andexecute the code.Since the release of Jython 2.5.1,the JSR 223 Jython engine ispackaged along with Jython, sosimply adding Jython.jar to yourCLASSPATH makes the engine avail-able for use by your application.Using JSR 223 is much likeusing PythonInterpreter, althoughthere is a bit more tweaking thatmust be done in order to makeit work. First, create an instanceof the ScriptEngine by calling theScriptEngineManager.getEngineByName() method and passing thestring “python”.Once an engine instance isobtained, Jython code can besent to the engine by calling theeval() method, much like call-ing the exec() method of thePythonInterpreter. The one addi-tional worry with this techniqueis that a ScriptException must beeither caught or thrown by theblock. However, in some cases,this makes code easier to debugif issues arise. Listing 14 demon-strates a complete example usingthe JSR 223 ScriptEngine.Jython 2.7 and BeyondMore-current implementations ofJython include even more ways tointegrate with Java. For example,in Jython 2.7+, it is possible togenerate proxy classes (compiledJava classes) by annotating Pythonobjects using annotations via athird-party API named Clamp.The Clamp project leveragesthe use of the org.python.compiler.ProxyMaker class to gen-erate proxy classes based uponmethod signatures that are speci-fied using Clamp annotations. Forinstance, to coerce a specific Javamethod signature from a PythonPythonInterpreter i =new PythonInterpreter();i.exec("print hello");import org.python.util.PythonInterpreter;public class PythonInterpreterExample {public static void main(String[] args){PythonInterpreter interpreter = new PythonInterpreter();System.out.println("ArrayList Using Java");interpreter.exec("from java.util import ArrayList");interpreter.exec("arr = ArrayList()");interpreter.exec("arr.add(one)");interpreter.exec("arr.add(2)");interpreter.exec("for a in arr:"+ " print a");System.out.println("Jython Standard Input");String pyStandardInput ="import sys n"+ "lang = raw_input(What is your favoritedevelopment language?)n"+ "print The BEST Development Language is%s % lang";interpreter.exec(pyStandardInput);}}LISTING 13 LISTING 14Download all listings in this issue as text
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH88COMMUNITYJAVAINACTIONABOUTUSblog//polyglot programmer /method by specifying return typeand arguments, decorate thePython method with @clamp.method(return_type, arg_types=[], name=None).In this case, return_typerefers to the methodreturn type, arg_typesis an array of argumenttypes that the methodaccepts, and nameaccepts an alternativemethod name.Listing 15 shows a ver-sion of the volume cal-culator Python class thatis annotated accordinglyfor use with Clamp. If youwould like to have the proxy classgenerated by simply instantiatingthe Python class, you could putthe code listed in Listing 16 directlyinto the Python class.To generate the proxy class fromthe decorated Python class, youcan call ProxyCompiler from Java asfollows:Other techniques for Jython/Java integration that mightbecome part of Jython 2.7 andbeyond include controlling gener-ated proxies, exposing Java typesas Python types for better perfor-mance, gradual typing, and blametracking. To learn more aboutthese and other advanced Java andJython integration tech-niques, refer to the PyCon2013 presentation byJython experts Jim Bakerand Shashank Bharadwajtitled “Integrating Jythonwith Java.”ConclusionThere are a variety ofways to use Java fromJython and vice versa.Interoperability betweenthe two languages hasbeen a key to the suc-cess of Jython. Any Java class thatis part of the standard library oris included in the CLASSPATH canbe imported into Jython for use.Using Jython from Java is a bitmore complex but still offers use-ful flexibility.This article demonstrated howto use Jython from Java throughobject factories and throughembedding Jython with both thePythonInterpreter and the JSR 223ScriptEngine. For more informa-tion regarding integration betweenthe two languages, refer to TheDefinitive Guide to Jython.Acknowledgements. The authorwould like to give special thanksto the following Jython/Java inte-gration experts: Jim Baker, Jythoncore developer and expert Pythondeveloper; Frank Wierzbicki, Jythonproject lead and expert Pythondeveloper; and Darjus Loktevic,Clamp project lead. </article>ProxyCompiler.compile("src/VolumeCalculatorClamp.py","src/VolumeCalculatorClamp");LEARN MORE• Jython Website• Jython Wiki• Jython Monthly newsletterNote: The following listing has been excerpted for space, as noted by the ...symbol. The full code listing is available by downloading the code listings forthis issue.from org.javamagazine.interfaces import Poolfrom java.lang import (Object, Void, Long, Integer, Float)import clampclass VolumeCalculatorClamp(Pool):. . .. . .@clamp.method(Void.TYPE,[Integer.TYPE])def set_diameter(self, d):self.diameter = dself.isRect = False@clamp.method(Void.TYPE, [Integer.TYPE, Integer.TYPE])def set_depth(self, shallow=0, deep=0):self.shallowDepth = shallowself.deepDepth = deep@clamp.method(Void.TYPE)def calculateVolume(self):volume = 0if self.isRect:return self.calc_rectangular()else:return self.calc_circular(). . .. . .LISTING 15 LISTING 16Download all listings in this issue as textINTERCHANGEAnyJavaclassthatispartofthestandardlibrarycanbeimportedintoJythonforuse.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH89COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /Telecommunications isevolving from simplephone calls to a new breed ofhybrid services that includevideo; content from weather,traffic, or media; or anythingaccessible from the internet.Next-generation wirelessnetworks support these newservices. Wireless networkshave evolved to handle highvolumes of voice, video, anddata with all IP technolo-gies. While combining wire-less communicationswith internet servicesmight seem like rocketscience, the commu-nications industry hasadopted the internetmodel of exposingcore network assetsthrough open appli-cation programminginterfaces (APIs).Simple communi-cation APIs includesending messages viashort message ser-vice (SMS), seeing ifsomeone is presenton the network, andgetting the location ofa device. The commu-nication APIs can get morecomplex when the applica-tions include charging to atelephone account, authenti-cation for others, multimediamessaging service (MMS), ormultimedia conferencing.This article discussesprogramming the com-munications network usingopen standard APIs to buildinteresting, compelling,and—with luck—revenue-generating communicationsservices.The Business of MakingConnectionsProgramming the commu-nications network not onlyinvolves APIs, but alsoservice-exposure platformsthat connect the internet tothe communications net-work and provide a relation-ship with the communica-tions service provider (CSP).A developer directs all APIinteraction to the API service-exposure platform (seeFigure 1).The API service-exposureplatform protects the net-work from any harmful activ-ity through access and policycontrols. A CSP builds arelationship with developersthrough Websites, confer-ence, newsletters, and so on,and the relationship is trans-lated into the service-exposure platform throughaccess and policy controls.Telecommunicationsservice providers are beingchallenged to stay relevantto their customers, competewith internet voice provid-ers, and provide compellingapplications that use theirnetwork. Because they aremaking less money fromsimple telephone calls, theylook to build business byProgrammable CommunicationsNetworkUse open, standards-based APIs to build compelling communications services.Figure 1SEBASTIANGRABOWSKI,JAROSŁAWLEGIERSKI,ANDDOUGLASTAITBIO
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH90COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /exposing their corenetwork assets andletting Java developersdream up the next coolapplication that workson their network.Therefore, telecom-munications serviceproviders are publishingopen APIs as standards-based interfaces intotheir business—thebusiness of makingconnections. The newcommunications ser-vices are built using aprogrammable commu-nications network.Open Java APIs forCommunicationsOpen APIs over the internet thataddress many industries havegrown dramatically over the pastfive years. For example, for devel-oping applications with the lat-est “news,” there are open APIsdefined at developer.nytimes.comand guardian.co.uk/open-platform. For open APIs intoFacebook, go to developers.facebook.com, and for Twitter, goto dev.twitter.com/doc.The key to API success for ven-dors is to clearly expose theirgreatest strength. For telephoneservice providers, their strengthis communications and billing.Some telephone compa-nies claim that exposingnetwork APIs is difficultand risks commoditiz-ing the core voice andmessaging assets. Theyargue that there aredifficulties in securelyexposing call-controland messaging, whichexplains their delay inimplementing APIs.However, some ven-dors have deployed anAPI service-exposureplatform that pro-vides access and policyprotection and is notonly secure and robust, but alsoenables an important source ofrevenue for them. Several tele-phone companies have recentlyopened up their networks toJava developers. A few examplesinclude Verizon, AT&T, andOrange Labs.CSPs are unique in their lackof adoption of APIs for serviceinnovation, which puts them at adisadvantage in harnessing eco-systems to deliver value to theircustomers. The first API imple-mentation for CSPs was based onCORBA, a protocol that was notuser friendly for developers andwas complicated to implement.The next-generation telecom-munications open APIs wereoffered as Web services, whichwere popular in the IT worldbecause of their standards-baseduse of HTML and XML. There aremany kinds of Web service APIsfor telecommunications net-works (fixed and mobile), whichenable software developers to usethe capabilities of an underlyingnetwork. The APIs are deliber-ately high-level abstractions anddesigned to be simple to use. Anapplication developer can, forexample, invoke a single Web ser-vice request to get the location ofa mobile device or initiate a tele-phone call.Standards-based APIs for com-munications have emerged fromthe ParlayX Web Services APIand the Group Special MobileAssociation (GSMA) OneAPI:■■ ParlayX Web services aredefined jointly by the EuropeanTelecommunications StandardsInstitute (ETSI), the ParlayGroup, and the Third GenerationPartnership Project (3GPP).The APIs are defined usingWeb Services DescriptionLanguage (WSDL), and theyconform to the Web ServicesInteroperability (WS-I) BasicProfile.■■ OneAPI is a set of APIs sup-ported by the GSMA that exposenetwork capabilities over theinternet. The APIs are RESTinterfaces that can be usedto access the capabilities ofmobile networks—such as mes-saging, authentication, andpayments—worldwide.Service-Exposure PlatformTo expose core network assets, atelephone communications pro-vider will attach a service-exposureplatform to its network (seeFigure 2). From a software archi-tecture point of view, the service-exposure platform is locatedbetween the operator network andthe internet.In Figure 2, the southbound(network-facing) interfaces of aservice-exposure platform areconnected to the operator networkand integrated with telecommu-nications functionalities such asSMS, MMS, location services, pres-ence services, charging services,and so on. Northbound (applica-tion-facing) interfaces connect tothe internet with standard SOAPand REST interfaces.The service-exposure platformis also connected with telecom-munications operations supportsystems (OSS)—which are respon-sible for maintenance, inventory,provisioning, and fault manage-ment—as well as with the busi-ness support systems (BSS) thathandle rating, charging, billing,and payments.TO THE COREToexposecorenetworkassets,atelephonecommunicationsproviderwillattachaservice-exposureplatformtoitsnetwork.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH91COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /An open, standards-basedservice-exposure platform isdesigned to interact with externalprograms through the API, providepolicy enforcement, and leveragethe unique network assets withthird-party developers and con-tent partners. Many telephonecompanies have successfullydeployed a service-exposure plat-form in their networks to create anopen, standards-based service-exposure layer.As telephone companies gradu-ally evolve and extend their servicedomain to better use the IT andWeb developer communities, theservice-exposure platform maxi-mizes their legacy, fixed-network,and mobile-network investments,such as those for location services,payments, and messaging. It alsofuture-proofs investments thatare made for exposing servicesthrough IP networks.Java ApplicationsOrange Labs created a societyof developers called OpenMiddleware 2.0 Community,which is oriented for telecommu-nications APIs. With the coopera-tion of several universities, OrangeLabs pursued master’s and bach-elor’s students to develop innova-tive communications applications.More than 300 Java developersdeveloped 30 services in Java withprogrammable network APIs. Thefollowing are a few interestingapplications developed by thiscommunity:■■ Emergency Button: This is asimple e-health application forlocating a person who is in adangerous situation. The mainidea of this application is toestablish one-button communi-cation between an elderly personor someone in need of monitor-ing due to a health conditionand a guardian, who needs to beinformed about that person’scondition. The application usesAPIs to receive UnstructuredSupplementary Service Data(USSD) messages, receive ter-minal location information, andsend SMS messages.■■ Integration UnifiedCommunications with Telco 2.0:This practical integrationof an enterprise UnifiedCommunications (UC) systemwith a telecommunications ser-vice provider’s service deliveryplatform (SDP) enables sendingSMS and USSD messages andgeolocalizing a user’s mobileterminal directly from the userinterface of the UC system.■■ BusStop: This application sup-ports public transportationin agglomerations. Using thisapplication, a user can ask for thelocation of the closest bus stopsand receive information via SMSabout routes and timetables■■ CourierAssistant: This applica-tion improves transportationplanning in a courier company.A call-center employee takesan order from a client usinga Voice over IP (VoIP) phone.The application uses terminal-location API searches to findcouriers that are near the client.The nearest courier is informedthrough SMS and USSD chan-nels about the package thatneeds to be picked up.The following sections provideexamples, including a ParlayX SMSimplementation, a OneAPI pay-ment gateway implementation, aOneAPI authorization application,and a OneAPI quality of service(QoS) API.Developing a ParlayXSMS ApplicationThe advantage of the ParlayX APIsis that the Java developer caninvoke a network function, such assending an SMS message, with-out knowing all the minutiae ofFigure 2
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH92COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /the network. ParlayX provides theprimitives to handle communi-cations in a simple way. SendingSMS messages from Web portalsis a common capability offered byservice providers.The sequence shown in Figure 3illustrates a self-care portal pro-viding SMS service via the ParlayXSendSMS API.The endpoint for the SendSmsinterface is http://<host>:<port>/parlayx21/sms/SendSms. Theapplication would include the codeshown in Listing 1.The SMS messages are retrievedusing a registrationIdentifier thatwas used when the notificationwas registered using a provisioningstep in the Services Gatekeeper.Listing 2 shows sample code forgetting messages received by theServices Gatekeeper.OneAPI Payment APIThe OneAPI Payment API providesan opportunity to improve thecustomer experience by allow-ing purchasing without the needto collect credit card numbers,financial information, user log-ins, or registration informationthrough a third-party Website.Applications use the API to chargean amount to an end user’saccount, refund amounts to thataccount, query charge amountstatus, and list the amountscharged for transactions.Applications can also reserveamounts, reserve additionalamounts, charge against thereservation, and release a reserva-tion. Below are two samples forusing the OneAPI Payment API.OneAPI application requestsflow through a service-exposureplatform via communication ser-vices. A communication serviceconsists of a service type (suchas Multimedia Messaging,Terminal Location, and so on),an application-facing interface(also called a north interface), anda network-facing interface (alsocalled a south interface).Figure 3Download all listings in this issue as textSendSms request = SendSms();SimpleReference sr = new SimpleReference();sr.setEndpoint(new URI("http://localhost:8111/SmsNotificationService/services/SmsNotification?WSDL"));sr.setCorrelator("cor188");sr.setInterfaceName("InterfaceName");ChargingInformation charging = new ChargingInformation();charging.setAmount(new BigDecimal("1.1"));charging.setCode("test");charging.setCurrency("USD");charging.setDescription("some charging info");sendInf.setCharging(charging);URI[] uri = new URI[1];uri[0] = new URI("1234");request.setAddresses(uri);request.setCharging(charging);request.setReceiptRequest(sr);request.setMessage("we are testing sms!");request.setSenderName("6001");SendSmsResponse response = smport.sendSms(request);String sendresult = response.getResult();System.out.println("result: " + sendresult);LISTING 1 LISTING 2
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH93COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /Sample Charge Amount opera-tion. The Charge Amount opera-tion charges an amount directlyto an end user’s application usingthe Diameter protocol. Listing 3shows sample Java code for invok-ing payment using the ChargeAmount interface.Sample Refund Amount opera-tion. The Refund Amount opera-tion refunds a currency amountdirectly to a subscriber’s applica-tion using the Diameter protocol.Listing 4 shows sample Java codefor invoking the Payment Datainterface.OneAPI AuthorizationAPIWith the OneAPIAuthorization API, alsoknown as OAuth, theservice-exposure plat-form secures resourceaccess for third-partyapplications. OAuthauthenticates sub-scribers and autho-rization of subscriberresources; exposescarrier authenticationas a service to partnersites and applications;offers a delegatedauthentication modeto support third-partyauthentication; andprovides an interface tomanage access tokens. The fol-lowing two samples illustrate howto use OAuth.Sample OAuth2 Authorize opera-tion. In Listing 5, Client1 builds upa request to endpoint /oauth2/authorize and a service-exposureplatform redirects the clientto the Authorize and Authenticate(AA) server .Sample OAuth2 Token operation.In Listing 6, the token endpointis used by the client to obtain anaccess token by presenting itsauthorization grant (that is, theauthorization code) or refreshtoken. After authenti-cation, the AA serverredirects Client1 toOCSG to issue thecode, and then Client1builds up a requestto OCSG endpoint/oauth2/a/token.OneAPI QoS APITo allow customersto pay for quality, theservice-exposureplatform offers dif-ferentiated servicesto customers, suchas increased band-width when watchinga video, clear voice forimportant calls, andlow latency for real-time applications suchDownload all listings in this issue as textOneAPIClient client = new OneAPIClient(JAXBContextResolver.class,"oma.xml.rest.payment._1.ObjectFactory","createAmountTransaction", AmountTransaction.class);client.setUri("http://localhost:8001/oneapi/1/payment/tel%3A1234/transactions/amount");client.setAuthorization(getAuthorizationHeader());AmountTransaction requestData = new AmountTransaction();PaymentAmount paymentData = new PaymentAmount();ChargingInformation chargingData = new ChargingInfomation();chargingData.setAmount(100);chargingData.setCurrency("USD");chargingData.setDescription("Sample");ChargingMetaData metaData = new ChargingMetaData();metaData.setOnBehalfOf("Example Games Inc");metaData.setPurchaseCategoryCode("Game");metadata.setTaxAmount(0);paymentData.setChargingInformation(chargingData);paymentData.setChargingMetaData(metaData);requestData.setTransactionOperationStatus(TransactionOperationStatus.CHARGED);requestData.setEndUserId("tel:1234");requestData.setClientCorrelator("987654321");requestData.setPaymentAmount(paymentData);requestData.setReferenceCode("Rfc4006");try{ret = client.post("", requestData);} catch (final OneAPIClientException e) {……}LISTING 3 LISTING 4 LISTING 5 LISTING 6API DRIVERSSometelephonecompanieshavedeployedanAPIservice-exposureplatformthatprovidesaccessandpolicyprotectionandisnotonlysecureandrobust,butalsoenablesanimportantsourceofrevenueforthem.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH94COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /as games. A service-exposure platformallows an entry pointfor applications toinfluence QoS andenable managementof the relationshipamong multipleapplications, sub-scribers, and net-work resources.The following twosamples are for usingthe QoS API.Sample ApplyQoSoperation. TheApplyQoS API is usedby an application torequest that eithera temporary or adefault QoS feature be set up onthe end-user connection. Listing 7shows sample code.Sample DeleteQoS operation. TheDeleteQoS API is used by an appli-cation to release a temporary QoSfeature that is currently active onthe end-user connection. Listing 8shows sample code.ConclusionAPIs are now a central strategy forbusinesses to expand and future-proof their core strengths. APIs aresimply an evolution of the Web.They make it easy to work withpartners, enable open innovation,and create a positive feedbackloop around cus-tomer experienceand revenue.CSPs are still look-ing for new openAPIs and servicesto better mon-etize their networks.Developers benefitfrom more open APIsbecause only theyprovide the pos-sibility to createinteresting and prof-itable applications.Telephone compa-nies can no longerafford to delay; theyneed an API strategyacross their entirebusiness—not just for third par-ties, but also for innovation inter-nally and with existing partners—in order to remain relevant totheir customers. </article>Download all listings in this issue as textApplyQoSFeatureResponse response = null;OneAPIClient client = new OneAPIClient(JAXBContextResolver.class,"oracle.ocsg.rest.qos.v1_0.ObjectFactory","createQoSFeatureProperties", QoSFeatureProperties.class,ApplyQoSFeatureResponse.class);QoSFeatureProperties data = new QoSFeatureProperties();data.setDuration(3600);//unit is secondsdata.setApplicationIdentifier("sampleAppId");data.setServiceInfoStatus(ServiceInfoStatus.FINAL_SERVICE_INFORMATION)data.setsubscriptionId("samepleSubId");data.setFramedIPAddress(new byte[]{0x0a,0x98,0x47,0x96});data.setCalledStationId("WAN_1");MediaComponentDescription mcd = new MediaComponentDescription();mcd.setMediaComponentNumber(0);mcd.setMediaType(MediaType.VEDIO);mcd.setMaxRequestedBandwidthUL(500);mcd.setMaxRequestedBandwidthDL(1000);mcd.setMinRequestedBandwidthUL(50);mcd.setMinRequestedBandwidthDL(100);mcd.setFlowStatus(FlowStatus.ENABLED);data.getMediaComponentDescription().add(mcd);String uri = new String("http://localhost:8001/ApplicationQoSService/tel%3A1234/qos");client.setUri(uri);try {response = (ApplyQoSFeatureResponse)client.post("", data);} catch (OneAPIClientException e) {......}LISTING 7 LISTING 8LEARN MORE• ParlayX Web services• OneAPIDID YOU KNOW?Anopen,standards-basedservice-exposureplatformisdesignedtointeractwithexternalprogramsthroughtheAPI,providepolicyenforcement,andleveragetheuniquenetworkassetswiththird-partydevelopersandcontentpartners.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH95COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /Did you hear aboutInstagram being sold toFacebook for a cool US$1billion? And do you thinkthat you can do better withyour own Java ME–basedapplication? Well, you can. Atleast, you can build your ownapplication that mimics thebehavior of the Instagramapplication. Selling it toFacebook . . . well, that’sanother kettle of fish.In this article, which isPart 1 of a two-part series,I will cover image manipu-lation and transformation.In Part 2, I will show how topost the modified imagesto Facebook.Note: The source code forthe examples described inthis article can be down-loaded here.What Is Instagram?Instagram is a photo-sharingapplication that is avail-able for iOS and Androiddevices. There is a plethoraof similar applications forthese devices, but Instagramstands out for its ease of use,the many filters that helpgive images a retro feel, andeasy integration into thesocial sphere.The Instagram applica-tion has two main parts:filters and social sharing.Both are key to the applica-tion’s success. Of course,sharing is not limited toFacebook; Instagram workswith the Instagram Website,Twitter, and several otherWebsites that support OAuthauthentication.Instagram also providesits own API, which develop-ers can use to create theirown applications on top ofInstagram and then custom-ize as they see fit.Let’s get started by creat-ing our own photo-sharingapplication in Java ME.Creating Our OwnInstagramSeveral elements are neededto develop a comparableapplication. We need to takean image using the MobileMedia API (JSR 135); manip-ulate it using the Image classRGB (red-green-blue) data;and then finally, make thisdata available as a byte array.And that’s just the first part.To keep it simple, I willshow you how to write twofilters: a “vintage” filter anda grayscale filter. But first,we need to understand theapplication flow and howimage manipulation works.PhotoShareMIDletApplication FlowA simple MIDlet calledPhotoShareMIDlet will beused to cycle through thedifferent choices that wehave: taking images, trans-forming them, and publish-ing them. This MIDlet willcreate the ImageCanvas classthat is used to display thecamera (the VideoControl)for taking images. Finally,the ImageTransform class willCreate a Java ME application that captures, filters, and transforms images.VIKRAMGOYALBIOPart1Build Your Own InstagramJava ME ApplicationFigure 1PHOTOGRAPH BYJONATHAN WOOD/GETTY IMAGESListen toauthorVikramGoyalintroducethe topicof buildingInstagramapplicationsin Java.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH96COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /be used to actually manipulatethe images.Figure 1 is a screenshot of theapplication running in an actualNokia device showing all the avail-able options.Manipulating images is per-formed at the pixel level by modify-ing the ARGB values. ARGB standsfor alpha, red, green, and blue, andit is the building block for imagedata. Let’s understand this conceptin detail before we proceed further.UnderstandingARGBIn Java imagerepresentation,ARGB representsthe pixel-levelinformationabout an image.RGB representsthe red, green,and blue colorsof the image,and A stands forthe alpha level.The alpha leveldescribes howtransparent oropaque eachpixel is. Thus,an alpha levelof 0xff (1111 1111)is completelyopaque, whilean alpha levelof 0x00 (0000 0000) is com-pletely transparent.It helps to think of a completeimage broken down into indi-vidual pixels and then identifyeach pixel using its integer value.Thus, an image in Java is simplyan array of integers, and eachinteger represents the ARGBvalue for a pixel.Table 1 represents a single imagepixel as a 32-bit integer:■■ The first eight bits are what iscalled the alpha channel, repre-senting the opacity of this par-ticular image pixel. In this case,the image at this pixel is com-pletely opaque.■■ The next eight bits are the redchannel. In this case, the redvalue of this pixel is 0101 0101(0x55).■■ The next eight bits are the greenchannel. In this case, the greenvalue is 1010 1010 (0xAA).■■ Finally, the last eight bits are theblue channel, with a blue valueof 1111 1111 (0xFF).With the image data availableat a pixel level in Java ME as anarray of integers, it becomes veryeasy to manipulate the data. Thus,in the example shown in Table 1,if we needed to convert the pixelto completely transparent (fromcompletely opaque), we wouldneed to manipulate the first eightbits to 0000 0000 (0x00).In Java ME, you get this datausing the getRGB() method of theImage class. To do the reverse,that is, to draw an image once youhave the RGB data, you use thecreateRGBImage() of the Imageclass.Now that we know this basictheory of ARGB and how Java MEallows us to manipulate the data,let’s see how we can use this togive our images an Instagramfeel. But first, we need to capturethe images.Capturing ImagesCapturing images is done by usingthe Mobile Media API, which is afairly mature technology that iseasy to use. (I even wrote the onlybook on it; see “Learn More” at theend of this article.)To capture the image, I have cre-ated a separate class to handle thewhole process: the ImageCanvasclass. In its constructor, I initializea VideoControl so that the user cansee through the camera, as shownin Listing 1.Once users have decided to takean image, they can press the FIREbutton (the default button) to takea snapshot. The snapshot is storedin an imageArray and presentedback to the calling MIDlet, asshown in Listing 2. Note that this isdone within a separate thread andthat the user will be asked for per-mission to take the image. Also,the camera at this stage must notbe used by any other application.The PhotoShareMIDlet nowcontains an image that can beshown to the user for furthermanipulation.Implementing Image FiltersAt this stage, the user has a choiceof applying one of two filters thatwe discussed earlier: vintage orgrayscale (see Listing 3). Of course,the user can apply these filters oneafter the other as well.Image transformation is per-formed using the ImageTransformclass; I have implemented twomethods dealing with eachmanipulation separately.The vintage filter. A vintage lookis achieved by aging the image.Aging is traditionally achievedby changing the red and greenchannels.I have done this by creatingtwo generic methods. They aregeneric because they can be usedto change any channel, not justthe red or green channel. TheTable 11 1 1 1 1 1 1 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 1 1 1 1 1 1 1THE PROCESSSeveralelementsareneededtodevelopanInstagram-likeapplication:weneedtotakeanimageusingtheMobileMediaAPI,manipulateitusingtheImageclassRGBdata,andthenmakethedataavailableasabytearray.
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH97COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /first method is the public method(see Listing 4). It accepts informa-tion about how much each chan-nel needs to be changed, whichis called the delta value of thechange. The method accepts theoriginal image and the delta valueof each channel. Then it proceedsto create the delta arrays for thetransformation of each channel.To create the vintage effect, Ihave set the red and green deltaeach at 60. You should playaround with these values (and thedelta values of the alpha and theblue channels) to see the differenteffects you can create.The method calls the internaldoTransformARGB_Internal methodwith the values of the arrays. Thisinternal method does the actualinteger manipulation. For vin-tage effect, only the red and greenchannels are manipulated, butagain, this internal method isalso generic. Part of the code thatmanipulates the red channel isshown in Listing 5.The manipulation of the alpha,green, and blue channels is similar(but not the same); that code isin the associated source code file.The code in Listing 5 has the effectof changing the red channel withthe delta array value that we pre-scribed while calling this code.Figure 2 shows an originalimage, and Figure 3 shows howDownload all listings in this issue as textpublic ImageCanvas(PhotoShareMIDlet midlet)throws Exception {this.midlet = midlet;videoControl =(VideoControl) midlet.getPlayer().getControl("javax.microedition.media.control.VideoControl");if (videoControl == null) {throw new Exception("No Video Control for capturing!");}videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);try { // try and set to full screenvideoControl.setDisplayFullScreen(true);} catch (MediaException me) {videoControl.setDisplayLocation(5, 5);try {videoControl.setDisplaySize(getWidth() - 10, getHeight() - 10);} catch (Exception e) {}repaint();}videoControl.setVisible(true);}LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5Figure 2 Figure 3
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH98COMMUNITYJAVAINACTIONABOUTUSblog//mobile and embedded /the image looks after it has beenfiltered using the code in Listing 5.These images were taken on anactual Nokia device.The grayscale filter. Grayscaletransformation means remov-ing all color from the image andreducing the image simply toblack and white. This is achievedby using two methods (seeListing 6). The first iterates overall the pixels within the image,while the second removes thecolor and opacity.In a very rough way, the codein Listing 6 achieves grayscale bycreating an average of all the indi-vidual color components whileleaving the opacity as is.As before, Figure 2 shows theoriginal image, and Figure 4 showsthe image after running the gray-scale filter. These images were cap-tured on an actual Nokia device.ConclusionHere in Part 1 of this two-partseries, you learned how to cre-ate filters and manipulate imagesusing advanced pixel manipula-tion of the Image class, whichwas demonstrated by developingtwo different filters. You learnedto do this as part of creating anInstagram-like application.In the next article in thisseries, you will learn how to sharea manipulated image onlineusing your Facebook identifica-tion. </article>Figure 4Download all listings in this issue as textpublic static Image doGrayScaleTransform(Image original) {int w = original.getWidth(); // original widthint h = original.getHeight(); // original heightint[] buffer = new int[w * h]; // buffer for new imageoriginal.getRGB(buffer, 0, w, 0, 0, w, h); // as RGB values// now, for each individual pixel, apply the transformationfor(int i = 0; i < buffer.length; i++) {buffer[i] = doGrayScaleTransform_Internal(buffer[i]);}return Image.createRGBImage(buffer, w, h, true); // return trans image}private static int doGrayScaleTransform_Internal(int bite) {// create an int array to hold the 4 levels of// transforms we are going to doint[] out = new int[4];out[0] = (int)((bite & 0xFF000000) >>> 24); // Opacity levelout[1] = (int)((bite & 0x00FF0000) >>> 16); // Red levelout[2] = (int)((bite & 0x0000FF00) >>> 8); // Green levelout[3] = (int)(bite & 0x000000FF); // Blue levelint new_bite = out[1]/3 + out[2]/3 + out[3]/3;out[1] = new_bite;out[2] = new_bite;out[3] = new_bite;return (out[0] << 24 | out[1] << 16 | out[2] << 8 | out[3]);}LISTING 6LEARN MORE• Mobile Media API• Pro Java ME MMAPI: Mobile Media API for Java MicroEdition (Apress, 2006)
  • ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013JAVATECH99COMMUNITYJAVAINACTIONABOUTUSblog//fixthis/GOT THE ANSWER?Look for the answer in the next issue. Or submit your own code challenge!In the March/April 2013 issue, Jason Hunter andBoris Shukhat gave us a code challenge around how the JavaPersistence API (JPA) handles parameterized SQL and theresult set. There were actually two bugs in the code challenge, andthe correct answer is both #3 and #4.For #3, when we set parameters in native SQL they are indexedstarting from 1, not 0. This fact is discussed in the JDBCdocumentation but not in JPA. The programmer was not aware ofthe fact and used zero-based indexing as with Java collections.For #4, the query.getResultList() call always returns a List. Ifthe result set is empty, it returns an empty List. This fact is notdocumented in JPA either.The correct code looks like this:EntityManager em = ...;String sql = "select department from emp where fname=?and mname=? and lname=?";Query query = em.createNativeQuery(sql);String[] name=new String[3];for (int i=1; i<4; i++) query.setParameter(i, name[i]);List departments = query.getResultList();if (departments.isEmpty())System.out.println("Not available");elsefor(String department : departments)System.out.println(department);This issues challenge comes from Michal Lisiecki, a businessprocess modeling notation/service-oriented architecture specialistat Oracle Poland.ART BY I-HUA CHENHint: Think carefullyabout pattern matching.1 THE PROBLEMSometimes when loading data from a file, we have problems with parsingdates. A simple solution that comes to mind is to use SimpleDateFormat.However, is that a good solution?2 THE CODEConsider the following code fragment and its result.String value = "01-04-1989";String dateFormatString = "yyyy-MM-dd";SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatString);try {System.out.println("Result: " +dateFormat.format(dateFormat.parse(value)));} catch (ParseException e) {System.out.println("Error date parsing: " + value + "in format " +dateFormatString);e.printStackTrace();}3 WHAT S THE FIX?1) Error parsing: 01-04-1989 in format yyyy-MM-dd2) 0006-09-103) 1989-04-014) 0104-19-89