Javamagazine2012,nov dec

Uploaded on


More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. //table of contents / COMMUNITY COMMUNITY 46 02 Mobile and Embedded From the Editor Get Started with Java JAVA IN ACTION 04 SE for Embedded Java Nation Devices on Raspberry Pi News from JavaOne, plus Bill Courington and Gary people, events, and books Collins walk you through getting Linux and Java SE for Embedded Devices to run on JAVA TECH the Raspberry Pi in less than 30 an hour. New to Java JAVA TECH Can You Teach Testing 55 to Beginners? Polyglot Programmer Michael Kölling wraps up his Building Actor-Based series on BlueJ with a look at Systems Using the Akka its interactive-testing support. Framework Ted Neward shows you how 34 to use Akka’s open source Java Architect actor model implementation ABOUT US Exploring Lambda to build distributed systems. Expressions for the Java Language and 60 the JVM Fix This Ben Evans, Martijn Verburg, Take our JDBC code and Trisha Gee help you get challenge. ready for lambda expressions in Java SE 8. 42 14 20 25 38 Mobile and Embedded JCP Executive Java in Action Java in Action Rich Client GROWING Wirelessly Recover Your Series AN ENGINE JAVAFX IN Device’s Address Book Q&A WITH MIKE FOR BIG DATA SPRING ON OPEN Vikram Goyal explains how MILINKOVICH Hadoop uses Java Stephen Chin to add a recovery model to The Eclipse for large-scale shows you why the backup capability of your Foundation’s analytics. to use the Spring device’s address book. executive director framework on AgroSense provides an all-Java open blog assesses the state the client. of Java and the JCP. source platform for sustainable farming and precision agriculture. COVER ART BY I-HUA CHEN, NICHOLAS PAVKOVIC 01ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 2. //from the editor / COMMUNITY T JAVA IN ACTION FIND YOUR JUG HERE JAVA TECH hey say that it takes a village to raise a child. As a parent, I wholeheartedly agree. The teachers, coaches, friends, and family who regularly interact with my son are influencing the person he is becoming— One of the most elevating things and giving him access to a much greater range of specialties and world views than his father and I could in the world is to build up a community where you can hang provide on our own. Open source software is not so different. It, too, is raised by a global village of contribu- out with your geek friends, educate tors, each of whom offers his or her own special breed of knowledge. This collaborative model keeps the each other, create values, and software evolving and improving and encourages innovation. give experience to you members. ABOUT US In this issue, we explore how Java provides a platform for two organizations to build their own open source Csaba Toth Nashville, TN Java Users Group (NJUG) projects. 2012 Duke’s Choice Award winner the AgroSense Project built an open source farm management system on Java and the NetBeans Platform that gives farmers the information they need to manage their LEARN MORE crops. Another 2012 Duke’s Choice Award winner, Hadoop, is an open source software platform written in Java that enables businesses to unlock potential value from big data. Because Hadoop is open source, decisions about it are made by consensus. “You can’t just do things unilaterally,” Hadoop creator Doug Cutting tells us. We also get an open source perspective from Eclipse Foundation Executive Director Mike Milinkovich in our Java Community Process Executive Committee //send us your feedback / member interview. Plus: Simon Phipps of the Open Source Initiative tells us what’s We’ll review all suggestions for future driving open source today in a video interview with Tori Wieldt, and Ted Neward improvements. shows us how to use Akka, an open source actor model implementation. Depending on volume, It’s been a great year at Java Magazine. Looking ahead to 2013, we are open to some messages may your feedback so that we, too, can keep growing and innovating. not get a direct reply. blog Caroline Kvitka, Editor in Chief BIO PHOTOGRAPH BY BOB ADLER 02ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 3. Answers. Fast.Subscribe and gain instant cutting-edgedevelopment insight from the world’s mosttrusted tech publishers — all in oneon-demand digital library. • Get unlimited access to 23,000+ online books and training videos from100+ publishers • Search full text to efficiently get the answers you need • Make notes and organize content into folders you control • Elevate your career with thousands of top business and professional development titles ANYTIME, ANYWHERE: Access on your desktop, notebook, tablet or mobile device. Start a free unlimited-access trial today
  • 4. //java nation / COMMUNITY JavaOne 2012 / JAVA IN ACTION MAKE THE FUTURE Mark Reinhold JAVA TECH JAVA The theme of JavaOne 2012, held September ABOUT US 30–October 4, was “Make the Future Java.” Throughout the week, attendees explored Java’s continued role as the most popular, complete, productive, secure, and innovative development Brian Goetz Georges Saab Nandini Ramani platform as well as its open, transparent, col- laborative, and community-driven evolution. At Sunday’s Strategy keynote, Oracle’s Hasan Rizvi Under stewardship, he noted Oracle’s continued announced that Oracle plans to contribute the detailed the three factors critical to Java’s suc- outreach—with four regional JavaOne confer- implementation to OpenJDK. cess: technology innovation, community par- ences last year and the launch of Java Magazine. Oracle’s Brian Goetz explored language and ticipation, and Oracle’s leadership/stewardship. Here are highlights from Sunday’s Strategy and library features planned for Java SE 8, including Under technology, he noted Macintosh OS X Technical keynotes: lambda expressions and better parallel librar- and Linux ARM support on Java SE, open sourc- Java 8/Java 9 ies. These feature changes both simplify code ing of JavaFX by the end of 2012, the release of Oracle’s Georges Saab discussed the upcoming and free up libraries to more effectively use Oracle Java Embedded Suite 7.0, and multiple JDK 8 release—including Project Lambda and parallelism. Oracle’s Mark Reinhold urged developers to blog releases on the Java EE side. Under community, Project Nashorn (a modern implementation of he said that the Java Community Process (JCP) JavaScript running on the Java Virtual Machine). get involved in the Java 8 development process— continues, with new JSR activity and Java user He noted that Nashorn functionality has already getting the weekly builds, trying out their current group participation up 25 percent since last year. been used internally in NetBeans 7.3, and code, and trying out the new features. PHOTOGRAPHS BY HARTMANN STUDIOS 04ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 5. //java nation / JavaOne 2012 / COMMUNITY Left: Nike’s Nicole Otto presented Oracle’s Cameron Purdy with a JavaOne Content on Video NikeFuel accelerometer wrist band JavaOne content is available on video in three so that he can track his activity. categories: keynote highlights; full keynotes; JAVA IN ACTION and all sessions, birds-of-a-feather (BOF) sessions, and tutorials. Right: Dr. Robert Ballard, oceanographer and National Geographic explorer in residence, presented an overview of the cutting-edge technology used in JAVA TECH deep-sea explorations. Saab also explored Java SE 9 and beyond— in Small Things” for details of Oracle’s product Jigsaw modularity; Project Penrose for interop- announcements.) Ramani encouraged devel- Welcome to JavaOne 2012 erability with OSGi; improved multitenancy opers to download the latest releases of Oracle for Java in the cloud; and Project Sumatra, an Java SE Embedded and try them out. OpenJDK project targeted at bringing Java to Java EE 7/Java EE 8 ABOUT US heterogeneous platforms. Oracle’s Cameron Purdy summarized the JavaFX latest developments in the enterprise space: Oracle’s Nandini Ramani announced that a greater developer productivity in Java EE 6 and developer preview of JavaFX on Linux ARM as portability between platforms, vendors, and well as JavaFX Scene Builder on Linux are avail- even cloud to cloud. The earliest version of the able for download. She noted other JavaFX 2 Java EE 7 Software Development Kit (SDK) is milestones including releases on Microsoft now available for download—in GlassFish 4— Strategy keynote highlights Windows, Macintosh OS X, and Linux; the with WebSocket support, better JSON support, JavaFX Scene Builder tool; the JavaFX WebView and more. The final release is scheduled for component in NetBeans 7.3; and an OpenJFX April 2013. project in OpenJDK. In JDK 8, JavaFX will offer Looking forward to Java EE 8, Oracle’s Arun 3-D and third-party component integration, Gupta explored how the platform will provide she said. multitenancy for applications, modularity Embedded based on Jigsaw, and cloud architecture. He blog Ramani discussed the latest on Java in the also talked about Project Avatar, for designing embedded space, declaring this to be “the next an end-to-end framework for building HTML5 IT revolution,” with Java as the ideal technology applications, and Project Easel, an advanced tooling capability in NetBeans for HTML5. Technical keynote highlights for the ecosystem. (See “A Huge Opportunity 05ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 6. //java nation / JavaOne 2012 / COMMUNITY Project Sumatra Update 2012 DUKE’S CHOICE AWARDEES RECOGNIZED Project Sumatra is a new OpenJDK project JAVA IN ACTION that will enable Java applications to take advantage of graphical processing units (GPUs) to improve application perfor- mance. The Sumatra effort is led by Oracle’s John Coomes, who has worked on the Java HotSpot VM for almost a decade. Initial development will focus on code generation, garbage collection, and runtime develop- JAVA TECH ment for offloading processing to GPUs. Subsequently, Java 8 lambda expressions will be utilized to further increase applica- tion parallelism. At the JavaOne Community keynote, Gary Frost of AMD (which has joined Project Sumatra) talked about the Sumatra effort ABOUT US Left: The 2012 Duke’s The winners of the 2012 Duke’s Choice Awards were recognized at a and demonstrated GPU speedups attained Choice Award. ceremony on the opening day of JavaOne. “This year’s Duke’s Choice using the related Aparapi (A Parallel API) Right: Oracle’s Orla open source project. Aparapi executes data- Nichorcora, senior Awards winners are spearheading a truly diverse and creative set of director business Java-based projects, and their efforts are invaluable to the Java com- parallel code on GPUs by converting Java development, presents munity,” says Oracle’s Peter Utzschneider. bytecode to OpenCL, which runs on a wide a 2012 Duke’s Choice One of the winners, The United Nations High Commissioner for variety of GPUs. In applications that plot- Award to the creators Refugees (UNHCR), was also recognized at Oracle Day in Kenya on ted Mandelbrot fractals, played the Game of of UNHCR’s Level October 12 and presented with its Duke’s Choice Award. To help facili- Life, and solved N-body gravitational physics One registration tool, tate its mission of humanitarian relief, UNHCR developed a light-client equations for 10,000 celestial bodies, Frost’s Doudoux Stanyslas demonstrations showed speedups of up to Java application on the NetBeans platform that collects information Matayo (left) and Abdouraouf Gnon- on the number of refugees and their water, food, housing, health, and 10 times using Aparapi compared with tradi- Konde. other needs in the field and combines that with geocoding information tional Java threads processing. from various sources. As with all OpenJDK projects, the com- “UNHCR, along with all of this year’s recipients, demonstrates the munity is invited to participate in Project remarkable work being done by Java community members across the Sumatra. While the project is still just getting blog world,” says Utzschneider. started, ultimately developers will be needed to test releases, suggest improvements, fix bugs, and more. PHOTOGRAPHS BY ORANGE PHOTOGRAPHY, HAIG ANYONYI 06ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 7. //java nation / JavaOne 2012 / COMMUNITY BY AND FOR THE COMMUNITY JAVA IN ACTION tion. He invited panelists better open standards. “Come join us, and make from Cloudera, Eclipse, your ecosystem better!” urged Verburg. Eucalyptus, Perrone Next, Paul Perrone of Perrone Robotics Robotics, and Twitter returned to profile the latest in his company’s JAVA TECH onstage to further dis- robotics work around Java—including the cuss the idea of inno- AARDBOTS family of smaller robotic vehicles, vation. Panelist Mike running the Perrone MAX platform on top of the Milinkovich, executive Java Virtual Machine (JVM). Perrone took his director of the Eclipse “Rumbles” four-wheeled robot out for a spin—a Foundation, noted, roaming, ARM-based security-bot vehicle, com- “The more open you plete with ultrasonic and “cliff” sensors. ABOUT US make your innovation Then, a mysterious voice from offstage pro- process, the more ideas nounced, “I’ve got some toys”—proving to be are challenged, and the surprise guest James Gosling, there to explore his more developers are cutting-edge work with Liquid Robotics. Gosling focused on justifying demonstrated real-time satellite tracking of their choices all the way several Wave Gliders currently at sea, noting that Clockwise from top: James Gosling describes the Wave Glider; Paul Perrone plays with robots; Sharat Chander proudly displays his JavaOne badge. through the process.” Java is actually particularly good at artificial intel- Continuing the topic ligence applications—due to the language hav- of innovation, Oracle’s ing garbage collection, which facilitates complex Thursday’s Community keynote reinforced the Georges Saab talked with Martijn Verburg of the data structures. idea that JavaOne is by and for the community. London Java Community (LJC) about the Adopt- Finally, Chander again took the stage, where Sharat Chander, JavaOne community chairper- a-JSR program. Other program participants also he passed the JavaOne Community Chairperson son, noted that 60 percent of the material at the took the stage, and the group explored the goals baton to Oracle Java Technology Evangelist 2012 JavaOne conference was presented by Java and tasks inherent in the Adopt-a-JSR program Stephen Chin. Wearing full motorcycle gear, blog community members, and he encouraged even —from organizing hack days, to managing Chin noted that he’ll soon be touring Europe by higher participation next year. mailing lists and forums, to triaging issues, to motorcycle on his NightHacking Tour, meeting Oracle’s Donald Smith explored the impor- evangelism—all with the goal of fostering greater Java community members and streaming live via tance of community in terms of fostering innova- community/developer involvement and building Ustream. Watch for coverage in our next issue. PHOTOGRAPHS BY HARTMANN STUDIOS 07ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 8. //java nation / JavaOne 2012 / COMMUNITY GEEK BIKE JAVA IN ACTION RIDE Following the tradition of JavaOne Latin America 2011, a Geek Bike Ride marked JAVA TECH the beginning of JavaOne 2012 on a gorgeous day in San Francisco. About 50 Java developers gathered at Fisherman’s Wharf, rode or skated through Fort Mason and Crissy Field, crossed the ABOUT US Golden Gate Bridge, and fin- ished in Sausalito. Riders returned to San Francisco by Clockwise from top: Geek Bike Ride participants paused ferry after a well-earned lunch. for a photo op at the water’s edge; SouJava’s Juggy joined Participants donned Duke in on the ride; bikers enjoyed a leisurely pace. bike jerseys, sponsored by Oracle Technology Network. To receive a jersey, partici- pants had to answer a ques- tion about Java. Questions included “Who is the father of Java?” “What’s the big- gest Java conference in San Francisco?” and “Name one Duke’s Choice Award blog winner from this year,” to which participant Régina ten Bruggencate answered, “Me!” PHOTOGRAPHS BY YOSHIO TERADA 08ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 9. //java nation / JavaOne 2012 / COMMUNITY A HUGE OPPORTUNITY IN SMALL THINGS JAVA IN ACTION Addressing the strong demand for Java in the embedded market, Oracle hosted a new Java Embedded @ JavaOne event in San Francisco October 3–4. In his keynote address, Oracle’s Judson Althoff said that devices are all around JAVA TECH us, on 24/7, and connected all the time. The explosion of devices is the next IT revolution and Java is the right solution for this space, he said. He noted that Java embedded solutions provide a framework to provision, manage, and secure devices as well as the ability to aggregate, pro- cess, and analyze a multitude of data. Finally, he ABOUT US said, Java is one platform to program them all. Terrance Barr, Java evangelist and Java ME expert, is enthusiastic about the huge opportu- nity. “It’s the right time and right place for Java embedded,” he said. “Oracle is looking for part- ners who want to take advantage of this next wave in IT.” constrained, connected, embedded systems. It Oracle Java Wireless Client 3.2. The embedded space continues to heat up. is designed and optimized to meet the unique Oracle Java Embedded Suite 7.0 is a packaged At JavaOne, Cinterion launched EHS5, an ultra- requirements of small, embedded, low-power solution (based on Oracle Java SE Embedded 7, compact, high-speed machine-to-machine devices such as microcontrollers and other Java DB, and versions of GlassFish for Embedded communication module providing secure wire- resource-constrained hardware without screens Suite and Jersey Web Services Framework), less connectivity for a wide variety of industrial or user interfaces. created to provide value-added services for col- applications. Oracle Java Wireless Client 3.2 is built around lecting, managing, and transmitting data to an optimized Java ME implementation that and from other embedded devices. It is a com- Oracle Unveils Embedded Products delivers a feature-rich application environment plete device-to-data-center solution subset for blog Just before JavaOne, Oracle announced several for mass-market mobile devices. embedded systems.  products in the embedded space. Java ME Software Development Kit (SDK) 3.2 Oracle Java ME Embedded 3.2 is a complete provides a complete development environment client Java runtime optimized for resource- for both Oracle Java ME Embedded 3.2 and 09ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 10. //java nation / JavaOne 2012 / COMMUNITY WOMEN IN TECH JAVA IN ACTION Every year, JavaOne hosts top-notch women technologists who are pursuing careers in IT. They are inspired technologists and community organizers. This year, Trisha Gee, Régina ten Bruggencate, and Saskia Vermeer- Régina ten Bruggencate Ooms—three seasoned developers with more than a decade of program- ming experience—talked about inspiring more women to be active in the New JavaFX community and to pursue careers in programming. They are leaders of Community Site JAVA TECH Duchess, a global network that connects women involved in Java. The net- work has 500 members in 60 countries and a strong Web presence. In her on session, “The Problem with Women: A Technical Approach,” Gee recom- mended that women speak at and organize events, blog, and share their Community activity sur- passion for programming—and not mention their gender. rounding JavaFX has been Fabiane Nardon and Yara Senger are developers and active community steadily growing, with leaders in Brazil. Nardon is a frequent speaker and a member of program tweets, blog posts, and ABOUT US committees at various Java conferences. Her JavaOne session covered projects increasing in num- auto-scaling Web-based Java applications. Senger, the president of the ber. Now, there is a JavaFX SouJava Java user group (JUG) and a cofounder of Globalcode, presented community site on sessions on the future of Java and on Java APIs for electronic devices and The main purpose of this external boards. Founders of the DuchessBrazil network, they encouraged Trisha Gee site is to provide a focal technical women to participate in the Java community. point for the JavaFX com- Patrycja Wegrzynowicz and Gail Anderson are both cofounders of tech- munity, where relevant nology companies. Wegrzynowicz specializes in automated software tweets, blog posts, and engineering and Java technologies and is a cofounder and CTO of Yonita. other resources can be eas- She presented on security vulnerabilities in open source Java libraries. ily found. Gerrit Grunwald Anderson has been designing technical courses and authoring textbooks and Jim Weaver, the com- for more than 20 years and is a cofounder of the Anderson Software Group, munity leaders for this site, a leading provider of software development training. She presented the welcome your feedback. session “Make Your Clients Richer.” blog “We need to stand up for ourselves in our lives and careers,” Senger said. She recommends that women get involved in the Java community by join- ing user groups and submitting proposals for talks at Java conferences. Yara Senger PHOTOGRAPHS BY ORACLE PHOTOGRAPHY, ORANGE PHOTOGRAPHY, TDC 10ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 11. //java nation / COMMUNITY JAVA BOOKS GREENVILLE, SOUTH CAROLINA JUG JAVA IN ACTION Java Magazine caught up with Greenville Java Users Group founder John Yeary and five-year Java user group (JUG) member Glen Peterson at JavaOne 2012. Greenville, South Carolina, is a small city surrounded by ORACLE CERTIFIED HADOOP IN PRACTICE rural communities. Peterson noted that ASSOCIATE, JAVA SE 7 By Alex Holmes JAVA TECH Greenville JUG is “the most interest- PROGRAMMER STUDY GUIDE Manning Publications ing thing going on between Greenville By Richard M. Reese (October 2012) and Charlotte” (the closest big city). Packt Publishing (August 2012) Hadoop in Practice collects So, does Greenville JUG have a tailor- Oracle Certified Associate, nearly 100 Hadoop exam- made, captive audience? By no means. Java SE 7 Programmer Study ples and presents them in Java evangelist Yeary founded the Guide addresses certifica- a problem/solution format. group in 2002. The first few meetings consisted of up to 3 attendees. Today the group tion exam objectives and Each technique addresses provides discussion and ABOUT US typically draws crowds in the 25-person range. a specific task you’ll face, Growing Greenville JUG was an ongoing labor for Yeary and his fellow members. examples to show the best such as querying big data The fact that the JUG was centered in a primarily rural area created difficulties in ways of applying Java lan- using Pig or writing a log contacting people who might want to participate. Yeary experimented with various guage features in real-world file loader. You’ll explore methods of outreach. His successes included a mailing list for technology managers. programming. Java SE 7 each problem step by step, These people told their developers about Greenville JUG, and many developers who Associate Programmer cer- learning both how to build had been initially encouraged by their managers to attend ultimately became regular tification adds to your quali- and deploy that specific attendees at the JUG’s monthly meetings. fication as a Java developer. solution along with gain- A recent turning point in Greenville JUG’s growth was when a JFrog representative Knowledge of Java is impor- ing an understanding of stopped by to participate in a Greenville JUG meeting while on his way to OSCON. The tant, but knowing how to the thinking that went into cost of making a stop at Greenville was small compared with the overall cost of the write efficient and produc- its design. As you work OSCON trip, so Yeary was able to negotiate to get the presentation at the meeting. tive code adds to your skills through the tasks, you’ll Yeary has this advice for JUG leaders who are seeking to find presenters for their and gives you an edge. find yourself growing more JUG meetings: “Be yourself, and introduce the person to your region of the world and Coverage of the certification comfortable with Hadoop to your local developer community—make them feel at home in your locale.” If you objectives goes beyond a and at home in the world of blog do this, word will likely spread among potential speakers that it’s well worth their simple review, and chap- big data. time to present at your JUG sessions. ters include sample exam questions. PHOTOGRAPH BY DAVE MCCLINTOCK, SNAPSHOTSC.COM 11ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 12. //java nation / COMMUNITY JAVA CHAMPION PROFILE JONAS BONÉR 2012 JCP AWARD WINNERS JAVA IN ACTION Jonas Bonér is a for fun (Programming Java Magazine: What Swedish entrepreneur, in C++), and I realized are you looking forward programmer, speaker, that that was what I to in the coming years? and writer. He became wanted to do. It was Bonér: Family-wise, a Java Champion in applied mathematics, I’m looking forward to February 2011. and suited me very well. seeing the kids grow Java Magazine: Where Java Magazine: What up; seeing what kind did you grow up? was your first computer of people they will turn JAVA TECH Bonér: I grew up in and programming into; and being there Uppsala, Sweden. Later, language? for them, listening, I lived in Stockholm, Bonér: I did my very first and coaching them and then in Östersund. programming in Pascal time with my family, to materialize their Since my family loves on a Solaris terminal fishing, skiing, reading dreams. Business-wise, skiing, we’ve also lived at the university; my novels, playing saxo- I’m looking forward in Åre, Sweden; Serre first computer ran phone (tenor, alto, and to building a success- ABOUT US Chevalier, France; Slackware Linux. soprano), and listening ful business around The 10th annual Java Community Process Alagna, Italy; and Bad Java Magazine: What to music. the open source stack (JCP) Award winners were announced at Gastein/Salzburg, was your first profes- Java Magazine: What we are working on and the JCP party at JavaOne 2012. The win- Austria, for periods sional programming side effects of your are passionate about. ners were selected from an impressive list of time—all great ski job? career do you enjoy the Personally, I hope to of nominees. This year’s JCP Member/ resorts. Bonér: My first pro- most? become a bit wiser and Participant of the Year Award went to Java Magazine: When gramming job was Bonér: Traveling to better at understand- two Java user groups, the London Java and how did you first as an IT consultant interesting places and ing, selecting, and Community and SouJava (shown above), for become interested in Uppsala, doing meeting and learning focusing on the impor- their historic contribution to the Adopt-a- in computers and CORBA [Common from smart, interest- tant things in life, the JSR program and for supporting Java devel- programming? Object Request Broker ing people who are tiny things that make opers through the JCP. The Outstanding Bonér: I was studying Architecture] and EJB passionate about all the difference. Spec Lead Award went to Victor Grazi, math at the university, [Enterprise JavaBeans] what they do. Also, I for his work on JSR 354, the Money and but I didn’t know what 1.0—what a joy! have enjoyed start- Visit Bonér’s company Currency API. The Most Significant JSR to do with it. First I was Java Magazine: What do ing my own business site, Typesafe, and his blog Award went to the JCP.Next effort, led by thinking of becoming you enjoy for fun and and everything I have latest open source JCP Chair Patrick Curran. a math teacher. Then relaxation? learned from this project, Akka. I took a CS course just Bonér: I enjoy spending journey! 12ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 13. //java nation / COMMUNITY convey that knowledge to Java JANUARY developers at large. Spend time Take Off with hundreds of other Java pro- JANUARY 17–18 fessionals, share best practices, LILLE, FRANCE and take home practical advice JAVA IN ACTION This English-language confer- that will make an immediate ence for Web developers and and measurable difference to designers focuses on trending your projects. topics. Session content ranges from server side to pure front Groovy and Grails eXchange end, from design and philoso- 2012 phy to new languages, and from DECEMBER 13–14 frameworks to development JAVA TECH LONDON, ENGLAND techniques. This two-day conference fea- EVENTS DECEMBER tures two dozen expert-led JDays 2012 FEBRUARY talks, along with discussion DECEMBER 3–5 Jfokus 2013 JavaOne Latin America DECEMBER 4–6, and brainstorming sessions, all GOTHENBURG, SWEDEN FEBRUARY 4–6 SÃO PAULO, BRAZIL focused on learning and sharing JDays 2012 is a conference STOCKHOLM, SWEDEN ideas, tools, and best practices about Java, open source, and Jfokus is the largest annual ABOUT US Join Java developers and technologists for Java- for enterprise Web develop- related technologies. The first conference for everyone who focused content, training, and networking. ment with Groovy and Grails. two days of the conference works with Java in Sweden. It is Experts from the worldwide Java community feature a lineup of sessions arranged in collaboration with share unique and leading-edge content with 7th Annual IndicThreads that were voted on by the com- Pune Conference Javaforum Stockholm, a Swedish attendees. As always, there are keynotes, tech- munity. Day 3 of the conference developer community and a Java DECEMBER 13–15 nical sessions, hands-on labs, demos, exhibi- offers a full day of free courses user group. Over three days, get PUNE, INDIA tors, and more. Featured content tracks include and hands-on training. up to date on the latest devel- This conference explores a Core Java Platform; Development Tools and opments in the Java platform. wide array of software develop- Techniques; Emerging Languages on the JVM; Java Conference The agenda includes rock-star ment tools and technologies in Enterprise Service Architectures and the Cloud; DECEMBER 8 speakers, both from Sweden Java; cloud computing; mobile Java EE Web Profile and Platform Technologies; BANGALORE, INDIA and around the world, with application development; and Java ME, Java Card, Embedded, and Devices; and The Java Conference is an ideal a focus on systems develop- emerging technologies such as JavaFX and Rich User Experiences. And of course, place to obtain critical skills to ment with Java and surrounding big data, gamification, HTML5, there are opportunities to network so that you help you build, run, and man- techniques such as dynamic and more. can build your community, share your expertise, age tomorrow’s software solu- languages and agile methodolo- blog and learn best practices. tions. The speakers are industry gies. Get the latest trends and practitioners, selected for their buzz about Java from people knowledge and their ability to who live and breathe technology. PHOTOGRAPH BY JEREMY WOODHOUSE/GETTY IMAGES 13ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 14. COMMUNITY (open source ) JAVA IN ACTION JAVA TECH C ontinuing our series of interviews with distinguished members of ABOUT US the Executive Committee of the Java Community Process (JCP), we turn to Mike Milinkovich, executive director of the Eclipse Foundation, which was cre- ated in January 2004 as an indepen- dent not-for-profit corporation to foster a vendor-neutral, open, and transpar- ent Eclipse community. Historically, Eclipse became famous as a Java IDE and a plug-in–based platform for building software development tools. JCP Executive Series A CONVERSATION WITH MIKE MILINKOVICH blog The Eclipse Foundation’s Mike Milinkovich assesses the state of Java and the JCP. BY JANICE J. HEISS ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY BLAIR GABLE/GETTY IMAGES 14ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 15. COMMUNITY Eclipse Foundation TopLink, which was acquired by a tools Executive Director company named WebGain in 2000. Mike Milinkovich meets Then in 2002, TopLink was acquired with a colleague in by Oracle, where Milinkovich served his Ottowa, Ontario, JAVA IN ACTION Canada, office. as vice president of Oracle application server technical services. In 2004, he assumed his present position where, among his many duties, he represents the Eclipse Foundation on the Executive Committee of the JCP. Java Magazine: Tell us about your day JAVA TECH job. Milinkovich: I’ve had jobs where I was a pure developer, and I’ve had jobs where I was a pure business per- son. And I’ve always been happiest when I’m oscillating back and forth between the two—and this job has ABOUT US this in spades. So basically I spend a lot of time keeping a pulse on what’s going on in the Eclipse projects and making sure the projects are well supported. We may help project leaders by introduc- ing them to others in the community or making sure that their code reposi- The Eclipse community now has more technologies have a say in the Eclipse tories and bug trackers are up and than 200 projects, 190 organizational Foundation. running. On the business side, Eclipse members, and a wealth of interest- Milinkovich has a long and diverse is also set up as a consortium. So we ing technologies that go far beyond its history with Java that enables him to have a lot of member companies that beginnings as a Java IDE. The Eclipse grasp a variety of perspectives. He first are trying to build a business or prod- Foundation’s mandate is to ensure worked with Java as IBM’s VisualAge for ucts on top of Eclipse. We help them that its projects are ready for commer- Java strategy manager in 1997. In 1999, move their business forward. Then blog cial adoption. As such, its governance he left IBM to work at Object People. there’s always both member and proj- model, development process, and IP In addition to its strong involvement ect recruitment. management are tailored to make sure in Java training and consulting, Object So I spend a lot of time talking to that consumers and adopters of Eclipse People had a persistence product, people in lots of different technology 15ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 16. COMMUNITY ate in a transparent manner. That’s a nity. We see that at Eclipse, and I think big step forward compared to six years it’s equally true at the JCP. ago. And looking at Java as a whole, the Java Magazine: What is the best thing Java platform is becoming more open, that has happened at the JCP in the JAVA IN ACTION with the basic platform work happen- last few years? ing at OpenJDK and with the participa- Milinkovich: It’s really simple—we tion of additional companies. got moving again. During the last Java Magazine: Do you have any com- couple of years with Sun at the helm, ments about the new presence of Java it was obvious that there wasn’t a lot user groups on both the Executive of investment going on in Java. There Committee and the JCP in general? was also the stalemate regarding Milinkovich: I think it’s great. moving forward with Java 7 at the JCP JAVA TECH Specifically, the presence of Ben Evans Executive Committee level. And since and Martijn Verburg from the London Oracle has taken the helm, we got Java Community and Bruno Souza going again. from Brazil’s SouJava has been a very Java 7 was shipped, and Java 8 and positive influence. They bring the per- Java 9 are underway. And within the spective of Java developers to the table, JCP itself, there have now been two which I think has been somewhat revisions of the process documents, ABOUT US lacking in the past. Their voices are bringing the JCP 2.8 process forward, Milinkovich is happiest domains about why they would want very important. In addition, in the last and then we have a second JSR to mixing development to do open source at Eclipse. We talk couple of years, what I call “Java user merge the two executive committees with business, and his about how they can use Eclipse to companies”—I’m thinking of Credit into one [JSR 355]. We are also starting Eclipse Foundation leverage their business models and Suisse and Goldman Sachs—have another JSR to rewrite the JSPA [Java position offers just that mix. move forward. I have been in this job also joined the Executive Committee, Specification Participation Agreement] now for more than eight years, and I bringing a very helpful perspective itself. So there’s been lots of valu- still really enjoy it. to the conversations as able work in bringing Java Magazine: In January 2007, consumers. They’re in OPEN VIEWS Java forward. Eclipse joined the JCP. At that time, you said, “Any changes we would be the position of trying to use this technology for “Broadening the Java Magazine: In walk- ing the fine line between proposing to the JCP would center their customers’ needs perspectives [of] respecting standards and around making the process more open and their business needs. your governance encouraging innovation, and transparent.” How have things gone in the subsequent five-and-a- That’s an important viewpoint. model helps any does the JCP err too far in one direction or the other? blog half years? Generally, broadening community. We see Milinkovich: Yes and no. Milinkovich: I think it’s gone fairly well. The new JCP 2.8 process document the perspectives that you have in your governance that at Eclipse.” The JCP has a lot of differ- ent JSRs underway, and requires all JCP expert groups to oper- model helps any commu- there are a lot of different 16ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 17. COMMUNITY on an OpenJDK mailing list—that’s a really good thing. Java Magazine: Do you have any ideas about how Oracle should best negoti- JAVA IN ACTION ate the inevitable tension between running a business and leading an open source Java community? Milinkovich: Let me offer a lesson from the Eclipse experience. Historically, Eclipse started as an IBM project and initially, there was lots of tension between IBM and Sun Microsystems JAVA TECH about the future of Java and how Java should be governed. And what IBM tried in part to do when they set up the Eclipse Foundation was demonstrate how they thought Java should be gov- Left: Milinkovich things going on. So there are areas innovation in the standards process. erned. The lesson learned was that if analyzes some where I think they get it right and some That’s particularly true of bringing you truly set it free at arm’s length, ABOUT US development details where it’s not so good. in very new technologies and adding good things can happen. The Eclipse with Wayne Beaton, First, innovating via standards is an them to the Java platform. Foundation today has nearly 190 orga- director of open source projects at Eclipse. inherently bad idea. Successful inno- Now, on the flip side, the JCP process nizational members. There are literally Right: Spelling things vation is inherently about seeing which is also the mechanism by which the thousands of products that are built out. ideas are truly useful. Standardizing Java platform has evolved. And I think on top of Eclipse. And to a consider- technologies that haven’t already the more open and community-based able degree, that happened after IBM proven themselves in that we can make the spec- let Eclipse go and set up the Eclipse the marketplace means IDEAS FIRST ifications and the imple- Foundation as an independent entity. that bad ideas inevitably “Innovating via mentations, the better the I’m not sure if Oracle could ever do leak in. To cite my favor- ite example, compare the standards is an platform is going to be. So in this context, the that, in part because of the business legacy of Java and the way it was ini- adoption and success of inherently bad recent direction of closely tially established. But the more it Spring versus CMP [con- tainer-managed persis- idea. Successfultying the work in the JCP with what’s going on in the can make the technology open to all comers and operate through a trans- tence]. So I think the JCP innovation is about OpenJDK implementation parent and meritocratic community- blog needs to focus on stan- seeing which ideas is very positive. There’s a based approach, the more successful dardizing innovations that have already happened as are truly useful.” process right now of get- ting some of the spec work it will be. One area of tension between the opposed to trying to inspire for the Java 8 JSR 337 done success of Java and Oracle’s business 17ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 18. COMMUNITY a board of directors that oversees the entire organization, sets the budget, sets the strategy, and so forth. OpenJDK is, like the JCP, effectively JAVA IN ACTION an arm of Oracle, which puts certain constraints on the way things get done. All the intellectual property flows to Oracle and, so far, the infrastructure for OpenJDK has been constrained by the ability of Oracle to put resources into improving it. So, for example, it’s taken quite some time—and it’s still JAVA TECH not done—to get an open, non-Oracle bug database available for the whole OpenJDK community. What can OpenJDK learn from Eclipse? I think that, to the degree possible, being truly vendor neutral in a level playing field across all of the ABOUT US companies and individuals involved is absolutely key. The degree to which OpenJDK can bring in other compa- nies, participants, and contributors will be the best measure of success. Magazine covers that needs is in the field-of-use restric- OpenJDK learn from the Eclipse OpenJDK has certainly done well in have featured Eclipse tions that are holding Java back from community? the last year and a half, bringing in line the walls in a success in the embedded and mobile Milinkovich: OpenJDK recently Red Hat, IBM, SAP, and a few others as hallway at the Eclipse spaces. At some point—I don’t know announced that they were going to well. That’s a big step forward for the Foundation. when or how—Oracle is going to have adopt Eclipse’s approach of shipping OpenJDK community. </article> to get rid of them because in today’s regular, predictable release trains. world, if you don’t have both a tech- I think that Eclipse has shown that Janice J. Heiss is the Java acquisitions nology and business adoption strategy predictable release schedules are very editor at Oracle and a technology editor at in mobile and embedded, you’re dead. helpful to the ecosystem. So that’s one Java Magazine. I don’t know the solution, but Oracle lesson that’s been shared already. blog will definitely need to change this in But in comparing OpenJDK to Eclipse order to make Java competitive with we need to understand that Eclipse LEARN MORE Android, to give but one example. is truly an independent organization, • Mike Milinkovich’s blog Java Magazine: Finally, what could set up as a separate corporation with • Follow Milinkovich on Twitter 18ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 19. Data Quality Tools for Java BEFORE Telephone Verification Name Parsing & Genderizing john smith iii phd melissa data corp. Geocoding 22382 Empresa 92688 7145895200 john@800miAL.con Address Verification & Standardization AFTER Melissa Data Corp. Email Address Verification John Smith III PhD 22382 Avenida Empresa Ste 100 Rancho Santa Margarita, CA 92688-2112 949-589-5200 Delivery Indicator: Business *Highlights indicate added and/or corrected data. Realtime NCOALink Change-of-Address Web Services & APIs Web Service available Duplicate EliminationNow, finding the right data verification tools doesn’t have to be so puzzling. • Global address verification for 240 countriesMelissa Data offers customizable APIs, Web services and enterprise appli- • Clean and validate data at point-of-entry or in batchcations to match your budget and business needs. For solutions to cleanse, • Correct misspellings, missing directionals, and confirm deliverabilityvalidate and standardize your contact data, we’re ready to help you find the • Enhance addresses with County, Census, FIPS, etc.perfect fit. • Append rooftop lat/long coordinates to street addresses • Update records with USPS and Canadian change of address infoRequest free trials or call 1-800-MELISSA
  • 20. COMMUNITY JAVA IN ACTION JAVA TECH (open source ) GROWING ON OPEN ABOUT US AgroSense provides an all-Java open source platform for sustainable farming and precision agriculture. BY PHILIP J. GILL S un, soil, seeds, water, fertilizer—for centuries these have been the essential ingredients for successful farming. But with the world’s popula- tion at 7 billion and growing; arable, fertile land at a premium, and environmental degradation a blog genuine concern, farmers around the globe are Timon Veenstra, Project Leader of looking to increase crop yield and quality while the AgroSense conserving resources—all in an environmentally Project friendly and sustainable way. ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY TON HENDRIKS 20ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 21. COMMUNITY JAVA IN ACTION JAVA TECH SNAPSHOT ABOUT US THE AGROSENSE PROJECT Industry: Agriculture Java version used: JDK 7, NetBeans Platform 7, Veenstra and members of the AgroSense NetBeans IDE 7 Project team in the Ordina offices in Nieuwegein, the Netherlands To do this, farmers—from small fam- tion about the soil, the soil type, the tractor going, what was the height of ily enterprises to giant, multinational complexity of the soil, its ingredients, the mower, what was my plow depth, agribusinesses—are looking to add a the nutrients present. There’s infor- things like that.” new ingredient to the mix: information. mation from satellites about weather For too many farmers, however, all blog “Farming today is a very information- and weather predictions. And then that information exists as raw data dense industry,” explains Timon there’s information that farm machin- with little meaning. “Farmers have lots Veenstra, project leader of the ery collects for every GPS coordinate and lots of data, but they have little AgroSense Project. “There’s informa- in the field—what direction was the information,” says Veenstra. “So much 21ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 22. COMMUNITY The central component of the AgroSense platform is an onscreen map that displays Precision Precision agriculture, also called preci- sion farming, is a relatively new farm not just the topography of the land, but also all the critical information that Agriculture management concept that many see farmers need to know. as the future of sustainable farming. JAVA IN ACTION Precision agriculture differs from traditional farming practices in that it enables farmers to manage their fields AGRICULTURAL POWERHOUSE at an intrafield level. In traditional agriculture, a farmer The Netherlands may be a small would just take a basic value of fertilizer or pesticide, for country, but it’s one of Europe’s and instance, and apply it to all of the land. “This approach will the world’s largest economies and always be too much, especially for pesticides,” explains most prosperous countries. Besides Timon Veenstra, project leader of the AgroSense Project, so that a lot of that data gets thrown being home to large industrial orga- an open source software platform for precision agriculture. JAVA TECH away because they lack a platform to nizations such as Philips Electronics “While there is disease on the land, it’s usually just on one process that data into information.” NV and Unilever and oil-and-gas giant part of the land, but farmers would apply the pesticides to Providing a suitable platform for just Royal Dutch Shell, the Netherlands is their entire land.” that task is the goal of the AgroSense the third-largest exporter of agricul- That’s not just a waste of expensive resources and pes- Project, an open source farm man- tural products in the world, behind the ticides; it’s also potentially damaging to the land and the agement system being built on Java United States and France. More than environment, notes Veenstra. and the NetBeans Platform. Veenstra 56 percent of the country’s arable land And too much fertilizer can result in poor-quality crops. ABOUT US launched AgroSense—originally is under cultivation, and agriculture “If you apply too much fertilizer, the crops will grow too fast named “Cloudfarming”—in June 2011 provides 1 in 10 jobs and generates and be too weak, so when the winter winds come they’ll with initial support and funding from 10 percent of the gross national prod- fall down,” he says. Ordina, an IT consulting and out- uct. Its leading crops are tomatoes, But with precision agriculture, Veenstra continues, sourcing firm based in Nieuwegein, cucumbers, chilies, and fresh-cut “farmers use information from sensor values and soil the Netherlands, where he works as a plants and flowers—the country has of samples taken from each part of the field and only need to software architect and devel- course been famous for its spray pesticides on the affected areas and to apply fertil- oper. Although Veenstra is BIG BUSINESS tulips for centuries. izer only to the part of the land that needs it.” focused on agriculture in the Farms cover “Because the country is Although precision agriculture originated in the United Netherlands right now, he says he sees no reason why more than 56 so densely populated, agri- cultural land is very scarce States in the 1980s, interest has spread worldwide, including to the Netherlands, which is the world’s third- the capabilities he envisions percent of the and very expensive,” says largest exporter of agricultural products, behind the United for the AgroSense platform would not be applicable to arable land in the Veenstra. “Farmers are sit- ting on millions of euros of States and France. farmers around the world. Netherlands and land value, so they are eager blog “The goal is to make every- employ 1 in 10 to get the most value in thing a farmer does available on the AgroSense platform,” workers. crops from their land.” This has also made Dutch says Veenstra. farmers open to a rela- 22ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 23. COMMUNITY tively new concept in farm manage- click on the field they will see all the in the first release, farmers will be able What’s Driving ment called precision agriculture. information about fertilizers being to plan their crops for a year,” says Open Source? Also known as precision farming, it combines crop science, responsible used on that field, how much is being used, even if the fertilizer is in stock,” Veenstra. “They will be able to import a shapefile with the digital represen- JAVA IN ACTION environmental stewardship, and effi- he says. “And if it’s not in stock and tation of their fields, or they can draw cient farm practices so that farmers they need more, the platform will con- new fields on their map. Then they can can grow more crops of higher quality nect farmers to an online catalog so select the crop they want to grow and while consuming fewer resources and they can order it.” which periods they plan to grow it in.” minimizing environmental impact “When the farmer changes the con- This first release will be geared and footprint (see sidebar, “Precision text to do something else—say, plan a toward the farm management home Agriculture”). new crop rotation—then the entire con- office, which usually has good internet “With precision agriculture, farm- text will switch to that new module,” he connections, says Veenstra. In later JAVA TECH ers can manage the land down to the adds, “and it will display the informa- releases, Veenstra envisions that farm square-meter level, rather than field tion and the appropriate tasks.” workers on tractors will have a variety by field,” explains Veenstra. “Precision In its first release, slated for late of mobile devices, such as cell phones agriculture makes farmers more pro- 2012, the AgroSense platform will and tablets, either mounted on trac- ductive, enabling them to produce focus on crop planning. “With the tools tors or carried in their pockets, that will Simon Phipps, higher quality and a higher quantity president of the of crops.” ABOUT US Open Source AgroSense—a 2012 Duke’s Choice Initiative, talks with Award winner—is a modular farm Java Magazine’s management system for precision Tori Wieldt about agriculture. The central component of what’s driving open the AgroSense platform is an onscreen source today. map that displays not just the topogra- phy of the land, but also all the critical information that farmers need to know, such as soil ingredients, crop types, fer- tilizers and pesticides used, and much more. AgroSense uses satellite images, JPEGs, and open source and proprietary mapping services to create maps, and even allows farmers to draw their own. The information is displayed in the blog context of whichever module or appli- cation is being used, explains Veenstra. “If you’re operating in the fertilizer module, for example, when farmers Veenstra and AgroSense Project team members catch up over coffee. 23ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 24. COMMUNITY collect data in the field and transmit it selves, such as saving state; connect- For Veenstra, another aspect of to the main office. ing actions to menu items, toolbar NetBeans’ appeal is the fact that it’s items, and keyboard shortcuts; and more than a technology platform; it’s OPEN PLATFORM window management. The NetBeans a vibrant, vital community with active JAVA IN ACTION Veenstra chose to go the open source Platform consists of a reliable and users worldwide who are always will- route with AgroSense for several rea- flexible application architecture and ing to pitch in and answer questions sons. First, such a comprehensive provides a time-tested architecture to help out fellow users. The NetBeans project is beyond the ability of a single for free—and it’s also an architecture IDE has more than 1 million active programmer or even a single company. that encourages sustainable develop- users worldwide, and there are at least Open source makes it accessible to as ment practices. Because the NetBeans hundreds of applications created on many programmers and developers Platform architecture is modular, it’s top of its framework. as possible, says Veenstra, who plans easy to create applications that are But Veenstra notes that the main JAVA TECH to open an online app store similar to robust and extensible. reason to go with open source for Apple’s to help round out AgroSense’s Veenstra also uses the NetBeans AgroSense is that open source projects capabilities. “We are looking to partner IDE and Apache Maven, an open take on a life of their own—far beyond with various manufacturers and oth- source software project management the funding of one company or the ers to provide links to their resources,” tool. The combination of the modu- efforts of one programmer. And the says Veenstra. “We also expect that lar NetBeans Platform and Maven is goals of the AgroSense Project, he says, different manufacturers and software very powerful, he says, noting that the are too important for it to wither. ABOUT US developers will build their own appli- Maven build structure allows for easy Although Ordina sponsored and cations that they can plug into the reuse of modules in other applica- funded AgroSense’s initial develop- AgroSense platform.” tions. “There are already NetBeans ment, the company is looking to Another reason was his choice of Platform applications using AgroSense partner with another firm to continue software. AgroSense is a rich-client modules, such as the map viewer, and development. “As an outsourcing platform built in Java on the NetBeans easy reusable components is one of firm, product development is not Platform. Although alternatives were the key factors of a successful develop- in line with our corporate strategy,” considered, says Veenstra, ment ecosystem,” Veenstra says Veenstra. “NetBeans is highly modular GOING OPEN adds. “Every new reusable “AgroSense is and will continue to and really solid.” Building Java software on top of the Open source module means a bigger head start in development of new be an open source project,” he contin- ues. “Although AgroSense’s develop- NetBeans Platform can save makes AgroSense applications. The NetBeans ment speed will be influenced by the years of development time— the platform is a generic accessible IDE supports Maven very well, and it is extended with involvement of sponsoring companies, its continuation won’t be.” </article> framework for JavaFX and to as many every new NetBeans release. blog Swing applications, and it programmers asThe great toolset that the Philip J. Gill is a San Diego, California– provides the “plumbing” developers would other- possible. NetBeans IDE provides allows for very high develop- based freelance writer and editor who has wise have to write them- ment productivity.” been following Java for 20 years. 24ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 25. COMMUNITY (open source ) AN Hadoop creator Doug Cutting (left) with members of the Cloudera team ENGINE JAVA IN ACTION FOR BIG DATA JAVA TECH Hadoop uses Java for large-scale analytics. BY DAVID BAUM ABOUT US W hether it’s searching for sub- atomic particles from an atom smasher or discerning purchasing pat- terns in billions of Web pages, big data blog presents a vast array of complex com- putational problems, stemming from the constant influx of digital informa- tion. The world created more than ART BY NICHOLAS PAVKOVIC, PHOTOGRAPHY BY BOB ADLER 25ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 26. COMMUNITY Caption goes here Ibus aut aut aut autaturionet fugia vero mollent ut ad Members of the Cloudera team brief quunt parum ventusam Cutting on their current projects. et eost dunt offictus is venditet quias utameni molorum rerferum JAVA IN ACTION dolupta e-mail exchanges, search indexes, clickstreams, equipment sensors, video cameras, and more. Hadoop can easily scale to accommodate more capacity simply by adding more servers and stor- age equipment. Its distributed nature and parallel processing architecture JAVA TECH ensure a high-availability infrastructure. “Hadoop is based on using commod- ity computers to construct a distrib- uted system that is tolerant to failure, so if you lose a node everything will continue operating,” Cutting explains. “If you want to crawl 10 billion Web ABOUT US pages each month without having to buy some sort of exotic hardware, then you need a bunch of computers work- SNAPSHOT 1.8 zettabytes (1.8 trillion gigabytes) and chairman of the Apache Software ing in parallel. We are talking about CLOUDERA of information last year, according to Foundation. Named after a toy ele- much more data than you can store on International Data Corporation’s 2011 phant that Cutting’s children used to an array of hard drives, and far more Digital Universe Study, fueled by bil- play with, this open source software than you can process in a reasonable Headquarters: lions of mobile phones, tens of billions platform, written in Java, enables busi- amount of time on a single server—at Palo Alto, California of social media posts, and an ever- nesses to unlock potential value from least an affordable server.” Industry: expanding array of networked sensors their data using inexpensive commod- Achieving this level of performance Enterprise software from cars, utility meters, shipping con- ity servers. Sometimes described as a and reliability at a reasonable price Employees: tainers, shop-floor equipment, point- distributed operating system, Hadoop point is appealing to all types of orga- 300 of-sale terminals, and many other makes thousands of computers appear nizations. Credit card companies use Java technology sources. Thanks to Apache Hadoop, as one unified system for storing data Hadoop to help them predict fraud. used: organizations now have a cost-effective and running computations. It’s an ideal Energy companies use it to search for blog Java SE way to analyze all this data. way not only to analyze structured data oil deposits. Social media sites such as Hadoop, a 2012 Duke’s Choice Award from enterprise applications, but also Facebook and LinkedIn use Hadoop to winner, is the brainchild of Doug to work with unstructured information personalize interactions between their Cutting, chief architect at Cloudera from Web pages, social media sites, members. Online dating companies 26ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 27. COMMUNITY JAVA IN ACTION JAVA TECH Left: Cutting works use it to make the perfect match based 1988, he went to work at the Xerox Palo key member of the team that built and through lunch as on a dizzying array of preferences from Alto Research Center (PARC), where he deployed a production Hadoop storage he prepares for an millions of singles. And many com- developed a high-performance retrieval and analysis cluster for mission-critical ABOUT US afternoon meeting. mercial organizations use it to gauge engine, several innovative search para- business analytics. He joined Cloudera Right: Cutting buzzes through the Cloudera customer sentiment. digms, advanced linguistic analysis in 2009 to help release CDH, a 100 offices. As different as these applications methods, and high-quality text sum- percent open source Hadoop distribu- may seem, they all have one thing in marization algorithms. His work at tion, built specifically to meet enter- common: the need to find patterns PARC resulted in six patents in the fields prise demands. in immense volumes of information. of text searching, retrieval, browsing, Thanks to the efforts of Cutting and Hadoop takes computational tasks and indexing. hundreds of other develop- that were formerly relegated to expen- After leaving PARC in 1993, GROUP EFFORT ers, Hadoop is now broadly sive supercomputers and spreads them out over thousands of commod- Cutting held positions at Apple, Excite, and Yahoo! Hadoop is not accepted throughout the technology world as a good ity servers and storage devices. before venturing into open controlled by any choice for crunching lots source in 2000 with the one institution, of data in large production FROM RESEARCH TO PRODUCTION Well-known in the open source com- Lucene project, an efficient, full-featured text search but by different settings. Facebook claims to have the largest Hadoop munity as the founder of the Lucene, engine written in Java. His institutions cluster, with 30 PB of data. blog Nutch, and Avro projects, Cutting is an expert in information retrieval and full- work in the open source community has proceeded in working in Yahoo! runs its Search Webmap as a Hadoop appli- text search. After earning a degree in tandem with his commercial collaboration. cation on more than 10,000 linguistics from Stanford University in ventures. At Yahoo! he was a core Linux clusters. Google, 27ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 28. COMMUNITY Joost, Microsoft, Netflix, Twitter, and the organizations. Yahoo! has been the Because debugging a distributed sys- New York Times also depend on Hadoop largest contributor to the project and tem is much more difficult than devel- for large-scale computing tasks. continues to use Hadoop extensively oping programs on a single computer, across its businesses. it makes sense to establish a common JAVA IN ACTION OPEN COLLABORATION “Hadoop is not controlled by any OS layer at the foundation. Java pro- Derived originally from Google’s one institution, but rather by all MapReduce and Google File System these different institutions working papers, Hadoop has a colorful history in collaboration,” Cutting explains. Industry Applications for Hadoop that illustrates the interplay between “Decisions about the software are “E-Tailing” today’s commercial and open source made by consensus. You can’t just ■■Recommendation engines for cross-selling interests. do things unilaterally.” ■■Ad-targeting, analysis, forecasting, and optimization “I was working with a small team on In order to explain the Hadoop eco- JAVA TECH ■■Event analytics (determining what series of steps led to a project called Nutch to create a Web system, Cutting often compares it to a desired outcome) crawler and indexer—similar to Google Linux. “Linux is more than just the ker- and Bing, but as an open source proj- nel,” he says. “Just as there is a whole Financial Services ect,” Cutting recalls. “When Google style of programming and interaction ■■Compliance and regulatory reporting published a paper about its distrib- that is built on top of Linux, developers ■■Risk analysis and management uted file system and the MapReduce in the Hadoop ecosystem build appli- ■■Fraud detection and security analytics computing layer that goes on top of cations that share essential coordina- Healthcare and Life Sciences ABOUT US it, we could see that this was what tion features, such as security.” ■■Patient care quality and program analysis we needed: a systemic way to spread ■■Supply chain management storage and computing across a set of ADVANTAGE: JAVA ■■Drug discovery and development analysis machines that wouldn’t be terribly dif- According to Cutting, developing a Retail/Consumer Packaged Goods ficult to program and operate.” distributed software platform is an ■■Merchandising and market basket analysis Cutting decided to rewrite those order of magnitude trickier than devel- ■■Campaign management and customer loyalty programs methods in Java as open source and oping software that only runs on one ■■Supply chain management and analytics include the methods in the Nutch proj- machine. Fortunately, Java simplifies Telecommunications ect. When Yahoo! expressed interest the process on many levels. ■■Customer churn prevention in the distributed parts of the file sys- “At each point that you interact with ■■Call detail record (CDR) analysis tem, Cutting split those methods out something remotely, you’re not sure ■■Network performance and optimization of Nutch, renamed them Hadoop, and what can happen,” he explains. “There Government began developing Hadoop as a sepa- can be delays, you can have lots of ■■Cybersecurity rate venture. strange timing issues, and there could ■■Compliance and regulatory analysis blog Today, many organizations contrib- be failures, which means you can have ■■Energy consumption and carbon footprint management ute to the Hadoop ecosystem. This errors popping up in places that you diverse worldwide community attracts didn’t expect. The more distributed independent developers, contractors, the system, the more these effects commercial ventures, and government are compounded.” 28ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 29. COMMUNITY vides the right combination of easy library of tools. The libraries available the nature of the MapReduce comput- debugging and good performance. to Java developers are more extensive ing metaphor on which it is based. “Type safety and garbage collection than for any language I’ve seen.” Most Hadoop jobs include a large set make it a lot easier to develop new Finally, Java’s broad acceptance of input files that generate a large set JAVA IN ACTION systems with Java,” Cutting notes. “You and inherent portability make it easy of output files. Queuing these jobs to don’t have to worry about memory to develop standard programs that run in batch mode allows organiza- leaks. And Java programs tend to crash run interchangeably across different tions to process massive amounts of less catastrophically. You can check a lot operating systems, such as the many data. In the future, however, Cutting of things at compile time. If a program 64-bit and 32-bit versions of Linux and foresees Hadoop evolving to support does fail at runtime, it is easier to debug Windows. This flexibility was essential interactive computations and incre- in Java than it would be in C or C++.” to the creation of Hadoop Distributed mental updates based on a variety Cutting values the rich ecosystem of File System (HDFS), the primary stor- of new query engines that have been JAVA TECH Java libraries, utilities, and tools, which age system used by Hadoop applica- added to the ecosystem. Cutting takes a break to give developers choices for how they tions, which was written in Java for the “You can now do simple queries and check e-mail in the lobby wish to develop, share, and maintain Hadoop framework. get results while you are waiting,” he of Cloudera in Palo Alto, their Java applications. “In the open “With Java, you can basically write explains. “I think this platform is going California. source community, we have a large once and run anywhere,” Cutting to become more and more general- emphasizes. “It lets us purpose. It will support new kinds of deliver results not just applications that aren’t based on batch ABOUT US reliably but quickly. On top computations and aren’t just simple of that, Java is a relatively key value stores. This means you will simple language to learn. be able to submit fairly complex que- It’s fairly constrained, ries over complex tabular data in ways while still being powerful. that are much more scalable than It is easier to program with traditional solutions.” best practices in Java sim- Whether it’s a manufacturing com- ply because there aren’t pany monitoring data from sensors on many things you can do the shop floor, an advertiser studying that would make the soft- location data to target consumers, or ware very difficult to main- an “e-tailer” examining Web log files tain. That helps when to improve customer segmentation, you’re developing a large, Hadoop has a solution. </article> collaborative project.” blog INTERACTIVE FUTURE Based in Santa Barbara, California, Hadoop grew up as a plat- David Baum writes about innovative form for batch computing. businesses, emerging technologies, and This was due, in part, to compelling lifestyles. 29ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 30. //new to java / COMMUNITY Part 3 Can You Teach Testing to Beginners? JAVA IN ACTION BlueJ melds interactive and regression testing, making testing a reality even for beginners. MICHAEL KÖLLING I n the previous issues of Java Magazine we had a look at the BlueJ environment Its tools are targeted at illus- trating object-oriented pro- gramming concepts, and the something similar. BlueJ’s interactive testing support is TEST ASAP One of the or students—in a “database” (well, a simple collec- BIO and how to use its unique emphasis generally is on the one of these tools. great features tion, really, but JAVA TECH tools to develop a small application. In this article, we development of small-scale projects. There are, however, As we will see, interactive test- of BlueJ is that’s OK for now). Its class diagram will concentrate on one very a few tools in BlueJ that I ing with optional that you can tells us that there specific aspect of BlueJ: its support for testing. sometimes wish I had avail- able when working on large, test recording is a great way to teach interactively test are five classes involved, and that As we said before, BlueJ professional projects; I wish beginners about any method as a Database holds was designed specifically the Eclipses and NetBeans testing, but it is soon as it has Person objects. It is ABOUT US to support the learning and teaching of programming. of this world would take a slice of this toolset and offer also occasionally useful for seasoned been completed. currently in a state where the imple- professionals. But mentation has let’s start at the been completed beginning. (according to the For this session, we will use programmer) and our job is a variation of the “people” to test whether it works. project that we saw earlier. This version is called people- Interactive Testing test. Download and unzip One of the great features of this file, and open it in BlueJ BlueJ is that you can inter- to play along. Figure 1 shows actively test any method the main window after you as soon as it has been open the project. completed. Right-click the Student class and select blog The Project the first constructor (see The sample project is a Figure 2) to interactively cre- small program that stores ate a Student object. PHOTOGRAPH BY JOHN BLYTHE Figure 1 details about people—staff The object will then appear 30ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 31. //new to java / COMMUNITY on the object bench, where you There is no need to complete a we have a student named James can right-click it to interactively whole project; as soon as a single Duckling with student ID 123456, run any of its public methods (see class compiles, we can test any of the account name should be Figure 3). its methods. Jam1234. However, when we call JAVA IN ACTION This technique was described Another aspect of this interactive the getAccountName method, in more detail in the July/August invocation is even more important: we can see that the result is edition of Java Magazine. You will it forms a strong mental model incorrect. (This is not the only see that you can create objects by of object orientation. By manu- problem here. We run into even Figure 2 invoking constructors, easily call ally playing through the creation worse trouble if the name or any method, pass parameters, and of objects and the invocation of the account name is too short receive return values. You can also methods, students develop an to extract the substring, but I’ll compose objects, that is, pass one almost natural view of an applica- leave that as an exercise for you.) JAVA TECH object as a parameter to another. tion as defined by a set of classes The first lesson here is this: Play around with this a bit: that can be instantiated into interactive testing, if done regu- Create some Student objects with objects. The class/object relation- larly, can uncover bugs early. different parameters and try their ship becomes clear, and it quickly That’s good. Figure 3 methods. Create a Database object seems natural that we communi- There is, however, one disad- and enter a few Staff and Student cate with objects by invoking their vantage to interactive testing: objects to it. methods. The concepts of param- to be valid, it has to be repeated ABOUT US eters, return values, types, and after every code change, and the Testing as a Teaching Tool state can also all be immediately tests accumulate (and, there- The possibility to interactively test experienced. As a teaching tool, fore, become more tedious) over your code has great benefit as a this is one of the most powerful time. It’s time for a regression teaching tool. aspects of BlueJ. testing tool. Figure 4 LEARNING BOOST Most obviously, The Bug Regression Testing The possibility you don’t need to write any test If you played around with some BlueJ supports regression test- To keep BlueJ’s interface simple, the testing tools are initially hid- to interactively drivers to test Student objects, and you paid ing via integration of the ever- den. They can be switched on in test your code your code. This makes testing attention to the comments, you may have noticed a bug in our popular JUnit tool. JUnit allows us to write test cases that can be the preferences by going to the Miscellaneous tab and selecting has great benefit much quicker Student code. The comment for the replayed easily, and regression the Show unit testing tools option. as a teaching tool. and easier. We always encour- getAccountName method stated that the account name for a stu- testing suddenly becomes man- ageable. (In this article, I will not Once testing has been enabled, BlueJ offers some more buttons in It forms a strong age our stu- dent should consist of a string try to explain JUnit or its termi- the left toolbar and also an addi- blog mental model of dents to test constructed from the first three nology. I assume you know about tional option in the class’s pop-up object orientation. any method as soon as it has letters of the student’s name, fol- lowed by the first four digits from JUnit already, or you can easily find out using one of several good menu: Create Test Class (Figure 4). If we use this function, a test been written. the student’s ID number. Thus, if tutorials available online.) class is created and attached to the 31ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 32. //new to java / COMMUNITY reference class; it is shown in the Test Recording on the object bench, call its diagram in green. When we drag In BlueJ, you not only have a choice getAccountName method. our classes in the diagram, the test between interactive testing and As before, we see the class will always be kept close to writing JUnit code, but you can method result showing JAVA IN ACTION the reference class. Figure 5 shows combine both. You can record your the (incorrect) account our project with two test classes interactive tests to get them trans- name, but when we’re created: one for the Student class lated automatically into replayable recording tests, there is an and one for the Database class. JUnit code. Let’s play this through additional element in the We can now open the editor for by creating a test case for the bug result dialog box: an area Figure 6 the test class, and we see that it with the incorrect account name, to add an assertion. Here, contains an automatically gener- which we discovered above. we can now add the asser- ated skeleton for a standard JUnit From the test class’s pop- tion for the expected result JAVA TECH class. If we are familiar with JUnit, up menu, choose Create Test (Jam1234; see Figure 7). we could now start writing JUnit Method, as shown in Figure 6. Once done, close the test cases in the standard JUnit BlueJ will ask you for a name for dialog box and end the way. This is a big improvement the new test method; let’s call it recording by clicking the over repeated interactive testing, testAccountName. End button under the and it is very useful. However, it Once we have selected this recording indicator. BlueJ gets really interesting when we name, we enter the test record- will immediately gener- ABOUT US start combining interactive testing ing mode. An indicator on the left ate JUnit test code for with JUnit. shows that we are now record- this test and add it to the Figure 7 ing, and buttons StudentTest class. You can are provided to open the editor to inspect it. ■■We can use the Run Tests but- end or cancel the ton in the left toolbar to run all recording. We Playback tests in our project. can now interac- Once we have some unit tests In each case, the results of the tively carry out our recorded, we will naturally want to test runs are displayed (see test. Create a new execute our tests at some point. Figure 8), and if an error was Student object There are three ways to do this: detected, BlueJ can take you named James ■■ We can select an individual test straight to the JUnit source where Duckling with stu- method (for example, the failure originated. dent ID 123456. testAccountName) from the (You will also have StudentTest class’s pop-up menu Test Fixtures to specify a birth to run only that test method. BlueJ can also use JUnit test fix- blog date, but this does ■■ We can select Test All from tures. Just create your fixture not matter much the StudentTest class’s pop-up objects interactively on the object for our test.) Once menu to run all tests defined in bench as you would like them Figure 5 the object appears that class. to be for the beginning of your 32ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 33. //new to java / COMMUNITY class, you will discover that one of its methods is also faulty. Create some tests for each of JAVA IN ACTION its methods until you find one that fails, and then fix that one, too. Conclusion Testing is an important aspect for learning pro- gramming. The interac- JAVA TECH Figure 8 tive testing feature in BlueJ usually leads to tests. Then use the Object Bench learners who test more often and to Test Fixture function from the test class’s pop-up menu, and the fixture will be added to your earlier. The interaction also helps in constructing a good mental model of object interaction. Both of these FIND YOUR test class. At the start of each test aspects aid in the understanding of JUG HERE ABOUT US recording, the fixture objects will programming principles. be placed automatically onto the For more-systematic develop- I have met so many amazing people object bench for you. ment, regression testing is impor- through the London Java Community— tant, and it should be taught in friends, mentors, new colleagues— Manual Test Editing any good software development and through it I have achieved much JUnit classes in BlueJ can also course. BlueJ’s support for JUnit more than I could have on my own. be edited manually, and you can allows easy creation of unit tests Trisha Gee freely mix manual writing of test for regression testing. The tight London Java Community (LJC) code with adding recorded test integration of interactive testing cases. This allows interactive with regression testing provides LEARN MORE recording for many straightforward probably the easiest mechanism tests, while adding the ability to available in any environment today write more-complex tests by hand. for creating unit tests. </article> Over to You blog You should now, of course, fix the bug we uncovered and make sure LEARN MORE that all your tests pass. If you cre- • Java SE 7 API ate some tests for the Database • BlueJ Website 33ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 34. //java architect / COMMUNITY Part 1 Exploring Lambda Expressions for the Java Language and the JVM JAVA IN ACTION With lambda expressions, write code that is more concise and can truly run in parallel. L ambda expressions, a name chosen by the tionality that can be passed around as data. A secondary classes that have only one function. to do is “pass in some new code of our own” to an exist- JAVA TECH Expert Group to describe a concept that you’ll need to For example, if your code ing method, which will then new functional programming master is understanding how has a large number of anony- call the code that we passed construct, are one of the collections will be iterated mous inner classes—defin- in. Lambda expressions can most eagerly awaited new over internally, as opposed to ing things such as listeners provide a good way to repre- features coming in Java SE 8. the external, serial iteration and handlers in UI code or sent the code that has been You’ll sometimes also hear we have today. callables and runnables in passed in and should be people using terms such In this article, we’ll take concurrent code—moving called back. ABOUT US as closures, function liter- you through the motivations to the lambda expressions Better support for multi- als, anonymous functions, behind lambda expressions, style can make your code core processing. Today’s and Single Abstract Methods some use cases for them much shorter and easier to CPUs have multiple cores. BEN EVANS, (SAMs). Some of these terms and, of course, the syntax. understand. This means that your multi- MARTIJN VERBURG, have slightly different mean- Ability to modify methods. threaded code can truly run AND TRISHA GEE ings from each other, but Why You Want Lambda Sometimes, methods don’t in parallel, as opposed to BIO they all refer to the same Expressions quite have the functional- being time-shared on a sin- basic functionality. There are three main rea- ity we want. For example, gle CPU. Lambda expressions Although lambda expres- sons why programmers want the contains() method in the will help you write simple sions might seem unfamiliar lambda expressions: Collection interface returns code that can use these cores to begin with, they’re quite ■■ More-concise code true only if the exact object efficiently by supporting the easy to pick up, and master- ■■ Ability to modify methods passed in is present in the use of functional program- ing them will be vital for writ- by supplying additional collection. There’s no way to ming idioms in Java. ing applications that can take functionality tweak that functionality, for For example, you will be full advantage of modern ■■ Better support for multi- example, to have the method able to manipulate large blog multicore CPUs. core processing return true if the string we’re collections in parallel using A key concept to remember More-concise code. Lambda looking for is present but all the available hardware PHOTOGRAPHY BY is that lambda expressions expressions provide a neater uses different capitalization. threads on your CPU by tak- JOHN BLYTHE (EVANS, GEE) AND BOB ADLER (VERBURG) are just small bits of func- way of implementing Java Loosely, what we want ing advantage of parallel 34ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 35. //java architect / COMMUNITY LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6 versions of idioms such as filter, from the left side of the assign- map, and reduce (which we will be ment. The right side looks like File dir = new File("/an/interesting/location/"); FileFilter directoryFilter = new FileFilter() { meeting shortly). a very shortened version of the public boolean accept(File file) { accept() method in the FileFilter return file.isDirectory(); JAVA IN ACTION Lambda Expressions in a interface, that is, it accepts a File } Nutshell and returns the Boolean from eval- }; In the example of different capi- uating f.isDirectory(). File[] directories = dir.listFiles(directoryFilter); talization of strings, what we want In fact, we can actually simplify to do is pass a representation of this further due to lambda expres- toLowerCase(). In order to pass this sions taking advantage of type Download all listings in this issue as text code into a version of the contains() inference, which works as follows. method as a second parameter, The compiler knows that FileFilter JAVA TECH we’d need to do the following: has only one method, accept(), The listener object can be reused the collection. This is the tradi- ■■ Find some way to treat a code so this must be the implementa- if necessary, but if it’s used only tional way of handling collections, snippet as though it were a tion code for that method. It also once, the code in Listing 6 is con- with which most Java program- value (some sort of object) knows that accept() takes only sidered good style. mers are very familiar—even if ■■ Find a way to be able to put that one parameter, which is of type In this example, the slightly they don’t know or use the term. block of code into a variable File. Therefore, f must be of type odd syntax involving extra curly For example, language con- In other words, we want to wrap File. See Listing 3. As you can see, brackets is needed because action structs such as the enhanced for ABOUT US up bits of logic in something that the use of a lambda expression Performed returns void. We’ll see loop create an external iterator can then be passed around. To radically reduces the amount of more about that later. and use that object to traverse the make this a little more concrete, boilerplate. Let’s move on to take a look at collection shown in Listing 7. let’s look at a couple of basic Once you’re used to lambda the role that lambda expressions With this approach, a collection examples of lambda expressions expressions, they make the flow of will play in writing modern code for class represents a “monolithic” that can be used to replace exist- logic much easier to read. One of handling collections, in particular view of all the elements in the col- ing Java code. the key ways this is achieved is by the transition between two pro- lection, and the collection object Filtering. A good example of a locating the filtering logic next to gramming styles known as external can provide random access to any snippet of code that you might the method that wants to use it. and internal iteration. element of the collection that the want to pass around is a filter. For Event handlers. Another area that programmer might require. example, imagine you were using features anonymous inner classes External Versus Internal In this view of the world, we (a pre–Java SE 7) quite heavily is UI code. Let’s take Iteration iterate by calling a method— in order to identify directories the assignment of a click listener Up until now, the standard way iterator()—on the collection that belong inside a given path, as to a button, as shown in Listing 4. of dealing with a Java collection is instance. This returns an object shown in Listing 1. With a lambda This is a lot of code just to say via external iteration. It’s called of type Iterator, which is a more blog expression, this can be drama- “when the button is pressed, external iteration because there is restricted view on the same tically simplified, as shown in call this method.” Using lambda control flow, external to the col- collection. It does not expose Listing 2. expressions, it’s possible to use lection, which is used to iterate an interface allowing random The type (FileFilter) is inferred the code shown in Listing 5. over the elements contained in access; instead, it is designed 35ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 36. //java architect / COMMUNITY LISTING 7 LISTING 8 LISTING 9 LISTING 10 for purely sequential handling ■■ Build up an overall value for a of the contents of the collec- property of the whole collection, List<String> myStrings = getMyStrings(); for (String myString : myStrings) { tion. This sequential nature for example, adding up or aver- if (myString.contains(possible)) also gives rise to the infamous aging the values System.out.println(myString + " contains " + possible); JAVA IN ACTION ConcurrentModificationException These tasks (which are called, } when you try to use the collection respectively, the filter, map, and } with parallel access. reduce idioms) have something The alternative is to require important in common: They all the collection object to manage require code to be run on each ele- the iterator (and loop) internally. ment of the collection in turn. This approach is called internal Whether the code is testing an Download all listings in this issue as text iteration, and it is the preferred element to see whether a condi- JAVA TECH choice when working with lambda tion is met (filter), transforming expressions. the element into a new element applying it to a collection returns common functional programming In addition to new syntax for for a new collection (map), or a new collection containing only style, you’d write that in one line, lambda expressions, Project computing a value to be fed into those elements that match the as shown in Listing 10. As you can Lambda includes a major upgrade an overall calculation (reduce), the predicate. see, the code is still very readable to the collections libraries. The key theme is “a bit of code that There are a number of interpreta- and we have the benefit of using aim of the collections upgrade is to needs to be run on each element.” tions of what a predicate is. In Java internal iteration as well. ABOUT US make it much easier to write code This implies that we need a SE 8, a predicate is a method that Let’s finish up by discussing the that uses internal iteration to sup- simple way of representing the evaluates to true or false depending full syntax for lambda expressions port a range of well-known func- code that is going to be used in on the values of its variables. in more detail. tional programming idioms. internal iteration. Fortunately, Java Let’s have another look at an SE 8 provides the building blocks example we saw earlier. We have a Syntax Rules for Lambda Functional Idioms with for such representations. collection of strings that we want Expressions Lambdas to test to see whether it contains The basic form of a lambda At one time or another, most Java SE 8 Classes for Basic a specific string, but we want the expression starts with the list of developers have found themselves Functional Idioms comparison to be done in a case- parameters that can be accepted needing to perform one or more Java SE 8 includes classes that insensitive manner. and ends with some code (called of the following operations on a are intended to be used to imple- In Java SE 7, we would need to the body), with an arrow (->) sepa- collection: ment the basic functional idioms use external iteration, with code rating the two. ■■ Create a new collection, which discussed above. These include that looks like Listing 8. In the Note: The syntax for lambda filters out any elements that Predicate, Mapper, and Block—as upcoming Java SE 8, we could expressions is still subject to don’t satisfy some condition well as some others—in a new write this in much more compact change, but at the time of this blog ■■ Apply a transformation to each package called java.util.functions. fashion using a Predicate and a writing, the syntax shown in the element of a collection, and Let’s look at Predicate in more new helper method (filter) in the following examples works. work with the transformed detail. This class is often used Collections API, as shown in Lambda expressions make fairly collection to implement the filter idiom; Listing 9. In fact, if you follow heavy use of type inference, which 36ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 37. //java architect / COMMUNITY LISTING 11 LISTING 12 LISTING 13 LISTING 14 is quite unusual compared to the rest of Java syntax. ActionListener listener = event -> {ui.showSomething();}; Let’s take a closer look at an example we’ve already seen (see JAVA IN ACTION Listing 11). If we look at the defi- nition of ActionListener, we can Download all listings in this issue as text see it’s an interface with just one method in it (see Listing 12). The lambda expression on the the return value is inferred from warnings that javac produces when right side of Listing 11 can, there- fore, easily be understood to mean the expression—in this case, f.isDirectory()—which is, of course, you first try lambda expressions. FIND YOUR “here is the method definition for a Boolean value. Conclusion JUG HERE JAVA TECH the single method declared in the This explains why methods that Lambda expressions are the larg- interface.” Notice that the usual return void need to be treated a est new language feature in Java My local and global JUGs rules of Java static typing must still bit differently. The extra syntax since generics were introduced are great places to network be obeyed; this is the is used to put an addi- in Java SE 5. Done right, lambda both for knowledge and work. KEEP IT CLEAN My global JUG introduces only way that type infer- tional set of braces expressions will allow you to write me to Java developers all ence can work correctly. From this, we can see Lambda around the code part of the lambda expression. code that is more concise, modify methods by supplying additional over the world. expressions ABOUT US Régina ten Bruggencate that lambda expressions Without this syntax functionality, and make multicore provide a JDuchess can be used as compact quirk, type inference processors sing. By now, we’re ways of writing code that would previously have neater way of would not work prop- erly—but you should be sure you must be eager to try lambda expressions, so without LEARN MORE used anonymous inner implementing aware that this syntax further ado . . . classes. There’s one other syn- Java classes that might change. A lambda expres- You can get a snapshot build of Java SE 8 with lambda expres- tax quirk that you should have only one sion’s body can contain sions at the official Project Lambda be aware of. Recall function. multiple statements. In page. As well as trying out the the example shown in such a case, the body binaries, you should also read the Listing 13. At first glance, should be surrounded “State of the Lambda” articles this looks just like the by braces, the “inferred hosted there. </article> ActionListener example. However, return” syntax does not work, and let’s take a look at the definition of the return keyword must always the FileFilter interface (see be present. blog Listing 14). One final word of warning: your LEARN MORE The accept() method returns IDE is unlikely to support the syn- • For help with lambda expressions a Boolean value, but there’s no tax at this stage, so you’ll need to or to join our global hack days, join explicit return statement. Instead, pay close attention to any compiler the Adopt OpenJDK project 37ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 38. //rich client / COMMUNITY Part 1 JavaFX in Spring JAVA IN ACTION Why use the Spring framework on the client? STEPHEN CHIN BIO I f you have done any server- side Java development, you have probably used some part ules that have their rela- tionships injected using a dependency management However, if you are building a large, multiscreen application that connects to a back-end and a back-end component done as a hybrid Spring Framework and JavaFX of the Spring framework to framework such as Spring. server or authenticates users, application. It will include JAVA TECH build or augment your Java ■■ One-line Web services— you will get an exponential an authentication module to enterprise Web applications. By using a compatible benefit from these features log in users, back-end Web It comes with a powerful REST framework on the as the size and complexity of service integration using the dependency injection (DI) client and server, you can your application grows. Spring RestTemplate, and system, Web model-view- reuse the same model To demonstrate these ben- create and delete opera- controller (MVC) framework, objects and implement efits in the context of a real tions that are appropriately and helper libraries for every- each Web service call with application, we will build out permissioned by role. The ABOUT US thing from database access to a single statement for a customer application from final application will look like security authorization control. retrieval, creation, dele- scratch with both a front-end Figure 1. With the 2.x release, tion, and even updates. JavaFX now has pure Java ■■ Authentication and APIs, which makes integrat- authorization—Rather ing Java libraries, such as than reinventing the wheel Spring, trivially easy. Some on the client, you can take of the benefits you can get advantage of the same by taking advantage of the authentication mechanism Spring framework on the cli- you use to secure your ent include the following: server requests. This also ■■ Inversion of UI Control— lets you do fine-grained Inversion of Control (IoC) authorization tests to is an object-oriented tech- modify the UI experience nique for decoupling the based on the permissions. blog execution of a task from For very simple applica- its implementation. For tions, these benefits may not UIs, this is very useful for outweigh the costs of learning creating standalone mod- and integrating a new library. Figure 1 38ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 39. //rich client / COMMUNITY LISTING 1 While this example will be built each graphics pulse to pre- out over the course of a two-part pare the scene for display. This public class CustomerApp extends Application { public static void main(String[] args) { series, you can browse, download, includes processing animation, launch(args); and run the full example from the CSS, and layouts; synchronizing } JAVA IN ACTION source code at GitHub right now. the scene graph with the render tree; and updating the mouse @Override An Application Template hover state. public void start(Stage stage) throws Exception { If you have done any Spring devel- For most purposes, the render ApplicationContext context = opment on the server side, you thread is something behind the new AnnotationConfigApplicationContext know that configuring a new appli- scenes that you don’t have to CustomerAppConfiguration.class); cation to use Spring is as simple as worry about; however, the applica- ScreensConfiguration screens = context. adding in the JAR files (or Maven tion thread does require a little bit getBean(ScreensConfiguration.class); JAVA TECH dependencies) and adding a cou- of attention. screens.setPrimaryStage(stage); ple of lines to your web.xml file. Whenever JavaFX calls you back screens.loginDialog().show(); On the client, you need to take either in application methods such } care of manually starting the as start and stop or in an event } Spring runtime from your main handler, it will do so on the appli- class. The application template we cation thread. This allows you to create in this section will show you safely create new JavaFX objects Download all listings in this issue as text ABOUT US how to start the JavaFX and Spring and manipulate the scene graph runtimes in a thread-safe manner. freely. However, if you are on the But first, let’s start with a little main thread or you spawn your new AnnotationConfigApplication nient depending on what you are background on JavaFX threading own thread, be careful not to call Context if you are using doing with your application. to explain why this matters. any JavaFX methods that would a Java configuration or a While it might be tempting to JavaFX has two different threads, affect the render tree or you will get ClassPathXmlApplicationContext if initialize the Spring context in the each with a distinct purpose: an exception, deadlocks, or worse. you are loading from XML. main method of your application, ■■ Application thread—This is Listing 1 ( I highly recommend using the this is a very dangerous practice the thread where all manipula- shows the main application class new annotation-based Java con- because loading the Spring con- tion of the JavaFX scene graph of a CustomerApp demo project figuration support that was intro- text might cause JavaFX objects and the creation of objects that takes care of initializing the duced in Spring Framework 3.0, to get loaded on the thread from that use top-level windows JavaFX application threads as well because it provides all the conve- which you started Spring. If you should occur. It is analogous as loading the Spring configuration nience of defining your configura- happen to create a JavaFX object to the Swing event dispatch from a Java class. tion in the code without sacrificing that uses top-level windows, such thread (although that is not the This code is very similar to a the power and debugability that the as Stage, Popup, Menu, and so blog same, so be careful with Swing boilerplate JavaFX application until Spring XML-based configuration on, you will get a nice exception to interoperability code). you get to the start method. This provides. In this example, we will remind you of this fact. The start ■■ Render thread—The render is where you initialize the Spring actually mix both styles of declaring method, however, is called on the thread is what gets called on ApplicationContext by creating a configuration, which can be conve- JavaFX application thread, which 39ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 40. //rich client / COMMUNITY LISTING 2a LISTING 2b means that you can safely create In the ScreensConfiguration JavaFX objects of any type and add file, we define each screen and @Configuration @Lazy them to the scene graph even from associated controller as a separate public class ScreensConfiguration { within your Spring configuration. bean by using the @Bean private Stage primaryStage; JAVA IN ACTION In this particular example, we annotation. Also, some of the load a subconfiguration class beans (in our case, all that display public void setPrimaryStage(Stage primaryStage) { called ScreensConfiguration, set the dialog boxes) are defined with this.primaryStage = primaryStage; stage on that configuration object, @Scope("prototype") so that a new } and call a method to show the instance gets created each time login dialog box. we fetch one. However, the main public void showScreen(Parent screen) { data screen gets the default scope primaryStage.setScene(new Scene(screen, 777, 500)); Modularizing Your UI With DI of "singleton", which means we will; JAVA TECH Now that you are able to load have only one main screen for the } Spring, it is time to take advantage entire application no matter how of some of its features to help mod- many times the method is called. @Bean ularize your JavaFX application. The Note that the entire configura- CustomerDataScreen customerDataScreen() { finished Customer Data App will tion class is annotated with @Lazy, return new CustomerDataScreen(customerDataScreenController()); include the following screens: to ensure that beans will not get } ■■ A login screen created until the first time they are ABOUT US ■■ A data screen @Bean accessed. However, this alone is CustomerDataScreenController customerDataScreenController() { ■■ An error screen not enough to ensure that beans return new CustomerDataScreenController(this); ■■ An “add customer” screen do not get created on startup, } Each of these screens will be because direct links between implemented as a separate JavaFX screens will cause a domino effect @Bean class or FXML file, and they will where loading the first screen loads @Scope("prototype") require references to other screens every other referenced screen. FXMLDialog errorDialog() { (when navigation is required) and To avoid loading all the screens return new FXMLDialog(errorController(), a model (when data access or at once, rather than injecting a ref- getClass().getResource("Error.fxml"), primaryStage, updates occur). We also want the erence to the screens we want to StageStyle.UNDECORATED); screens to get created on first use, connect, we instead pass in a ref- } but we want to have no more than erence to the ScreensConfiguration a single instance of each screen at class. This still gives us the flex- a given time. ibility to swap implementa- Listings 2a and 2b tions by providing a different blog ( show ScreensConfiguration instance, but a Spring configuration class that it defers object construction until defines each of our screens as a the method for loading a specific Download all listings in this issue as text separate bean. screen gets called. 40ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 41. //rich client / COMMUNITY LISTING 3 LISTING 4 LISTING 5 LISTING 6 LISTING 7 late the logic for loading an FXML file as well as inject- @Configuration @Import(ScreensConfiguration.class) ing the controller object. @ImportResource("classpath:applicationContext-security.xml") The full source code for the Figure 2 public class CustomerAppConfiguration { JAVA IN ACTION FXMLDialog is shown in @Bean Listing 5 ( CustomerModel customerModel() throws IOException { The rest of the configuration This class generalizes some of CustomerModel customerModel = new CustomerModel(); for the model and Web services is the code you would normally need customerModel.setRestTemplate(restTemplate()); defined in a separate class file that in order to load an FXML file as a customerModel.loadData(); loads the ScreensConfiguration via new dialog (Stage). However, the return customerModel; annotation, as shown in Listing 3 important part for injecting the } ( controller is the call to loader JAVA TECH .setControllerFactory(), which cre- @Bean Injecting Controllers into FXML ates an inner class that will return RestTemplate restTemplate() { In the previous section, we defined the controller passed in as a RestTemplate restTemplate = new RestTemplate(); several screens, some as Java parameter. restTemplate.setMessageConverters class files and others as FXML. By using this technique to cre- Collections.<HttpMessageConverter<?>>singletonList( While it is fairly straightforward ate and inject the controller, it new MappingJacksonHttpMessageConverter())); return restTemplate; to attach a Spring-initialized con- is treated the same as any other ABOUT US } troller to a Java object, doing the Spring-managed object, letting } same for FXML was not even pos- you use DI, autowiring, and other sible with the JavaFX 2.0 release. features of the framework. The Fortunately, the JavaFX team full code for the ErrorController is added an API in the 2.1 release shown in Listing 6 (ErrorController to specifically address this for .java). And the base DialogController IoC frameworks such as Contexts interface is shown in Listing 7 and Dependency Injection (CDI), ( Guice, and, of course, Spring. The FXML UI was created using As an example, let’s take a SceneBuilder, which is a great Download all listings in this issue as text closer look at the definition of the visual tool for learning the JavaFX ErrorDialog. The view and con- components and quickly mocking troller are both created in the up UIs. The finished error dialog you can reuse in your own projects. a lightweight back end with reus- ScreensConfiguration class with the box I created looks like Figure 2. Just taking advantage of Spring able model objects and one-line lines shown in Listing 4. configuration and DI already gives Web services on the client using blog Notice that the errorController is Conclusion your application design an advan- RestTemplate. </article> injected as a dependency into the In this article, I have given you an tage over writing in pure Java. FXMLDialog class. This is a custom application template for using In Part 2, I will build out the LEARN MORE class I put together to encapsu- Spring and JavaFX together that rest of the application including • Stephen Chin’s blog 41ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 42. //mobile and embedded / COMMUNITY Part 2 Wirelessly Recover Your Device’s Address Book JAVA IN ACTION VIKRAM GOYAL Learn how to add a recovery mode to the backup capability of your device’s address book. BIO I n Part 1, I created an appli- application, which you could 1. Receive the data (that doReceive() (see Listing 2) in JAVA TECH cation that allowed you to schedule to start automati- is, the backup file) the BluetoothServices class back up your device’s address cally, restoring must be an from the Bluetooth (from the existing code). book to a remote destination on-demand service. Hence, destination. This method is called by the specified as a Bluetooth I have provided it as an 2. Decompress the data. startRestore() method (see destination. The application explicit option. In a real-life 3. Add the individual Listing 1) in the main MIDlet had several functions: dis- scenario, if the user lost his items to the user’s class and is the only call in covering destinations, setting address book data (either address book. the startRestore() method. ABOUT US a schedule, performing on- because he got a new phone I will follow these steps demand backups, and view- or there was some sort of in creating the restore ing logs. However, it lacked a data corruption), he would functionality. recovery mode. In this follow- try to recover it using this up article, I will add that new application (provided a Receiving the Backup missing element. backup had been done). File via Bluetooth Note: The source code for the To do the restore, we have To receive the data.gz application described in this to turn the backup pro- backup file that we cre- article can be downloaded as cess on its head. The steps ated in the previous a NetBeans project and as a involved in a backup were article, the user has to desktop application. 1. Iterate over the individ- initiate the application on ual address book items. both the backup device The Application Flow 2. Compress them into an and the phone. The appli- Figure 1 shows the target LZCOutputStream. cation will then actively application in action with 3. Send the data to a pre- listen for any incoming blog the new option added (and determined Bluetooth data requests. selected). destination. To implement this, PHOTOGRAPH BY Unlike the backup func- In the reverse recovery pro- I have created a new JONATHAN WOOD/ GETTY IMAGES tionality in the previous cess, the steps are as follows: method called Figure 1 42ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 43. //mobile and embedded / COMMUNITY LISTING 1 LISTING 2 LISTING 3 Listing 2, which creates a local ServerRequestHandler class from server on the phone, is used to the javax.obex package. I have private void startRestore() { log("Restore Started At: " + new Date()); create this listening socket in a handled only the methods that btServices.doReceive(this); separate thread. The identification are essential for the completion of } JAVA IN ACTION of this server is done by using the this exercise. name “Backup” and then creating The real point of interest in a SessionNotifier that will accept this code is when the onPut() new connections. Check out method is called. When the server Figure 2 to see how this process thread on the phone receives a looks when the user initiates it on connection, this method handles the phone. the interaction. It receives the Notice that we have set a backup file (as a .gz compressed JAVA TECH RequestHandler object to listen for file) from the remote (backup) new connections as they are made computer and then gives the file and to handle them. It is this class, to the callback method in the shown in Listing 3, that accepts originating MIDlet. the connections from the remote The question now arises as to backup computer and makes them the mechanism for sending this available to the calling MIDlet. file from the backup computer. ABOUT US This RequestHandler extends the If you were to use the built-in Bluetooth software on the backup computer, it would send the backup file only to the phone’s default mechanism for handling such files, not to your applica- tion. In most phones, the default mechanism for receiving files is to receive them as SMS messages. This is not ideal, because our MIDlet application has no way to retrieve the data.gz backup file. It is clear that we need to send this file using our own software interface. For this, I have cre- blog ated a simple desktop-based class, which essentially is the code in the doSend() part of the Download all listings in this issue as text Figure 2 BluetoothServices class. This code 43ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 44. //mobile and embedded / COMMUNITY LISTING 4a LISTING 4b LISTING 5 is shown in Listings 4a and 4b and in parallel allows the data.gz file to uses the BlueCove library, which is be sent to the phone (see Figure 3). public void servicesDiscovered(int transID, ServiceRecord[] servRecord) { a JSR 82 implementation. Operation op = null; Try as I might, I wasn’t able to Decompressing the Data OutputStream out = null; JAVA IN ACTION get the right service code to iden- Now that we have received the for (int i = 0; i < servRecord.length; i++) { tify my phone. The service was data from the remote backup String connURL = servRecord[i].getConnectionURL( discovered but the name wasn’t computer, the rest of the steps ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false); always the same as what I was are easier. System.err.println(connURL); expecting, so I had to hack this by In order to decompress the // found the right service? identifying the correct service by data, we simply pass it through if (connURL.contains("5")) { the presence of the number 5. This the LZC decompressor. The System.err.println("Found service, connecting to it..."); number might be different for you. receiveBackup(byte[] data) method try { JAVA TECH To run this code on your desktop, in the MIDlet application is called // read the local backup file you will need to have the BlueCove by the RequestHandler method InputStream input = directory in your class path and the once the data has been success- new BufferedInputStream(new FileInputStream("data.gz")); data.gz file must be present in the fully received. The first step in this // read it in to our bucket same directory where you are run- method is the decompression of byte[] bucket = new byte[32 * 1024]; ning this code. The combination of the data: ByteArrayOutputStream result = null; result = new ByteArrayOutputStream(bucket.length); fulfilling these two requirements ABOUT US int bytesRead = 0; LZCInputStream lzc = while (bytesRead != -1) { new LZCInputStream( bytesRead =; new ByteArrayInputStream(data)); if (bytesRead > 0) { result.write(bucket, 0, bytesRead); Adding the Individual Items to } the User’s Address Book } The Personal Information Management (PIM) API helps us in this step, although only to an Download all listings in this issue as text extent. It provides the PIM .getInstance().fromSerialFormat() method (see Listing 5), which file; as soon as it encounters the single entry, which is not ideal if reads an input stream to decipher end of this entry (by means of the you are trying to recover multiple the contents and then automati- END vCARD), it stops. It leaves entries from the backup file. cally creates the right PIM item the InputStream object open and It is easy to overcome this, blog from the contents. leaves its character position on the however, because the method This is where the usefulness of character after the end of the entry hints that you can iterate over the this method ends. Unfortunately, (if there are no errors). Thus, this InputStream to get the rest of the Figure 3 it reads only the first entry in the method allows you to read only a entries. I will leave this as an 44ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 45. //mobile and embedded / COMMUNITY JAVA IN ACTION JAVA TECH Figure 4 Figure 5 FIND YOUR JUG HERE ABOUT US exercise for the reader. To be able to use this applica- Figure 4 and Figure 5 show tion, we had to create a separate CEJUG is celebrating our 10-year anniversary this functionality running on desktop application that did the in 2012! We follow Java technology with the phone. We have successfully heavy work on the backup com- passion, share knowledge with pleasure, restored our contacts! puter, bypassing the built-in and create opportunities for students and mechanism for sending files via professionals with ambition. Conclusion SMS. This enabled our phone’s Hildeberto Mendonça This was the final part of a two- MIDlet application to “catch” the The Ceará Java User Group (CEJUG) part series on identifying how file and process it. </article> we could back up and restore LEARN MORE our address book in a Java ME– enabled phone over the network. LEARN MORE In this part, we looked at how we could create a server on the phone • Bluetooth article on discovering to listen for incoming connections and sending data blog over the Bluetooth network and • The compress-j2me project then use that server to receive the • BlueCove project, a Java library for backup file and restore the con- Bluetooth for interaction on the tacts into our address book. desktop 45ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 46. //mobile and embedded / COMMUNITY Get Started with Java SE for Embedded Devices on Raspberry Pi JAVA IN ACTION How to get Linux and Java SE for Embedded Devices running on the Raspberry Pi in less than an hour. I t is hardly larger than a tions given here, especially The Raspberry Pi Ethernet connection gives JAVA TECH credit card. It costs about with respect to which opera- The Raspberry Pi is a small, another option: interact- the same as a book on Java tions you execute on a host low-power board built around ing from a networked host programming. (desktop or laptop) computer a 700 MHz ARMv6 CPU with via ssh. The “Performing It’s the Raspberry Pi com- and which you execute on hardware floating point and a Optional Linux Tuning and BILL COURINGTON puter, and it can support the Raspberry Pi. Use your graphics processor integrated Tweaking” section of this AND GARY COLLINS a full Java SE runtime for knowledge and preferences in a single chip. The graph- article describes how to headless embedded appli- (and perhaps some of the ics processor and the CPU enable ssh logins. ABOUT US BIO cations. This article gets topics in the “Performing share 256 MB of RAM. There you started with Java on the Optional Linux Tuning and are connections for USB, Prerequisites Raspberry Pi. Tweaking” section of this Ethernet, high-definition To set up the Raspberry Pi Note: There are many poten- article) to create a workflow graphics, audio, an SD card, model B to run Java SE for tial variations of the instruc- that works for you. and general-purpose I/O. Embedded Devices, you need Figure 1 shows a Raspberry ■■ A wired network to HDMI Pi model B with an SD card which you can connect inserted for scale. The SD the Raspberry Pi by an card plays a special role: the Ethernet cable. The net- Ethernet Power Raspberry Pi boots from it. work must supply DHCP IP This article largely consists of addresses. USB SD Card instructions for creating and ■■ A Linux host computer on modifying files on a bootable the same wired Ethernet SD card. network as the Raspberry You can interact with the Pi. You can perform blog Raspberry Pi using a USB equivalent operations keyboard and mouse and an on a Microsoft Windows Audio RCA Video General Purpose I/O HDMI monitor or television or Apple Mac host, but Figure 1 (up to 1,080 p). The board’s the details differ and this 46ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 47. //mobile and embedded / COMMUNITY LISTING 1 article does not describe them. speed cards can be too fast You need the root password for for the Raspberry Pi bus. We [ 110.084625] sdb: detected capacity change from 0 to 3963617280 the host computer. On the host have been successful with [ 118.055249] sd 2:0:0:0: [sdb] 7741440 512-byte logical you also need the following: Transcend 4 GB Micro and blocks: (3.96 GB/3.69 GiB) JAVA IN ACTION ■■ A way to download a file from Patriot 4 GB Class 4 cards. The [ 118.059409] sd 2:0:0:0: [sdb] Assuming drive cache: a Website, such as a Web RPi VerifiedPeripherals page write through browser or the wget utility. has lists of cards that have and [ 118.064547] sd 2:0:0:0: [sdb] Assuming drive cache: ■■ A disk partitioning tool. We use have not worked for Raspberry write through GParted here, which is simple Pi users. [ 118.066015] sdb: sdb1 and effective. If you don’t have ■■ A 5 V DC micro-USB power sup- it, you can acquire and install ply capable of at least 700 mA. it on the host as follows: As mentioned on the Raspberry JAVA TECH Download all listings in this issue as text Pi Website, do not use a USB sudo apt-get install gparted hub or a computer as a power source. 1. Download the Debian Copy the Debian Squeeze image to ■■ A Web browser and e-mail Squeeze Linux image to a the SD card. client for downloading Java SE Performing the Essential new directory called 1. On your host computer, for Embedded Devices from Linux Setup ~/RaspberryPi. discover the SD card device Oracle. When power is applied, the You can find a link to a zipped handle as follows (or use a ABOUT US ■■ An SD card reader/writer. If Raspberry Pi firmware boots Debian Squeeze image for different way if you prefer): your host is running Linux in from the SD card slot. Java SE for the Raspberry Pi here. The a. In a Linux terminal window, a virtual machine, be sure it Embedded Devices runs on Linux; file size is about 450 MB. To run dmesg | tail, which shows can read from and write to therefore, your first task is to get verify the downloaded file, messages associated with SD cards. Linux on an SD card. follow the SHA-1 Checksum device mounts. Only the final ■■ A monitor that can connect Download the Debian Squeeze instructions on the page that messages are of interest. directly or through an adapter to Linux image for the Raspberry Pi. is displayed when the down- b. Insert the SD card into the the Raspberry Pi’s HDMI port. Note: These instructions are load starts. The following reader/writer. ■■ A USB keyboard and mouse for Debian Squeeze. Other instructions assume you have c. In a second terminal win- connected to the Raspberry Pi by Linux implementations for the downloaded the image to a dow, run dmesg | tail again. a powered USB hub. Raspberry Pi might work, but they new directory ~/RaspberryPi. The additional lines in the ■■ An SD card to hold the Raspberry must have been built for the ARM 2. Unzip the image as follows: output (compared to the first Pi’s operating system and Java chip’s software floating point window) relate to the newly runtime. A 4 GB card has ade- capability. Images referenced by $ cd ~/RaspberryPi mounted SD card. They will quate capacity for Linux, Java the Raspberry Pi Website might $ unzip *.zip vary in detail but should look blog SE for Embedded Devices, and have been built for hardware something like the output most embedded applications. floating point capability; they Unzipping creates a subdi- shown in Listing 1 (some lines Note: Not all SD cards work will not work with Java SE for rectory called something like have been broken to fit the with the Raspberry Pi. High- Embedded Devices. debian6-19-04-2012. available space). 47ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 48. //mobile and embedded / COMMUNITY LISTING 2 The clue is sdb, which means mand, as shown in Listing 2. that device handle /dev/sdb. Caution: In the following com- $ cd ~/RaspberryPi/debian6-19-04-2012 $ sudo dd if=yourDebian.img of=/dev/sdb bs=1M sdb1 refers to the example mand, be certain to enter the 1859+1 records in card’s single partition. Your output file (of) argument value 1859+1 records out JAVA IN ACTION card might have multiple correctly. You are about to invoke 1950000000 bytes (2.0 GB) copied, 212.344 s, 9.2MB/s partitions. a low-level disk copy that over- Note: In the following instruc- writes all data. Specifying the tions, we assume that the SD wrong device will destroy data. Download all listings in this issue as text card device handle is /dev/sdb Using the dd command with and that it has a single partition, an SD card is a slow operation. sdb1. Adjust the instructions, if It can take 5 to 10 minutes for section, and then return to ■■ /dev/sdb1: Boot partition. necessary, for your environment. a 4 GB Class 4 card. Also, dd the “Resize the SD card parti- /dev/sdb2: Linux root file sys- JAVA TECH ■■ 2. Unmount the SD card gives no indication of progress, tions” section. tem. Most of its 1.5 GB allo- partition(s): so be patient while it slowly Resize the SD card partitions. The cation is already used. does its work. SD card now contains three parti- ■■ /dev/sdb3: Linux swap area. $ sudo umount /dev/sdb1 4. If you want to be sure now tions and unallocated space. Now About half the card’s space that your SD card’s Linux we’ll add the unallocated space to is unallocated. The biggest 3. Copy the Debian image to the installation works, skip to the Linux file system to make more chunk of free space follows SD card using the dd com- the “Perform the first boot” room for Java SE for Embedded the /dev/sdb3 partition. To ABOUT US Devices and applications. To add this space to /dev/sdb2 assign unallocated space to the file (the file system), we tem- system, we modify the partitions porarily delete /dev/sdb3, on the SD card by deleting and re- extend /dev/sdb2, and then creating one of the partitions and re-create /dev/sdb3. resizing another. 3. In the Partition column, 1. Start GParted: select /dev/sdb3 (linux- swap); then right-click and $ sudo gparted choose Delete. The partition is shown as GParted initially shows the deleted (see Figure 3), but partitions of the host’s disk. GParted has actually queued You do not want to change the operation and will run it these partitions. later. 2. Choose GParted -> Devices 4. In the Partition column, blog to display the partitions and select /dev/sdb2, which unallocated space on /dev/ is the Linux file system; sdb, as shown in Figure 2. then right-click and choose Figure 2 The three partitions are Resize/Move. 48ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 49. //mobile and embedded / COMMUNITY 5. In the dialog box that swap), as shown in Figure 4. the change. system partition, we re-create appears, drag the right arrow You might not be able to drag 7. In the “Moving a partition” a swap partition. until Free space following to exactly 512, but the exact warning dialog box that 8. Select the 512 MiB unallo- (MiB) is about 512 (or however size is not important. appears, click OK. cated partition, right-click, JAVA IN ACTION much you want to leave for 6. Click Resize/Move to queue Now that we’ve grown the file and choose New. JAVA TECH ABOUT US Figure 5 Figure 3 blog Figure 4 Figure 6 49ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 50. //mobile and embedded / COMMUNITY 9. In the Create New Partition operations we’ve queued. tion is complete. At the time this article was dialog box, in the File system 12. In the “Are you sure” dialog The new partition map is written, the username and list, choose linux-swap, as box, click Apply. similar to Figure 6. password were pi and shown in Figure 5. Repartitioning is another 14. Quit GParted and eject the raspberry, respectively. If pi JAVA IN ACTION 10. Click Add. lengthy operation, easily run- SD card so you can try your and raspberry do not work, 11. In the main GParted win- ning several minutes. A dia- first boot. consult the Linux distribution dow, choose Edit -> Apply All log box shows progress. Perform the first boot. Website. Operations to perform the 13. Click Close when the opera- Note: For these steps, you must Note: An incompatible key- have the following components board can prevent login, for connected to the Raspberry Pi: a example, by repeating char- monitor, a keyboard, and a known- acters. If you cannot log in, try to-work Ethernet cable. another keyboard. JAVA TECH 1. With the Raspberry Pi power 3. Obtain and write down the disconnected, insert the Raspberry Pi’s IP address as Linux SD card in the slot, and follows: then connect the power. In a few seconds, boot progress $ sudo /etc/rc.local messages should appear on RaspberryIP the monitor. If they do not, ABOUT US the SD card is likely the wrong 4. Permit ssh logins by using type or formatted incorrectly. this command: It’s normal for error messages Figure 7 to appear during the first $ sudo update-rc.d -f ssh boot because some services defaults 20 are not yet configured. The first boot might also appear 5. Reboot to actually enable ssh to hang waiting for portmap logins: to shut down. As a console message indicates, you can $ sudo sync; sudo shutdown -r either let it run (typically for now a few minutes) or discon- nect the Raspberry Pi power If the shutdown takes too and, optionally, boot again. long, you can power-cycle the Subsequent boots are com- Raspberry Pi. blog paratively fast.
 Now we can read from and 2. After you get the login prompt, write to the Raspberry Pi SD card log in with the Raspberry Pi over the network from the host Figure 8 username and password. computer. 50ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 51. //mobile and embedded / COMMUNITY LISTING 3 Performing the Java SE for Another download page Embedded Devices Setup appears, as shown in Figure 8 $ ls ejre* ejre1.7.0_04 Oracle offers Java SE for Embedded (some details might have $ cd ejre* Devices binaries free of charge for changed since this article $ ./bin/java -version JAVA IN ACTION development and testing use. In was written): java version "1.7.0_04-ea" this section, we use the host to 6. Select the Accept License Java(TM) SE Runtime Environment for Embedded (build download Java SE for Embedded Agreement option, and then 1.7.0_04-ea-b20, headless) Devices and copy it over the net- click the link in the ARMv6/7 Java Hotspot(TM) Embedded Client VM (build 23.0-b21, mixed mode) work to the Raspberry Pi’s Linux Linux - Headless row. file system. Then, still working Note: At the time this article remotely, we unpack the download was written, the ARMv7 Linux Download all listings in this issue as text and launch Java. - Headful software had not JAVA TECH Acquire the Java SE for Embedded been tested on the Raspberry Devices evaluation software. Pi. The ARMv7 Linux - 10. Unpack the Java download: Raspberry Pi. To simplify diagnos- 1. In the host computer’s Web Headless - Server Compiler ing problems, reboot after each browser, go to the Java SE for software does not work on $ ssh pi@RaspberryIP change you make. Embedded Devices down- the Raspberry Pi, because $ cd /home/pi/java Set up a static IP address. If your load page, which is shown in that software requires an $ tar -zxvf *.gz network reuses dynamic IP Figure 7. ARMv7 chip. If you want an ... addresses, you can skip chang- ABOUT US The Web page might have ARMv7-compatible Java run- ing to a static IP address, because changed in detail since this time, consider the ARM JDK 11. Launch Java, as shown in the Raspberry Pi’s IP address article was written. downloadable. Listing 3. will effectively be constant. If the 2. In the Java SE Embedded 7 7. Save the .gz file to your Some details, such as version Raspberry Pi’s dynamic IP address column, click the EABI, VFP, Downloads directory. and build numbers, might is likely to differ each time it is SoftFB ABI, Little Endian link. 8. Log in over the network to have changed since this arti- booted, a static IP address is more A survey page appears. the Raspberry Pi as user pi, cle was written. convenient for using ssh. 3. Complete the survey and click and create a directory for the 12. Optionally, remove the down- In the following procedure, we Submit. Java download: load file: assume that you want to assign A verification page appears. the host name raspberrypi to the 4. Examine the verification page $ ssh pi@RaspberryIP mkdir $ rm /home/pi/java/*.gz Raspberry Pi. for correctness (in particular, /home/pi/java 1. Begin by opening /etc/hosts verify your e-mail address), Performing Optional Linux as superuser in a text edi- and then click Submit. 9. Copy the Java download to Tuning and Tweaking tor, for example, sudo vi/etc/ In a short time, an e-mail the new directory on the The procedures in this section can hosts. blog from JavaSE-Embedded- Raspberry Pi: make your Raspberry Pi system run 2. Add a line for the Raspberry LinkNotify appears in your more reliably, more responsively, Pi consisting of a static IP inbox. $ scp ~/Downloads/*.gz or more conveniently. Choose address that is valid in your 5. Click the link in the e-mail. pi@RaspberryIP:/home/pi/java those you like and run them on the network, an optional domain 51ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 52. //mobile and embedded / COMMUNITY LISTING 4 LISTING 5 LISTING 6 LISTING 7 LISTING 8 name, and aliases. ware address, as superuser, Listing 4 shows a hypothetical open /etc/network/interfaces localhost raspberrypi.yourDomain raspberrypi loghost example in which we des- in a text editor and add lines ignate the Raspberry Pi as analogous to those that fol- JAVA IN ACTION raspberrypi. low the # New entries com- 3. Save the file and exit the ment shown in Listing 6 (sub- editor. stitute your network details). 4. As superuser, open /etc/ Enable swapping and optimize file hostname in a text editor. system access time. By default, 5. Add a line analogous to this: swapping is disabled in Debian raspberrypi. Linux. If an operation exceeds the 6. Save the file and exit the Raspberry Pi’s 256 KB RAM, the JAVA TECH editor. system crashes. Less serious is The following instructions can the fact that, by default, the file prevent a problem in which an system spends time maintaining overloaded network causes the a last-accessed time for each file, operating system to change the which is of little use in embedded Raspberry Pi’s static IP address. applications. Maintaining last- As a result, ssh or other operations accessed times can also reduce Download all listings in this issue as text ABOUT US that use the static IP address the life of an SD card. Both default stop working. behaviors are specified in the 1. Discover the Ethernet con- /etc/fstab file. When the file looks similar to 1. To change the time zone, troller’s hardware address by To enable swapping, do the Listing 8, save it and exit the enter this command: running the command shown following. editor. in Listing 5 (some output Note: Swapping is slow on an SD 4. Now assign p3 (the swap $ sudo dpkg-reconfigure lines have been broken to fit card. For an embedded applica- partition we created on the tzdata the text column). tion, you probably want to manage host as /dev/sdb3) to the In Listing 5, each x in the memory so as to avoid swapping. swap space: A pseudographical user inter- output stands for an address 1. As superuser, open /etc/fstab face appears, as shown in digit. In this example, the in an editor such as vi. $ sudo mkswap /dev/ Figure 9. name of the Ethernet con- The file looks like Listing 7. mmcblk0p3 2. Move the selection cursor troller is eth0. The hardware 2. To enable swapping, uncom- through regions and cities address consists of the hex ment the third line. Set the time zone and locale. By using the Up and Down arrow digits following link/ether, so 3. To eliminate the last- default, the Raspberry Pi is config- keys. Use the Left and Right blog in this example, the address accessed overhead, insert ured for the Europe/London time arrow keys to highlight <Ok> is b8:27:eb:b5:e8:90. a p2 mount point between zone and the en_GB_UTF-8 locale. or <Cancel> and press Return. 2. Now that you have the p1 and p3. The noatime and To localize your computer, follow 3. Set the locale by running the Ethernet controller’s hard- nodiratime options do the job. these instructions. following command: 52ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 53. //mobile and embedded / COMMUNITY $ sudo dpkg-reconfigure -p rc.local to add the following 3. To set the proxy each time Debian worldwide mirror low line before the script exits: you log in, add the export sites page has information locales command to ~/.bash_profile about Debian repository ntpdate yourNTPServer (or to the equivalent if you locations. JAVA IN ACTION The user interface is similar to use a different shell). 2. To update your installed the interface for setting the time Set up an internet proxy. Remap the keyboard. packages, after verifying that zone. 1. Ping a well-known internet 1. If keyboard keys are being the Raspberry Pi has an inter- Set up a time server. Many opera- host, such as misinterpreted or if you net connection, enter these tions, including software package 2. If the host does not respond, want to change the keyboard commands: updates, rely on a correct date find out whether your net- layout, run the following and time. work is behind a proxy and, command: $ sudo apt-get update 1. To set the date and time if necessary, set the environ- $ sudo apt-get upgrade JAVA TECH automatically, first learn the ment variable http_proxy $ sudo dpkg-reconfigure identity of a network time according to your network keyboard-configuration 3. If you get a message that server, and then run this conventions. there are duplicates in the command: Here is a hypothetical 2. Make appropriate selections. package list, open /etc/apt/ example: The user interface is simi- sources.list in an editor again $ sudo ntpdate yourNTPServer lar to the one described in and comment out one of the $ sudo export the “Set the time zone and duplicate entries. ABOUT US 2. To set the time on each boot, http_proxy = locale” section of this article. The entry containing more as superuser, edit /etc/ http: Update the Debian packages. information is usually the 1. Before updating the packages best one to keep. distributed with Debian, as Automatically start the graphical superuser, open /etc/apt/ user interface. If you want the GUI sources.list in a text editor. to start automatically when you This file contains the reposi- log in locally to the Raspberry Pi, tory locations of new and change the default runlevel as updated packages. As dis- follows. tributed, the locations have 1. As superuser, open /etc/ in their URLs. If you inittab in a text editor. are not located in the United 2. Find this entry: Kingdom, you can improve performance by changing the # The default runlevel. entries to a location that is id:2:initdefault: blog physically closer to you. For example, you can globally 3. Change the runlevel to 5: change to if you Figure 9 are in the United States. The # The default runlevel. 53ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 54. //mobile and embedded / COMMUNITY id:5:initdefault: Pi just as easily as on other devices based on the ARM architecture Note: Graphics consume a large or on one of its other supported chunk of the Raspberry Pi’s RAM, architectures, including x86 and JAVA IN ACTION on the order of 90 MB. PowerPC. The Raspberry Pi’s lim- Add a different Web browser. If ited memory (256 MB RAM) and you experience difficulties with processing power (700 MHz CPU) the default Midori browser, try make it a good development plat- Iceweasel: form for embedded use cases and ideal for the Java SE for Embedded $ sudo apt-get update Devices runtime. $ sudo apt-get install iceweasel The advent of the Raspberry JAVA TECH Pi device is an example of the Enable sound. Raspberry Pi sound increasing presence of ARM-based is not enabled by default. To devices in both the embedded- enable it, do the following: 1. As superuser, open /etc/ modules in a text editor. device and desktop-device mar- kets. To offer a solution for higher- end devices, the full-featured FIND YOUR 2. Add this line to the end of the JDK provides support for the JUG HERE ABOUT US file: ARM platform architecture in the Java SE 7 update 6 and later My local and global JUGs are great places snd_bcm2835 releases. </article> to network both for knowledge and work. My global JUG introduces me to Java 3. Save and close the file. developers all over the world. Sound is enabled when you LEARN MORE Régina ten Bruggencate reboot the Raspberry Pi. • Raspberry Pi JDuchess • Java SE for Embedded Devices Conclusion Being both affordable and com- LEARN MORE pact, the Raspberry Pi is ideal for developing applications on an ARM-based device, and it has quickly risen in popularity since its initial release in early 2012. The blog cross-platform architecture of the Java SE for Embedded Devices runtime enables developers to cre- ate applications for the Raspberry 54ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 55. //polyglot programmer / COMMUNITY Part 1 Building Actor-Based Systems Using the Akka Framework JAVA IN ACTION TED NEWARD Learn how to use Akka’s open source actor model implementation to build distributed systems. BIO A s just about any expe- rienced Java developer distributed system that sat- isfies all of the above criteria tems. It is a new abstraction, one divorced from the tra- Typesafe Stack that includes Scala, Akka, and the Play JAVA TECH will tell you, building a dis- still requires deep knowledge ditional objects-in-threads framework. If you’re not tributed system is hard. of the platform, language, model that underlies many familiar with Scala, check Building a distributed system and threading model. of the other Java approaches out this Java Magazine article that responds well to failure, Outside the Java world, to distributed systems. for a succinct overview of scales well, handles all con- however, interesting things In essence, using actors, the language or, for a longer, currency issues well, and still were afoot. A “new” (to Java developers no longer think older take on Scala, check out remains even remotely easy users) language and plat- about objects calling meth- my “Busy Java Developer’s ABOUT US to understand comes pretty form, Erlang, began gaining ods on other objects across Guide to Scala” series. close to a working example of interest based on its suc- remote systems to obtain the word impossible. cesses in building distrib- data and modify it. Instead, Installing Akka and Scala Sun tried to build a model uted systems in the tele- they focus on sending mes- Akka is an open source actor that made it easier to build communications industry. sages to actors operating model implementation, so a distributed, fault-tolerant, Telecoms aim for “five nines” independently in a share- the first step for using Akka scalable, concurrent sys- availability, so any language nothing, immutable-state is to make sure you have the tem, and they or platform that environment. Akka library downloaded and called it Enterprise IN WITH THE NEW can achieve such If that last sentence installed somewhere on your JavaBeans (EJB). By most accounts, All this flies success is worth examining. sounded a bit like gibber- ish, that’s OK—it represents machine. If you’re going to use Scala (as I will), you’ll also it didn’t work well. directly in the In this particular a different way of thinking need to install the Scala bits. Spring tried to create a simpler face of traditional case, part of what came back was the about building systems, something we will explore For these examples, I’m using Akka 2.0.3 and Scala EJB approach, as object orientation. actor model, which in more detail. Specifically, 2.9.2. If neither is currently blog did other “micro- That’s a good is a different way we’re going to investigate on your machine, you can containers.” Despite their thing. of approaching the construction of building actor-based sys- tems using the Akka frame- download the Typesafe Stack as a whole, which manages PHOTOGRAPH BY PHIL SALTONSTALL efforts, building a distributed sys- work, which is part of the some of the dependencies 55ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 56. //polyglot programmer / COMMUNITY LISTING 1 and offers some additional fea- Main, just as you would for Java), tures beyond just Akka. and lo and behold, a message to import{ ActorSystem, Actor, Props } Make sure that you have Scala the console appears. case object Start available at the command prompt, And . . . the program never JAVA IN ACTION and ensure that the Akka libraries returns. This is expected, and we’ll object Main { are accessible to your CLASSPATH. fix it in a second, but to under- def main(args: Array[String]): Unit = { For simplicity’s sake, I’ll be explicit stand why requires first diving a bit val system = ActorSystem() about which libraries we’re com- into the concepts behind Akka. system.actorOf(Props[HelloActor]) ! Start piling and running against, rather } than letting sbt (Scala Build Tool) Actors, to Your Places! } or Maven hide those details. In a traditional object-based remoting system, we build objects class HelloActor extends Actor { JAVA TECH Hello, Akka (and Scala) that expose methods over some def receive = { First, verify that Scala is installed form of remoting protocol or API. case Start => System.out.println("Hello, Akka!") by running scala -version at the Unfortunately, doing so requires } command line, and make sure it that we think explicitly about a } reports at least version 2.9. Then, number of sticky issues. let’s look at what is probably the For example, should the param- simplest “Hello Akka” program eters be passed by value (that is, Download all listings in this issue as text ABOUT US that follows the style and ideas should what’s passed in be a copy embodied in Akka (see Listing 1). of the parameter objects and, if For now, don’t worry about what so, should it be a “deep” or “shal- eliminating the shared mutable a domain object, a model object, the code does; let’s make sure it low” copy?) or by reference (that is, state that passing parameters by or a business object, as has been builds and runs first. To build it, should what’s passed in be a proxy reference might introduce, and by used in other systems, such as EJB we’ll need two libraries from the to a remote object that lives else- eliminating direct access to object or Servlets. Akka distribution (akka-actor- where?). Also, can other remote internals, we eliminate the poten- An actor, on the other hand, is 2.0.3.jar and its sole dependency, clients call this same method on tial for two clients to be accessing simply an entity that responds to config-0.3.1.jar). So for ease of use, this same object during the time the same variables at the same messages—it’s never intended to copy them to the same directory that the first client is calling this time, which eliminates the need be a domain object or to represent where Listing 1 (Main.scala) lives, object’s method? And . . . to worry about locking. By sticking something in the business domain. and build. (If you’re new to Scala, In an actor-based system, by with messages, instead of objects, It simply processes incoming mes- scalac, the command-line com- contrast, we never expose meth- as the parameters we pass around, sages. (Yes, an actor might in turn piler, uses many of the same flags ods to the outside world. Instead, we avoid accidentally handing talk to a domain object, but that’s that javac uses. So pass in the JAR to simplify a bit, clients of an a huge graph of domain objects getting ahead of ourselves.) blog files using the -classpath option actor send messages to the actor, across the wire. A message is essentially a data just as you would for javac.) which are always “by value” cop- To be clear, I use the term object transfer object, or a parameter If it builds successfully, then run ies, and they are processed in an to mean a traditional union of object, to use Martin Fowler’s it (again, using scala -classpath ... entirely asynchronous fashion. By state plus behavior, such as with term. A message, contrary to tradi- 56ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 57. //polyglot programmer / COMMUNITY LISTING 2 tional object-oriented principles, method on another—instead, offers no encapsulation of its state, message passing takes place, and object Main { def main(args: Array[String]): Unit = { because it needs none—the whole any data inside those messages (of val system = ActorSystem() point of the message is to convey which there is none, yet) is copied system.actorOf(Props[HelloActor]) ! "Start" JAVA IN ACTION data, not to hide it or offer any kind instead of passed by reference. } of processing. In main(), we first initialize the } From an implementation Akka actors system by obtain- standpoint, yes, all three kinds of ing an instance of ActorSystem, class HelloActor extends Actor { entities (objects, actors, and mes- and then we use Props (think def receive = { sages) are built using the same of it as a dictionary of actors for case "start" => System.out.println("Hello, Akka!") atoms (classes, fields, and meth- now) to obtain an instance of the } ods) but in very different propor- HelloActor actor. } JAVA TECH tions. For example, if your actors Note that where we get this actor are trying to track business data in from is hidden from us—it could fields, you’re closer to building an be local or remote. We don’t care. Download all listings in this issue as text object than an actor. If your mes- (Obviously transmission times will sages are defining anything other be much longer if it’s remote, but than public fields (and maybe a since actor-delivered messages example, we could change the (Worse yet, even if you’re unit test- few convenience methods such are intended to be asynchronous, code to use Strings instead, as ing the HelloActor, the tests won’t ABOUT US as toString() for easier diagnostic we shouldn’t care). shown in Listing 2. catch it—the error is in the client messages), you’re closer again to Then, we use the ! method on But the dangers here are exactly code, not the actor.) building an object than a message. the actor to send the Start mes- what we saw in the earlier code, And yes, all this flies directly in sage to it, which tells it to print to because now that we’re using a Cut! Horrible! Do It Again! the face of traditional object orien- the console. String—and the data held inside We have two problems with the tation. That’s a good thing. HelloActor is the actor imple- the String—to convey the mes- code as it currently is. One is that it Getting back to the example mentation, and it’s pretty straight- sage, typos and case-sensitivity never terminates. The other is that code, what we’re doing here is forward. As a class, it derives from become issues. Granted, we could it’s a pretty limited example. What creating an instance of an actor the base class Actor, and defines set a “corporate standard” that if we want to print more than just (HelloActor) and sending it a mes- a receive method that pattern- says “all messages must be in “Hello” or we want to repeat that sage (Start). This is the heart of matches for incoming Start objects. uppercase,” but this becomes one message a few times, to name a actor-style programming: creating Akka can use any Serializable more thing we have to remember, few possible enhancements? entities (actors) that respond to type as a message type, but the as opposed to something the com- Fixing the first issue is easy: we messages and, depending on the type-safe tendencies of Scala lead piler can check for us. have to tell the Akka runtime to purpose of the message, replying us to prefer using simple class If we go back to the original stop. When the HelloActor was blog back with values or passing those types (case class and case object code, trying to send a Strat object created, the Akka runtime spun messages on to other actors. are perfect for this) rather than will yield a compiler error, whereas up a collection of threads under Take careful note: At no point data-driven types that might be trying to send a Strat string will the hood. Then, when a message will one object directly invoke a misinterpreted at runtime. For compile and just do nothing. was received by the Akka run- 57ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 58. //polyglot programmer / COMMUNITY LISTING 3 LISTING 4 LISTING 5 LISTING 6 time, it borrowed a thread from Note that in Listing 4, just the pool, called the HelloActor to prove a point, I created the import{ ActorSystem, Actor, Props } receive() method with the message RepeatMessage to extend the case object Start as a parameter, and—when that Message, because this is common case object Stop JAVA IN ACTION returned—returned the thread in some actor systems and was back to the pool. This is normal sometimes used in earlier Akka object Main { behavior; no actor has an explicit code examples. Scala 2.9 will issue def main(args: Array[String]): Unit = { thread of its own. a deprecation warning about this, val system = ActorSystem() But the runtime was never told however, and because the inheri- val helloActor = system.actorOf(Props[HelloActor]) to stop, so let’s fix that. Let’s cre- tance here isn’t critical to what helloActor ! Start ate a new message type, Stop, that we’re doing, if deprecation warn- helloActor ! Stop tells the actor that it’s time to go ings bother you, you can remove } JAVA TECH away now. Doing so requires only the “extends” clause (and elimi- } that we define a new message nate the “override,” too). The rest class HelloActor extends Actor { type, Stop, and that when the actor of the code will work just as well. def receive = { receives that message, it shuts However, there is one impor- case Start => System.out.println("Hello, Akka!") down the Akka runtime, as shown tant aspect about messages in case Stop => context.system.shutdown() in Listing 3. Akka that might go unnoticed: } Now, when the code is run, the messages need to be immutable. } ABOUT US actor prints to the console, and There’s no way to enforce this at then the whole thing stops. Where compile time, unfortunately. But did this “context” thing come in Scala, case classes and objects Download all listings in this issue as text from? We inherited it from Actor— are immutable by default (unless every actor lives inside an Akka you explicitly make them mutable, runtime context, and from that which is a bad idea), making them Again, we’re using the ! method the HelloActor—the client doesn’t we can get a variety of interesting perfect for message types. in Akka (also called the “tell” style feel any of that performance hit, tidbits, such as a reference to the Next, we need to modify the of message-send), which fires because it drops the message off Akka system, which we then use to HelloActor to respond to these these messages off in a fire-and- into a mailbox inside of the Akka shut the Akka system down. messages, as shown in Listing 5. forget fashion, because no reply runtime and immediately returns. But let’s also make the Again, it’s all pattern matching, is returned from any of them. Build it, run it, and bask in the HelloActor slightly more powerful; so if that part isn’t clear, check out This is the best approach to an glorious results. let’s break the messages up a little some of the available Scala refer- actor-based system, because the into an “initializing” sequence ences. The rest of the code—what lack of a reply means no block- Cut! Excellent! Next Scene! (Start), a “finished” sequence we do after matching on a mes- ing on the part of the client. Also, Admittedly, calling these results blog (Stop), and a “do something” sage type—should be pretty self- if the actor takes a bit longer to “glorious” is a bit of a stretch— sequence (Message) that carries evident. Finally, there’s the change process one of them—imagine after all, all the demo is doing is with it some additional data. See to the client to start using it this sending a RepeatMessage(“Really just printing to the console, and Listing 4. way. (See Listing 6.) long message here”, 100000) to how exciting is that, really? But the 58ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 59. //polyglot programmer / COMMUNITY LISTING 7a LISTING 7b LISTING 7c LISTING 7d concepts behind the demo high- cess would take incoming HTTP light some of the basic, funda- requests on port 80, hand the /** * Copyright (C) 2009-2012 Typesafe Inc. <> mental principles of actor-based request and all of its necessary con- */ programming: establishing actors, text to a slave process for process- package akka.tutorial.first.scala JAVA IN ACTION sending messages, avoiding muta- ing, and then hand the results back ble state, and avoiding shared over the port to the client. It’s also import objects or remote objects. how the SETI@Home screen saver import akka.routing.RoundRobinRouter It’s a different approach to pro- works (a master hands out chunks import akka.util.Duration gramming than an expatriate of data over the internet to client import akka.util.duration._ Java EE programmer is used to, machines signed up for the pro- and more than anything, success gram, and each client analyzes the object Pi extends App { with Akka means rewiring your signal data and then hands back JAVA TECH brain to think in this new style and the results to the master, signaling calculate(nrOfWorkers=4, nrOfElements=10000, approach. If you want to under- the desire to process more data). nrOfMessages=10000) stand the heart and soul of how an actor-based model works, this is That’s a Wrap! Print It! sealed trait PiMessage all that you need to know. There’s a great deal more to the case object Calculate extends PiMessage Let’s consider an example from Akka runtime than what we saw case class Work(start: Int, nrOfElements: Int) extends PiMessage the Akka distribution, which calcu- here, but we explored the basic, ABOUT US case class Result(value: Double) extends PiMessage lates the mathematical constant Pi fundamental principles of actor- case class PiApproximation(pi: Double, duration: Duration) (see Listings 7a–7d). We won’t go based programming: establishing over the math involved; we’ll cover actors, sending messages, avoid- just the design. ing mutable state, and avoiding Again, leaving alone the algo- shared objects or remote objects. rithm by which we calculate Pi, In the next article, we’ll look at notice that the work is essentially how Akka provides more support broken down into a collection of than just the basic actor model Worker actors, who are given work shown above. We’ll talk about by the Master actor, who spins off supervision, Akka’s Actor Models pieces of the work to each Worker of how fault tolerance works and, actor and then collates the results of course, we’ll explore a bit more and hands back the completed Akka code just for fun. </article> answer to the original client. This is a common concurrency blog pattern, sometimes called the Master-Slave pattern. It’s how the LEARN MORE original Apache Web server worked, • Akka Download all listings in this issue as text where a master lightweight pro- • Jonas Bonér on Akka 59ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 60. //fix this / COMMUNITY Hint: Check the purpose of the JPA Exceptions. In the September/October issue, Stephen Chin presented a code challenge around JavaFX 2 THE CODE designed to talk to a database via JAVA IN ACTION Media APIs. He gave us a code snippet from the The program was originally Application start method of the MediaQuiz class and JDBC using the following fragment of code: asked us to figure out why the video clip does not play. try { statement.executeUpdate(sqlInsertStatement); The correct answer is #3. While we have loaded the connection.commit();"Transaction committed"); media and inserted the MediaView into the scene } catch(SQLException e) {connection.rollback(); correctly, we have not actually started playing the"Transaction rolled back");} JAVA TECH media by calling play() on the MediaPlayer class. After several years the program was redesigned to use JPA: This is an easy bug to overlook with three different entityTransaction.begin(); media classes in use, but with a little detective work, it s not that try{ hard to diagnose. entityManager.createNativeQuery(sqlInsertStatement) .executeUpdate(); This issue s challenge comes from Jason Hunter (top left), entityTransaction.commit();"Transaction author of Java Servlet Programming, 2nd Edition (O Reilly committed"); ABOUT US } catch(Exception e) {entityTransaction.rollback(); Media) and deputy CTO at MarkLogic, and Boris Shukhat,"Transaction rolled back");} applications programming manager, vice president, Bank of America Merrill Lynch. As a result the code failed. 1 THE PROBLEM 3 WHAT S THE FIX? 1.)  heck whether entityTransaction.isActive() is true before C Porting JDBC code to use JPA requires a surprisingly calling entityTransaction.rollback(). different treatment of transactions rollbacks. 2.) Call entityTransaction.rollback() for RuntimeException. 3.) Do not call entityTransaction.rollback() for RollbackException. 4.) All of the above. blog GOT THE ANSWER? ART BY I-HUA CHEN Look for the answer in the next issue. Or submit your own code challenge! 60ORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012
  • 61. COMMUNITY EDITORIAL Editor in Chief Caroline Kvitka Community Editors Cassandra Clark, Sonya Barry, PUBLISHING Vice President Jeff Spicer Publisher Jennifer Hamilton +1.650.506.3794 Learn Java On Demand Yolande Poirier Audience Development and JAVA IN ACTION Java in Action Editor Operations Director Michelle Kovac Karin Kinnear +1.650.506.1985 Technology Editors Janice Heiss, Tori Wieldt ADVERTISING SALES Associate Publisher Contributing Writer Kyle Walkenhorst +1.323.340.8585 Kevin Farnham Northwest and Central U.S. Contributing Editors Tom Cometa +1.510.339.2403 Blair Campbell, Claire Breen, Karen Perkins Southwest U.S. and LAD —Oracle University— DESIGN Shaun Mehr +1.949.923.1660 Senior Creative Director Northeast U.S. and EMEA/APAC Francisco G Delgadillo Mark Makinney +1.805.709.4745 JAVA TECH Senior Design Director Advertising Sales Assistant Suemi Lam Cindy Elhaj +1.626.396.9400 x 201 Design Director Mailing-List Rentals Richard Merchán Contact your sales representative. Contributing Designers Jaime Ferrand, Nicholas Pavkovic RESOURCES Oracle Products Production Designers +1.800.367.8674 (U.S./Canada) Sheila Brennan, Kathy Cygnarowicz Oracle Services +1.888.283.0591 (U.S.) Complete Classroom Content ABOUT US Oracle Press Books Highest Rated Instructors ARTICLE SUBMISSION If you are interested in submitting an article, please e-mail the editors. Immediate Online Access SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the subscription form. Search, Pause & Rewind Anytime MAGAZINE CUSTOMER SERVICE  Phone +1.847.763.9635 PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or e-mail address not be included in this program, contact Customer Service. Copyright © 2012, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwise reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLY DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. The information is intended to outline our general product direction. It is intended for information purposes only, and may not be blog Preview Now incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly with a free subscription price by Oracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600. Digital Publishing by TexterityORACLE.COM/JAVAMAGAZINE  ////////////////////////////////  NOVEMBER/DECEMBER 2012