//table of contents /
05 28 66 COMMUNITY FROM SMART JAVA ME 8 AND GRIDS TO THE INTERNET JAVA 8: JAVA MICROBREWS OF THINGS V2COM uses Java to Top features of EXPLORE THE connect millions of Java ME 8 POSSIBILITIES intelligent devices. JAVA IN ACTION From embedded to the cloud, get there with Java 8.
Java 8 Is Here JAVA TECH New theme icon. See how it works.
COMMUNITY JAVA TECH 50 62 03 33 Java Architect Embedded From the Editor New to Java Processing Data with JavaFX and Near 15 How to Become an Java SE 8 Streams Field Communication Java Nation Embedded Developer Use stream operations to on the Raspberry Pi ABOUT US News, people, books, in Minutes express sophisticated data Use your Java skills to create and events Jump into programming processing queries. end-to-end applications that the next big thing using 56 span card readers on embedded 23 embedded Java. devices to back-end systems. JCP Executive Series Java Architect Q&A with Goldman Sachs 41 JSR 308 Explained: 69 John Weir and Donald Raab New to Java Java Type Annotations Polyglot discuss the impact of Three Hundred Sixty– The benefits of type annotations Take Time to Play lambda expressions. Degree Exploration and example use cases Learn how to take advantage of Java EE 7 of the client tier. Part 3 in our series 75 on Java EE 7 Fix This blog Take our concurrency code challenge!
COVER ART BY I-HUA CHEN 01
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 EDITORIAL PUBLISHING Editor in Chief Vice President Caroline Kvitka Jeff Spicer COMMUNITY Community Editors Publisher Cassandra Clark, Sonya Barry, Jennifer Hamilton +1.650.506.3794 Yolande Poirier Associate Publisher and Audience Java in Action Editor Development Director Michelle Kovac Karin Kinnear +1.650.506.1985 Technology Editors Janice Heiss, Tori Wieldt ADVERTISING SALES President, Sprocket Media Contributing Writer Kyle Walkenhorst +1.323.340.8585 Kevin Farnham Western and Central US, LAD, and Contributing Editors Canada, Sprocket Media Claire Breen, Blair Campbell, Karen Perkins Tom Cometa +1.510.339.2403 IN ACTION JAVA DESIGN Eastern US and EMEA/APAC, Senior Creative Director Sprocket Media Francisco G Delgadillo Mark Makinney +1.805.709.4745 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 RESOURCES TECH JAVA Jaime Ferrand, Arianna Pucherelli Oracle Products Production Designers +1.800.367.8674 (US/Canada) Sheila Brennan, Kathy Cygnarowicz Oracle Services +1.888.283.0591 (US) Oracle Press Books oraclepressbooks.com
ARTICLE SUBMISSION ABOUT US If you are interested in submitting an article, please e-mail the editors. SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the subscription form. MAGAZINE CUSTOMER SERVICE [email protected] 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 © 2014, 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 incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied blog upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly with a free subscription price by Oracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600. Digital Publishing by GTxcel 02
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //from the editor / COMMUNITY
FIND YOUR JAVA IN ACTION hange is good—when it comes with benefits. In the case of Java 8, those benefits come in the JUG HERE form of more productivity for developers plus expanded opportunities to develop applications that span from My local and global JUGs embedded devices to the cloud. Java 8 is here—you can download Java SE 8 today, while Java are great places to network
C JAVA TECH Java 8 ME 8 is available in Early Access form. We’ve dedicated most of this issue to Java 8—just look both for knowledge and work. Is Here My global JUG introduces for the theme icon for articles on this topic. me to Java developers all The biggest change in Java SE 8—what some have called the most significant upgrade to the Java program- over the world. ming language ever—is lambda expressions, or closures. “Lambda expressions are anonymous methods that Régina ten Bruggencate JDuchess provide developers with a simple and compact means for representing behavior as data,” explains Brian Goetz, Java language architect at Oracle. “In a few years, developers will wonder how they ever lived without [them].” LEARN MORE ABOUT US There’s plenty more to get excited about, including Nashorn, a next-generation JavaScript engine; Compact Profiles, which offer a convergence of the Java ME Connected Device Configuration (CDC) product with Java SE 8; and a new date and time API. You, the Java community, also played a huge role in bringing Java 8 to fruition. We examine all that and more in our Java 8 cover story. In “Java ME 8 and the Internet of Things,” we explore the new features that make //send us your feedback / Java ME 8 a comprehensive platform for connected devices. And if you’re ready to get We’ll review all going with embedded development, Angela Caicedo shows you how. suggestions for future improvements. This issue is jam-packed with information to get you started with Java 8 (including Depending on volume, articles on streams and type annotations). So go on . . . embrace change and explore some messages may the possibilities. Let us know where you take Java 8. not get a direct reply. blog
Caroline Kvitka, Editor in Chief BIO
PHOTOGRAPH BY BOB ADLER 03
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014
COMMUNITY
1. LAMBDA EXPRESSIONS 2. NASHORN AND JAVASCRIPT 3. COMPACT PROFILES JAVA IN ACTION JAVA 4. DATE AND TIME API EXPLORE THE 5. JAVAFX 8 POSSIBILITIES 6. COMMUNITY INVOLVEMENT JAVA 7. JAVA ME 8 TECH JAVA 8. JAVA SE 8 AND THE JVM ABOUT US
Java 8 From embedded to the cloud, get there with Java 8. Is Here
BY TIMOTHY BENEKE ava 8, which encompasses both Java SE 8 and Java ME 8, might be the most significant expan- sion of the Java platform yet. JLambda expressions and the Stream API increase the expres- sive power of the platform and blog make it easier for developers to take advantage of modern, multicore processors. Compact Profiles in Java SE 8 allow developers to use just ART BY I-HUA CHEN 05
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY
a subset of the platform, 1 and are a significant step toward the convergence of Java SE and Java ME. Java ME 8 itself, meanwhile, has JAVA IN ACTION JAVA been updated to include more-recent Java Virtual LAMBDA Machine (JVM), language, and library features while retaining the focus on small EXPRESSIONS embedded devices. Java 8 allows developers to apply TECH JAVA the same skill set across Lambda expressions are at the over behavior. As Goetz explains, readability, and performance.” a wide range of scenarios, heart of Java SE 8. “Lambda “If we want to model a workflow According to Goetz, the typical from the smallest embed- expressions, also known as clo- such as ‘do A before you start, do developer’s initial experience with ded Internet of Things (IoT) sures, are anonymous methods B for every file in this group, do C lambda expressions is likely to be devices to enterprise serv- that provide developers with a if you encounter an error, and do through the powerful new APIs
ers in the cloud. simple and compact means for D when you’re done,’ for manipulating ABOUT US As Mark Reinhold, chief representing behavior as data,” we don’t have ideal collections. Business architect of the Java Platform explains Brian Goetz, Oracle’s tools for express- “This is the most logic typically is full Group at Oracle, put it, “Java Java language architect and ing the behaviors A significant upgrade of ad hoc query-like 8 is the first truly revolution- Specification Lead for JSR 335, through D, and this of the Java calculations over ary release we’ve done in a Lambda Expressions for the Java affects the sort of collections; the core very long time.” Programming Language. “This APIs we design. We programming model libraries now make Here, we take a look at enables the development of have to break up ever. In a few years, it easier to express eight key pieces of Java 8. libraries that do a better job of the phases of the the “what” of such abstracting over behavior, which workflow, and the developers will a query without in turn leads to more-expressive, client code has to be wonder how they getting bogged less error-prone code.” directly involved in ever lived without it. down in details While Java has always provided each phase, rather about the “how.” blog reasonable tools such as classes, than saying ‘here’s I certainly do!” The other major inheritance, and generics for what I want; go do —Brian Goetz, Java language feature of abstracting over data, Java SE 8 it.’ This negatively Language Architect, Oracle Java SE 8 is default provides new tools for abstracting affects reusability, methods, which PHOTOGRAPH BY TIM GRAY/GETTY IMAGES 06
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY SPOTLIGHT EASIER QUERIES ADOPT-A-JSR not simply a matter of AND CALCULATIONS COMMUNITY new syntax; there are WITH LAMBDAS some new concepts that JSR 335: Lambda developers will have to Java Language Architect which is good because Expressions for the Java learn just to be able to Brian Goetz shows how code that is easy to read read Java code, even if Programming Language Brian Goetz does a live the Java core libraries have also is more likely to be they do not plan to take hacking session on lambda been enhanced to enable correct,” says Goetz. ADOPTED BY: Jozi JUG expressions. advantage of these new
more-query-like calcula- This shift from hand- IN ACTION JAVA (Johannesburg, South features in the code they tions over collections. written loops to aggregate Africa), London Java write. There are also big enable interfaces to “Consider something like operations using lambdas additions to the core Community, and SouJava evolve over time. Default ‘find artists with albums and streams inverts the libraries that develop- (São Paulo, Brazil) methods are necessary that have fewer than eight control of the computa- ers will have to learn— for Java SE 8 given that tracks.’ This is easy enough tion. “With thefor loop, the WHAT: Jozi JUG organized but these costs should some core library classes, to write with a for loop, but client is in control at every be more than offset by TECH JAVA a Java 8 hackathon and such as Collections, are the resulting code is full step, asking the Iterator increases in productivity presented a talk on lambda more than 15 years old. of accidental detail about for the next element on and expressiveness.” expressions to its members. Without default meth- ‘how,’ which obfuscates the each iteration,” Goetz Goetz makes no effort ods, some core library ‘what,’” he says. In Java says. “With lambdas and to hide his enthusiasm London Java Community classes would be unable SE 8, it looks like this: streams, the library is in for lambdas: “I think this held three hackdays and to support lambdas. control, but still allows the is the most significant presented a “Lambdas: “More generally,” Set
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY NASHORN AND 2 JAVASCRIPT IN ACTION JAVA
“Nashorn is a part of Java SE 8 that the wealth of libraries normally only is intended to provide a version of available to Java developers, and can JavaScript that would run as part implement portions of their applica- of the JVM—a more modern ver- tion in a simpler, lightweight pro- TECH JAVA sion of JavaScript using newer JVM gramming language. Developers can technologies,” observes Jim Laskey, now implement runtime dynamic engineering lead for multilan- features and bypass build cycles, guages at Oracle. With Java SE 8, while users and field engineers can Nashorn is being shipped as a javax make configuration changes without
.script engine embedded in the JDK, having to rebuild the application. ABOUT US which means that any Java applica- “Nashorn will allow JavaScript to tion can now contain components be used in ways that have not been written in JavaScript. JavaScript is available before,” he says. a popular language with features Laskey is quick to point out, similar to Java’s features that is “Although Nashorn JavaScript is not ideal for transmitting code across the same as browser JavaScript, and networks. In addition, there is now currently lacks DOM components, it a command-line tool (jjs) that is a full-featured programming lan- allows developers to use Nashorn guage with access to all of the avail- as a scripting tool. Nashorn, which able Java libraries.” replaces Rhino, also an open source “Nashorn will allow JavaScript to be used JavaScript engine, is both faster and in ways that have not been available before.” blog lighter and integrates JavaScript and MORE ON NASHORN —Jim Laskey, Engineering Lead for Multilanguages, Oracle Java more tightly. • Project Nashorn As a consequence, JavaScript • “Oracle Nashorn: A Next-Generation developers can take advantage of JavaScript Engine for the JVM” PHOTOGRAPH BY DAN CALLIS/GETTY IMAGES 08
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY “With the introduction of Compact Profiles, we now have a single Java SE standard with all of the productivity that Java is famous for that can truly scale from small embedded IoT devices to large enterprise server installations.” —Bob Vandette, Consulting Engineer, Oracle JAVA IN ACTION JAVA
much smaller than the full Java SE Java runtime environment (JRE), they enable applications to be deployed on platforms with limited storage.
The smallest of these runtimes is 11 MB, which is TECH JAVA more than four times smaller than the equiva- lent traditional JRE. Java SE applications can now be designed to run on resource-constrained devices by targeting the specific APIs that are available in Compact Profiles. The Compact Profiles were primarily ABOUT US designed for embedded developers who wish to use Java for the creation of embedded solutions with limited static and dynamic storage. By keep- ing the amount of RAM and flash to a minimum, the bill of materials (BOM) cost for embedded devices is also kept to a minimum, resulting in COMPACT PROFILES increased profit for device distributors. 3 Bob Vandette, consulting engineer at Oracle, sums it up: “With the introduction of Compact Compact Profiles, three well-defined API subsets For many years, embedded developers have Profiles, we now have a single Java SE standard of the Java 8 specification, offer a convergence wanted to allow subsetting of the Java SE plat- with all of the productivity that Java is famous of the Java ME Connected Device Configuration form in order to deploy smaller binaries in their for that can truly scale from small embedded IoT blog (CDC) with Java SE 8. With full Java 8 language embedded devices. Compact Profiles enable devices to large enterprise server installations.” and API support, developers now have a single the creation of applications that do not require specification that will support the Java ME CDC the entire platform to be deployed and run on MORE ON COMPACT PROFILES class of devices under the Java SE umbrella. small devices. Because Compact Profiles are • “An Introduction to Java 8 Compact Profiles” PHOTOGRAPH BY TIM GRAY/GETTY IMAGES 09
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 4 DATE AND COMMUNITY TIME API COMMUNITY SPOTLIGHT Java SE 8 introduces a new java rency issues when ADOPT-A-JSR JAVA IN ACTION JAVA .time API with a fluent and famil- used in multitask- iar style that is easy to read and ing environments. JSR 310: Date and Time API write without the aid of IDEs. It In addition, the ADOPTED BY: Guadalajara provides excellent support for extensibility of the JUG (Guadalajara, Mexico), the international ISO 8601 time API enables the Jozi JUG (Johannesburg, standard that global businesses addition of new use and also supports the fre- calendars, units, South Africa), London Java TECH JAVA quently used Japanese, Minguo, fields of dates, and “The new java.time API will make Community, and SouJava Hijrah, and Thai Buddhist calen- times. Developers developers more productive, (São Paulo, Brazil) dars. Each of the new core Java can focus on completing a partic- KEY CONTRIBUTIONS: classes—for date, time, date ular task without being concerned whether they are using the global and time combined, time zones, about unrelated functions. date and time standards or one of Guadalajara JUG held a live
instants, duration, and clocks— The new API uses immutable date and time coding session. ABOUT US has a specific purpose and has values, with each computation the regional calendars.” Jozi JUG organized a hack- explicitly defined behavior with- producing a new value. With —Roger Riggs, Consulting Member out side effects. The types are immutable objects, an instance of Technical Staff, Oracle athon with more than 25 immutable to simplify concur- can be shared with a library or a participants. concurrent task without concern Calendar combine many functions London Java Community that the value will change unex- in each type, which often results pectedly, explains Roger Riggs, separated out technology in unexpected interactions that consulting member of the techni- compatibility kit (TCK) tests increase programming complex- cal staff at Oracle. This contrasts ity,” explains Riggs. “The new APIs versus implementation- with the current Date and Calendar offer greater clarity of purpose, specific tests. types that hold a mutable value ease of use, and maintenance.” and are not multithread safe. SouJava held several talks at blog Using immutable values elimi- their meetings and provided nates many problems for multi- MORE ON DATE AND TIME feedback to the JSR 310 Jim Gough of the London Java threaded programming. • Package java.time Expert Group. Community hacks on date and time. “The current APIs for Date and • “Java SE 8 Date and Time” PHOTOGRAPH BY TIM GRAY/GETTY IMAGES 10
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 “JavaFX 8 is integrated with Java SE 8 and works well with lambda expressions. It simplifies many COMMUNITY kinds of code, such as event handlers, cell value factories, and cell value factories on TableView.” —Richard Bair, Client Java Architect, Oracle JAVA IN ACTION JAVA
nents, many of which can now work out of the box. All of the above will lead to enhanced pro- ductivity for JavaFX developers, he says.
Much progress has also been made on the TECH JAVA Mark Reinhold (left), performance front, largely due to the effort chief architect of the Java Platform Group at to bring JavaFX to embedded devices such as Oracle, and Richard Bair, the Raspberry Pi and Freescale i.MX 6 boards. client Java architect Increased 3-D support in JavaFX has opened at Oracle, talk about new opportunities for developers, with AMD JavaFX 8 and lambdas. contributing COLLADA importer functionality to OpenJFX, which is a lively and thriving ABOUT US community, Bair adds. “The new Scene Builder 2, the first Scene Builder actually built with Scene Builder, has an excellent CSS inspector, so developers can JAVAFX 8 better understand why things are styled as they 5 are,” explains Bair. It is also modular and can be embedded in any IDE. Scene Builder 2 works with FXML, an open and published format, so “JavaFX 8 is integrated with Java SE 8 and works In addition, says Bair, JavaFX 8 offers a pow- developers can hack the FXML file directly. well with lambda expressions. It simplifies many erful rich text node for the scene graph, and “I encourage everybody to download kinds of code, such as event handlers, cell value the Java community is fast at work on several JavaFX 8, try it out, and provide feedback blog factories, and cell value factories on TableView,” projects building rich text and code editors on to the team,” he adds. explains Richard Bair, client Java architect at top of this support. In addition, the default look Oracle. “It brings some much-requested new of JavaFX applications has been refreshed with UI controls and APIs such as TreeTableView and a new theme, called “Modena.” JavaFX 8 also MORE ON JAVAFX 8 APIs that enable modal dialogs.” offers increased support for third-party compo- • JavaFX 8 Overview PHOTOGRAPH BY BOB ADLER 11
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY
COMMUNITY IN ACTION JAVA 6 INVOLVEMENT
The Java community has been vital in the cre- standards as well. More than 26 JUGs have
ation of Java 8. It has provided ongoing feed- participated in the program. TECH JAVA back to Specification Leads, made requests for The Java Community Process (JCP), with its new Java functionality, uncovered bugs, con- enhanced openness and flexibility, has made tributed to code fixes, and much more. it easier for both organizations and individu- Java user groups (JUGs), which are centers als to contribute to the Java platform. “The of Java community learning and participation, JCP now has a much more transparent pro- have been essential. As Java Champion and cess,” says Souza. “It’s a lot easier for some- SouJava JUG Leader Bruno Souza explains, one to go to the JCP site and get involved. This ABOUT US “Java 8 has set a new standard of community increased transparency has made it easier for participation. There are Java user groups all the community to participate.” over the world running programs and providing feedback for the JCP “Java 8 has set a new standard of community specifications and being active in participation. There are Java user groups all over the OpenJDK.” The OpenJDK community is where developers collaborate on world running programs and providing feedback for the open source reference imple- the JCP specifications and being active in OpenJDK.” mentation of the Java SE platform. —Bruno Souza, Java Champion and SouJava JUG Leader The Adopt-a-JSR program, cre- ated to encourage JUG members, blog individuals, and other organiza- tions to get involved in JSRs, has resulted in increased grassroots and developer partici- SouJava’s Bruno Souza explains how community pation in not only Java 8 but other emerging participation has changed with Java 8.
PHOTOGRAPH AND VIDEO BY BOB ADLER 12
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 7 JAVA ME 8 COMMUNITY “Java ME 8 is a major step in the convergence of Java ME and Java SE and the unification of the Java ecosystem.” —Terrence Barr, Senior Technologist and Product Manager, Oracle JAVA IN ACTION JAVA
“Java ME 8 is a major step in the iar platform, language, pro- convergence of Java ME and gramming model, and tools. TECH JAVA Java SE and the unification of With the embedded space the Java ecosystem, enabling and the fast-developing IoT Java developers to more eas- in a state of flux, Java ME 8 ily deploy their existing skills offers a flexible and scalable across a range of embedded development/deployment
devices, drawing upon the rich- environment. ABOUT US ness and portability of the Java See “Java ME 8 and the platform,” explains Terrence Internet of Things” in this Barr, senior technologist and issue for details. product manager at Oracle who focuses on the IoT and embed- ded technologies. “This results MORE ON JAVA ME 8 in a faster time to market, • Oracle Java ME Embedded 8 as well as cross-platform Early Access compatibility and embedded • Connected Limited Device device scalability.” Configuration 8 With the advent of Java ME 8, developers can take their exist- • Generic Connection blog ing skills and begin writing Framework 8 applications for the rapidly • Micro Edition Embedded developing realm of embedded Profile 8 devices—using the same famil- • Device Access API 8 PHOTOGRAPH BY TON HENDRIKS 13
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY SPOTLIGHT TAKE IT FOR A SPIN JAVA SE 8 TEST JAVA 8 COMMUNITY The Test Java 8 program All in all, Java 8 offers a new oppor- 8 tunity for enhanced innovation for was initiated by the London Java developers who operate on AND THE JVM Java Community as part of anything from tiny devices to cloud- the Adopt-a-JSR program. based systems. We can expect increases in developer productiv- “Java SE 8 offers an improved, member of the technical staff The aim of the program was IN ACTION JAVA ity and application performance more mature G1 garbage col- at Oracle. “G1’s basic design is for Java user group members through the reduced boilerplate lector. G1’s scalability is getting not changing, but incremental to help with testing Java 8 code and increased parallel pro- better, and more work is being improvements toward more- on several open source gramming that lambdas offer. Java 8 done concurrently,” explains dependable pause times have software projects prior to offers best-in-class diagnostics, Jon Masamitsu, principal been made in many areas. the launch of Java 8. with a complete tool chain to con-
More generally, in all the gar- TECH JAVA tinuously collect low-level and bage collectors the command- detailed runtime information. line flags are now more con- By bringing the advantages of sistent, with flag discrepancies Java SE to embedded development, corrected. This should make out of the permanent genera- developers can transfer their Java it easier for users to switch tion (which has been removed skills to fast-evolving new realms in among the different garbage entirely) and moved into native
the IoT, enabling Java to support any ABOUT US collectors and have the com- memory and/or the Java heap. device of any size. It is an exciting mand-line flags have a com- Previously, tuning the size of time to be a Java developer, so take it mon meaning where possible.” the permanent generation was for a spin, and tell us about the ride. In addition, Java SE 8 a tiresome, trial-and-error pro- removes the need to tune the cess. The maximum size of the permanent generation. The permanent generation had to MORE ON TOPIC: Java HotSpot VM’s internal rep- be set at startup, and there was Java 8 resentation of Java classes has no intuitive way to know how Is Here been re-engineered and moved large it should be. Developers need no longer guess about Timothy Beneke is a freelance writer “Java SE 8 offers an improved, more mature G1 a size for the permanent and editor, best known for his books generation. on gender. blog garbage collector. G1’s scalability is getting better, Finally, Java ME 8 has been updated with the JVM, the lan- DOWNLOAD JAVA 8 and more work is being done concurrently.” guage, and the libraries to be • Java SE 8 —Jon Masamitsu, Principal Member of Technical Staff, Oracle aligned with Java SE 8. • Java ME 8 PHOTOGRAPH BY BOB ADLER 14
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 // java nation / IOUC Summit /
Clockwise: COMMUNITY The JCP’s Heather VanCura; Simon Ritter, Georges Saab, and Mark Reinhold field
questions IN ACTION JAVA about the Java platform; summit attendees engage during a session. JAVA TECH JAVA
More than 20 Java user group (JUG) leaders from all over the world attended the International Oracle ORACLE USER GROUP User Group Community (IOUC) Annual Summit ABOUT US January 21–23, 2014, in Redwood Shores, California. The IOUC is a community of leaders representing LEADERS’ SUMMIT Oracle user groups worldwide. User group leaders from all over the world, including more than 20 JUG leaders, attended the summit to learn about Oracle products and technologies, provide feedback to product groups, network, and share best practices. The unofficial kickoff to the Java track was a Brazilian barbecue at the home of Stephen Chin, a Java evangelist at Oracle. Bruno Souza, leader of SouJava in Brazil and a member of the Java blog Community Process (JCP) Executive Committee, acted as executive chef, manning the barbecue for hours after just stepping off a flight from Brazil. The official Java track began the following day, PHOTOGRAPHS BY BOB ADLER 15
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation / IOUC Summit //
powering small devices.
HOT TOPIC: The panel also dis- COMMUNITY cussed the challenges of IoT. Chin asked, “How INTERNET many people have a wire- less router at home?” and many hands went up. But OF THINGS when he asked how many
people had updated IN ACTION JAVA Clothes that monitor your baby’s vital signs. their router firmware Prescription medicine bottlesthat remind you in the last six months, to take your pills (and can tell others when you most hands dropped. don’t). Wind turbines that turn themselves With more devices come Summit attendees have a healthy discussion over lunch. on in anticipation of high energy usage. Traffic more software, more
lights that adjust to traffic conditions. Trash management, and more TECH JAVA cans that send a text when they are full. These vulnerability. Security is with a session on the future with the JCP and JSRs, a real issue, especially for of Java. Oracle’s Mark including the Adopt-a-JSR are all examples of the rapidly growing world devices and industries Reinhold, Georges Saab, program. “Adopt-a-JSR has of the Internet of Things (IoT). There is a lot that haven’t had to con- Henrik Stahl, and Simon been a great push and has of interest in this topic, so it wasn’t surprising sider it before. And it’s Ritter hosted an interactive put the JCP back in the spot- that the Internet of Things session was full at not you get hacked, but discussion of what’s next light,” said VanCura. “There the IOUC Summit. if . “One good thing ABOUT US for the Java EE, Java SE, and is more interest from JUGs, when Oracle’s Sharat Things. Most computers about Java in the IoT Java ME platforms (beyond more people are involved, Chander assembled a already talk to a “back space,” Suri commented, Java EE 7, Java SE 8, and Java and there are more discus- panel of experts to dis- end,” so what makes IoT “is that it provides a level ME 8). Topics included the sions.” One way that many cuss IoT: Bruno Souza, different? “IoT makes of abstraction that allows Internet of Things, big data, JUGs are involving their SouJava president computers invisible,” for better security and Project Sumatra, OpenJDK, members is through hack- and Java Community Souza explained. “They quicker updates. That’s alternative languages for the athons. Badr Elhouari of the Process (JCP) Executive are everywhere and all especially important in Java Virtual Machine, mod- Morocco Java User Group Committee member; connected. You don’t devices that are out in the ularity, adoption of the Java said that getting a hack- Stephen Chin and Jai Suri think of your refrigera- field for years.” platform, and more. athon going is easy. “Have a of Oracle; Ian Ferguson tor as a computer.” Suri Whatever it is, IoT is In a session on JUGs and speaker,” he said, “and then of ARM; and Richard talked about the mul- coming fast. New applica- the JCP, Heather VanCura do a hands-on activity at blog Niemiec, Midwest Oracle titude of devices and tions are happening daily. and Patrick Curran of the JCP your JUG meeting.” Users Group leader. networks involved, the The coolest IoT innova- led a discussion about how Other topics of discus- The panel started by challenge of data in many tion hasn’t even been JUGs can be more involved sion were barriers to par- defining theInternet of different formats, and thought of yet. PHOTOGRAPH BY BOB ADLER 16
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation / IOUC Summit //
GAMIFICATION FOR COMMUNITY USER GROUPS At the Gamification session at the IOUC Summit, user group lead- ers discussed how to drive mem- IN ACTION JAVA bership. Typically, they give away software licenses, books, and goodies to encourage attendance at monthly meetings. Others have used gamification to get their communities to brainstorm on TECH JAVA SouJava’s Bruno Souza (center) grilled up a traditional Brazilian ArabOUG Leader Mohamed Chargui talks feast to welcome Java user group leaders to the summit. mascot names, or post pictures about his experience using gamification. and comments on social media. ticipation in the JCP for those to promote experimenta- Hackathons also require the use of who don’t speak English and tion. By participating in the similar techniques to keep attendees motivated to create applications over ways to work around this; Adopt-a-JSR program, said several days. SouJava Leader Bruno Souza said that his Java user group (JUG) successfully ran hackathons that combined brainstorming, team building, lack of awareness of the JCP; SouJava’s Souza, your mem- ABOUT US and complexity in getting bers will feel like they are training, hacking sessions, and prizes to keep participants engaged. involved. However, Adopt- participating and they will Gamification lets you turn life into a game, said Houston JUG LeaderJim a-JSR is helping to lower the learn more about Java. Bethancourt. The key advantages are driving audience engagement, mak- barriers to participation and Other session topics dur- ing the user experience more enjoyable, and getting users to come back. ing the summit The forum platform Stack Overflow is a great example of running a thriv- included gamifi- ing community of developers with its point systems, he said. Contributors cation, managing get rewarded with points for their useful entries, and visitors easily find the your community, most-relevant and best-rated entries. getting the most The ArabOUG has implemented a point system to keep its community out of Java.net, and active. The group gives out points to its members, who contribute applica- feedback about tions, articles, and translations. It partnered with training organizations and blog JavaOne. other services to give its members free training and services in exchange for points. As a result, members don’t have to pay for services using online payments, which governments in many countries in North Africa and the Java user group leaders share their reasons for attending the summit. Middle East don’t allow.
PHOTOGRAPH COURTESY OF STEPHEN CHIN; VIDEO BY BOB ADLER 17
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation / COMMUNITY
IoT Developer Challenge IN ACTION JAVA From March 3 to May 30, 2014, Oracle Technology Network is hosting an Internet of Things (IoT)
Developer Challenge. Open TECH JAVA to online submissions, the HACKING AT challenge gives developers the chance to submit an innovative, ground- CAMPUS PARTY breaking, business-ready IoT project using embedded Java and any hardware, whether it Brazilian Java user group SouJava ran a is computer boards such as the Raspberry Pi,
Raspberry Pi and Java hackathon from ABOUT US sensors, or other IoT technologies. Members of January 30–February 1, 2014, at Campus Clockwise from top left: Duke is ready to hack; winning teams will each receive a JavaOne 2014 Party, the weeklong technology gathering Yara Senger welcomes participants; hackers pass, plus up to US$2,000 for flight and hotel of geeks, developers, gamers, scientists, work on their projects. expenses. A student category with prizes is also and students in Brazil. Sponsored by Oracle available, thanks to Oracle Academy. Technology Network, the hackathon was During the challenge period, Oracle Tech- designed for enthusiasts who wanted to cre- ects. Onsite experts were available to help nology Network will offer free online training ate Internet of Things (IoT) projects with the participants. These veteran Java developers on IoT, the Raspberry Pi, embedded Java, and Raspberry Pi and Java. The objectives were for of web, enterprise, and embedded develop- more. By registering, you will enter a chance to attendees to learn, practice, and innovate. ment included GlobalCode Founder Vinicius win a Raspberry Pi. Oracle Java evangelist Angela Caicedo Senger, Senior Developer at Vitae Futurekids opened the hackathon with an overview of Brazil Rubens Saraiva, SouJava Leader Bruno blog IoT and Java development. Over three days, Souza, Java Champion Yara Senger, Oracle participants formed teams, brainstormed, Product Manager Bruno Borges, and Senior attended training, received a kit from the Mobile Developer at Mobilidade é tudo organizers, and hacked on their own proj- Ricardo Ogliari.
PHOTOGRAPHS COURTESY OF SOUJAVA ART BY I-HUA CHEN 18
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation /
JAVA CHAMPION PROFILE COMMUNITY FEATURED JAVA USER GROUP HOWARD LEWIS SHIP
doing payrolls for his invoicing, inventory, interested to see how JUG Münster CPA business. It came accounts payable, people are using my with a “Battleship” and accounts receiv- open source projects. Java User Group Münster was game you played by able business suite. It is fascinating that so formed in December 2008 printing the map on An early programming much innovative work by Thomas Kruse and Gerrit the line printer and accomplishment was happens in smaller IN ACTION JAVA Grunwald (inset), who continue entering shots using developing an auto- cities, not just the to lead the group today. Howard Lewis Ship is the keyboard. matic zip-code-to- larger technology cen- Münster’s geographic loca- a Java EE and Clojure Java Magazine: What UPS-zone lookup that ters. It’s everywhere! tion posed some challenges developer, author, was your first com- saved my Dad’s order Java Magazine: What as the Java user group (JUG) was getting blogger, and speaker. puter and program- entry team lots of time are you looking for- started. Münster is only about 50 km away The creator of the ming language? and tedious effort. ward to? TECH JAVA from Germany’s populous Ruhr area, which Apache Tapestry open Ship: I had access to Java Magazine: What Ship: It will be inter- has some long-established larger JUGs that source web frame- our high school’s PDP- do you enjoy for fun esting to see the func- included members from the Münster area. work, he became a 11 when I was in junior and relaxation? tional programming Nevertheless, the JUG continued to meet; Java Champion in high. I started out Ship: I have a four- aspects of Java SE 8 go Kruse and Grunwald continued spreading the February 2010. by entering and run- year-old and a one- mainstream. For some word; and JUG Münster’s membership steadily Java Magazine: Where ning BASIC code from year-old, so fun and developers, it will open ABOUT US grew to the current level of 280 members. did you grow up? David Ahl’s BASIC relaxation are mostly their eyes to the limi- JUG Münster has had an active meeting Ship: I grew up Computer Games. I “something I used tations that have been and events schedule from the start. “Since we south of Boston, also experimented to do.” I enjoy skiing, around them. I fear, started in 2008, we’ve met every two weeks for Massachusetts, and with Pascal and Logo photography, read- though, that for many a so-called ‘Java Roundtable,’” says Grunwald. got my CS degree at on an Apple, and even ing, flying stunt kites, others it will mostly “In addition, we arrange 10 events each year Worcester Polytechnic wrote some games and playing board and provide a new way to where we invite external speakers; and we have Institute. that had a smidgen of card games. do things wrong. an annual event for Software Freedom Day.” Java Magazine: When 6502 assembly code. Java Magazine: What But what I’m really Developers who come to Java after having did you first become Java Magazine: What “side effects” of your looking forward to worked with other languages are often sur- interested in comput- was your first profes- career do you enjoy is the kids being old prised by Java’s community aspect. “Java is not ers and programming? sional programming the most? enough to take care a young language/environment anymore, but Ship: My dad bought job? Ship: I love to speak at of themselves in the blog still has the greatest community that I know, a Burroughs B800 Ship: I helped my conferences and see morning, so that I can and one reason for this is the Java user groups… computer, a beast dad after school, the work people are sleep in every once in so let’s keep this alive,” says Grunwald. I called “HAL,” for customizing an doing. I’m especially a while. 19
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation /
THE JAVAFX ANDROID COMMUNITY COMMUNITY PROJECT Vos blogged about the project’s their applications on Android, which background, present, and future in is very cool.” IN ACTION JAVA the post “JavaFX and Android.” There The JavaFX Android Community he notes that with respect to porting Project currently has 4 active software to unsupported platforms, developers. About 20 developers “developers are usually better in have contributed feedback that JUG doing it themselves than in com- has resulted in patches and new plaining. With the JavaFX code being code. But, as the project’s task list Tour TECH JAVA open-sourced over the past years, and reveals, there’s a lot more work to Oracle Technology with lots of work already being done do. So, the project is actively seeking Network is hosting by Oracle people, a community effort broader participation. a Java user group for porting JavaFX to mobile platforms “All contributors are very wel- (JUG) tour follow- turned out to be a viable option.” come,” Vos says. “Tool support is ing the launch of You can findinstructions for high on our list. People who can Java 8. Events will be ABOUT US building and deploying JavaFX help with integrations with IDEs and held at JUGs across The JavaFX Android Community applications on the Android plat- packaging tools are very welcome. the globe, with Java Project seeks to make JavaFX code form on the project site. The proj- Also, native Android developers are evangelists and Java runnable on Android devices. The ect’s source code is available in very much appreciated, especially Champions talking project was started by Johan Vos the Bitbucket android-graphics-rt people with feedback on how to about key features in (@johanvos) after he talked with repository. You can download a complete the last mile toward send- Java 8. Follow @java JavaFX architect Richard Bair prebuilt JavaFX Android runtime, or ing an application to the Play store. for more information. (@richardbair) at Devoxx 2013. The you can build it yourself. Developers with Gradle knowledge project got off to a fast start due to The project has come a long way are also very welcome.” work that Oracle’s Tomáš Brandalík in a relatively short time. In his blog, If you’d like to contribute to the had already done on the native parts, Johan says, “Most of the JavaFX JavaFX Android Community Project, and the Java 7 backport maintained 8 Ensemble applications are now visit the JavaFXAndroid Google blog by Stefan Fuchs. “After only a few working out of the box on Android Group, or contact Vos. weeks, we delivered a JavaFX runtime devices. I’ve seen many reports from for the Android platform,” says Vos. JavaFX developers demonstrating
PHOTOGRAPH BY TON HENDRIKS 20
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation /
4Developers GeeCON 2014 APRIL 7 MAY 14–16 WARSAW, POLAND KRAKOW, POLAND COMMUNITY 4Developers is a technical confer- With its motto “Let’s move the Java ence intended for developers, archi- world,” the conference focuses on tects, testers, coders, team leaders, Java technologies, dynamic lan- project managers, IT departments, guages, rich internet applications, as well as all IT students. The event is enterprise architectures, patterns, designed for both professionals and distributed computing, software
Paris, France IN ACTION JAVA amateurs working in different tech- craftsmanship, and more. nological fields. JEEConf Great Indian Developer Summit MAY 23–24 (GIDS) KIEV, UKRAINE APRIL 22–25 JEE is the largest developer con-
BANGALORE, INDIA ference in Ukraine. It focuses on TECH JAVA Twenty-five thousand develop- Java technologies for application ers are expected at this four-day development. conference. At the dedicated Java track, top experts Stephen Chin, Devoxx UK Venkat Subramaniam, Erik Hatcher, JUNE 12–13 Kito Mann, Pratik Patel, and oth- LONDON, ENGLAND
ers will talk about Java 8, lambdas, Devoxx UK is part of the Devoxx fam- ABOUT US InvokeDynamic, the Raspberry Pi, ily of conferences. Run by the local EVENTS JavaFX, and more. Java community, this developer con- ference consists of a packed sched- Devoxx France APRIL 16–18 JAX 2014 ule of presentations, hands-on labs, PARIS, FRANCE MAY 12–16 quickies, and Birds-of-a-Feather MAINZ, GERMANY (BOF) sessions. Top local and inter- Now in its third year, Devoxx France brings together 1,500 Java This conference on Java and the national speakers present an array enthusiasts in an adrenaline rush of technical content, training, enterprise focuses on current and of Java topics on web, mobile, Java and community networking. The conference focuses on Java, web future trends in web, Android, soft- Virtual Machine languages, agile, technologies, mobile, cloud, agile, Java Virtual Machine languages, ware architecture, cloud, agile man- and more. and entrepreneurship. This year’s theme, “Born to Be,” is about agement methods, big data, and blog being and becoming a developer. more. More than 180 speakers will present 230 talks and 20 day-long sessions on Java 8, Java EE, JavaFX, embedded Java, Java core, and agile. PHOTOGRAPH COURTESY OF WILHELM LAPPE ON FLICKR 21
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //java nation /
JAVA BOOKS COMMUNITY JAVA IN ACTION JAVA
JAVA SE 8 FOR THE REALLY JAVA 8 LAMBDAS JAVA: THE COMPLETE JAVA FOR DUMMIES, NightHacking IMPATIENT By Richard Warburton REFERENCE, NINTH EDITION 6TH EDITION By Cay S. Horstmann O’Reilly (April 2014) By Herbert Schildt By Barry Burd Tour Addison-Wesley Professional If you’re an experienced Oracle Press (April 2014) Wiley (March 2014) JAVA TECH JAVA Java Evangelist Stephen (January 2014) Java programmer, Java 8 In Java: The Complete In this update of a best- Chin is making his way Author of Core Java Lambdas shows you Reference, Ninth Edition, selling book, veteran across Europe—visiting and internationally how to make use of your Herbert Schildt uses the author Barry Burd shows Java user groups, con renowned Java expert existing skills to adapt clear, concise, uncom- you how to create basic ducting interviews, and Cay S. Horstmann con- your thinking and your promising style that has Java objects and clearly broadcasting it all. Chin cisely introduces Java codebase to use lambda made the previous eight explains when you should SE 8’s most valuable new will be talking with com- expressions properly. editions so successful simply reuse existing code. ABOUT US munity experts about Java features (plus a few Java Starting with basic exam- worldwide. This compre- He explores how Java SE 8 8, the community, the SE 7 innovations that ples, this book is focused hensive volume covers the offers more-robust func- future of Java, the Internet haven’t gotten the atten- solely on Java SE 8 lan- entire language, including tionality and new features of Things, and more. Join tion they deserve). If you’re guage changes and related its syntax, keywords, and such as closures to keep him at an event or watch an experienced Java pro- API changes. Lambdas fundamental program- Java competitive with more his sessions online at grammer, Horstmann’s make a programmer’s job ming principles. Schildt syntax-friendly languages nighthacking.com. practical insights and easier, and this book will also presents detailed like Python and Ruby. He sample code will help you teach you how. Coverage information about Java’s also covers object- quickly take advantage includes introductory core libraries and key oriented programming of these and other Java syntax for lambda expres- programming techniques. basics with Java, code language and platform sions, method references Of course, coverage of new reuse, the essentials of improvements. that allow you to reuse features added by Java creating a Java program blog existing named methods SE 8, such as lambda using the new JDK 7, creat- from your codebase, and expressions and modules, ing basic Java objects, and the collection library in is included. new Eclipse features. Java SE 8. 22
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Goldman Sachs’ Donald Raab (left), manager of the JVM
Architecture team, COMMUNITY and John Weir, global head of Application Platforms, talk at the company’s New York City office. JAVA IN ACTION JAVA TECH ABOUT US
JCP Executive Series Java 8 Is Here
Goldman Sachs’ GS Collections ohn Weir is the global head of Application Platforms at Goldman JSachs. In 2011, Goldman Sachs was Leverages Lambdas elected to the Executive Committee of the Java Community Process (JCP), with Goldman Sachs’ John Weir and Donald Raab discuss the creation of GS Collections, Weir as the firm’s representative. He blog the impact of Java SE 8’s lambda expressions, and how their work interacts with previously represented Goldman Sachs the JCP. BY STEVE MELOAN on the FpML Standards Committee for Credit Derivatives and was also on the PHOTOGRAPHY BY LAURA BARISONZI/GETTY IMAGES FpML Architecture Committee. He joined 23
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Goldman Sachs in 1997 and has held a and sometimes tens of thousands of COMMUNITY number of senior technology roles. He iteration patterns implemented with was named technology fellow in 2004 handwritten for loops. and managing director in 2008. Prior to Java SE 8, in the collec- Donald Raab manages the JVM tions space, there was no rich API. Architecture team, which is part of Developers had to re-create patterns the Enterprise Platforms group in the again and again. Our goal was to pro- Technology division at Goldman Sachs. vide a functional API that would reduce JAVA IN ACTION Raab serves as a member of the JSR 335 duplicate code by separating the Expert Group (Lambda Expressions for “what” from the “how” in a developer’s the Java Programming Language) and code. We also wanted to leverage paral- is one of the alternate representatives lelism using the fork/join library, allow- for Goldman Sachs on the JCP Executive ing developers to optimize performance Committee. He joined Goldman Sachs in across multiple processor cores. JAVA TECH 2001 as a technical architect on the PARA The API for GS Collections was heavily team. He was named technology fellow influenced by my experiences program- in 2007 and managing director in 2013. ming in Smalltalk, which had useful methods like select, reject, and collect. Java Magazine: Tell us about the genesis Over the years, we’ve added methods Raab: Internal iterators reduce errors Weir tackles a problem of GS Collections. When did you begin like flatCollect, groupBy, partition, and hide the implementation details on the whiteboard, while Raab looks on.
work, and what were your initial goals? and zip, which were influenced by of collections they’re operating across. ABOUT US Raab: GS Collections began in 2004 as our experiences with languages like They relieve the developer from the a Goldman Sachs internal project called Haskell, Ruby, and Scala. There are also responsibility of optimizing the various CARAMEL, which stood optimized replacements for datatypes being processed. An inter- for collections, arrays, map REALITY CHECK the JDK Collections classes, nal iterator is passed an operation to iteration library. We were “Innovation needs to like HashMap, ArrayList, and perform, and the iterator applies that dealing with very large Java HashSet. GS Collections is operation to every element in the heaps, on the order of ten be carefully vetted tuned for both large- and data collection. gigabytes to a hundred by the community small-scale performance. For example, if one collection is being gigabytes. And in these It’s ready for Java SE 8 transformed to another, and I know the spaces, we operated on through the JSR lambdas today, but it also target is the same size as the source, large collections to process process.” works with Java 5 through it can be presized in the algorithm, so lists, sets, and maps that —John Weir, Global Head Java 7. the developer doesn’t have to handle blog had millions or even hun- of Application Platforms, Java Magazine: Internal implementation details. This approach dreds of millions of ele- Goldman Sachs iteration is a key concept simplifies code and promotes reuse. ments. The codebases were for GS Collections. Why is In the Java space, most developers very large—with thousands it so powerful? implement what’s called eager iteration, 24
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Collections? Are there other Java SE 8 Collections testing hierarchy by COMMUNITY features of interest? building-in default methods and Raab: GS Collections was developed behaviors. This will allow the mixing at the outset around the concepts and matching of different testing con- embodied in lambda expressions. cerns across the framework. Having lambdas built into Java SE 8 is Method references, another Java SE 8 absolutely terrific; we will be able to feature closely tied to lambdas, will also leverage them extensively across our benefit GS Collections. They provide an JAVA IN ACTION APIs. We have 90+ functional methods even more concise and readable format that can be called by passing lambdas. for leveraging functional APIs. This Java SE 8 feature will deliver a The following is a method reference huge upside. We’ll be able to delete a code example from our GS Collections lot of code. I imagine a savings between Kata Java 8 Solutions: 20 percent and 30 percent. JAVA TECH For example, the Select pattern /** handwritten in Java SE 7 looks like this: * Aggregate the total order values by item. List
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Optimizations have been made within method that replaces getDateTimeMillis COMMUNITY the language and the JVM [Java Virtual from Joda-Time. The new method to Machine] to take advantage of these extract time in milliseconds ran about innovations. three and a half times slower and cre- Java Magazine: When did GS ated some garbage on the JVM. The Collections become open source? Tell Goldman Sachs community uncovered us about that process. this due to our extensive codebase, and Raab: We open-sourced GS Collections we were able to offer feedback through JAVA IN ACTION in January 2012. Before doing that, we our role in the Executive Committee. open-sourced it internally. At Goldman We also participate directly in the JSR Sachs we have a large number of process. We’ve been involved as con- developers and applications; it’s a very tributing members in lambda expres- collaborative and consensus-driven sions, the Collections API, the JCache organization. We wanted to find out API, and also the Identity API. We also JAVA TECH if there was a viable community of participate in debates and discussions potential users for GS Collections. And as to how the JCP process should oper- we discovered that the demand was ate, evolve, and move forward. definitely there. Java Magazine: JCP member companies In addition to open-sourcing the col- have diverse interests and priorities. lections library, we decided to include How are these needs best orchestrated
the associated training libraries, the within the JCP? ABOUT US GS Collections Kata, which is a great Weir: One of the great strengths of the Raab and Weir look at way to learn not just GS Collections Executive Committee is its breadth of the effect that lambda but also Java SE 8 lambda expressions organizational participation—from -ven expressions have on and method references. dors and redistributors of the Java plat- their code. Java Magazine: How has Goldman form, to framework and library provid- Sachs contributed to the JCP process? ers, to Java user groups [JUGs] and end Weir: We’re engaged in the JCP pro- users. It’s an excellent representative Java Magazine: What is the proper bal- cess at several different levels. Our role community all sitting at the virtual table ance between promoting standards and with the Executive Committee involves with the goal of guiding Java’s evolution. promoting innovation? reviewing JSRs at various stages. And That goal unifies the community, in Weir: We all want innovation. And inno- internally we leverage our network spite of some vigorous competition on vation is always there. It’s a fundamen- to interact with several thousand the vendor side. We try to maintain tal ingredient when developers solve blog Goldman Sachs developers to get their a cohesive Java platform that doesn’t problems. Donald talked earlier about JSR feedback. For example, on JSR 310, become fragmented and continues to CARAMEL evolving into GS Collections. the new and improved Date and Time accommodate a broad array of func- That software resulted from develop- API, we uncovered a problem with a tional demands. ers striving for a simplified, transpar- 26
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Raab: ent, and more engaging API. In the (JSPA). Because this is a legal contract, I would echo John’s comments COMMUNITY Java ecosystem, we have a great degree there can be restrictions for some regarding our commitment to Java. of openness, which spurs innovation. companies. Consequently, some Java We’re working with JUGs globally, There is a collective wisdom that comes developers don’t have a mechanism to including groups in New York, London, from talented people solving real-world become involved. Having seen the ben- and Hong Kong. The community is problems. But innovation needs to efit from large numbers of developers huge and diverse, which is fantastic. be carefully vetted by the community engaged in software evolution, with GS We’ve also just signed the agree- through the JSR process, to make sure Collections, we’re particularly invested ment to participate in OpenJDK, and
CHANGE MAKER JAVA IN ACTION that a diverse range of needs are being in the process as a core value. So we’re we look forward to making direct con- “[Lambda met. Millions of developers are affected intent on broadening involvement, tributions. We want to give back to expressions] will by these standards. The platform has to but it must be done in a thoughtful the open source community through deliver a huge function as an integrated whole. and methodical way that reflects the this process. The work that was done in JSR 348 best interests of the community. JSR The Java platform is a very impor- upside. We’ll be to improve transparency across the 348 is tackling that. I believe that tant element of the Goldman Sachs JAVA TECH able to delete JSR process has been very beneficial. It increasing participation will increase infrastructure. We’re committed to requires that Expert Groups use pub- the rate at which new innovations can making sure that it continues to evolve a lot of code. lic mailing lists and maintain a public be integrated into the Java platform. and develop to provide benefits for the I imagine a Issue Tracker. JSR 348 mandates that There are millions of Java developers community and our firm. all JCP members and members of the out there, and we’d like to give them savings between public must have the opportunity to all the opportunity to participate in
20 percent and view, comment on, and participate in the process. MORE ON TOPIC: ABOUT US the process. These developments will Java Magazine: Any closing remarks? 30 percent.” Java 8 make the JSR process a lot less opaque, Weir: We enjoy engaging in the JCP Is Here —Donald Raab, and will extend the reach to as broad a process. Our role on the Executive JVM Architecture community as possible. Committee is a high-priority task. Steve Meloan is a former C/UNIX soft- Team Manager, Java Magazine: What are your views on Frequently we leverage our internal JUG Goldman Sachs ware developer who has covered the web improving JCP participation? to comment on JSRs. and the internet for such publications as Weir: The Executive Committee is cur- JSR participation is beneficial for Wired, Rolling Stone, Playboy, SF Weekly, rently debating the topic of how to us, and also beneficial for the broader and the San Francisco Examiner. He improve participation. A wide range Java enterprise. Donald mentioned the recently published a science-adventure of enterprises—from pharmaceuti- GS Collections Kata. People are using novel, The Shroud, and regularly cals, to financial services, to consumer the training materials we created for contributes to The Huffington Post. products—have significant numbers GS Collections and applying them to blog of Java developers. For an individual to general training for lambda expres- join the JCP and participate in the pro- sions and Java SE 8. We’re pleased to LEARN MORE cess, their employer must sign the Java have made contributions to the • GS Collections Specification Participation Agreement greater community. • lambda expressions 27
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 Guilherme Spina (left), managing director at V2COM, talks with Leonardo De Moura Rocha Lima, chief
technology officer, COMMUNITY at the company’s headquarters in São Paulo, Brazil.
Java 8 Is Here
he science fiction films of -yes JAVA IN ACTION teryear often depict a world of T pervasive automation. Computers are everywhere, and people are con- stantly interacting with them. Other, perhaps more-prescient cinematic visions foresee chic living environments JAVA TECH without a CPU in sight. The gadgets work autonomously, with circuits and controllers hidden from view. Fast-forward to the present. The technologies that we use every day are fading into the background as the ABOUT US Internet of Things ushers in a new era of intelligent, seamlessly connected devices. With embedded microproces- sors and a wireless communications fabric, today’s “computers” require less intervention than ever before, even as they enable a higher degree FROM SMART GRIDS of automation. At the forefront of this transformation is V2COM, a leading Latin American provider of smart grid TO MICROBREWS technologies and advanced metering V2COM uses Java to connect millions of intelligent devices. infrastructure. blog “The Internet of Things is here, now,” BY DAVID BAUM AND ED BAUM says Guilherme Spina, managing direc- tor at V2COM. “This is an interesting PHOTOGRAPHY BY PAULO FRIDMAN phase as IT moves from the data cen- 28
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 COMMUNITY
V2COM JAVA IN ACTION v2com.mobi Industry: High technology/ energy Location:
São Paulo, Brazil JAVA TECH Employees: 50 Oracle technologies used: Lima checks in with Oracle Java ME V2COM colleagues. Embedded, Oracle Java SE Embedded, ABOUT US Oracle Utilities Meter Data Management, GlassFish Server Open Source Edition, Oracle Database, Oracle WebLogic Server ter and the desktop out to the streets FROM STARTUP TO INDUSTRY connects people to automate remote to be embedded in all types of things. LEADER WITH JAVA devices. For example, in the energy industry, When it was formed in 2002, V2COM One of the first orders of business companies are replacing dumb meters was—in Spina’s words—a “bootstrap for V2COM’s founders was to choose a with smart meters that not only enable startup.” The fundamental ideas upon software platform to manage the inter- people to conserve energy but also to which the company is based were for- actions between these remote devices play an active role in providing other mulated during the mobile phone phe- and legacy systems. “We chose Java blog services, such as internet connectivity nomenon that swept through Brazil from the beginning,” Spina says. “We and in-home automation solutions. Java in the 1990s. Spina and his colleagues liked the speed of development and is key to creating and delivering these realized they could leverage the same ability to reuse components by writing solutions to our clients.” communications infrastructure that code once and deploying it many times, 29
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 supporting functionality on both the “A complex set of rules governs these agement of energy distribution—some-
mobile side and the server side. Also, devices, so we need a software infra- thing for which Java is innately suited. COMMUNITY we found that the majority of the peo- structure that allows us to code in a way ple we hired were proficient with Java.” that is manageable, expandable, scal- LAYING THE GROUNDWORK Spina and his colleagues also favored able, and not too complex,” Spina says. FOR SMART CITIES Java for its high level of support for “Our system embeds Java in all these In the energy sector, V2COM’s inno- object-oriented programming and for different computing platforms, from vative solutions use Gemalto M2M’s its open source development environ- the back-end applications to the edge Cinterion modules with Oracle Java ment, which makes it easier to add devices and pole-top smart concentra- ME Embedded to share energy usage intelligence to a wide variety of end tors, creating an environment of distrib- data over cellular wireless networks. JAVA IN ACTION units such as meters, transformers, and uted processing.” These modules communicate with Lima (center) and circuit breakers. These components Today V2COM offers hardware, soft- V2COM’s Intelligenceware Suite, which Spina (right) get a work together to manage energy flow at ware, and services that can reduce uses Oracle Java SE Embedded, Oracle project update from homes and businesses and report back losses and increase water and energy Utilities Meter Data Management, and a V2COM team to the energy distribution systems at a efficiency, connecting more than 1 GlassFish Server Open Source Edition member. utility company’s head office. million devices on its platform. Spina to transmit meter and sensor data to JAVA TECH believes the electric power back-end utility systems. industry is ripe for disrup- One of V2COM’s most successful tion, as analog distribution projects was for Elektro, an energy dis- systems, control mecha- tribution company in Brazil controlled nisms, and usage meters by Iberdrola Group. Elektro, which are replaced by computer- serves 2.3 million clients and reaches ABOUT US ized devices. Smart grids 5.5 million people, enlisted V2COM to can support millions of automate its commercial and industrial remote intelligent devices metering processes. Together the com- that handle complex panies created a flexible solution that is operations in the field, all modernizing electrical power delivery connected to a data center in Latin America. The project includes through smart concentra- intelligent communication modules tors. These massive, intelli- connected to legacy electronic meters gent networks allow elec- through the public cellular network. In tric companies to better addition to improving energy efficiency manage the flow and con- and decreasing energy loss, the solution sumption of energy, with has helped Elektro improve its remote blog less equipment and fewer monitoring capabilities and respond to IT and field resources. And incidents faster. It also helps the com- for that, Spina explains, pany detect fraud and field installation you need dynamic man- problems that weren’t visible before. 30
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 V2COM and the Java COMMUNITY Community Process All Java technology is developed through the Java Community Process (JCP), an open, industry-led orga- nization chartered with evolving the Java platform. V2COM is on the JCP Executive Committee, through which it has influenced the Java ME 8 specification.
V2COM owes its involvement with the JCP to a for- JAVA IN ACTION tuitous seating arrangement that placed V2COM’s chief technology officer, Leonardo De Moura Rocha Lima, next to Terrence Barr, principal product manager for Java ME, at an Oracle Technology Network community event for Java developers in Brazil a few years ago.
“As we chatted about V2COM’s product strategy, JAVA TECH technical requirements, and use cases, it became clear to me that the company’s general concept and approach to the solution was something that Oracle should sup- port in its architecture,” Barr recalls. Barr and Lima kept in touch. When the JCP program Smart meters line office later contacted Barr looking for candidates for the the walls of the lab at V2COM Executive Committee, he suggested V2COM as a likely ABOUT US headquarters. member. “They have a lot of experience with embedded Java,” Barr says. “We like their vision for the Internet of Things, and we are confident the community will benefit from their contributions to the standardization process.” V2COM and Elektro consider the other for investments, jobs, and talent. For example, V2COM’s work with modularization venture to be an important step toward Technology is the best answer to man- makes it easier to partition an application across a wide a much more extensive set of dis- age these challenges.” range of remote devices and reuse the code in differ- tributed computing solutions. “The V2COM’s smart grid solutions are ent projects. It also simplifies software updates because Elektro engagement is exciting because the first vector for smart cities that will developers only have to update a single module, rather it lays the groundwork for smart-city have smart street lighting, smart traffic than multiple modules tailored to each type of field device. projects,” says Leonardo De Moura control, smart video monitoring, and “V2COM’s input has been extremely valuable,” Barr blog Rocha Lima, chief technology officer other remote intelligent devices shar- says. “They are helping adapt the Java ME platform to at V2COM. “Cities face huge chal- ing the same architecture and working support a variety of Internet of Things use cases.” lenges including congestion, pollu- in an orchestrated fashion. Elektro is tion, blackouts, crime, debt, and ris- using V2COM’s solution as a test bed ing costs, while competing with each for these highly automated cities. 31
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 “The backbone of tomorrow’s smart predicts will include 26 billion con- Through the JCP, V2COM contributed
cities is the distribution network of the nected devices by 2020. key concepts to the Java ME 8 specifi- COMMUNITY electrical utility,” Lima explains. “Java is Beyond the modernization of Brazil’s cation. (See the “V2COM and the Java the connecting fabric.” energy infrastructure, says Spina, Community Process” sidebar.) Spina predicts that Brazil will deploy Java will play a key role in connecting V2COM’s work with Java took a as many as 60 million smart meters and enabling the Internet of Things refreshing turn when company directors over the next 10 years. “Java is a good on a global scale. In the meantime, as realized they could use the same distrib- fit for this massive project because it is V2COM’s distributed computing uted infrastructure to accurately monitor available both on the embedded devices model transforms the energy sector, and control refrigerator temperatures—a and on the server side,” Lima adds. “It’s embedded Java technology is estab- crucial variable in brewing beer. JAVA IN ACTION the same technology, the same lan- lishing new patterns and precedents for “Our home-brew project is just one guage, and the same feature set.” many industries. example of how flexible this technol- For example, just as Java took com- ogy can be,” Lima says. “In addition to JAVA 8 IN THE WORLD OF plexity out of processes and operat- monitoring beer temperature, it could CONNECTED DEVICES ing systems, it will eventually simplify be used in medical laboratories to con- Left to right: JAVA TECH Guilherme Vallerini, V2COM has come a long way since networks and network protocols. “Lots trol the temperature of vaccines or in Lima, and Spina 2002. Today, with more than 1 million of devices utilize proprietary networks. other sensitive environments.” taste the beer they devices connected to its platform, the But with Java, we can standardize,” Whether V2COM is monitoring elec- make at V2COM’s company is a significant contributor to says Spina. “The almost 10 million Java trical usage, the temperature of beer, or headquarters. the Internet of Things, which Gartner developers can easily start program- movements in a video field, it uses the ming for the Internet of Things without same basic Java infrastructure to com- having to learn a lot of complex net- municate between the end devices and ABOUT US work protocols. Today programming the central controllers. mobile apps is cool. Tomorrow it will be “It’s the same set of Java services up to Internet of Things solutions.” the application layer on the embedded New features in Java ME 8 are par- device,” Lima summarizes. “In the fast- ticularly important to this development. growing Internet of Things, Java can be “Java 8 permits a distinct separation of the common connecting technology for services,” Spina continues, “along with all these possible use cases.” modularization so we can run different services on the same virtual machines, MORE ON TOPIC: with a clearer boundary between them.” Java 8 It’s no coincidence that these features Is Here that are so valuable in delivering smart blog grid technology are now part of Java Based in Santa Barbara, California, David ME 8. V2COM shares its expertise as a Baum and Ed Baum write about innova- member of the Executive Committee of tive businesses, emerging technologies, Oracle’s Java Community Process (JCP). and compelling lifestyles. 32
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java /
How to Become an Embedded COMMUNITY Developer in Minutes Jump into programming the next big thing using embedded Java. ANGELA CAICEDO JAVA IN ACTION
BIO n my 10 years as a Java to build and where you are On the other hand, if you Embedded (at least not yet), I evangelist, I’ve never been planning to run your applica- are looking for an easy way to so if you still want to use more excited about a Java tion. This is critical, because connect peripherals, such as Oracle Java SE Embedded and release. Not only is Java 8 a there are different flavors of switches, sensors, motors, also work with peripherals, great release with cool new embedded Java that will fit and the like, Oracle Java ME you have to rely on external JAVA TECH features in the language your needs perfectly. Embedded is your best bet. APIs, such as Pi4J. itself, but it also provides If you are looking to build It has the Device Access API, In term of devices, great things on the embed- applications similar to the which defines APIs for some embedded Java covers an ded side, great optimizations, ones you run on your desktop, of the most common periph- extremely wide range from and really small specifica- or if you are looking for great eral devices that can be found conventional Java SE desk- tions. If you are a Java devel- UIs, you need to take a look in embedded platforms: top and server platforms ABOUT US oper and ready to jump with at Oracle Java SE Embedded, general-purpose input/output to the STMicroelectronics me into the new wave of which is derived from Java SE. (GPIO), inter-integrated circuit STM32F4DISCOVERY board, machine-to-machine It supports the same plat- (I2C) bus, serial peripheral Raspberry Pi, and Windows. technology—better said, into forms and functionality as Java interface (SPI) bus, analog- For this article, I’m going to programming the SE. Additionally, it to-digital converter (ADC), use the Raspberry Pi, not only next big thing— SHARED ROOTS provides specific digital-to-analog converter because it’s a very powerful let’s get started features and sup- (DAC), universal asynchronous credit-card-size single-board with the Internet of Oracle Java ports additional receiver/transmitter (UART), computer, but also because Things (IoT). SE Embedded platforms, it has memory-mapped input/out- it’s very affordable. The latest Before you small-footprint Java put (MMIO), AT command model costs only US$35. get started with supports the runtime environ- devices, watchdog timers, embedded pro- same platforms ments (JREs), it pulse counters, pulse-width Getting Your Raspberry blog gramming, you and functionality supports headless modulation (PWM) genera- Pi Ready Java 8 need to under- configurations, tors, and generic devices. In order to boot, the Is Here stand exactly what as Java SE. and it has memory The Device Access API is Raspberry Pi requires a Linux you are planning optimizations. not present in Oracle Java SE image on a Secure Digital 33
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java /
(SD) memory card. There is no hard Win32 Disk Imager to easily your location by selecting the address. Although this is not
drive for the computer. Instead, an create your image. Internationalisation option. required, I find it very useful COMMUNITY SD card stores the Linux image that Once you have your SD card 3. Set up the Raspberry Pi as a when using the Raspberry Pi the computer runs when it is pow- ready, you can turn on your headless (that is, without a headless. To set up the static ered on. This SD memory card also Raspberry Pi. The first time you monitor attached) embedded IP address, edit the /etc/ acts as the storage for other appli- boot your Raspberry Pi, it will take device by allowing access via network/interfaces file. An cations loaded onto the card. you to the Raspberry Pi Software Secure Shell (SSH). To config- example of this file is shown To configure your SD card, per- Configuration Tool to perform ure this, select the Advanced in Figure 1. form the following steps: some basic configuration. Here are option from the main menu. Now you are ready to connect to 1. Format your SD card. the additional tasks you should 4. Ensure that the Raspberry the Raspberry Pi. One option is to JAVA IN ACTION 2. Download Raspbian, a free perform: Pi always has the same IP use PuT T Y. An example of how to operating system based on 1. Ensure that all the SD card address by setting a static IP connect is shown in Figure 2. Debian that is optimized spe- storage is available to the cifically for the Raspberry Pi operating system by selecting hardware. the Expand Filesystem option. 3. Create a bootable image. You 2. Set the language and JAVA TECH can use applications such as regional setting to match ABOUT US
blog
Figure 1 Figure 2 34
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 1
public class Midlet extends MIDlet { COMMUNITY @Override public void startApp() { System.out.println("Started..."); }
@Override public void destroyApp(boolean unconditional) { JAVA IN ACTION System.out.println("Destroyed..."); } } JAVA TECH Download all listings in this issue as text Figure 3
Installing Embedded Java on the Putting Things Together embedded applications on your before it gets destroyed. The code Raspberry Pi One great option for creating your Raspberry Pi, you need to have the in Listing 1 just prints a text mes- Now, this is where you decide the embedded application is using the Application Management System sage on the device console. kind of application you want to NetBeans IDE with the Java ME (AMS) running. Through SSH, sim- ABOUT US run on your device. I personally SDK. Combining these two allows ply execute the following command: Turning on the Lights! love having fun with peripherals, you to test your application, even Now let’s do something a bit more so in this article I’m going to use before you run it on your device, by pi@raspberrypi sudo interesting, such as turning an LED Oracle Java ME Embedded, so I can using an emulator. You will be able javame8ea/bin/usertest.sh on and off by pressing a switch. leverage the Device Access API. to automatically transfer your code First, let’s have a look at the GPIO But remember, you can also run and execute it on your Raspberry Pi, Your First Embedded App pins on the Raspberry Pi (see Oracle Java SE Embedded on your and you can even debug it on the Oracle Java ME Embedded applica- Figure 3). Raspberry Pi. fly. All you need to ensure is that tions look exactly like other Java ME The GPIO connector has a num- Installing the Oracle Java ME the Java ME SDK is part of the Java applications.Listing 1 shows the ber of different types of connec- Embedded binary on the Raspberry platforms on your IDE. You need simplest example you can have. tions on it: Pi is very simple. Just use FTP to to enable the SDK in the NetBeans Your application must inherit ■■ GPIO pins transfer the Raspberry Pi distribu- IDE by selecting Tools->Java from the MIDlet class, and it should ■■ I2C pins blog tion zip file from your desktop to Platforms, clicking Add Platform, override two lifecycle methods: ■■ SPI pins the Raspberry Pi over the SSH con- and then specifying the directory startApp and destroyApp. These two ■■ Serial Rx and Tx pins nection. Then unzip the file into a that contains the SDK. methods will be invoked when the This means that we have several new directory, and you’re done. In order to remotely manage your application gets started and just options for where to connect our 35
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6 LED and switch; any of the private static final int LED1_ID = 23;
GPIO pins will work fine. COMMUNITY Just make a note of the pin ... GPIOPin led1 = (GPIOPin) PeripheralManager.open(LED_ID); number and ID for each device, because you will need this information to reference each device from your code. Let’s do some basic soldering and create the JAVA IN ACTION circuit shown in Figure 4. Note that we are connect- ing the LED to pin 16 (GPIO 23) and the switch to pin 11 (GPIO 17). A cou- Download all listings in this issue as text ple of resistors are added JAVA TECH to make sure the volt- age levels are within the ■■ Trigger: none, falling-edge, the pins when you are done, and required range. rising-edge, both edges, high- also make sure you turn your LED Now let’s have a look level, low-level, or both levels off (see Listing ).6 at the program. In the Figure 4 ■■ Initial value The whole class can be found Device Access API, there Then, we call the open method here. ABOUT US is a class called PeripheralManager It really can’t get any easier. using this configuration object, as Now, all we are missing is the that allows you to connect to any To connect the switch, we could shown in Listing .4 main MIDlet that invokes our peripheral (regardless of what it is) potentially use the sameopen We can also add listeners to the code. The startApp method shown by using the peripheral ID, which method on PeripheralManager, pins, so we will get notified every in Listing 7 will create an object simplifies your coding a lot. For but because we would like to set time a pin value changes. In our to control our two GPIO devices example, to connect to your LED, some configuration information, case, we want to be notified when (LED and switch) and listen to our simply use the static methodopen , we are going to use a slightly dif- the switch value changes, so we inputs, and the stopApp method and provide the pin ID 23, as shown ferent approach. First, we create a can set the LED value accordingly: will make sure everything is closed in Listing 2. Done! GPIOPinConfig object (see Listing ),3 (stopped) properly. To change the value of the LED which contains information such as button1.setInputListener(this); (to turn it on and off), use the the following: Sensing Your Environment setValue method with the desired ■■ Device name Then implement the value LEDs and switches are nice, but blog value: ■■ Pin number Changed method that will be called what is really interesting is when ■■ Direction: input, output, or both when events occur, as shown in we start sensing our surround- // Turn the LED on ■■ Mode: pull-up, pull-down, push- Listing .5 ing environment. In the following led1.setValue(true); pull, or open-drain It’s also important that you close example, I want to show how to get 36
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 7 started with sensors that use the Getting I2C Working on the 2 public class Midlet extends MIDlet{ I C protocol. Raspberry Pi COMMUNITY I2C devices are perhaps the most If you look at the Raspberry Pi pins private MyFirstGPIO gpioTest; widely available devices, and their again (see Figure 3), you will see
biggest advantage is the simplicity that there are two pins for I2C: pin 3 @Override 2 of their design. I C devices use only is the data bus (SDA) and pin 5 is public void startApp() { 2 two bidirectional open-drain lines: the clock (SCL). I C is not enabled gpioTest = new MyFirstGPIO(); Serial Data Line (SDA) and Serial by default, so there are a few steps try { Clock Line (SCL). we need to follow in order to make gpioTest.start(); JAVA IN ACTION Devices on the bus will have a it available to our application. } catch (PeripheralTypeNotSupportedException | specific address. A master control- First, use a terminal to connect PeripheralNotFoundException| ler sets up the communication to your Raspberry Pi, and then add PeripheralConfigInvalidException | with an indi- the following lines to the /etc/ PeripheralExistsException ex) { NOW IS THE TIME vidual compo- modules file: System.out.println("GPIO error:"+ex.getMessage()); If you are a Java nent on the bus } catch (IOException ex) { by sending out i2c-bcm2708 System.out.println("IOException: " + ex); JAVA TECH developer and a start request i2c-dev } you are ready to on the SDA line, } followed by the It’s very useful to have the jump into the new @Override address of the i2c-tools package installed, so the public void destroyApp(boolean unconditional) { wave of machine- device. If the tools will be handy for detecting try { device with that devices and making sure every- to-machine gpioTest.stop(); ABOUT US technology— address is ready, thing works properly. You can install } catch (IOException ex) { it responds with the package using the following System.out.println("IOException: " + ex); let’s get an acknowledge commands: } started with request. Data is } then sent on the sudo apt-get install } the Internet of SDA line, using python-smbus } Things (IoT). the SCL line to sudo apt-get install i2c-tools control the tim- ing of each bit Lastly, there is a blacklist file of data. called /etc/modprobe.d/ When the communication with raspi-blacklist.conf; by default SPI a single device is complete, the and I2C are part of this blacklist. blog master sends a stop request. This What this means is that unless simple protocol makes it possible we remove or comment out these to have multiple I2C devices on a lines, I2C and SPI won’t work on Download all listings in this issue as text single two-line bus. your Raspberry Pi. Edit the file and 37
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java /
remove the following lines: COMMUNITY blacklist spi-bcm2708 blacklist i2c-bcm2708
Restart the Raspberry Pi to make sure all the changes are applied.
Adding Sensors JAVA IN ACTION The BMP180 board from Bosch Sensortec is a low- cost sensing solution for measuring barometric pressure and temperature. Because pressure changes Figure 6 JAVA TECH with altitude, you can also use it as an altimeter. It ■■ What is the register’s address? Once again, the way we connect uses the I2C protocol and In our case, we are going to read programmatically to the device is a voltage in the range of the temperature value, and this using the PeripheralManager’s static 3V to 5V, which is per- Figure 5 register is located at address method open. In this case, we will fect for connecting to our 0xF6. (This is specific to the provide an I2CDeviceConfig object ABOUT US Raspberry Pi. sudo i2cdetect -y 1 BMP180 board.) that is specific to an I2C device (see Let’s go back to soldering to con- ■■ Do you need to configure any Listing ).9 The I2CDeviceConfig nect the BMP180 board to your You should be able to see your control registers to start sens- object allows us to specify the Raspberry Pi using the diagram device in the table. Figure 6 shows ing? Some devices are in a sleep device’s bus, address, address size shown in Figure 5. Normally, when two I2C devices: one at address 40 mode by default, which means (in bits), and clock speed. you use an I2C device, a pull-up and one at address 70. they won’t be sensing any data To take a temperature reading, resistor is required for the SDA until you wake them up. The we need to follow three steps: and SCL lines. Fortunately, the Using an I2C Device to Get the control register for our device is 1. Read calibration data from Raspberry Pi provides pull-up resis- Temperature address 0xF4. (This is specific to the device, as shown in tors, so a simple connection is all There are a few things you need to the BMP180 board.) Listings 10aand 10b. This is you need. know before you programmatically ■■ What is the clock frequency for specific to the BMP180 board, Once we connect the board to connect to an I2C device: your device? In our case, the and you might not need to blog the Raspberry Pi, we can check ■■ What is the device’s address? BMP180 board uses 3.4 MHz. perform this step when using whether we can see an I2C device. I2C uses 7 bits for a device Listing 8 defines the values for other temperature sensors. On your Raspberry Pi run the fol- address, and the Raspberry Pi the BMP180 as static variables to 2. Write to a control register on 2 lowing command: uses I C bus 1. be used later in the code. the device to initiate a tem- 38
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 8 LISTING 9 LISTING 10a LISTING 10b LISTING 11 LISTING 12 perature measurement (see //Raspberry Pi's I2C bus
Listing 11). COMMUNITY private static final int i2cBus = 1; 3. Read the uncompensated // Device address temperature as a two-byte private static final int address = 0x77; word, and use the calibration // 3.4MHz Max clock private static final int serialClock = 3400000; constants to determine the // Device address size in bits true temperature, as shown in private static final int addressSizeBits = 7; Listing 12. (Once again, this is ... specific to this sensor.) JAVA IN ACTION Finally, the temperature in // Temperature Control Register Data Celsius will be stored in the celsius FIND YOUR private static final byte controlRegister = (byte) 0xF4; variable. You can find the entire // Temperature read address program here. JUG HERE private static final byte tempAddr = (byte) 0xF6; As an exercise, you can extend One of the most elevating things // Read temperature command the program to read the pressure, in the world is to build up a private static final byte getTempCmd = (byte) 0x2E; the altitude, or both. community where you can hang JAVA TECH out with your geek friends, educate ... each other, create values, and Conclusion give experience to your members. // Device object This article took you through the private I2CDevice bmp180; Csaba Toth steps required to start creating Nashville, TN Java Users' Group (NJUG) embedded Java applications by showing real examples of how to LEARN MORE ABOUT US use GPIO and the I2C devices. Now it’s your turn to find more devices that you would like to connect to your Raspberry Pi so you can have fun with embedded Java on the Raspberry Pi.
MORE ON TOPIC: Java 8 Is Here blog
LEARN MORE Download all listings in this issue as text • Getting Started with Oracle Java ME Embedded 3.3 on the Keil Board 39
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014
//new to java / Part 3 Three Hundred Sixty–Degree COMMUNITY Exploration of Java EE 7 JOSH JUNEAU Learn how to use the Java API for Batch Processing, utilize Java Message Service, BIO and create a chat client using WebSockets. JAVA IN ACTION
his article is the third in a which will also be used for ticket sales for each show and .batch. Click Finish. Tthree-part series demon- building and deploying the populate the database by 2. Right-click the newly strating how to use Java EE 7 application in this article. We reading cumulative sales from created package, select improvements and newer web built the application from the a comma-separated values New and Java Class, and JAVA TECH standards, such as HTML5, ground up, using JavaServer (CSV) file. then provide the name WebSocket, and JavaScript Faces (JSF) 2.2 and making Batch processing is a SalesReader. Change the Object Notation (JSON) pro- use of new technology, such method for executing a series class definition to extend cessing, to build modern as the Faces Flow for naviga- of tasks or jobs. Most often, AbstractItemWriter, and enterprise applications. tion. We demonstrated how these jobs do not require resolve imports. In this third part, we will to utilize Java Persistence API intervention, and they are AbstractItemReader ABOUT US improve the movieplex7 (JPA) 2.1, Java API for RESTful bulk-oriented and long- implements the application, which we started Web Services (JAX-RS), and running. For details regarding ItemReader interface, in the first two articles, by JSON Processing (JSON-P) 1.0 batch processing terminol- which defines methods adding the ability to view for implementing business ogy, please refer to the “Java for reading a stream of ticket sales, accumulate movie logic and data manipulation. EE 7 Tutorial.” items. points, and chat with others. For the remainder of this Generate classes. First, let’s 3. Add @Named and Note: The complete source article, please follow along create the classes that will @Dependent as class- code for the application can using the Maven-based proj- be used to process movie level annotations, and be downloaded here. ect that you created using sales and persist them to the resolve imports. NetBeans IDE in Part 1 and database. The @Named annota- Overview of the Demo Part 2 of this series. 1. Right-click Source tion allows the bean to Application Packages, select New be injected into the job blog In the first two articles, Movie Ticket Sales and Java Package, and XML, and @Dependent we learned how to down- Java API for Batch Processing then specify the name makes the bean avail- load, install, and configure 1.0 (JSR 352) will be used in of the package as org able for injection. NetBeans and GlassFish 4, this section to import movie .glassfish.movieplex7 4. Add the following field 41
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 1 LISTING 2 LISTING 3 LISTING 4
public void open(Serializable checkpoint) throws Exception { reader = new BufferedReader( COMMUNITY new InputStreamReader(Thread.currentThread() .getContextClassLoader().getResourceAsStream ("META-INF/sales.csv"))); } Figure 1
to the class to declare the the following to the class JAVA IN ACTION reader: definition: Download all listings in this issue as text private BufferedReader reader; implements ItemProcessor
5. Provide an implementation for ImplementingItemProcessor 10. Create a new Java class within instance into the class by add- reading the CSV file by adding allows the class to operate on the org.glassfish.movieplex7 ing the following declaration: JAVA TECH the open method shown in an input item and produce an .batch package, and name Listing 1. output item. it SalesWriter. Extend @PersistenceContext For this example, the CSV 8. Add @Named and AbstractItemWriter by add- EntityManager em; file must be placed within @Dependent class-level anno- ing the following to the class the META-INF directory of the tations, and resolve imports. definition: 14. Replace the code within the application, which resides at Click the yellow lightbulb, writeItems method with a for ABOUT US the root of the application and choose Implement all extends AbstractItemWriter loop, which will be used for source packages. abstract methods, as shown persisting all theSales objects 6. Override the readItem method in Figure 1. 11. Add @Named and that have been aggregated and replace with the code 9. Change the implementation @Dependent class-level anno- from the batch runtime, as shown in Listing 2. Resolve of processItem to match that tations, and then resolve shown in Listing .4 imports. shown in Listing 3 and resolve imports. 15. Add the @Transactional anno- The readItem method is imports. 12. Click the yellow lightbulb to tation to the method to incor- responsible for reading the The processItem method add the import for javax.batch porate transaction control next item from the stream, creates a new Sales object, .api.chunk.AbstractItemWriter. into your method. Resolve the with a null indicating the end and then it creates a Once the import has been imports. of the stream. StringTokenizer that is used added, click the lightbulb and Create a batch job. The next task 7. Add a new Java class to the to parse through each item choose Implement all abstract is to implement a procedural task blog org.glassfish.movieplex7.batch within the object passed in. methods to add the writeItems within XML. In this case, the job package, and name it The Sales object is populated method to the class. will consist of one chunk that con- SalesProcessor. Implement with the processed item value 13. To gain access to the data tains three items. Those items ItemProcessor by adding and then returned. store, inject an EntityManager are the
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 5 LISTING 6 LISTING 7 LISTING 8 LISTING 9 and
respective class implementations implementation for invoking the COMMUNITY
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 10
@NotNull @ P a tt e r n(r e g e x p = "^\\d{2},\\d{2}", COMMUNITY message = "Message format must be 2 digits, comma,
2 digits, e.g. 12,12") private String message;
Download all listings in this issue as text JAVA IN ACTION
sending that data to the queue. data. Generate the getters/ 1. Create a new package in the setters for the field by right- movieplex7 application by clicking the editor pane and right-clicking Source Packages selectingInsert Code and then and then selecting New and Getter and Setter. Select the JAVA TECH Java Package. Specify the field, and click Generate. name org.glassfish.movieplex7 Note: This field uses bean .points, and then click Finish. validation annotations to 2. Create a class within the new ensure that the text entered package by right-clicking the into the field adheres to the Figure 2 package and selecting New required format. ABOUT US and then Java Class. Specify 4. Inject an instance of processing the CSV file and and complexity that are necessary the name SendPointsBean. JMSContext and a Queue into inserting the amounts into for sending and receiving messages Implement Serializable, and the class by adding the fol- the SALES database table. compared with prior releases. add the following class-level lowing code. Then resolve Click the Refresh button to Note: In order to work with JMS, annotations to make the imports, taking care to import display the list of sales that a topic or queue must be cre- bean Expression Language javax.jms.Queue. have been processed, as ated within the application server (EL)–injectable and session- shown in Figure 2. container. This can be done with scoped. Resolve imports. @Inject code or via the application server’s JMSContext context; Movie Points administrative utilities. In this @Named To implement a movie point sys- example, you will learn how to cre- @SessionScoped @Resource(mappedName = tem for the movieplex7 applica- ate a queue using code. "java:global/jms/pointsQueue") blog tion, we’ll use Java Message Service Create a JSF managed bean. First, 3. Add the String field shown in Queue pointsQueue; (JMS) 2.0 and its new API. JMS 2.0 let’s create a JSF managed bean Listing 10 to the class, which increases developer productivity that will be bound to a JSF view for will be bound to a JSF JMSContext is a new JMS by decreasing the amount of code collecting movie points data and inputText field to capture point 2.0 interface that combines 44
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 11 LISTING 12 LISTING 13 LISTING 14 LISTING 15 Connection and Session required resources. In this public void sendMessage() {
objects into a single object. case, the annotation is used COMMUNITY System.out.println("Sending message: " + message); Note: Java EE–compliant to create a javax.jms.queue context.createProducer().send(pointsQueue, message); application servers con- named java:global/jms/ } tain a default JMS con- pointsQueue. nection factory under 7. Inject the JMSContext and the name java:comp/ Queue resources that will be DefaultJMSConnectionFactory, used within the class by add- which is used when no con- ing the following code. Then nection factory is specified. resolve imports, being sure JAVA IN ACTION 5. To send the message to the to import the correct classes: JMS queue, add the method javax.jms.Queue and so on. shown in Listing 11 to the class. The JMSContext @Inject createProducer method can be JMSContext context; used to create a JMSProducer, @Resource(mappedName= JAVA TECH which provides methods to "java:global/jms/pointsQueue") Download all listings in this issue as text configure and send messages Queue pointsQueue; synchronously and asynchro- nously. The send method of Note: Although we are in the queue. Resolve imports. shown in Listing 15 to the the JMSProducer is used to creating the queue by using This method creates a view, replacing the code send a message to the queue the @JMSDestinationDefinition QueueBrowser and then uses within the
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 16 which will read a message An error will be displayed
from the queue and decre- (see Figure 4). This message COMMUNITY
Figure 3 Figure 5
blog
Figure 4 Figure 6 46
ORACLE.COM/JAVAMAGAZINE /////////////////////////////////////////// MARCH/APRIL 2014 //new to java / LISTING 17 LISTING 18 the WebSocket 1.0 API, which WebSocket endpoint. The value public class ChatServer {
provides a full-duplex, bidirec- attribute defines the URI to be COMMUNITY tional communication protocol used for accessing the endpoint. private static final Set