Javamagazine Mayo Junio 2013


Published on

Revista Java

Published in: Technology, News & Politics
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Javamagazine Mayo Junio 2013

  1. 1. 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 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.
  2. 2. 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  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
  3. 3. 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
  4. 4. 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
  5. 5. 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.
  6. 6. 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
  7. 7. 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 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.”
  8. 8. 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
  9. 9. ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////////////////////  MAY/JUNE 2013COMMUNITY09JAVATECHABOUTUSJAVAINACTIONblog//java nation /In a recent 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%
  10. 10. 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.
  11. 11. 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]
  12. 12. 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.
  13. 13. #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 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
  14. 14. 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.
  15. 15. 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.
  16. 16. 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.”
  17. 17. 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. /articleLEARN 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.”
  18. 18. 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.
  19. 19. 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, 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
  20. 20. 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, 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’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.”
  21. 21. 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 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 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.” /articleBased 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
  22. 22. 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
  23. 23. 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—ão Paulo, BrazilIndustry:IT servicesEmployees:28,000Revenue:R$1.5 billion(2012 estimate)Java technology used:Java EE 6
  24. 24. 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.
  25. 25. 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.” /articleJavainBrazil 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 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
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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
  31. 31. 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 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 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 theui: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 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:definesection, as shown in Listing 6.@PersistenceContextEntityManager em;Figure 11Download all listings in this issue as textui:define name=contenth2Pick a movie/h2h:form prependId=falseh:selectOneRadio value=#{booking.movieId}layout=pageDirection required=truec:forEach items=#{movieFacadeREST.all} var=mf:selectItem itemValue=#{} itemLabel=#{}//c:forEach/h:selectOneRadioh:commandButton id=shows value=Pick a timeaction=showtimes /}//h:form/ui:defineLISTING 1 LISTING 2 LISTING 3 LISTING 4
  32. 32. 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 theui: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 theaterListShowTiming 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
  33. 33. 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). /articleFigure 13Figure 14Figure 15Figure 16LEARN MORE• GlassFish resources• “Java EE 7—Introduction”• “Java EE 7 Hands-on Lab”• Java EE Platform specification
  34. 34. 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
  35. 35. 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 ComparableMethodModel {public String name = ;public String body = ;public CompilationUnitTree compUnit;public long start;public long end;private ListString varTypes = new ArrayListString();private ListString varNames = new ArrayListString();LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5
  36. 36. 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 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 TreePathScannerVoid, Void {public Void visitClass(ClassTree classTree, Void aVoid) {String clsName = classTree.getSimpleName().toString();currrentClass = new ClassModel(); = clsName;currentPackage.add(currrentClass);return super.visitClass(classTree, aVoid);}LISTING 6 LISTING 7 LISTING 8 LISTING 9 LISTING 10