List
Collections.sort(groceryTransactions, new Comparator(){ List
COMMUNITY 31 48 62 03 Internet of Things Career Architect From the Editor Brewing Java with the More Ideas to Boost Robots Running Wild Warning: Java Magazine is going radically Raspberry Pi Your Developer Career Using the Java NAOqi SDK to more technical. Interact with a USB scale to accurately Study code, go to conferences, but use program companion robots
06 measure your coffee beans and brew the conferences to build your network. 68 ABOUT US Java Nation the perfect cup of Java. 52 Contact Us Calendar of events, the NYJavaSIG, the 38 JCP Executive Series Have a comment? Suggestion? Units of Measurement API, interview Architect Working on Java from Want to submit an article proposal? with Java Champion Arun Gupta Contexts and Dependency Within the JCP Here’s how to do it. 11 Injection: the New Java EE SourcePoint’s Geir Magnusson Jr. Java Books Toolbox discusses the advantages of building Review of Core Java for the Impatient Using strong typing in dependency systems with Java, and how the JCP and news blurbs of other worthy reads injection in Java EE has affected the platform’s evolution. 44 JAVA IN ACTION JAVA TECH New to Java 24 57 Create a Simple Paddle Game blog What’s New in JPA with Microsoft Kinect Deep Learning Attribute conversion, schema Startup Skymind looks to take deep More fun with using Greenfoot learning technology out of the labs and generation, enhanced SQL queries, to drive Kinect from Java and a host of other improvements into the enterprise with an open source highlight JPA 2.1. framework built on Java and Hadoop. 01
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 EDITORIAL PUBLISHING Editor in Chief Publisher Andrew Binstock Jennifer Hamilton +1.650.506.3794 COMMUNITY Interim Associate Editor Associate Publisher and Audience Kay Keppler Development Director Copy Editors Karin Kinnear +1.650.506.1985 20 Years of Claire Breen, Karen Perkins Audience Development Manager Section Development Jennifer Kurtz Blair Campbell - Java in Action Michelle Kovac - Java in Action, Features ADVERTISING SALES Bob Larsen - Java Nation President, Sprocket Media Yolande Poirier - Java Nation Kyle Walkenhorst +1.323.340.8585 Innovation Technical Reviewers Western and Central US, LAD, and Canada, Sprocket Media
Stephen Chin, Reza Rahman, Simon Ritter, IN ACTION JAVA # James Weaver Tom Cometa +1.510.339.2403 1 Development Platform Eastern US and EMEA/APAC, DESIGN Sprocket Media Senior Creative Director Mark Makinney +1.805.709.4745 Francisco G Delgadillo Advertising Sales Assistant Design Director Cindy Elhaj +1.626.396.9400 x 201 Richard Merchán Mailing-List Rentals Contributing Designers Contact your sales representative. Jaime Ferrand, Diane Murray, Arianna Pucherelli RESOURCES TECH JAVA Production Designers Oracle Products Sheila Brennan, Kathy Cygnarowicz +1.800.367.8674 (US/Canada) Oracle Services Since 2002 Since 1999 Since 1995 +1.888.283.0591 (US) Oracle Press Books oraclepressbooks.com
ARTICLE SUBMISSION Since 1996 Since 1998 Since 1996 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 Since 1996 Since 2008 Since 1998 [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. Since 1999 Since 2001 Since 1996 Since 2012
Copyright © 2015, 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 at no cost to qualified subscribers by Oracle, 500 Oracle Parkway, MS OPL-3A, Redwood City, CA 94065-1600. Digital Publishing by GTxcel 02
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //from the editor / COMMUNITY JAVA IN ACTION BIO Warning: We’re Going Technical Java Magazine heads in a new direction. JAVA TECH everal weeks ago, I was hired by Oracle to ers who work regularly with code. The magazine will head up Java Magazine. This happy event both reflect and cater to our shared love of pro- S means that I get to write about Java from the gramming, our passion for great tools and technolo- very heart of Java. How cool is that? The joy I feel is gies, and the abiding enjoyment we all derive from akin to the excitement of setting out on a journey Java and JVM languages. for which one has long prepared. I’ve been an edi- To do this, we’ll enlist more Java experts, accom- ABOUT US tor of developer publications for many years, most plished programmers, algorithm junkies, design recently heading up Dr. Dobb’s. I’ve also spent much mavens, build wizards, bad-code scolds, experi- of my free time during the last 10 years program- enced teachers, and skilled architects to share their ming in Java and, to a lesser extent, Groovy. wisdom in our pages. We’ll also explore tools— Mixed with the joy of this new work is the aware- especially open source tools—and important open ness of the long road ahead, defined by the end- source projects. point I am driving toward; so, let me share my plans I also expect to remove some sections, mainly for the new direction of our magazine. those that don’t focus tightly on program- In simple terms, I plan to take Java Magazine in ming. There will be fewer case histories in Java blog a radically more technical direction. The editorial Magazine—and those that do appear will bear team and I will be catering squarely to Java develop- directly on a relevant technical topic. We’ll also
PHOTOGRAPH BY BOB ADLER/GETTY IMAGES 03
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //from the editor /
transform other sections. For exam- readers), and to Kay Keppler, who ple, the section that used to con- was the key to making this transi- COMMUNITY tain book blurbs will run detailed tion possible. Learn Java 8 reviews, signed by the reviewers. Finally, allow me to emphasize (The first book review appears on one more point: I really like hear- page 11 of this issue.) ing from you. Comments, plaudits, From the Source Finally, you’ll see fewer articles grumbles, contrasting opinions, telling you how great Java is. There’s corrections, proposals for articles— JAVA IN ACTION no need for that. You get it. I get it. these are all welcome and make for Oracle University Let’s move forward. a better magazine. My address is You can expect to see these at the end of this editor’s note, and changes roll out over the next few more contact information appears
issues. Changing magazines is not on the Contact Us page at the end JAVA TECH New Java SE 8 training and certification a stop-the-world-while-I-do-this of the magazine. Our staff reminds kind of project. It’s more like chang- me that the last paragraph of that Available online or in the classroom ing a tire on a moving truck. In this page should not be overlooked. issue, you’ll see some initial tweaks. Looking forward to this journey Taught by Oracle experts For example, code is now presented together,
100% student satisfaction program ABOUT US in a monospaced font (hey, hey!). There’s also a new last page about Andrew Binstock, Editor in Chief how to contact us and propose [email protected] articles. The next issue will have @platypusguy more-substantial changes, and the one after that will have a lot more PS: For more on my background, of the content I have promised. By you can click on the link marked year’s end, the transition will be “Bio” on the previous page. Learn More nearly complete and we should be rolling in high gear. blog A word of thanks to my predeces- sor, Caroline Kvitka, for bringing Java Magazine to this point (where we have nearly a quarter of a million 04
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015
//java nation /
Devoxx UK COMMUNITY São Paulo, Brazil JUNE 17–19 LONDON, ENGLAND The innovative London Java User Group organizes this conference, and puts developers front and center with the theme “The League
of Extraordinary Developers.” IN ACTION JAVA The schedule is packed with pre- sentations, hands-on-labs, and Birds-of-a-Feather (BOF) sessions. Developers can meet top British and international experts in a
casual atmosphere. TECH JAVA
Devoxx Poland JUNE 22–25 KRAKOW, POLAND Seven tracks focus on Java tech- nology. Participants can dive deep
in the conference sessions, ABOUT US evening BOFs, and workshops and labs led by world-class trainers. QCon New York EVENTS JUNE 8–12 Java EE Summit NEW YORK, NEW YORK JUNE 24–26 JavaOne Latin America JUNE 23–25 QCon is designed for technical MUNICH, GERMANY SÃO PAULO, BRAZIL team leads, architects, engineer- The Java EE Summit includes 14 JavaOne Latin America is the premier Java conference in Latin ing directors, and project manag- intensive workshops led by top America. Visionaries and world-renowned speakers will present con- ers who influence innovation. The German-speaking Java EE experts. ference and hands-on sessions in five tracks, including clients and event includes two days of tutori- Developers and software architects blog the user interface; core Java platform; Java and the Internet of Things; als followed by a three-day confer- will receive in-depth knowledge server-side Java; and a new track about Java, DevOps, and the cloud. ence. One track focuses on Java to plan and implement successful innovations. Java EE 6 and Java EE 7 projects.
PHOTOGRAPH BY GETTY IMAGES 06
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation /
EVENTS OSCON Fix This—Solution COMMUNITY JULY 20–24 PORTLAND, OREGON In the March/April 2015 issue’s Fix This, Stephen Chin FISL Open source pioneers, experts, and inno- showed us a problem of the new TemporalAdjuster JULY 8–11 vators have gathered at OSCON over the class introduced with the Java SE 8 Date and Time API: PORTO ALEGRE, BRAZIL past decade. With a dozen tracks and What if you want to do something specific to your appli- The International Free Software Forum hundreds of sessions, the conference has cation, such as finding the next occurrence of Friday the
(FISL) event is jam-packed with lec- practical tutorials, inspirational keynotes, 13th? Here’s a quick explanation of each possible issue: IN ACTION JAVA tures, workshops, demonstrations, and a wealth of information on open and presentations. source languages and platforms. 1). Variations in month. By using thetemporal.plus method, variances in month length are automatically fixed ÜberConf by the underlying LocalDate instance. JULY 21–24 2). A time zone issue. The underlying implementation
DENVER, COLORADO of a Temporal passed in to the TemporalAdjuster is TECH JAVA ÜberConf is part of the No Fluff Just Stuff responsible for taking care of compensating for time zones Software Symposium Series that explores (which would be the case if a ZonedDateTime was used, the ever-evolving ecosystem of the Java for example). platform. The conference offers 100 tech- 3) .An error in the formula. This is the problem. The for- nically focused sessions including more mula works fine if the given day of the month is on or than 25 hands-on workshops about archi- before the 13th or the given month has no Friday the 13th. tecture, cloud, security, enterprise Java, If both of those cases coincide, then the Temporal ABOUT US languages on the JVM, build/test, mobil- Adjuster incorrectly returns a date in the past. To fix this, ity, microservices, Docker, and agility. you can simply add a check for the day of the month and increment the month in advance of running the loop. Java Forum The Developer’s Conference (TDC) JULY 9 JULY 21–25 if (temporal.get( STUTTGART, GERMANY SÃO PAULO, BRAZIL ChronoField.DAY_OF_MONTH) > 13) Organized by the Stuttgart Java User One of Brazil’s largest conferences for temporal = Group, Java Forum attracts more than developers, IT professionals, and stu- temporal.plus(1, ChronoUnit.MONTHS); 1,000 participants who learn about Java dents offers Java tracks over five days. and the Java environment. The forum Java-focused content includes intro- A simple fix, and thanks to the new Date and Time API includes lectures, presentations, work- ductory sessions in the Java University you can focus on debugging your algorithm rather than blog shops, demos, and BOF sessions. track, and advanced and intermedi- second-guessing whether your date fields are 0, 1, or 1900 ate sessions in the Java EE, mobile, and based. (For an explanation, check out slide 10 of Chin’s embedded tracks. ZombieTime talk.)
PHOTOGRAPH BY GETTY IMAGES 07
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation /
FEATURED JAVA SPECIAL COMMUNITY
FEATURED JAVA SPECIFICATION REQUEST INTEREST GROUP: NEW YORK Long ago, on September 21, 1995— JSR 363: Units of back when the years still began with a 1 and flannel was considered the epit- IN ACTION JAVA Measurement API ome of fashion—a group of Java devel- opers gathered after a Java developer JSR 363: Units of Measurement API seeks conference. Because the term Java to support “the programmatic handling of user group didn’t exist yet, they called physical quantities and their expression as themselves the New York Java Special numbers of units.” It provides type-safe Interest Group (NYJavaSIG). TECH JAVA support for units of measure that is neces- Since that time, membership in the sary for machine-to-machine communica- NYJavaSIG has grown to almost 8,000 tion and the Internet of Things, especially of what Frank Greco, NYJavaSIG founder and leader as well as lead guitar- when you’re working with sensors or in ist for the NullPointers (the now world-famous band composed entirely of the manufacturing, engineering, or scien- Java developers), describes as “extremely opinionated technologists.” He tific fields. You have no need to worry if the quickly follows up with “But hey...it’s New York.” Monthly meetings aver- length passed to or from that API is in feet or age about 240 members, and bimonthly hands-on workgroups with titles ABOUT US meters—or even leagues! such as “Cloud/HPC and Languages” ensure that something will pique The Specification Leads for JSR 363—Jean- the interest of almost any Java developer. Marie Dautelle, Werner Keil, and Leonardo The future of NYJavaSIG looks to be every bit as promising as its past. Lima—are working with the support of gov- According to Greco, “The local NY Java community is enjoying a renais- ernment organizations, private companies, sance thanks to the release of Java 8 with new functionality and power. Java user groups, and individuals like you. If Every meeting seems to add many new NYJavaSIG members. And it you’d like to comment on or contribute to appears to be a larger phenomenon with Java excitement growing glob- the work on JSR 363, or even just track the ally. With more cloud and IoT [Internet of Things] functionality coming progress, visit java.net and help steer the and with the Java ecosystem growing even bigger, there’s still a lot of future of Java. excitement yet to come.” If you plan to be in the New York area and would like to participate in blog an NYJavaSIG event, look them up at the NYJavaSIG website or on Twitter @nyjavasig.
08
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java nation / COMMUNITY JAVA CHAMPION PROFILE ARUN GUPTA
Java Magazine: Where did Gupta: My first job was way Gupta: Meeting people of you grow up? back in 1996 doing Java different cultures from all Gupta: Delhi, India programming. around the world. I’ve been IN ACTION JAVA to more than 40 countries Java Magazine: When and Java Magazine: What do so far. how did you first become you enjoy for fun and interested in computers relaxation? Java Magazine: Has being and programming? Gupta: I like doing long- a Java Champion changed Gupta: My elder sister was distance running, teaching anything in your daily life? TECH JAVA doing a Master of Science STEM [science, technology, Gupta: Bragging rights. I degree in computers engineering, and math- also feel a social respon- when I was growing up, ematics] workshops to kids, sibility to grow the Java and I found that intrigu- and cooking with family. Champion circle bigger and ing and engaging. My first create more of us. interaction with comput- Java Magazine: What hap- ABOUT US ers was when I got a mas- pens on your typical day off Java Magazine: What are ter’s degree in computing from work? Do you spend you looking forward to in myself. time with family and/or the coming years? friends? Do you wander off Gupta: I want 9 million Java Java Magazine: What was alone? developers to grow to 10, 11, your first computer and Gupta: A day off is typically 12, and 13 million, and keep programming language? packed with kids’ activities, growing. Arun Gupta, the director of technologies since his days Gupta: Intel 386, 4 MB watching a movie with the technical marketing and as a founding member of RAM, 200 MB disk. First family, Devoxx4Kids work- Follow Arun Gupta’s blog developer advocacy at Red the Java EE team at Sun programming language: shops, and socializing with or reach him on Twitter Hat, promotes Red Hat Microsystems. He travels Pascal. friends. @arungupta. technologies that focus on the world speaking about a blog JBoss middleware. He has wide variety of topics and Java Magazine: What was Java Magazine: What “side been an avid proponent of is a JavaOne Rock Star and your first professional pro- effects” of your career do the Java community and best-selling author. gramming job? you enjoy the most? 09
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015
// java books / COMMUNITY
CORE JAVA FOR THE IMPATIENT By Cay S. Horstmann Addison-Wesley Professional, February 2015
This book follows on the slimmer volume Once into the meat of Java SE 8, however, JAVA IN ACTION JAVA by Horstmann, Java SE 8 for the Really Horstmann displays his widely recognized Impatient, which came out in early 2014. skill at explaining difficult concepts clearly That book targeted existing Java develop- and choosing code examples that cogently ers and explained concisely what was new support his textual presentation. The book in Java SE 8 (as well as some important but also contains many wise and pragmatic overlooked features in Java SE 7). recommendations about the right way to JAVA TECH JAVA This 500-page volume is an introduc- do things (a central strength of his previous tion to the full Java SE 8 language, aimed writings), so that the work is not merely an at developers coming to Java from another exposition but truly a guide. language, but not at novices new to pro- There is a fair amount of duplication gramming. It is a bridge between the between the examples in this book and earlier Java SE 8 book and the upcoming Horstmann’s earlier one on Java SE 8, so
revision of Core Java—the two-volume if you bought that book, I’d recommend ABOUT US masterpiece that Horstmann coauthors waiting for the arrival ofCore Java before with Gary Cornell—which should see light upgrading. However, for all other readers, later this year. this is an excellent tutorial for Java SE 8. To my eyes, the added introduction to the —Andrew Binstock language seems rushed and a bit too thin. For example, Horstmann writes, “Java has … five integral types.” Six pages later, he Over the next few issues, the book sec- asserts that “four [primitive types] are inte- tion of Java Magazine will evolve from ger types.” Only careful comparison reveals descriptive blurbs to critical reviews, that the char type has been reclassified signed by the respective authors. Due from its correct group (integral primitives) to potential conflicts of interest, books to an invented one (integer primitives) from Oracle Press will be presented but blog without explanation. It’s not a big point, not reviewed. —Ed. but it suggests that a reader looking to learn Java would find the early sections confus- ing, whereas they should be the simplest. 11
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //java books / COMMUNITY JAVA IN ACTION JAVA
THE CUCUMBER FOR JAVA BOOK: NETBEANS IDE 8 COOKBOOK JAVA EE 7: THE BIG PICTURE BEHAVIOUR-DRIVEN DEVELOPMENT FOR By David Salter and Rhawi Dantas By Danny Coward JAVA TECH JAVA TESTERS AND DEVELOPERS Packt Publishing, October 2014 Oracle Press, October 2014 By Seb Rose, Matt Wynne, and Aslak Hellesoy Pragmatic Bookshelf, February 2015 This book will show you how to perform Java EE 7: The Big Picture explores the many key tasks with the NetBeans IDE, entire Java EE 7 platform in an all- Teams working on the Java Virtual uncovering more about mobile, desk- encompassing style while examining Machine (JVM) can now say goodbye top, and enterprise Java along the way. each tier of the platform in enough forever to misunderstood require-
You will start by creating Java projects detail so that you can select the right ABOUT US ments, tedious manual acceptance and learning how to refactor and use technologies for specific project needs. tests, and out-of-date documentation. NetBeans tools to increase developer In this authoritative guide, Java expert Cucumber—the popular open source efficiency. You then get a walkthrough Danny Coward walks you through the tool that helps teams communicate of how to create a desktop application, code, applications, and frameworks that more effectively with their custom- and then JavaFX, mobile applications, power the platform. Take full advan- ers—now has a Java version, and the and how to use external services. Having tage of the new capabilities of Java EE 7, best-selling Cucumber Book has been seen how to create many different types increase your productivity, and meet updated to match. It has the same good of applications, you are then shown how enterprise demands with help from this advice as the earlier book about how to to test and profile them before storing Oracle Press resource. deliver rock-solid applications collab- them in revision control systems such as oratively, but with all code completely Git or Subversion. Finally, you will learn rewritten in Java. New chapters cover how to extend NetBeans itself by adding blog features unique to the Java version of new features to the IDE. Cucumber, and reflect insights gleaned by the Cucumber team since the original book was published. 12
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 COMMUNITY JAVA IN ACTION JAVA TECH //20 years of java //
{THE MASTERS SPEAK} ABOUT US The code masters behind Java’s success discuss what has surprised them most over the years and what innovations are coming in the years ahead.
In the history of language development, example, was the language 15 years ago, but has made in two key areas: advancing the language “crossing the chasm” refers to the stage at which a seen its popularity decline rapidly during the last and optimizing the Java Virtual Machine (JVM). language breaks out of a niche in which it was used decade—largely under pressure from Python. With this work in mind, we sat down with John only by aficionados and hobbyists and begins its Java, however, crossed the chasm and con- Rose, JVM architect at Oracle, and Mark Reinhold, journey into the programming mainstream. tinued to thrive in the mainstream. It has been chief architect of the Java Platform Group at blog Languages that cross the chasm become robustly healthy for two decades. In fact, by Oracle, and asked them to tell us what has most widely used. While they are assured of a almost all measures, its popularity continues to surprised them in their work on Java during these prolonged period of popularity, they are not grow. I attribute this success to the substantial last 20 years and what lies immediately ahead for guaranteed good health and long life. Perl, for investment Sun, Oracle, and various partners the language. —Ed. 13
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015
TWENTY YEARS OF INNOVATION COMMUNITY
A CONVERSATION WITH JAVA IN ACTION JOHN ROSE With Projects Valhalla and Panama, the JVM continues JAVA TECH to add useful features. BY TIMOTHY BENEKE
ny celebration of Java would be incomplete without
a discussion of the remarkable versatility of the JVM, ABOUT US which now hosts numerous languages such as Clojure, Groovy, JRuby, Jython, Kotlin, and Scala. JVM Architect AJohn Rose, whose history with Java dates back to his days at Sun Microsystems in 1995, contributed to the design of Java inner classes, the initial port of Java HotSpot VM to SPARC, and the Unsafe API. His work enhanced the performance of the HotSpot and OpenJDK stack, affecting everything from hardware architec- ture to code generators, libraries, and programming languages. He is currently the lead engineer of the Da Vinci Machine Project, a part of the OpenJDK effort, and the JSR 292 Specification Lead, responsible for specifying new support in the JVM standard for dynamic invocation and related facilities, such as type profiling blog and improved compiler optimizations. We spoke with him to get Rose’s first project on the JVM was designing and implement- his take on the past and future of the JVM. ing inner classes for Java 1.1.
PHOTOGRAPHY BY BOB ADLER/GETTY IMAGES 15
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Tell us a little about your history with Java on the Java language.” James Gosling had a Java problem—
and the JVM. how to do method pointers and delegation—and asked for COMMUNITY Rose: I sometimes refer to myself as a “Lisp refugee” because my help. So I designed and implemented inner classes for I spent some of my early years happily programming in Lisp, Java 1.1. So I got onboard fairly early. which is a managed language with garbage collection and Because I’ve mentioned two of the main designers of Java safe dynamicity, with safe typing in a rich library. Like many who are not currently on the Java team, I should also mention language geeks, I invented my own Lisp VM, which I used Guy Steele, who is at Oracle Labs and has been instrumental successfully at Sun on a couple of projects. and is even now helping us think through the value type pro- Then Java exploded on the scene in the mid-1990s and posals for the JVM, which are part of Project Valhalla. So the JAVA IN ACTION I discarded my own VM and joined the Java project as one influence of the original designers of Java is still being felt. of the engineers who onboarded the HotSpot performance engine. I remember Bill Joy calling me “fresh meat” when I Java Magazine: Do you still do any coding yourself? joined the project and saying, “We need someone to work Rose: I still do code, even in C++. At Oracle I’ve been pri- marily concerned with the Java HotSpot VM and especially with its just-in-time [JIT] compiler and, of course, with the implementation. I was the main implementer of JSR 292, JAVA TECH the invokedynamic construction. I wish I could say that I code a lot. I mostly content myself with doing small proto- types to prove that things are possible, and I review other people’s core code. I have fun hammering out architectural documents with some really brilliant people in the organiza- tion. We have a good community, not only of coders whom ABOUT US I interact with all the time, but also hardware and software designers, theorists, and other folks who are trying to figure out the next great thing for Java. I’ve had two really good cod- ing sessions in the last couple of months. One was a proof of concept in Java for a way of doing value types, and another involved solving a C++ puzzle that should let us structure our Java HotSpot VM code better. There’s a good prospect that Java will naturally grow to assume more tasks that are currently being done with C++. When I’m frustrated with using C++, it’s usually because I’m building some part of the JVM that needs to be done right. When people on the team commiserate with each other blog about C++ and how come we have to do C++ when everybody around us is using Java on the VM, we are fond of saying that we do C++ coding so that millions of other people won’t have to. 16
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Give us some historical perspective on “invokedynamic” instruction.
the JVM. But it took a good five years to implement, because we had COMMUNITY Rose: The original authors of Java understood that they could a lot of ideas about what dynamic invocation might look like not aggressively solve problems all at once, so they addressed and the design went in various directions. Our first prototype them in a layered manner. They not only invented Java but took some wrong turns, as the experts in the JSR 292 Expert also the virtual machine and, in particular, the bytecode and Group [in the Java Community Process —Ed.] pointed out. So object architecture that the Java compiler compiles to. We it was redesigned and came out in JDK 7 and has been an think of these things as bytecodes for Java, but there’s a lot important part of the stack ever since then. invokedynamic more to them—they have their own identity and their own is a completely general invocation Swiss army knife that lan- JAVA IN ACTION special powers, so we can think of bytecodes as a very power- guage implementers can use to implement not only dynamic ful and tastefully designed execution model in its own right. method invocation but also some kinds of static invocations The earliest versions of the JVM manual made it clear that that were not possible in the previous instructions. So it hit a the bytecodes were not sweet spot. It gives you full just replicating Java but JAVA VS. C++ access to the JVM’s capabili- could actually support other ties and full flexibility to the languages. And whether “People on the team commiserate with each other about C++: language implementer JAVA TECH people took the hint from ‘How come we have to do C++ when everybody around us is who’s working on top of the the architecture manual or JVM. To make a proof of because they perceived that using Java on the VM?’” concept, we had early the bytecodes were very involvement with Charlie inviting for such purposes, Nutter, the lead on JRuby, from the beginning, devel- who accelerated several ABOUT US opers began writing other languages for the JVM. Just a few prototype implementations of JRuby using invokedynamic. years after Java began, there were literally hundreds of known So we had dynamic language people involved extremely early. language implementations running on top of the JVM. There In recent years, Oracle has created a brand-new JavaScript were versions of Scheme, like Kawa, that came out very early, implementation called Nashorn [part of JDK 8 —Ed.], which and even today developers are continually inventing new lan- is a high-performing JavaScript engine that runs on top of guages to run on the Java bytecodes. It’s extremely exciting. the JVM, and was designed from the start to build on top of invokedynamic. Java Magazine: How has the JVM developed and changed over I want to make it clear that when you add a change to the the years? bytecode architecture—and this holds for the future—it can Rose: Around 2005, Sun Microsystems got serious about take years to think around and finally come to a good design. adding a new invocation mode in the JVM to support dynamic And once we’re committed to an implementation, it can take languages. We realized that our invocation modes were more years to establish the optimization dynamics of the blog all organized toward static typing and Java in particular, design. That’s one reason we go very slow in JVM evolution. and we wanted to add a new invocation mode or methods As James Gosling said recently at JavaOne, “We don’t want to that would more directly support dynamic languages and do things until we know we can do them right—in Java and semantics. So before we had any details, we called it the on the JVM.” 17
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: Where is the JVM headed? struct that looks like a class, but when you use it, it feels like
Rose: Oracle and the Java community are making serious an int. COMMUNITY investments in two new OpenJDK projects, Valhalla and The addition of value types also makes it easier for other Panama. Project Valhalla is ultimately aimed at closing the languages to migrate to the JVM. It no longer forces languages divergence between references and primitives so that users that have other datatypes to conform them to the JVM. can define new primitive-like types, which we call “value They can create datatypes to reflect their natural datatypes. types.” Java doesn’t have a complex number or an unsigned They can do that today, but at the cost of a pointer and a int type. It doesn’t have a 128-bit integer type, but with value storage allocation. types we will be able to create all of these as library code, not JAVA IN ACTION as VM intrinsics. That’s a big vision. A basic physical reason Java Magazine: What is Project Panama? why we need this is because value types are natural units Rose: With Project Panama, we are creating a more robust for flatter, more compact data structures. You can look at interconnection with native code. Developers like Java our current Java architecture and say, “Suppose you don’t because it’s a friendly language to write in. But sometimes have value types, and suppose you’re not allowed to make they have to program in C or C++ because, for example, new primitives. Surely you can use classes to make 128-bit there’s a low-level system library with the C API. So they have integers and unsigned ints and complex numbers.” This is to pull out their C editor and include some header files and JAVA TECH something people do. But the problem is that it’s tied up start coding up in C. To weave that into their Java project, they with this object-oriented data model that is native to Java, have to write a bunch of Java Native Interface [JNI] code. But which puts pointers everywhere. And it turns out that once JNI is intentionally difficult to use. In its early days, Java was you make an object that’s reachable by a pointer, it’s hard to fighting to differentiate itself and needed to maintain a- cer get rid of the pointer. There’s a class tain amount of integrity and control over its own execution. of effects called “identity semantics” So the JVM was pretty unwilling to share trust with native JVM LANGUAGES ABOUT US that makes it difficult or impossible libraries. If you’re going to attach a native library, you might “Clojure is a mad-scientist library of how for compilers to ignore the pointer. If have to sign up for months of engineering work to create the to rethink concurrent programming with this were not a problem, Java wouldn’t necessary JNI bindings. need primitive types with everything So to enter the JVM world from the C world, you had to persistent data structures in the setting of being an object. With value types, either leave your C behind or bring it in at great cost. It’s an idiosyncratic Lisp-like language.” the same performance feel that you like an import duty. Java now has a stable place in the com- get from an int, you’ll get from a puting world, so it would be helpful to Java to have a more complex number. The same things tax-free entry from the C world to the Java world—that’s that make you hesitate before using Project Panama. a Java.lang.Integer on your data also push you away Here’s a picture: If Java is the Pacific Ocean and C is the from using a Java map complex class. But once the complex Atlantic Ocean, Panama offers an easy bridge or canal to con- becomes a value type instead of an object type, it loses its nect the two great bodies. I posted a manifesto on my blog a blog indirection—it gains flat data representation, and the perfor- few months ago called “The Isthmus in the VM” that lays mance profile feels like an int. out the risks and rewards of connecting Java and C. I’m happy In fact, that’s our slogan for value types: “Codes like a class, to say that Project Panama is making good progress. So works like an int!” You define your complex in a library con- JVM users should one day enjoy not only a wide variety of 18
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 languages with more and more pow- IN THE JVM formers in the market today, because
erful datatypes, but also the ability the bytecodes are not only a good COMMUNITY to resort to C libraries with much less “Bytecodes are not only a good execution format but they’re a good overhead. execution format but they’re a good representation of a program that can be representation of a program that can manipulated in its own right. Java Magazine: What’s happening with bytecode transformers? be manipulated in its own right.” Java Magazine: Tell us about the role of Rose: Let me first provide some back- the JVM Language Summit. ground. The idea of having a flexible vir- Rose: When we started doing the JVM JAVA IN ACTION tual machine that runs at high speeds is Language Summit in 2008, we realized fairly old. Pascal achieved some portability using p-code and that there was a substantial community doing very interest- if you look at the early Java papers, they acknowledge a debt ing things just on the bytecodes. So it was a fun idea to have to previously existing bytecode and virtual-machine instruc- them all gather together. They talk in a very specialized kind tions. One reason that Java’s bytecode design has been of technical language—these are people who speak bytecode an extremely successful VM instruction set is that it hides and are interested in what the bytecodes could do for them. enough detail about the underlying machine, so that it can They are knowledgeable about compilation techniques that JAVA TECH be easily moved and re-executed from machine to machine. would take a high-level language into bytecodes. We’ve met It also has security properties that were not present in previ- once a year since 2008, and it’s usually the best conference ous bytecodes. In other words, the information-hiding aspect that I go to each year because the attendees care passion- of the bytecodes implies a secure ability. It means that your ately, not only about Java but also about efficiently imple- bytecodes can, in certain situations, be proven by a verifier to menting languages on top of Java bytecodes. As a result, not subvert the type system. We don’t allow unsigned or pos- we’ve been able to slowly evolve the virtual machine so that it ABOUT US sibly hostile code to run on the JVM, because the bytecode is will serve more and more languages. hardened against such attacks. By the way, we take very seri- Of course, now we have Clojure, Groovy, Jython, JRuby, ously any reports of loopholes or cracks in the armor, and we Scala, and other established languages. Scala is a wonder- patch them up as vigorously as we can. It’s one of our priori- ful mad-scientist library of excellent language ideas. And ties to keep the attack surface as clean as possible. Clojure is a mad-scientist library of how to rethink concur- Our bytecode set is not just an executable format but is rent programming with persistent data structures in the also a clear expression of the abstract structure of a program. setting of an idiosyncratic Lisp-like language that some Users can perform a neat trick and transform bytecodes. people find extremely compelling when it fits their problem So, people have written all sorts of really ingenious byte- space. code transformers, which do not execute the bytecodes but modify them incrementally to make them more useful from Timothy Beneke is a freelance author whose work has pre- their perspective. So, bytecode-to-bytecode transforms are viously appeared in this magazine. He has written extensively blog practical and interesting in part because of the good vision of about Java. the original designers of the VM to not be too closely bound either to hardware or to a language. LEARN MORE You will see all sorts of interesting annotation-driven trans- • John Rose’s blog 19
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 TWENTY YEARS OF INNOVATION
USING JAVA COMMUNITY “Despite being internally complex, Java has a feeling of initial simplicity. It has a high ‘DWIM’ factor—‘Do
What I Mean.’” JAVA IN ACTION A CONVERSATION WITH MARK REINHOLD The changes that have driven Java’s wide use, and the JAVA TECH changes to come BY TIMOTHY BENEKE
ark Reinhold, chief architect of the Java Platform Group at Oracle, has made many contributions to the Java
platform in the past 19 years, working first at Sun ABOUT US Microsystems and then at Oracle: character-stream Mreaders and writers, reference objects, shutdown hooks, the NIO high-performance I/O APIs, library generification, and service load- ers. He was the lead engineer for the Java 1.2 and 5.0 releases, the Specification Lead for Java SE 6, and both the project and Specification Lead for JDK 7 (Java SE 7) and JDK 8 (Java SE 8). He currently leads the JDK 9 and Jigsaw projects in the OpenJDK com- munity, where he also serves on the governing board. Reinhold, who calls himself an old Lisp hacker in disguise, holds a PhD in computer science from the Massachusetts Institute of Technology, where he worked on garbage collection, compilation techniques, type systems, semantics, and the visualization and blog analysis of program performance.
PHOTOGRAPHY BY BOB ADLER/GETTY IMAGES 20
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: What has surprised you most about Java over order to address the inherent complexities that we find in
the years? modern computing systems. But despite being internally COMMUNITY Reinhold: I’d have to say it’s the strength of its foundation. complex, Java has a feeling of initial simplicity. It has a high I don’t think anybody understood at the beginning what a “DWIM” factor—“Do What I Mean.” Once newcomers with strong foundation James Gosling and the rest of the original a good IDE learn the basic plumbing, they can get around Java team built into the Java Virtual Machine [JVM] and Java pretty easily. You don’t have to go read the VM specifica- language specifications. They’re clear but evolvable designs tion or memorize the language specification. Those refer- that are not so self-contained and interdependent that you ences are available and you might eventually need them, wouldn’t dare change them. but you can often just “write what you mean”—and it turns JAVA IN ACTION If you look at the VM specification, for example, it’s very out to be what you meant a large fraction of the time. As a clear about the structure of the VM, how class files are Java programmer, you can get into the zone and solve your defined, what all the bytecodes are, and what they mean. problem—and the language and platform tend to get out of Yet there’s room to grow because there are plenty of unused your way. bytecodes and the conceptual framework in which they exist There are some people who disagree with this because they has room for flexibility. The language specification has the prefer other styles of languages, but for this style of language same characteristics. Java does that pretty well. JAVA TECH I’ve also been surprised at the number of times people have declared Java to be dead, which has not yet proved to be true. Java Magazine: Why have you devoted so much of your pro- fessional life to Java? Java Magazine: You have spoken about the importance of Reinhold: What attracted me to Java initially is what keeps retaining what James Gosling calls the “feel of Java,” which me here still. As someone deeply interested in programming includes readability, simplicity, languages, the opportunity to work on one that’s used every ABOUT US CLEAR CODE and universality. day by millions of developers is exceedingly rare. It’s exciting Reinhold: Those properties are and rewarding—there’s a kind of visceral thrill that’s hard to “Readability is the most critical because, with really important. We recognized describe. I’m enjoying it as much now as I did when I started software, the amount of time you spend writing their value early on, and we’ve nearly 20 years ago. a piece of code that goes into production is worked very hard to preserve them. Readability is the most Java Magazine: Tell us a little about what you do all day. Do microscopic compared with the time that you critical because, with software, the you still write code? and your successors will spend reading it.” amount of time you spend writ- Reinhold: I still write code and I’ve had code in every release ing a piece of code that goes into starting with JDK 1.1, although sometimes not a lot. I spend a production is microscopic com- fair amount of time mentoring junior engineers and advising pared with the time that you and people on various things. As one of the old-timers, I know a your successors will spend reading it in order to maintain it, lot of obscure facts, so I’ve wound up being a steward of his- blog fix bugs in it, and enhance it. tory of the platform. I also do a fair amount of design work. Simplicity refers to the comprehensibility of the platform. I’m the Specification Lead for the module system that we’re Any production-quality language and surrounding plat- working on for Java SE 9, and that involves coding and design form must have a certain amount of internal complexity in and architecture and language changes. 21
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Java Magazine: It has been more than five years since Oracle
acquired Sun Microsystems. How do you feel about Oracle’s COMMUNITY stewarding of Java? Reinhold: I feel pretty good about it. Once we got through the initial challenge of merging these two large organizations, Oracle astutely decided that keeping Java vibrant was the top priority. The investments and deliveries over the last five years demonstrate that Oracle is serious about that commit- ment. There was a five-year hiatus when Sun basically failed JAVA IN ACTION to deliver Java SE 7, and then Oracle picked up the pieces and delivered it. Oracle then funded the development of Java SE 8 with the very successful lambda and streams features. Oracle is continuing to invest in the future: We’ve got Java SE 9 com- ing with modules, and we’re already investing in some deep language features for releases beyond Java SE 9. JAVA TECH Java Magazine: You remarked that Java “evolves by taking on the next big pain point.” Could you give us some examples? Reinhold: Our basic recipe for evolving Java is to identify a pain point, figure out which abstractions are missing from the platform, and then add them. We make sure they fit in with everything that’s already there so that the new features pass code around as data. Lambdas introduced a better way ABOUT US feel like they were there from the beginning. of abstracting over behavior and also introduced the Stream One example is generics, introduced in Java SE 5 in 2004. API, which makes it much easier to take advantage of multi- Prior to that release, any complex data structure was, essen- core processors. tially, dynamically typed. You could put a bunch of objects of some type T into a list, for example, but when you got them Java Magazine: What pain point will Java SE 9 address? back out they’d just be raw objects rather than objects of Reinhold: There really are two pain points, which turn out type T. So you’d have to insert cast operations wherever you to share a common solution. One pain point is that the Java did that, and that was error-prone and difficult to scale. The platform is a huge, monolithic thing that can’t be made generics feature addressed this pain point by introducing the any smaller. The other pain point is that large applications ability to abstract over types, also known as parametric poly- today are fairly brittle—that is, they’re constructed by morphism. You can now declare that a list is a list of objects of throwing tens or hundreds or even thousands of JAR files a particular type, and you no longer have to insert cast opera- onto the classpath, which is prone to all kinds of difficult-to- blog tions when accessing its elements. diagnose pathologies. The next big change to the language was lambda expres- The missing abstraction here is modules—that is, a way to sions, which were our response to another specific pain point: gather multiple packages of Java code and ancillary data, such It was too awkward to express computations that needed to as native code and resource files, and treat them as one unit 22
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 that declares explicit dependencies upon other modules and different kinds of developers who are going to use it. What is
controls exactly which packages are exported for use by other it we’re asking them to learn? What is it that they can learn COMMUNITY modules. Once we have a module system, we can apply that later, when they get around to it? What’s the best way to to the platform itself, dividing the platform into a set of mod- structure it so that it’s something they can learn and remem- ules so you can pick and choose the ones you need for your ber in a way that’s consistent with what they’ve learned and application. Applications themselves, rather than using the remembered about Java so far? classpath, can migrate to modular form so that they can be We also have to consider the uptake of new versions of reliably and safely configured. the platform. People often ask, “Why didn’t you just add the Looking beyond Java SE 9, we’re working on value types module system in an update release of Java SE 8?” Well, we JAVA IN ACTION and specialization. There, the pain point is the performance couldn’t, for many reasons. One is that Oracle is not the sole of applications that need very large implementer of the Java platform. amounts of data, especially data IBM, Red Hat, and SAP, among many JAVA SE 9 that would normally be held in very others, also implement it, and while small objects. When you have billions “Once we have a module system, we can many of those implementations of small objects you waste a lot of divide the platform into a set of modules so share some code, they can still be memory space and also a lot of time very different. Qualifying an imple- JAVA TECH accessing them, due to all the cache you can pick and choose the ones you need.” mentation takes a lot of time and is misses. The missing abstraction here not something that an implementer is value types, which are a lighter- can do at the drop of a hat. weight way to aggregate data values Another issue is uptake in enter- that does not require instantiation in the heap so that the JVM prises. People running large websites, for example, are not can, for example, pass them around in registers and lay them keen to update the underlying Java platform in a big way very ABOUT US out efficiently in arrays. frequently, because that, too, takes a lot of time and effort.
Java Magazine: Could you describe how your work on Java dif- Java Magazine: Finally, do you have any advice for younger fers from the standard bread-and-butter programming that developers? most developers engage in? Reinhold: Yes—learn how to write clear prose in English, Reinhold: If you’re a developer and your job is to deliver a or whatever your native language happens to be. If you working system that has to meet some requirements and can write clearly, then you can think clearly—and that’s run within one organization, then, well, life is actually pretty more important than learning any specific programming straightforward. You deliver code that meets the require- language. ments, it’s put into production, and you move on to the next thing. That’s not to say the work itself is easy, just that it’s not Timothy Beneke is a freelance author whose work has pre- hard to understand your ultimate goal. viously appeared in this magazine. He has written extensively blog Working on a widely used platform is very different—for about Java. example, there isn’t just one customer. When we design a new feature, especially one that’s far-reaching such as gener- LEARN MORE ics, or lambdas, or modules, we have to think about all the • Mark Reinhold’s blog 23
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java /
What’s New in JPA COMMUNITY Attribute conversion, schema generation, enhanced SQL queries, and a host of other improvements highlight JPA 2.1.
JOSH JUNEAU he Java Persistence API data. The application was Java type to a database type of a Java Boolean value. JAVA IN ACTION (JPA) is a fundamental originally built in an article or vice versa. For instance, We can code a converter into BIO T component for relational entitled PrimeFaces“ in perhaps JPA contains a speci- the application to convert a database–driven Java EE the Enterprise,” which fied mapping, and an appli- Java false value to an N applications. Although JPA 2.1 was published on Oracle cation requires something and a Java true value to a Y, was a minor release, some of Technology Network. different. JPA 2.1 allows you to and then store the values the new features that were write an attribute converter in in VARCHAR fields. To do so, JAVA TECH added pack a punch, and they Database Schema and such cases, to specify which you must create a converter can vastly improve overall Type Mapping database type should corre- class, which implements developer productivity. Developers face several spond to a specified Java type. the javax.persistence This article covers some of challenges when modeling Similar to a custom .AttributeConverter inter- the latest features in JPA 2.1, database tables with Java Hibernate type, attribute face. This interface accepts which was introduced with objects. JPA 2.1 brings various conversion can be applied to an X and a Y value, with X ABOUT US Java EE 7. Throughout the enhancements in database a basic attribute being the Java article, we will delve into the schema and type mapping, or to an element SCHEMA type and Y being new features of JPA 2.1, exam- helping to ease the transi- of a collection Automatic the corresponding ining examples of each in a tion between a relational type in order to con- database type. real-world application, so that database and Java objects. vert between schema A type con- you can begin applying these This section covers two of the a database attri- generation is verter should not new features to your Java EE new features that help in this bute (column) type be applied to Id applications today. area: attribute conversion and and a Java object achieved in attributes, version The AcmePools appli- schema generation. type. For instance, JPA 2.1 via a attributes, relation- cation we will use for the Attribute conversion. In order in the example combination of ship attributes, or examples in this article was to represent database tables application, we attributes denoted developed using Java EE 7 as objects, you must map would rather see a annotations and as Enumerated blog with JavaServer Faces (JSF) each database type to a Java String value of N or by specifying or Temporal, for the front end and using type, aka type mapping. For Y in the database because doing so Enterprise JavaBeans (EJB) some cases, JPA does not than a 0 or 1 for the properties. makes an applica- beans for working with automatically convert from a representation tion nonportable. 24
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6 Listing 1 demonstrates a converter generation. Automatic schema @Converter
for Boolean-to-String conversion. generation is achieved in JPA 2.1 COMMUNITY public class BooleanToCharacterConverter implements A converter can be applied auto- via a combination of annotations AttributeConverter
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 7 LISTING 8 LISTING 9 Invocation of Database providing a name, resultClass, public static void obtainCustomerPoolInformation(
Constructs procedureName, and parameters COMMUNITY long customerId, JPA 2.1 brings new techniques within the annotation. String[] poolInformation) throws SQLException { to invoke database constructs, In the example shown in Connection conn = null; enabling both passing parameters Listing ,8 the OBTAIN_ PreparedStatement stmt = null; and retrieving values. Now it is eas- CUSTOMER_POOL_INFORMATION ResultSet res = null; ier and less error-prone to invoke stored query is assigned to a database procedures and functions. name of ObtainCustomer try { This section covers a couple of PoolInformation, and it // "jdbc:default:connection" tells the JAVA IN ACTION these new features. returns a Pool object. A list of // DriverManager to use the existing connection. Named stored procedures. In @StoredProcedureParameter conn = DriverManager some instances, applications annotations can be specified to .getConnection("jdbc:default:connection"); need to call into the database assign parameters or return values // prepare the query and invoke stored procedures. In to the stored procedure. String sql = "SELECT STYLE, SHAPE, LENGTH, " + the past, developers relied upon In more-complex scenar- "WIDTH, RADIUS, GALLONS " + native SQL calls to invoke stored ios, a stored procedure might "FROM POOL P, CUSTOMER CUST " + JAVA TECH procedures in a database, but the require more than one result "WHERE P.ID = CUST.POOL_ID " + "AND CUST.CUSTOMER_ID = ?"; @NamedStoredProcedureQuery mapping. In these cases, the stmt = conn.prepareStatement(sql); annotation was introduced with the resultSetMappings attri- stmt.setLong(1, customerId); release of JPA 2.1, providing a more bute can be specified within res = stmt.executeQuery(); convenient and standard technique the annotation, passing a list of for invoking procedures that are @SqlResultSetMapping names. poolInformation[0] = ABOUT US stored within a database. Using this As seen in Listing ,9 to (res.next()) ? res.getString(1) : "N/A"; annotation, you can map a stored invoke the stored procedure . . . procedure to an identifier and map that is declared via the resultSet to one or more @NamedStoredProcedureQuery, } finally { entity classes. call upon the Entity Manager’s // Perform cleanup To demonstrate this function- createNamedStoredProcedure . . . ality, consider invoking a stored Query(), passing the assigned } procedure within the AcmePools name of the stored procedure. } database that retrieves pool Parameters can be passed to the information based upon a speci- resultingStoredProcedureQuery Download all listings in this issue as text fiedCustomer ID. The stored object by calling setParameter() procedure might look something and passing a position/value pair. blog like that shown in Listing .7 The Results can be returned by call- register parameters, or perhaps ParameterMode) method can stored procedure can be declared ing the StoredProcedureQuery do it in a more dynamic manner, be used. within an entity by specifying getOutputParameterValue() the registerStoredProcedure Stored procedure query via @NamedStoredProcedure and method. If you wish to manually Parameter(position, type, Entity Manager. Stored 26
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 10 LISTING 11a LISTING 11b LISTING 12 LISTING 13 procedures can also be mapped tor result mapping allows you to StoredProcedureQuery spq =
via the Entity Manager’s populate entities via the results of COMMUNITY em.createStoredProcedureQuery( createStoredProcedureQuery() a query. To implement such a solu- "OBTAIN_CUSTOMER_POOL_INFORMATION" method, passing the name of the tion using constructor result map- ); database-stored procedure. You ping, the @SqlResultSetMapping spq.registerStoredProcedureParameter( can then register parameters or annotation must specify a name, 1, Integer.class, ParameterMode.IN); assign return values using the and it should contain the classes spq.setParameter(1, customerId); setParameter() methods in the attribute with an assigned return spq.getResultList(); same manner as seen in Listing .9 @ConstructorResult. To demonstrate, Listing 10 In essence, the JAVA IN ACTION utilizes the same stored proce- @ConstructorResult annota- dure that was used in the pre- tion maps a target class to a series vious example. Only this time, of columns that are noted via there is no requirement to @ColumnResult annotations. The annotate any entity class with columns must be listed in the @NamedStoredProcedureQuery. order in which they are listed as JAVA TECH Instead, simply initiate arguments for the target class con- the stored procedure call structor. Listings 11a and 11b dem- using the Entity Manager’s onstrate how to construct an entity createStoredProcedureQuery() that facilitates constructor map- method, passing the name of the ping, and Listing 12 demonstrates database-stored procedure. how to populate the objects via a ABOUT US native query. SQL Queries, Updates, and Dynamic named queries. In some Query Enhancements circumstances, named queries Perhaps the area that received the need to be built dynamically, most updates with JPA 2.1 was the depending upon the specified SQL realm. Several improvements application. Under these circum- were added, facilitating more stances in pre-JPA 2.1 days, it was options than ever before for query- not possible to create a named ing, updating, and removing data query on the fly using dynamic from an underlying datastore. tactics. This is now possible thanks Download all listings in this issue as text Constructor result mapping. to EntityManagerFactory Constructor result mapping allows .addNamedQuery(). blog you to map the results of a query to The addNamedQuery(String, object itself, which can be gener- JPA Query Language enhance- the constructor of a Java object uti- Query) method accepts a String as ated dynamically. An example of ments. There are several improve- lizing the @SqlResultSetMapping the name that you wish to assign to generating a dynamic named query ments in the JPA Query Language annotation. As a result, construc- the query, and it accepts a Query is shown in Listing 13. (JPQL) area, providing the ability to 27
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 14 LISTING 15 LISTING 16 LISTING 17 perform more-complex queries. tion name and a comma-separated public List obtainAllCustomers(){
For example, to achieve a finer list of parameters, as follows: COMMUNITY TypedQuery
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 18 LISTING 19
public void updateMaintenanceByCity(String city, boolean enabled) { COMMUNITY CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaUpdate
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 20 LISTING 21 LISTING 22 be loaded. The hint can be of type to using them. public List
javax.persistence.fetchgraph Unsynchronized persistence COMMUNITY EntityGraph eg = or javax.persistence.loadgraph. context. Applications might contain em.getEntityGraph("customerWithDiscount"); The fetchgraph type treats a series of forms that are related return em.createQuery("select o from Customer o") all specified attributes as to each other, allowing a user to .setHint("javax.persistence.fetchgraph", eg) FetchType.EAGER, and it enter information into each form. .getResultList(); treats unspecified attributes as An example is a shopping cart or } FetchType.LAZY. The loadgraph an application wizard, for which a type also treats all specified attri- user needs to complete a series of butes as FetchType.EAGER, but it tasks prior to the completion of a JAVA IN ACTION then reverts to the default specified transaction. In such instances, it fetch type of the other attributes. can be beneficial to wait until all Listing 20 demonstrates the use the updates have been successfully of the customersWithDiscount made before flushing them to the entity graph. database. What happens if you wish to What happens if the power goes JAVA TECH access a relationship that exists out while a user is in the midst of Download all listings in this issue as text within the relationships that have making a purchase online? It would been loaded via an entity graph? In be best if the entire transaction such a case, it is possible to define were either committed at once or method is invoked. Listing 22 dem- each. I recommend that you work subgraphs within an entity graph to rolled back, instead of being only onstrates how to specify whether with the examples, and read the load relationships within those that partially completed. By default, an EntityManager should be Java EE 7 tutorial for more details. ABOUT US are loaded by an entity graph. Even when a database transaction has marked as UNSYNCHRONIZED. It also Although JPA 2.1 is not con- though this might sound confusing, been made, the changes are auto- shows an example of completing sidered a major release, there it is quite easy to achieve. Consider matically committed by the persis- the transaction. are several additions that help the case where a DiscountCode tence context. to solidify Java EE 7 as one of the entity included a relationship with The new UNSYNCHRONIZED enu- Conclusion most productive platforms avail- a SpecialSale entity.Listing 21 merated value allows you to indi- The feature list described in this able. Applying some of the tech- demonstrates the syntax that is cate that a specified persistence article does not cover the entire set niques that were covered in this used to load the SpecialSale context should be committed of new features that were intro- article will not only make you more entities as a subgraph. only after all transac- duced with JPA 2.1. There are sev- productive as a developer, but will There is a lot more THERE’S MORE tions that belong to a eral others, including the ability also allow you to achieve more to know about entity specified conversation to inject beans into entity listen- functionality. graphs, such as how to Read the Java have been completed, ers and implement @PreDestroy blog use the programmatic EE 7 tutorial for which is indicated when and @PostConstruct methods. API. Entity graphs are a the EntityManager Moreover, the features in this arti- LEARN MORE very powerful addition more details. instance’s cle were covered only briefly, and • Java EE 7 tutorial to JPA once you get used joinToTransaction() there is much more to learn about • AcmePools source code on GitHub 30
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things /
Brewing Java with the Raspberry Pi COMMUNITY Interact with a USB scale to accurately measure your coffee beans and brew the perfect cup.
he Raspberry Pi comes communication where the 80–compliant Place all these
USB DEVICE JAVA IN ACTION STEPHEN CHIN Tpreloaded with Java SE current scale value is repeat- implementation files in a new Embedded 8, so getting edly broadcast out over a of the standard The concept folder called BIO lib started with Java is as simple single endpoint on the first JavaX-USB speci- of stability is in your project as typing the java command interface. fication that has directory, and at the prompt. However, To use the scale, simply support for ARM important, because add them to your the ability to run Java on plug it into one of the host Linux distribu- scales do not project depen- your Raspberry Pi wouldn’t ports on your Raspberry Pi tions such as the immediately dencies in your JAVA TECH be complete without an and turn it on. It consumes Raspberry Pi. You IDE of choice. application to help perfect only 16 mA, so it can be can download register new You also need your coffee-brewing skills. safely powered right off the the latest ver- weights, so the to create a prop- This article takes a scientific Raspberry Pi USB bus. sion of usb4java erties file in the approach to coffee brewing The vendorId and from the project value can fluctuate root package that in order to obtain the perfect productId show up when website. tells the JavaX- quite a bit before it ABOUT US “cup of Joe.” you plug in the scale and run Make sure to settles down. USB wrapper to the dmesg command. For download both use usb4java as Communicating with a the Dymo M10 scale they are the core library as the implementa- USB Scale 0x0922 and 0x8003, respec- well as the javax tion. To accom- In order to precisely measure tively. For its sister scale, the extension. From the core dis- plish this, create a file called weight for coffee brewing, we Dymo M25, they are 0x0922 tribution you need to grab the javax.usb.properties are going to use a USB ship- and 0x8004, respectively. following JAR files: in the root package (under ping scale. USB communica- However, any compatible ■■ usb4java-1.2.0.jar src), and give it the contents tion is based on a series of Stamps.com or DymoStamp ■■ libusb4java-1.2.0- shown in Listing 1. pipes (logical channels) that scale should work fine as long linux-arm.jar To test the data returned are connected to the device as you change the vendorId ■■ commons-lang3-3.2.1.jar from the scale, we are going via endpoints. Furthermore, and productId in the code. And you need these addi- to use a single-class imple- blog these endpoints are grouped For communication with tional JAR files from the mentation of the USB scale into a set of interfaces. The the USB scale, we are going usb4java-javax distribution: protocol that returns 60 data protocol used by most ship- to use the usb4java library. ■■ u s b - a p i-1.0.2.j a r points and prints out the ■■ ping scales is simple one-way This is an open source, JSR usb4java-javax-1.2.0.jar results on the command line. 31
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6 This will be the basis for our coffee- same-named method on the javax.usb.services = org.usb4java.javax.Services
brewing application. UsbPipe: COMMUNITY The main method for our appli- cation is shown inListing 2 and can private void syncSubmit() be summarized as follows: throws UsbException { ■■ Find a connected USB scale. pipe.syncSubmit(data); ■■ Open a connection to the scale. } ■■ For 60 data points, submit a request to retrieve data. However, the real work happens JAVA IN ACTION ■■ Close the scale. in the callback. To receive the call- To ensure the scale is closed back, our class needs to implement properly even in the case of an the UsbPipeListener class, which error or exception, we are using a has two required methods. The try finally block. first is dataEventOccurred, which Listing 3 shows the implementa- will be called as a result of invoking tion of the first method,findScale , syncSubmit and contain the data JAVA TECH which discovers Dymo M10 or M25 returned from the scale. The second scales using the JavaX-USB API. is errorEventOccurred, which This calls the findDevice method, will be invoked when there is a which contains code that traverses problem interfacing with the scale. the USB device tree (see Listing ).4 The data sent by these shipping To read data from the scale, scales is a simple byte array that ABOUT US we need to connect to the cor- contains six values. The protocol Download all listings in this issue as text rect interface and endpoint. is not well documented, but it has Fortunately, the USB scale protocol been reverse-engineered by the is fairly simple, so you can simply open source community. The data ■■ Byte 5—Base weight high- In the case of an error, the best grab the first interface and end- is as follows: order byte we can do is log the error and con- point and then start listening to ■■ Byte 0—Unused Listing 6 shows the implementa- tinue (see Listing ).8 the data coming in from the scale ■■ Byte 1—Special flags: empty=2, tion of dataEventOccurred, which And the last method to finish the directly, as shown in Listing .5 overweight=6, negative=5 takes apart the byte array returned scale test is the close algorithm. Notice that we had to use the (The conditions indicated by and prints out a human-readable This simply closes the pipe and claim method that accepts a overweight and negative are scale value to the command line. interface cleanly so that the next UsbInterfacePolicy. This allows described later.) Besides doing a little bit of bit- application that tries to use the us to force the kernel to detach ■■ Byte 2—Unit of measure: shifting to get the weight mag- scale will be able to access it: blog from the USB interface so we can grams=2, ounces=11 nitude, we also need to scale the claim it for our application. ■■ Byte 3—Weight scale weight by the scalingFactor public void close() throws The implementation of ■■ Byte 4—Base weight low- returned in byte 3, as shown in UsbException { syncSubmit is trivial, calling the order byte Listing .7 pipe.close(); 32
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 7 LISTING 8 LISTING 9 LISTING 10 iface.release(); Specialty Coffee Association of private double scaleWeight(int weight, int scalingFactor) {
} America (SCAA) Coffee Brewing COMMUNITY return weight * Math.pow(10, scalingFactor); Control Chart to select the opti- } When you run the completed mum amount of ground coffee for UsbScaleTest class, it will compile our beverage. This chart is based and deploy the JAR file as before, on research in the 1960s led by Dr. but this time it will show some Earnest Earl Lockhart, who is best more-interesting output. If you known for his graphical representa- have your scale connected and tion of coffee brewing parameters turned on, it should output the first along with a recommended guide JAVA IN ACTION 60 readings from the scale, includ- for optimum strength and extrac- ing information about whether the tion. The North American version of scale is empty, overweight, or nega- this chart is shown in Figure 1. tive, as shown inListing .9 There are three different units Try adding a few objects of dif- represented on this chart. The ferent weights while the scale is strength of the coffee is repre- JAVA TECH returning data to get a feel for how sented on the vertical axis as a the USB interface works. If you percentage of the total dissolved want to get a negative value, add solids (TDS), the extraction rate is an object to the scale, press the represented on the horizontal axis TARE button (to zero the scale), and as a percentage, and the brewing Download all listings in this issue as text then remove the object. To get an ratio is represented in grams per ABOUT US overweight reading, add an object liter by the diagonal lines. that is heavier than the scale sup- Our target density for a “regular” the Norwegian Coffee Association assuming all values are in grams, ports (for example, an 11-kilogram cup of coffee will be 55 grams further moves the optimum because this is what most scales object on the Dymo M10 scale). per liter, which gives the highest strength up from 1.3 percent to use and there is a straightforward Be careful not to use an object chance of hitting the SCAA’s opti- 1.5 percent soluble concentration, conversion from volume to mass of that is too heavy, because it can mum balance for a given extraction which will define our “strong” cup water in the metric system. break the scale’s sensitive internal percentage. of coffee at 62 grams per liter. A simple example of using this components. There is also a Specialty Coffee Listing 10 shows a class would be to calculate how Now it’s time to apply this to Association of Europe (SCAE), CoffeeCalculator class that much ground coffee to use for a brew some perfectly proportioned which recommends the same takes these principles and turns 300-gram cup of water: coffee, and for that we need a 18 percent to 22 percent extrac- them into code that will help us coffee calculator. tion rate, but moves the optimum calculate the perfect brew. grindWeight(REGULAR, 300) blog strength up from 1.2 percent to 1.45 Given a target liquid volume Calculating Perfect Coffee percent soluble concentration. (cup size), the CoffeeCalculator This code returns 17.4 grams, The science behind our appli- This will define our “rich” cup of class will help us determine how which should sound about right cation is that we will apply the coffee at 58 grams per liter. Finally, much ground coffee to use. We are if you have ever followed a coffee- 33
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 11
public void dataEventOccurred(UsbPipeDataEvent upde) { processData(); COMMUNITY if (closing) { busy = false; } else { try { pipe.asyncSubmit(data); } catch (UsbException ex) { errorEventOccurred( JAVA IN ACTION new UsbPipeErrorEvent(upde.getUsbPipe(), ex)); } } scalePhaser.arrive(); } JAVA TECH
Download all listings in this issue as text
the current weight to take a read- Phaser is one of the new thread ing, it is impossible to differentiate control classes introduced in Java between the stale buffered data SE 7, and it is ideally suited for this ABOUT US and the current scale weight unless purpose, because it allows the we read and discard a fixed amount notification of arrival from a single of data. By reading data continu- thread to unblock potentially mul- ously, we have an instantaneous tiple threads. To create aPhaser for snapshot of the current scale value this purpose, simply construct one in memory at all times, and we can with a single party like this: simply block our thread until the next reading is available if we are private final Phaser scale- Figure 1 waiting for a specific value. Phaser = The code in Listing 11 implements n e w Phase r(1); brewing recipe from one of the our earlier example, this turns out a new USBPipeListener callback, popular gourmet coffee roasters. to be a poor choice for our coffee which processes the returned data, Because there is only one reg- blog algorithm. The reason is that USB submits a new request for data, istered party, the Phaser fires on Asynchronous Communication scale data is buffered, so reading on and notifies any threads blocked each call that arrives. Then, block- While we used a synchronous demand returns stale data initially. on the scalePhaser that we have ing on it is as simple as calling algorithm for reading the scale in If we wait until we need to know new data. awaitAdvance with the current 34
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 12 LISTING 13 LISTING 14 phase value, as shown in Listing 12. for the Scale method is shown in public void waitFor(DoublePredicate condition) {
The waitFor method dem- Listing 13. COMMUNITY while (!condition.test(getWeight())) { onstrates the use of the There are two additional scale scalePhaser.awaitAdvance(scalePhaser.getPhase()); DoublePredicate functional concepts introduced here in order } interface introduced in the Java 8 to improve the reliability and con- } release to support lambdas. This sistency of our coffee recipe: a allows it to take an arbitrary condi- stable scale value and a program- tion as a lambda expression to wait matictare . The concept of stabil- for, such as waiting for the scale to ity is important, because scales read 80 grams or more: do not immediately register new JAVA IN ACTION weights, so the value can fluctuate scale.waitFor(w -> w >= 80); quite a bit before it settles down. Some scales implement the con- This is the basis for an improved cept of stability directly in their version of the USB scale communi- data reporting; however, USB scales cation logic refactored into a new do not do this. As a workaround, JAVA TECH class called UsbScale.java. It also when updating the weight, we will Download all listings in this issue as text implements a unifiedScale inter- compare the last few results to see face that can be used to create an whether we have reached a steady alternate implementation for serial state, as shown in Listing 14. Resetting the scale value to zero, } scales. The full set of methods This allows us to have more- also called taring, is an important reliable results when executing part of executing our coffee recipe. The full source code for the ABOUT US the recipe, because we know that Some scales allow you to send a Scale and UsbScale classes can when we hit a target value, the command that programmatically be downloaded from the GitHub value is no longer bouncing but tares; however, these USB scales repository. has actually stabilized. You can do not, so the best we can do is to control the number of weights to prompt the user to press the TARE Coffee Brewing Recipe compare for stability by adjusting button manually. To indicate that Now that we can asynchronously the size of the pastWeights array. programmatic taring is not sup- communicate with a scale hooked There is a trade-off between speed ported by our scale, we are going to up via USB, the next step is to and accuracy, but a good number reuse the built-in Unsupported build a coffee recipe that uses our seems to be comparing two past OperationException: CoffeeCalculator and UsbScale readings against the current classes. While you can use any cof- weight measurement: @Override fee brewing method of your choice, blog public void tare() { we are going to recommend try- private final int[] past- throw new ing the Aerobie AeroPress brew- Weights = UnsupportedOperationExcep- ing system shown in Figure 2. It is Figure 2 new int[] {-1, -1}; tio n(); a simple and inexpensive coffee 35
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 15
public AeroPressCoffee(double strength) { beans = Ingredient.byWeight(CoffeeCalculator.grindWeight( COMMUNITY strength, CUP_SIZE), "Coffee Beans"); brewingWater = Ingredient.byWeight(beans.getWeight() / BREW_RATIO, "Water"); extraWater = Ingredient.byWeight(CUP_SIZE – brewingWater.getWeight(), "Water"); } JAVA IN ACTION @Override public Ingredient[] ingredients() { return new Ingredient[]{beans, brewingWater, extraWater}; } JAVA TECH
Figure 3 Download all listings in this issue as text brewing device that also travels well free filtered output similar to what as a portable coffee maker. you get with filtered brewing. As a a Recipe interface to describe method is the actual set of steps. The way the AeroPress works is result, it is much less sensitive to how we are going to specify our While it would be possible to sim- that you put your ground coffee and grind size and uniformity; however, AeroPress brewing method and ply write the steps as straight Java ABOUT US a portion of the heated water into we still recommend using a high- other recipes you might create in code, this method allows us to later the main chamber. The extraction quality conical burr grinder that will the future. The Recipe interface make improvements in recipe flow, occurs directly in the main chamber not heat up your beans. If you don’t has four methods: such as skipping or repeating steps. as you stir the grounds and brew have an electric grinder already, The Ingredient and Step for 60 seconds. Then you insert the a good choice that pairs well with public interface Recipe { classes are fairly straightforward, plunger and create a pressurized the travel-friendly nature of the String name(); and both follow a factory pattern space to force the water through AeroPress is a Japanese-made hand String description(); where they supply static methods the filter. The resulting liquid is a grinder, such as the Porlex Mini Ingredient[] ingredients(); that can be used to construct an concentrated form of coffee closely shown in Figure 3. Not only does Step[] steps(); instance of the class. In the case resembling espresso, which can it produce very fine and consistent } of the ingredients, we will specify then be diluted to the desired cof- grounds, but it also perfectly fits in them by weight, making use of fee strength by adding additional the AeroPress chamber once the The first two methods provide our CoffeeCalculator class, as blog hot water. crank handle is removed. the name and description of the shown in Listing 15, which shows The AeroPress combines the ben- To support reusable recipes, we Recipe we will be making. The the initialization of ingredients for efit of uniform extraction provided are going to build a little bit of infra- third returns a list of ingredients the AeroPressCoffee recipe. by a French press with a sediment- structure first. To start, we need using a wrapper class, and the final This algorithm is designed to 36
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //internet of things / LISTING 16 LISTING 17 LISTING 18 LISTING 19 create a fixed volume of liquid, through the process of creating the private static final double CUP_SIZE = 300; // grams
which is set by the CUP_SIZE con- perfect cup of Java, as shown in COMMUNITY private static final double BREW_RATIO = .2; // beans/water stant in grams/milliliter, and it will Listing 17. To give this a try, down- use the strength passed in to the load the full source code from the constructor, which should be one GitHub repository. of the constants defined in the The main class is called CoffeeCalculator class for a JavaScale, and it executes a regular, rich, or strong cup of coffee. CommandLineRecipeRunner Because we are using an that will fire off our AeroPress, there is an additional AeroPressCoffeeRecipe for a JAVA IN ACTION constant called BREW_RATIO, strong cup of coffee (see Listing 18). which deter- Listing 19 shows the output of run- GOOD COFFEE mines how ning the JavaScale application much water with the default settings. The important part: we mix with Once you have tried it with the The recipe consists the ground default settings, here are some JAVA TECH of 19 steps that coffee initially things you might want to try and affects tweaking: walk you through the extrac- ■■ Change the strength of the cup the process of tion process. of coffee REGULAR( or RICH). If you notice ■■ Adjust the volume of coffee creating the that your cof- created (but remember that the ABOUT US perfect cup of fee is bitter AeroPress has a physical limit on (overextracted how much liquid it can use dur- Java. from too much ing the extraction process). water) or sour ■■ Fine-tune the BREW_RATIO for (underex- your bean type and preference. tracted from not enough water), you can tweak this parameter Conclusion to change the volume of water With luck, you have enjoyed pro- Download all listings in this issue as text pressed through the ground cof- gramming your brew as much fee. Our recommended targets as you did drinking it! For more for these constants are shown in examples of what you can do article was adapted. It includes LEARN MORE Listing 16. with embedded Java, check out this coffee recipe example as well blog • GitHub repository And finally, we come to the upcoming McGraw-Hill book as examples for general-purpose the important part: the entitled Raspberry Pi with Java: input/output (GPIO) devices, • usb4java, a Java library for AeroPressCoffee recipe. This Programming the Internet of networking, drones, 3-D printing, accessing USB devices • JSR 80 (Java USB API) consists of 19 steps that walk you Things (IoT), from which this and more. 37
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / Part 1 Contexts and Dependency Injection: COMMUNITY the New Java EE Toolbox ANTONIO GONCALVES Using strong typing in dependency injection BIO JAVA IN ACTION
ependency injection With type-safe injection, BookService <
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 1 LISTING 2 LISTING 3 LISTING 4 public class Main { don’t have to do construction of public class BookService {
public static void dependencies by hand. To see how COMMUNITY main(String[] args) { this works, let’s re-examine our private NumberGenerator generator; Book book = example. new BookService( In CDI, there’s an annotation you public BookService(NumberGenerator generator) { new IsbnGenerator()). need to remember: it’s @Inject, this.generator = generator; createBook("H2G2"); which is used by the runtime to } System.out.println(book); inject the reference of an imple- } mentation. So, change the code public Book createBook(String title) { JAVA IN ACTION } of the BookService, get rid of the return new Book(title, generator.generateNumber()); constructor, and use @Inject on } In the Main class, the implemen- the NumberGenerator interface, as } tation of the NumberGenerator shown in Listing 2. is passed as a parameter of the Which implementation is Download all listings in this issue as text constructor. So if you need a injected: the IsbnGenerator, which BookService that generates an generates a thirteen-digit ISBN JAVA TECH ISBN number, you just pass the number, or the IssnGenerator, the IsbnGenerator implementa- Then, if you need to inject the IsbnGenerator implementation which generates an eight-digit ISSN tion, I created a qualifier called IsbnGenerator, qualify the injec- to the constructor. If you need to number? Neither. CDI considers @ThirteenDigits: tion point on the BookService (see generate an ISSN number, you this injection ambiguous, won’t Listing )3 and the IsbnGenerator change the implementation to be deploy the application, and throws @Qualifier implementation (seeListing ).4 IssnGenerator. This is what’s called an exception. At system initializa- @Retention(RUNTIME) As you might have guessed, if ABOUT US Inversion of Control (IoC): the con- tion, the CDI runtime must validate @Target({FIELD, TYPE, METHOD, you change the injection point trol of choosing the dependency that exactly one bean satisfies each PA R A M ETER}) to @EightDigits, CDI injects the is inverted because it’s given to an injection point. So, if two imple- public @interface IssnGenerator implementation. external class. But at the end of mentations of NumberGenerator ThirteenDigits { A CDI qualifier is basically a the day, you end up constructing were available, the container } Java annotation with an extra dependencies programmatically, would inform you of an unsatisfied @Qualifier annotation. A qualifier and you can leave an injector to do dependency and wouldn’t deploy I also created a qualifier called represents some semantics associ- it. And that’s where CDI can help. the application. @EightDigits for the IssnGenerator: ated with a type that is satisfied by To solve this ambiguous depen- some implementation of that type. Injecting with CDI dency, the solution is to have dif- @Qualifier It’s a user-defined annotation and CDI is a standard solution that ferent qualifiers: a different one @Retention(RUNTIME) can be called whatever you want to manages dependencies between for each implementation. That’s @Target({FIELD, TYPE, METHOD, call it. You can introduce a qualifier blog classes. Injection is made using when you need to create your PA R A M ETER}) to represent a thirteen-digit gen- strongly typed annotations, called own annotations and give them public @interface EightDigits erator or an eight-digit generator. qualifiers. CDI removes boilerplate a specific name that suits your { The idea is that you can create as code by using a simple API, so we business. In this case, to qualify } many qualifiers as your application 39
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 5 LISTING 6 LISTING 7
BookService <
Book EIsbnGenerator PIsbnGenerator public Book createBook(String title) { -title return new Book(title, generator.generateNumber()); -number } } EIssnGenerator PIssnGenerator JAVA IN ACTION
Figure 2
needs. After you define the needed fier, which is why the dependency qualifiers, they must be applied on is ambiguous. CDI doesn’t know JAVA TECH the appropriate implementation which implementation to choose Download all listings in this issue as text and injection point. from. That’s why you had to create The default qualifier. Now let’s see specific qualifiers. why the dependency in Figure 1 The injection point. The @Inject every Java EE specification has an or interceptors. was ambiguous. Assume that you annotation defines an injection optional XML deployment descrip- Qualifiers with members. Imagine haven’t qualified anything yet, point that is injected during bean tor. It usually describes how a that our NumberGenerator inter- and that @ThirteenDigits and instantiation. Injection can occur by component, module, or application face has several implementations ABOUT US @EightDigits don’t exist. three mechanisms: property, setter, should be configured. With CDI, (see Figure 2): EIsbnGenerator Whenever a bean, or injection or constructor. The code in Listing 2 the deployment descriptor is called generates thirteen-digit ISBN point, doesn’t explicitly declare a uses property injection. With this beans.xml (see Listing 7) and is numbers for electronic docu- qualifier, CDI assumes the qualifier mechanism, you don’t have to cre- also optional. ments, and EIssnGenerator gen- @javax.enterprise.inject.Default. In ate a getter and a setter. CDI can In the beans.xml, you can set erates eight-digit ISSN numbers fact, the BookService in Listing 2 is access an injected field directly, bean-discovery-mode to change for electronic documents. For any identical in having a default injec- even if it’s private. But instead of the CDI bean discovery resolution. document that is printed on paper, tion point, as seen in Listing .5 annotating the attributes, you can The default is annotated, in which you need different generators: the @Default is a built-in qualifier that add the @Inject annotation on a case CDI discovers only annotated PIssnGenerator generates an eight- informs CDI to inject the default constructor (see Listing ).6 In this beans. But it can be changed to all digit number, and PIsbnGenerator bean implementation. If you define case, the rule is that you can only (so all the beans are discovered) or generates a thirteen-digit number. a bean with no qualifier, the bean have one constructor injection none (to disable CDI discovery on You could imagine having even blog automatically has the qualifier point. The other choice is to use a particular archive). The beans more implementations. You could @Default. Both implementations setter injection, which looks like .xml descriptor can also be used create as many qualifiers as you IsbnGenerator and IssnGenerator constructor injection. to configure certain functionalities have implementations. But if you have the same @Default quali- The deployment descriptor. Nearly such as alternatives, decorators, create a qualifier each time you 40
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 8 LISTING 9 LISTING 10 LISTING 11 LISTING 12 LISTING 13 need to inject something, your The way you use qualifiers with @Target({FIELD, TYPE, METHOD})
application will be very verbose members on injection points COMMUNITY @Retention(RUNTIME) with lots of empty qualifiers. That’s doesn’t change from what we’ve @Qualifier when qualifiers with members seen. The injection point quali- public @interface Generator { can help. fies the needed implementation A qualifier is an annotation, so by setting the annotation -mem NumberOfDigits numberOfDigits(); it can have as many members bers. In Listing 10, you inject boolean printed(); of any type as needed. Here, I the thirteen-digit generator for got rid of the @ThirteenDigits electronic documents, and just by public enum NumberOfDigits { JAVA IN ACTION and @EightDigits qualifiers and changing the printed value to true, EIG H T, replaced them with a more- CDI injects a different implemen- THIRTEEN generic one called @Generator tation. Change the enumeration } (see Listing ).8 This @Generator value and you get an eight-digit } qualifier has a first member of number generator for printed type NumberOfDigits. With this documents. Download all listings in this issue as text enumeration, you can differenti- Multiple qualifiers. Another way JAVA TECH ate beans that generate 13 digits of qualifying a bean and an injec- or 8 digits. The second member is tion point when there are many Alternatives the novelty is that MockGenerator called printed and is of type bool- implementations is to specify With qualifiers, you can choose is annotated with the @Alternative ean. It is set to true to represent a multiple qualifiers. So, you could between multiple implementa- qualifier (see Listing 12). This number for printed documents, keep @ThirteenDigits to qualify a tions of an interface at develop- means that CDI treats it as and it is set to false for electronic thirteen-digit number generator ment time in a type-safe manner. the default alternative of the ABOUT US documents. and @EightDigits to qualify But sometimes you want to inject NumberGenerator. To differentiate the four imple- an eight-digit number generator. an implementation depending on In terms of the injection point, mentations, use your Generator But because this is not enough, a particular deployment scenario. nothing changes. BookService is qualifier and set different values you could create other qualifiers For example, you might want to not affected (see Listing ).2 The on each member. EIsbnGenerator for electronic documents and use a mock number generator code injects the default imple- generates a thirteen-digit printed documents. but only in a testing environment. mentation of a number generator, number for electronic The idea is always to That’s when you can use alterna- because alternatives are disabled CDI QUALIFIERS documents, so the mem- identify each imple- tives. Alternatives are beans anno- by default. So until this point, ber numberOfDigits has Qualifiers are mentation uniquely so tated with the special qualifier CDI would not inject the mock the value THIRTEEN and a type-safe CDI can wire dependen- @Alternative, which are disabled by implementation. To enable the the member printed cies. Another way to default. You need to enable alterna- @Alternative, you need to add it to is false (see Listing ).9 way to resolve qualify EIsbnGenerator tives in the beans.xml descriptor to the beans.xml deployment descrip- blog Each implementation ambiguous would be to aggregate make them available for instantia- tor (see Listing 13). It’s just a matter is uniquely defined, both @ThirteenDigits tion and injection. of adding the fully qualified class thanks to the values of dependency. and @Electronic (see Let’s add a new MockGenerator name of the MockGenerator inside the qualifier. Listing 11). implementation. In terms of code, an alternatives element. You can 41
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 14
@Alternative @ThirteenDigits COMMUNITY public class MockGenerator implements NumberGenerator {
public String generateNumber() { return "mock-" + Math.abs(new Random().nextInt()); } 3 Billion }
Devices Run Java JAVA IN ACTION Download all listings in this issue as text
have several beans.xml files declar- are annotations, so they can have ing several alternatives, depending members or be aggregated with on your environment—for example, other qualifiers to form a uniquely ATMs, Smartcards, POS Terminals, Blu-ray Players, JAVA TECH one beans.xml file for testing with defined injection point. Alternatives Set Top Boxes, Multifunction Printers, PCs, Servers, all the mock alternatives, one for can be used to affect injection production without any mocks, and points at deployment time, thanks Routers, Switches, Parking Meters, Smart Meters, so on. to the beans.xml deployment Lottery Systems, Airplane Systems, IoT Gateways, Alternatives can be quali- descriptor. As you can see, CDI is fied. So you could define the rich in terms of injection, is type- Programmable Logic Controllers, Optical Sensors, ABOUT US MockGenerator as the alterna- safe, and has an easy-to-use API. tive for only IsbnGenerator (thir- This article is the first of four Wireless M2M Modules, Access Control Systems, teen digits). Listing 14 says that about CDI. The next article explains Medical Devices, Building Controls, Automobiles… if the alternative is enabled in how to integrate third-party frame- beans.xml, and if you inject the works using producers. The third @ThirteenDigits implementation, article focuses on how you get CDI always injects the mock. loose coupling with interceptors, decorators, and events. The last Conclusion article covers the integration of CDI CDI accommodates simple injec- in Java EE. #1 Development Platform tion cases, such as the default injection, but it can also solve blog LEARN MORE more-complex cases, thanks to qualifiers. Qualifiers are used as • CDI specification a type-safe approach for solving • Weld reference implementation ambiguous dependency. Qualifiers • Beginning Java EE 7 (book) 42
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015
//new to java / Part 2 Create a Simple Paddle Game with COMMUNITY Microsoft Kinect MICHAEL KÖLLING More fun with using Greenfoot to drive Kinect from Java BIO JAVA IN ACTION
reenfoot is a Java-based one held in each hand (see installed, and then open the previous article. Now you’re Ggraphical programming Figure 1). scenario and play it. Read ready to get started with environment aimed at novice through the code of the exist- the Kinect programming for developers. In the September/ Old-Style Pong ing classes—they should be this scenario. October 2014 issue of Java Start by downloading the easy to understand. JAVA TECH Magazine, we started pro- base project so you can Then set up your Kinect Detecting Users gramming with Greenfoot program along as you read and start the Kinect The first thing we want to do and Microsoft Kinect, a sen- through this article: kinect- server, as described in the is to detect when a user steps sor board that lets you track pong.zip. This body movements of people Greenfoot sce- in front of a camera. If you nario implements ABOUT US aren’t familiar with either a basic Pong-style Greenfoot or Kinect, read the game: Players previous article first to learn bounce a ball up more about the setup of the and down with hardware and the system, paddles at the the basics of accessing Kinect top and bottom from Greenfoot, and the pro- of the screen. The gramming tasks required for bottom paddle is a painting program that let us controlled by the paint onscreen by moving our player using the hands in the air. cursor keys on the In this article, we take a tra- keyboard, and the blog ditional, keyboard-controlled top paddle is com- Pong-style game and turn it puter controlled. into a game controlled with Make sure you PHOTOGRAPH COURTESY OF UNIVERSITY OF KENT Figure 1 gestures—using two paddles, have Greenfoot 44
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 1 in front of the Kinect camera. Our method is called repeatedly while public class PongWorld extends KinectWorld
game should be in an idle state the scenario is running, many balls COMMUNITY { (waiting) as long as there is no user, and paddles would be created. We private boolean idle; and then starts when a user enters need to make sure that this hap- Kinect’s view. In our project, we pens only once, when the player /* Create the game world with the game objects in it. */ implement this in the PongWorld first enters the view. Use theidle public PongWorld() class. flag, which is already defined in the { We can get an array of all class, for this purpose: su p e r (); users being tracked by using the addObject(new ComputerPaddle(), 200, 30); JAVA IN ACTION getTrackedUsers method: if (idle) { idle = true; if (users.length > 0) { } UserData[] users = startGame(); getTrackedUsers(); idle = false; /* Nothing to do. */ } public void act() We can then check whether } { any users are present by checking s u p e r.a c t(); JAVA TECH whether the length of this array You can see the code completed UserData[] users = getTrackedUsers(); is zero: so far in Listing 1. if (idle) { // check whether a user has arrived if (users.length > 0) { Controlling the Paddle if (users.length > 0) { ... At the moment, our game detects // discovered a new user } a player in front of the camera, but startGame(); ABOUT US the player can’t control the paddle idle = false; Start by moving the code that yet. This is what we will do next. } creates the PlayerPaddle and For the paddle to make use of the } the Ball from the PongWorld player’s information, we need to } constructor into a new private pass the tracked user data into the method called startGame. Then, PlayerPaddle object. Because this private void startGame() we can call this method from our is a single-player game, we can just { act method when a user enters use the first tracked user out of our addObject(new PlayerPaddle(), 200, 450); the game: array (ignoring all others if there is addObject(new Ball(), getWidth()/2, getHeight()/2); more than one user) and pass it to } } if (users.length > 0) { our startGame method: startGame(); blog } startGame(user[0]);
This code is somewhat prob- We then add the appropriate Download all listings in this issue as text lematic, though: Because the act parameter to the definition of our 45
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 2 LISTING 3 LISTING 4 startGame method, and pass the setLocation( hand.getX(), private void startGame(UserData user)
parameter into the PlayerPaddle g e t Y()); COMMUNITY { constructor. The new version of the addObject(new PlayerPaddle(user), 200, 450); startGame method doing this is Listing 3 shows the complete addObject(new Ball(), getWidth()/2, getHeight()/2); shown in Listing 2. class at this stage. Try it out: You } Now we’ll move on to the should be able to play the game PlayerPaddle class. In the now and control the paddle with PlayerPaddle constructor defini- your hand. tion, we add a parameter to receive the UserData object and then Stopping the Game JAVA IN ACTION store it in an instance field: Currently, we start the game when a player enters the view of the cam- private UserData user; era, but we don’t stop it when the player leaves. That makes our game public PlayerPaddle( unplayable for anyone after the first UserData user) player has finished. JAVA TECH { Let’s add some code that detects this.user = user; when a player leaves the game and } have it respond appropriately. For this, go back to our PongWorld Now we have the user data avail- class. able to rewrite the act method. In this class, add a new private ABOUT US The current act method con- method called stopGame, which tains code that moves the paddle removes the PlayerPaddle and in reaction to cursor keys. Remove Ball objects when the game stops. this code. Listing 4 shows an implementation. Instead, we now want to add code You must also modify your act that sets the position of the paddle method so that it calls stopGame according to the right hand of the when the world isn’t idle and no user. We can achieve this by getting users are visible. (Look ahead to the user’s hand’s x-coordinate and Listings 6a and 6b if you have trou- Download all listings in this issue as text using that as the paddle’s x-coordi- ble doing this on your own.) nate. We’ll leave the y-coordinate of After this much coding, it’s good the paddle unchanged. The code to to test. When you start the sce- start. When you leave the view of The Two-Paddle Version blog do this is as follows: nario, there should be no ball and the camera, Kinect should attempt The last task is to extend our game no player paddle. Once you step into for another few seconds to track to use both our hands by giving the Joint hand = user.getJoint( Kinect’s view, the paddle and ball you, and then give up. The paddle player two paddles, one controlled Joint.RIGHT_HAND); should appear, and the game should and ball should then disappear. by each hand. 46
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //new to java / LISTING 5 LISTING 6a LISTING 6b In the current version of the stant to create the second paddle: import greenfoot.*;
PlayerPaddle class, we used the COMMUNITY constant Joint.RIGHT_HAND to new PlayerPaddle(user, /** specify which hand we want to Joint.LEFT_HAND) * A pong game paddle controlled by the player. track. We now generalize this class * so that it can track either hand, Listings 6a and 6b show the * @author Michael Kölling and then we can create two paddle complete PongWorld class, includ- * @version 1.0 objects—one for each hand. ing these additions. */ The type of this constant is an public class PlayerPaddle extends Paddle JAVA IN ACTION int. We, therefore, add an int Conclusion { parameter to specify the hand to This example shows how to use the private UserData user; the PlayerPaddle constructor, and Microsoft Kinect’s input to control private final int HAND; // right or left hand store the value we receive in a field. a little game. If you programmed Then, when we want to retrieve along as you read this article, you’ve /** the hand’s x-coordinate in the act seen that using the location data of * Create a player paddle. method, we use this field to specify tracked users to control your pro- * The parameters are the user data of the controlling JAVA TECH which hand to use. The full code for gram isn’t difficult. * user, and a constant specifying which hand to track. */ this is shown in Listing .5 The Kinect-based examples public PlayerPaddle(UserData user, int hand) After setting the paddle like this, work very well to demonstrate how { we must adapt the code that cre- easy it can be to program in Java. this.user = user; ates the paddle to pass the addi- Greenfoot makes it easy to get this.HAND = hand; tional parameter for the hand. started with Java programming, } ABOUT US Previously, the instruction to create including working with Kinect. the paddle looked like this: The example presented here /** is taken from Introduction to * Place the paddle at the x-location of the new PlayerPaddle(user) Programming with Greenfoot * user's hand. (Pearson, 2015), which discusses */ Now we add the second param- it in more detail. You can also find public void act() eter to make it look like this: other Greenfoot Kinect projects { there. Joint hand = user.getJoint(HAND); new PlayerPaddle(user, setLocation(hand.getX(), getY()); Joint.RIGHT_HAND) } } LEARN MORE Adding a second paddle for the blog other hand is now easy. Just dupli- • Greenfoot download page cate the line of code that creates • Instructions for Greenfoot and the paddle and adds it to the world, Kinect setup Download all listings in this issue as text and then use the left-hand con- • Greenfoot book 47
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //career / Part 2 More Ideas to Boost Your COMMUNITY Developer Career Study code, go to conferences, but use the conferences to build your network. JAVA IN ACTION
n the first article of this to do, nor time consuming. In the software world, the and see how other develop- I series (January/February You can squeeze them into way to watch others perform ers do it. Don’t know the 2015 issue, p. 25), we intro- your busy day. is by looking at their software, proper way of doing logging duced three broad areas and the source code they in your systems? Get an open BRUNO SOUZA AND that you could focus on to Code: Open Source wrote. That allows us to study source project you use that JAVA TECH EDSON YANAGA improve your career as a Software it, experiment with it, and provides great logging infor- BIO developer. Code is the most We have already seen that to even improve it. But for that, mation and learn to do it the important, because this is be good at coding, you must we need access to the source same way. the basic skill for a developer. practice a lot. But even with code of great developers. Contributing to open source But the other two, which practice, how do you know if This is the beauty of open enables you to practice some we named and you’re writing good code or source: It’s freely available skills that maybe you don’t
Community ABOUT US Think Differently, can’t be left bad code? We still have not for you to study and compare (or can’t) use in your daily behind. They are the things reached the point of having a with your own code. You can work. Many of us are limited that will help you break practical and noncontrover- find a huge variety of differ- at work to creating traditional through the boundaries of sial way of measuring code ent projects on GitHub and enterprise systems with cre- your career. quality. Code quality is still Bitbucket, ranging from small ate, read, update, and delete Spending some weekly most of the time a qualita- to enterprise-level projects. (CRUD) features. But in our practice time in those three tive, rather than quantitative, You can learn new tech- spare time, we can choose areas will help you become a subject. You can’t say for sure niques, and you can explore any open source project that better developer. It will make if your code is good, but you different points of view. You sparks our interest to learn you a more complete pro- can always recognize better can be awed by great code or contribute to. Sometimes fessional, and enable you to or worse code. To make sure and learn what not to do even at work, we can take a go after new opportunities. you’re on the right path to from developers who are not relevant open source tool or blog All this helps you boost your becoming a better developer, accomplished. library and fix a bug or imple- career and find new paths. your best bet is to assess your Want to explore different ment a new feature. It cer- And the suggestions we pres- progress against other devel- ways of testing code? Dig tainly is exciting, and it helps BRUNO SOUZA PHOTOGRAPH BY BOB ADLER/GETTY IMAGES ent here are not hard things opers’ code. into open source projects us to think outside the box. 48
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //career /
You can start small, probably just allocation. Maybe it is something we meet in person and whom we You can also submit a talk to
adding some documentation or else, for example a music proj- share moments with. become a speaker at an event. That COMMUNITY opening an issue at the bug tracker. ect, games, or something you That’s why when you go to an will give you another perspective on Later maybe you’ll get to sub- always wanted to do as a kid— event, large or small, you should event participation—a topic we’ll mit your own pull requests with such as space exploration or soc- decide to enjoy the interactions: explore in the future. bug fixes or new features. At that cer. Learn the code. See if there is a conversation in the registra- ACTION ITEM: Register and attend point, you’ll get another great anything you would like changed tion line, sitting down to eat with a local event on a topic that inter- benefit of open source: the feeling or improved. strangers in the crowded lunch- ests you. While there, focus on the you get when your contribution is room, late night dinner or drinks. people. Make a point of meeting accepted and gets in the hands of Community: Events At an event, there are countless as many people as you can. Set out JAVA IN ACTION dozens (or thousands) of devel- Even with the great technology opportunities to just say hi and an event schedule that gives you opers in the next version of the innovations we have had in the expand your network. It is amaz- room to talk with speakers and project. Bragging rights included! last few years, nothing compares ing how easy it is to find people hold extended hall conversations. Recognition, more networking, to face-to-face conversations. To who are having problems similar to Do not spend all the time with your new friends, maybe many people, the value yours, or who have experience with friends. Meet new people every day. even a job offer. Open FACE-TO-FACE of participating in events things you would love to try. ACTION ITEM: When meeting JAVA TECH source puts your code in These days on is questionable. They can And you can maximize your people, ask what projects they have the open, and the light be large time and money experience by going a step above been working on recently. Be pre- that shines on it helps the internet, investments, while ses- most attendees. Go say hello to a pared to share what you have been your developer career being seen is sions can be seen online speaker you just watched. Track working on. It’s a much better con- to blossom. instead, and there is him or her later in the halls for a versation starter than asking, “How ACTION ITEM: Choose easy. The hard no guarantee of good friendly conversation. Skip a couple are you?” ABOUT US one open source proj- part is being content—not to mention of sessions to have a discussion or ect that you use in your remembered. being away from family enjoy a drink with someone you Think Differently: The Internet daily job, and look at the while work keeps piling just met. Sit down to show your of Things code behind it. It can be Go out and enjoy up back at the office. solution, or ask someone to show Research indicates that the a framework, a library, the interactions. Don’t be misled—the you their work. Share moments Internet of Things (IoT) will change maybe the Java Virtual real value of events is with other developers. the world in the next decades. Machine (JVM) in the in the people and rela- And bring those moments back According to Forbes, by 2020, an OpenJDK project or the tionships. Face-to-face to your own team! Present in your estimated 50 billion devices around code in a JSR reference implemen- events are a great place to increase words the best talks you have seen. the globe will be connected to the tation. But do not only stare at networking and visibility. Introduce people you meet to internet. The worldwide impact will the code; learn how it works, and “Whoever is not seen is not those on your team who would be come from the evolution of experi- experiment with it. remembered” is a useful observa- interested in their work. Blog about ments done today by developers blog ACTION ITEM: Choose one open tion. These days on the internet, something cool you have learned, and hobbyists. We are in the early source project in an area that you being seen is easy. The hard part or share that little tidbit of a hall days of IoT, and most projects are love. It could be technical, such is being remembered—and we conversation that probably no one seen as mere toys used for fun. as database internals or memory are best remembered by those else heard but you. But we already have a large array 49
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //career /
of tools, kits, boards, and sensors opposite side of virtualization— can do. The Java.net IoT Developer
readily available for anyone to use. when computers become part of Challenge has a series of great COMMUNITY We are seeding and fertilizing the our world, and are able to read real- videos that will get you going in ground, and when the crops start ity and directly manipulate it. no time. to grow, it will be an explosion of This changes how we interact opportunity everywhere. with those computers and how Put It All Together But as we have been saying in the software we write interacts One of the best things about this series, you don’t need to be with us. It’s a different kind of events is that they give us a chance interested directly in IoT for it to software, in terms of usability, to meet people and participate help improve your career. Most longevity, security, and even size in activities that can expand our JAVA IN ACTION of us will only be on the receiving and performance. When we deal networking. How about joining an end of the IoT explosion, with the cloud, we try to Adopt-a-JSR hackathon? You can being users of products TO DO think how our applica- learn, code, and contribute to an and services enabled by tion would be different if open source reference implemen- those ideas. More prob- “Use Java on the everything were infinite. tation. Why not attend JavaOne, able than not, your com- Raspberry Pi.” When dealing with IoT, the premier Java conference in the JAVA TECH pany or project will have we think how our appli- world? Or easier, join a local Java nothing to do with IoT for cation needs to be dif- user group (JUG) event about IoT. quite some time. Maybe ferent if it never stops, if There’s no need to spend all your you won’t have a real opportunity it does one thing only and is never time in sessions. Sit in the hall, to use it careerwise anytime soon. upgraded. Network access can be and hack on projects together with So, why bother? an issue, and there may be differ- other attendees. ABOUT US IoT is one of those ideas that ent constraints that will sharpen Does being bold and introducing forces us to think differently. your thinking in ways that will help a new topic to a user group seem Maybe you remember the Sun in your daily work. Working with IoT intimidating? In the next article, Microsystems slogan that “the might well open up your career for we’ll discuss how you, too, can network is the computer,” and how new opportunities in the future. It become a speaker and how that the emergence of the network in will also show a fun side of devel- can help you improve your devel- the 1990s changed how we create opment, one that we sometimes oper career. software and services. We are still forget exists. riding that wave today. Being able ACTION ITEM: Buy a Raspberry Pi LEARN MORE to experiment and peek into the kit (they are cheap these days) and future right now does change how load some software on it to get a • Join a JUG we do things today, and how we feeling for what can be done. Bonus • “Code Java on the Raspberry Pi,” blog choose our path for tomorrow. points if you get a few sensors! November/December 2014 issue, IoT makes us think differently ACTION ITEM: Use Java on the p. 35 because it changes the basic tool Raspberry Pi, and get started • “Brewing Java with the Raspberry of our trade: the computer. It is the exploring some ideas of what you Pi,” in this issue 50
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Your Destination for Java Expertise
Written by leading Java experts, Oracle Press books offer the most definitive, complete, and up-to-date coverage of Java available.
Java EE 7: The Big Picture OCA/OCP Java SE 7 Mastering JavaFX 8 Controls Java EE Applications Danny Coward Programmer I & II Study Guide Hendrik Ebbers on Oracle Java Cloud Master the code, applications, and Kathy Sierra, Bert Bates Create custom Java FX 8 controls and Harshad Oak frameworks that power Java Platform, This self-study tool offers full coverage deliver state-of-the-art applications Build highly available, scalable, Enterprise Edition 7. of OCA/OCP Exams 1Z0-803 and with visually stunning UIs. secure, distributed applications on 1Z0-804. Electronic content includes Oracle Java Cloud. 500+ practice exam questions.
Available in print and as eBooks www.OraclePressBooks.com • @OraclePress urrently the CTO
of SourcePoint, COMMUNITY CGeir Magnusson Jr. was a cofounder of the Apache Geronimo J2EE project and the Apache Harmony J2SE project. He is a member of and has served on the board of JAVA IN ACTION directors of the Apache Software Foundation. He is currently an individual representative on the Java Community Process (JCP) Executive Committee, and JAVA TECH previously represented the Apache Software Foundation on the JCP Executive Committee.
Java Magazine: Given
that we’re celebrating 20 ABOUT US years of Java, what has Magnusson surprised you most consulting with about the evolution of developer colleagues the platform during that at SourcePoint time frame? Magnusson: I’ve been impressed by how Java JCP Executive Series has remained so rel- evant. I can’t think of many developer-focused Working on Java from Within the JCP technologies that have survived and blossomed blog SourcePoint’s Geir Magnusson Jr. discusses the advantages of building systems with Java, in the same way. and how the JCP has affected the platform’s evolution. BY STEVE MELOAN There are obviously other programming PHOTOGRAPHY BY MATT MILLS MCKNIGHT/GETTY IMAGES 52
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 languages that have been in the game COMMUNITY for a long time, like C and C++. But in my opinion, they are not adapting to new computing niches and opportuni- ties with the same flexibility as Java. In every iteration of technology—from smartphones to tablets to whatever will come next—I believe Java will JAVA IN ACTION be there.
Java Magazine: Why do you think Java has continued to flourish? Magnusson: I build software systems every day, and I’ve done it for a variety JAVA TECH of industries during my career. Java is not the only tool I use, because other languages are more appropriate for cer- tain parts of the architecture. But when Java is a good fit, it’s a really great fit. I can depend on it for reliability, scal-
ability, and performance. Java is a main ABOUT US tool in my toolbox. And that usability some platforms, and then a descent. sophisticated pieces of software they Magnusson started underpins my continued interest in But I think the fact that we’re cel- will encounter. It’s something they his career in R&D at participating in the broader ecosystem ebrating the 20th anniversary of this can rely on as they build their careers. Bloomberg. around Java, such as the JCP. general-purpose application devel- With languages like Scala, Groovy, opment platform indicates that Java and Jython also running on the JVM, Java Magazine: What would you like technologies should be known and there’s tremendous flexibility for younger developers to know about the understood by any modern coder or building systems. So Java is a great 20th anniversary of Java? And do you system architect. skill-set investment for young profes- have any advice for students and new Except for a few niche markets, sional developers. developers regarding Java technologies, virtually every developer will need or software technologies in general? to write, interface with, or maintain Java Magazine: What is the impor- Magnusson: Developers are very much Java software. tance of the JVM in the world of Java blog creatures of fashion—not necessarily And regarding students and young technologies? in their attire, but certainly in the tools developers, I think it’s important for Magnusson: I would call the JVM the and technologies they use. Because of them to understand that the JVM [Java crown jewel of the Java ecosystem. this, we’ve seen the meteoric rise of Virtual Machine] is one of the most It provides a computing model that 53
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 And it continues ing can all be done in very fast itera-
to improve all the tions. Modern Java IDEs like IntelliJ, COMMUNITY time. I’ve used other Eclipse, and NetBeans do most of the garbage-collected lan- housekeeping, and streamline the guages, but the JVM entire endeavor. is head and shoulders If you look at the flourishing big data above the rest. area, most of those technologies are written in Java: the open source soft- Java Magazine: Are ware framework Hadoop and com- JAVA IN ACTION there any misconcep- plementary technologies; the open tions about Java that source distributed database system need to be dispelled? Cassandra; and many others, such as Magnusson: There is the processing and querying library a common misper- Cascalog. Java is an environment that ception that Java is a you can control, tune, and understand. JAVA TECH slow language, which The tooling and profiling are excellent. is completely untrue. Endless application areas are evolving It’s used in the high- because Java is getting the job done. frequency trading Says Magnusson, handles concurrency and memory community and other domains that Java Magazine: You’ve previously “Being able to write management in a consistent and highly require excellent performance and very represented the Apache Software code that is very clear
reliable fashion. low latency. Foundation as a JCP Executive ABOUT US to the reader on the first time through is The garbage collector, for instance, Java, the language, is also sometimes Committee member, but now you’re incredibly important.” simplifies the life of a programmer viewed as being overly ver- involved as an individual. immensely. If I need large heap, I have bose. But programming OPEN SOURCE Will you explore those differ- no concerns, due to the fine-grained languages are for humans to ent roles and experiences? control over garbage collection. I read, not computers. Being “From my point of Magnusson: When I repre- don’t have to worry about memory able to write code that is very view, the bulk of sented the Apache Software management. clear to the reader on the innovation today Foundation, my personal In addition, just-in-time [JIT] compi- first time through is incred- concerns were certainly in lation has stopped seeming like magic. ibly important for maintain- is being driven the mix. But at the end of I now take it for granted that the JVM ability and clarity. by open source the day, Apache’s issues will convert bytecodes into very fast I’ve also heard the occa- were first and foremost. machine code that is completely opti- sional claim that software communities Now that I’m a JCP indi- blog mized. As I’ve mentioned, a variety development in Java is a and open source vidual member, I want to of languages have blossomed to take slow process. But in my represent people who are advantage of this amazingly sophisti- experience, writing, com- projects.” using Java daily to build cated piece of software technology. piling, executing, and test- innovative software, in open 54
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 SourcePoint is producing a set
of tools that allow COMMUNITY publishers to detect ad blockers, and react in the manner that they choose. JAVA IN ACTION JAVA TECH ABOUT US
source, for internal use or as commer- trepidation in the legal departments of Java Magazine: As a voice for the cial products. many companies about open source. practitioner within the JCP, what is the I have a very strong interest in ensur- But now I think the world has become balance between establishing stan- ing that the Java ecosystem is a safe fairly comfortable with it and the myr- dards while still fostering and encour- and compatible place for open source. iad advantages it delivers. Open source aging innovation? From my point of view, the bulk of is just another dimension of the tools Magnusson: Having a set of standards blog innovation today is being driven by and resources that developers have at that mandate predictable behaviors is open source communities and open their disposal. The JCP has made sig- extremely important to me as a devel- source projects. nificant progress in this area. But there oper. It’s essential for efficiently building Years ago, there was significant is still more work to be done. reliable and maintainable systems. If I’m 55
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 using software from commercial entities more interesting and accessible to a enable publishers to engage in a deeper
such as Oracle or IBM, or open source broad swath of developers in the conversation with the consumer. COMMUNITY projects that build to the standards, I ecosystem. Certainly technology ven- Regarding Java’s role—it has been can be assured that standard Java com- dors need continued representation, key. Our front-end web pages are ponents will perform consistently. And and some individuals currently have a implemented using JavaScript and Ruby that assurance is one of the things that voice and a role. But on Rails. But virtually make Java so compelling. As a developer, we need to increase JCP our entire back-end you have confidence that all the ele- the breadth of partici- infrastructure is writ- ments will interoperate smoothly. pation. We must find “The most pressing issue is ten in Java. Data col- JAVA IN ACTION In terms of innovation, there are a new ways to make the making JCP participation more lection from the inter- wide variety of implementations of the JCP more relevant in net is handled by Java JVM that focus on various aspects of the day-to-day lives of interesting to developers.” servlets that route performance, system integration, mon- developers. everything into a data itoring, and so on. Many different play- Most software is pipeline written in ers are in this space. But it’s still a stan- written by developers Java and running on JAVA TECH dard Java environment, guaranteeing at companies that are not in the soft- the JVM. Then we use custom software predictable and reliable performance. ware business—construction compa- written in Java to process the data, and But not everything needs to be nies, banks, retailers, and so forth. We store the results in databases written in standardized. The Hadoop software need to make sure that Java remains C and Java. library has established a de facto stan- relevant for all of these businesses and For a very long time, Java has been dard in the marketplace. There would their related application areas. an indispensable tool in my devel-
be nothing to gain from making it a opment processes. And the JCP will ABOUT US formal standard. Java Magazine: Tell us a bit about your ensure that it will continue to evolve For the most part, the JCP has done startup venture, and how Java technol- and thrive. a very good job in this area. And I think ogy is part of the picture. that’s one of the reasons Java has Magnusson: The company is called remained so relevant during the past SourcePoint, and it is focused on devel- 20 years. oping technology for web and mobile Steve Meloan is a former C/UNIX soft- The formal standards process can publishers. ware developer who has covered the web slow down innovation, and sometimes In the near term, we’re producing and the internet for such publications as that’s a good thing—so that evolving a set of tools that allow publishers to Wired, Rolling Stone, Playboy, SF Weekly, technologies can be established as detect ad blockers, and react in the and the San Francisco Examiner. He re- the right way to do things, not just the manner that they choose—for example, cently published a science-adventure newest way. by reminding the user that the con- novel, The Shroud, and regularly contrib- blog Java Magazine: How can the JCP better tent they are consuming is paid for by utes to The Huffington Post. serve the community going forward? advertising and asking the consumer to Magnusson: The most pressing issue turn off the ad blocker. For the longer LEARN MORE right now is making JCP participation term, we are building technologies that • Becoming an individual JCP member 56
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 COMMUNITY JAVA IN ACTION JAVA TECH
Cofounder Adam Gibson, center, meets with ABOUT US Christian Nicholson, left, and George Takeo to go over Skymind features.
eep learning is a form of machine learning that seeks to enable Dintelligent devices of all shapes DEEP LEARNING and sizes to emulate learning capabili- Startup Skymind looks to take deep learning technology out of the labs and ties of the human brain. Although such capabilities could blog into the enterprise with an open source framework built on Java and Hadoop. offer enormous payoffs for big data BY PHILIP J. GILL and the Internet of Things—enabling
PHOTOGRAPHY BY BOB ADLER/GETTY IMAGES 57
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 Like many tech startups in San Francisco, Skymind is headquartered in a former COMMUNITY industrial building that has been converted to office use. JAVA IN ACTION JAVA TECH ABOUT US SKYMIND applications such as the driverless car— recognition, and similar applications,” learning library written in Java and skymind.io production-grade deep learning still explains Gibson, 25. “Enterprise devel- designed for business environments. remains largely confined to a few uni- opers want a way to use deep learning Location: versities and corporate research labs. technology on these big data problems San Francisco, EMULATING THE BRAIN California But Adam Gibson, cofounder and chief and others, and to deploy it in the same Many common computing tasks today, developer of a year-old San Francisco, production environment as their day- such as spam filters, optical character Industry: Software California–based business intelligence to-day operations.” recognition, and search engines, incor- and enterprise software startup called With that goal in mind, the Skymind porate aspects of machine learning. “At Employees: Skymind, hopes to make this technol- team has developed and released as a very high level, machine learning is Four ogy more accessible. open source technology the Deep driving advances in big data analytics,” Java technology “There’s a huge gap between aca- Learning for Java framework, also Gibson says. used: demia and the enterprise when it called Deeplearning4J (DL4J), and But big data has also hit a wall, as cer- blog Java Development Kit 7 comes to the deep learning tools each made it available for free download tain unstructured datatypes—images, deploys in such areas as big data and at deeplearning4j.org. The company video, speech recognition, and text— big data analytics to solve such prob- describes DL4J as the first commercial- that have the potential to offer enter- lems as facial recognition, speech grade, open source, distributed deep prises large benefits remain beyond 58
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 the understanding of today’s big data HISTORY
The DL4J Framework tools. Deep learning could potentially COMMUNITY Deep Learning for Java (DL4J) is an open source frame- solve that problem. Also known as deep The first deep learning artificial work for developing deep learning algorithms in Java for structural learning, this type of machine neural network is believed to have enterprise computing environments. This framework learning combines artificial neural been the neocognitron, developed includes a variety of artificial neural networks (ANNs) for networks (ANNs), pattern recognition, developers to deploy on a Java Virtual Machine (JVM), statistics, mathematical optimization, by Kunihiko Fukushima in 1980. depending on what kind of data they want their deep and other technologies associated with learning application to understand. ANNs are statistical artificial intelligence. learning algorithms that loosely approximate the capa- In deep learning, a signal is relevant JAVA IN ACTION bilities of biological neural networks, such as the central information that a deep learning algo- website. Everything else is the oppo- nervous system of animals—particularly the human brain. rithm running on an ANN can use to site: noise. There are several common types of ANNs. Convolutional properly classify a piece of data and “A deep learning algorithm automati- networks are often used to learn images, while recursive give it meaning—for example, recog- cally extracts a signal from data and neural tensor networks can be deployed in natural- nizing facial features from a photo or a solves problems with that data in a way JAVA TECH language processing, text mining, and parsing sentences. video, spoken words from a recording, that doesn’t require preprogramming. Deep-belief networks, which are simply stacked or written words from a document or The more signals the algorithm is able restricted Boltzmann machines, work with multiple datatypes. Deep autoencoder networks are useful for data compression, reducing the dimensionality of complex input. Stacked denoising autoencoders utilize a denoising
technique that helps them generalize over new data, ABOUT US while recurrent nets are typically used to learn sound and times series. Also included in the DL4J framework is N-Dimensional Arrays for Java (ND4J), a scientific computing library that brings NumPy and MATLAB-type data analysis tools to the JVM. NumPy is an extension to the Python program- ming language that supports multidimensional arrays and a large library of high-level math functions—while MATLAB, from MathWorks, is a multiparadigm numerical computing environment and fourth-generation program- ming language. DL4J also supports Scala, a language that runs on blog the JVM.
59
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 to strike from that data, the more it will enterprise,” he says. “We are able to BIG DATA AND BEYOND
be able to make inferences, just like use the same security mechanisms and Because of the broad number of neural COMMUNITY in big data analytics. These are things operate in an environment that enter- network types that DL4J supports, the DOMAIN NAME that humans can do easily that are very prise programmers already know.” framework can be used as a platform difficult for computers. Deep learning DL4J is integrated with Hadoop and to build applications to parse just about The .io top-level algorithms teach computers to parse Spark—both de facto standards for big any datatype (see sidebar, “The DL4J domain is particularly information automatically in much the data production environments in the Framework”). Skymind, like other open same way humans do,” says Gibson. enterprise that are available from the source companies before it, offers fee- popular with Silicon Most current deep learning algo- Apache Software Foundation—whose based training, implementation, cus- Valley startups these rithms and ANNs are written in other 2.0 license Skymind is using for DL4J. tomization, and ongoing support ser- JAVA IN ACTION days, because it programming languages, such as Hadoop is written in Java, and Spark in vices. Its major areas of focus include Python. But for Gibson, Java was the Scala (a language that runs on the JVM). text analysis and images. calls to mind the natural choice for DL4J because of the “Along with Java, Hadoop and Spark are “Text analytics is a common office term input/output. prominent place it holds in the enter- the leading open source technologies problem and something a lot of people prise today. “Developing DL4J in Java in the enterprise, and they are all going come to us with,” Gibson says. “A lot of makes us first-class citizens in the to stick around,” says Gibson. companies have customer service logs JAVA TECH ABOUT US
blog Gibson, Nicholson, and Takeo meet frequently to discuss product features and schedules. 60
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 COMMUNITY 5,000 and Counting Since the first stable release of the Deep Learning for Java framework (DL4J) in November 2014, Skymind has seen 5,000 downloads from unique IP
addresses, and the company’s website JAVA IN ACTION gets roughly 21,000 visits per month, says Cofounder Adam Gibson. “Our Google Group community has nearly 600 members,” Gibson continues, “and more than 250 software engineers have forked our GitHub repository to JAVA TECH create their own version to work on.” ABOUT US that they don’t know what to do with, Facial recognition in particular has of embedded intelligence that will read and they don’t know how to extract many important applications, espe- and parse signals in real time and on- a lot of signals from that data. For cially in security. If someone walks up the-fly, and communicate with other instance, they can’t tell when custom- to a company entrance, for example, a devices through the cloud. ers are unhappy, because they can’t deep learning–enabled system can use Gibson concludes, “While the self- mine the text to see if there are excla- facial recognition algorithms to identify driving car is the ‘Big One,’ there will mation points that show customers are that person. be many other Internet of Things angry and excited.” “If you want to do facial recognition applications in e-commerce and other The same algorithms that can give for security purposes, the system will areas that will rely on deep learning meaning to the customer service logs keep taking pictures until it figures out capabilities to understand and learn can also help improve another common who the person is.” from a steady stream of incoming text-mining chore: “Deep learning algo- Deep learning algorithms, Gibson data.” blog rithms can automatically recognize that adds, are also essential to the success two words are used in a similar context. of many applications in the Internet Philip J. Gill is a San Diego, California– The algorithm can learn that, and thus of Things, in which virtually every based writer and editor who has followed help improve search results.” machine or device will have some form Java technology since its inception. 61
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect /
Robots Running Wild COMMUNITY Using the Java NAOqi SDK to program companion robots.
ldebaran (SoftBank life to Aldebaran’s robots. The Java NAOqi SDK offers to your build path. A Group) designs human- In other words, NAOqi is a Java bindings and dedicated The first step is to cre- JAVA IN ACTION oid and programmable framework that allows you wrapper classes so you can ate an Application in the robots. In less than 10 years, to create distributed robotic use NAOqi easily. This SDK is main method, as shown in we’ve created three com- applications. These applica- available as a JAR file and can Listing 1. For this, you must panion robots: NAO, Pepper, tions are normally written be used as any other third- pass your robot’s IP address and Romeo. in Python or C++, but you party Java library is used. as an argument in the con- These three human- can use other programming structor of the Application. JAVA TECH ERWAN PINAULT AND oid robots run the same languages through the libqi The Java NAOqi SDK The Application is in charge THALÍA CRUZ operating system: NAOqi, library, which provides cross- This article shows how to cre- of initializing the frame- a GNU/Linux distribution platform and cross-language ate a new robot client appli- work and connecting it to a BIO based on Gentoo. This dis- support. Thus, NAOqi can cation using the Java NAOqi Session, which connects tribution contains all the support other platforms SDK. The robot can listen services together, locally or required libraries and pro- (Windows, Linux, and Mac to your orders and move over the network. When the ABOUT US grams to make NAOqi the OS) and any language (with accordingly: turn right or left, Application is started, a main software that gives its corresponding bindings). move forward, walk faster or Session is created and con- slower, and stop. nected to your robot. To begin, download the Once the Session is JAR files fromAldebaran’s ready, you can get services. Community website. (Please A service is an interface note that these JAR files are that exposes what the robot available for customers only.) can do. Each robot has a There is one JAR file per plat- ServiceDirectory that lists form and NAOqi version. all its available services. For The example in this article this example, you need the was done with NAOqi ver- following services, as shown blog sion 2.1.4, and we tested it in Listing :2 on Linux x64 and Mac OS X. ■■ ALSpeechRecognition: A A robot responding to voice commands Download the JAR file that service that gives the robot PHOTOGRAPHS COURTESY (video) OF ALDEBARAN fits your platform and add it the ability to recognize 62
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 1 LISTING 2 LISTING 3 LISTING 4 LISTING 5 LISTING 6
public static void main(String[] args) throws Exception { String robotUrl = "tcp://nao.local:9559"; COMMUNITY // Create a new Application Application application = new Application(args, robotUrl);
// Create a session and connect it to the robot. a p plica tio n.sta r t(); JAVA IN ACTION // Retrieve the created session. Session session = application.session(); ... JAVA TECH
Download all listings in this issue as text
this example, the vocabulary is a to this event and set a callback, list of the possible directions that as shown in Listing .5 When you ABOUT US you can give to the robot. Leave subscribe to an event, you get a “word spotting” disabled, because subscription ID, so you can unsub- we want the robot to understand scribe later. Figure 1 specific given words: nothing more, Because the EventCallback is nothing less. a functional interface, you can also predefined words or phrases in ■■ ALTextToSpeech: A service that Then, you need to subscribe to use lambda expressions, as shown several languages. allows the robot to speak. the ALSpeechRecognition service, in Listing .6 ■■ ALMemory: A service that pro- ■■ ALAutonomousMoves: A ser- as shown in Listing 4, to enable the Each time the robot recognizes vides centralized memory used vice that enables subtle move- robot to listen to your voice inputs. a word, you make the robot move to store and retrieve key infor- ments that the robot does Each time the robot hears a word, according to the given order. To do mation related to the hardware autonomously. the ALMemory WordRecognized so, use the ALMotion service, tak- configuration, which acts also Let’s start by using event is raised. This event contains ing into account the following axis blog as a hub for the distribution of ALSpeechRecognition. To make the recognized word and the esti- definitions. The X axis is positive event notifications. the robot listen and understand mated probability that this was, in toward the robot’s front, the Y axis ■■ ALMotion: A service that facili- what you say, you must establish fact, what you said. For handling is from right to left, and the Z axis is tates making the robot move. a vocabulary (see Listing ).3 For this input, you need to subscribe vertical, as shown inFigure 1. 63
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 7 LISTING 8 LISTING 9 LISTING 10 LISTING 11 LISTING 12 Because you want the robot to For this example, you also public void handleOrder(String order) throws CallError,
move forward, turn left or right, go want to subscribe to the COMMUNITY InterruptedException { faster or slower, and stop, use the MiddleTactilTouched event float x = 0; moveToward(float x, float (Tactile is misspelled in the event’s float y = 0; y, float theta) method of name), so that every time you touch float theta = 0; ALMotion (see Listing 7), where the tactile sensor on the robot’s if (order.equals("forward")) { ■■ x is the normalized, unitless head, the robot starts listening, if it x = 0.6f; velocity along the X axis. +1 and was not already listening, or stops } else if (order.equals("left")) { -1 correspond to the maximum listening. See Listing .9 theta = 0.4f; JAVA IN ACTION velocity in the forward and back- The same can be done with } else if (order.equals("right")) { ward directions, lambda expressions, theta = -0.4f; respectively. FRAMEWORK as shown in Listing 10. } else if (order.equals("stop")) { ■■ y is the normalized, NAOqi is a powerful Use the ALTex tTo x = 0f; unitless velocity Speech service to y = 0f; along the Y axis. +1 framework that make the robot give theta = 0f; and -1 correspond allows homogeneous feedback about its } else if (order.equals("faster")) { JAVA TECH to the maximum state, for example, if (x > 0) x += 0.2; velocity in the left programming, in the disable else and right directions, Listening() method communication x -= 0.2; respectively. shown in Listing 11. between different } else if (order.equals("slower")) { ■■ theta is the nor- You’re almost ready if (x < 0) malized, unitless to start testing this services, and x += 0.2; ABOUT US velocity around the information sharing. Java application. else Z axis. +1 and -1 cor- Because you want the x -= 0.2; respond to the max- application to keep } imum velocity in the listening to the sub- motion.moveToward(x, y, theta); counterclockwise and clockwise scribed events, add the following } directions, respectively. lines to the main method, which Because the robot moves auton- blocks the main thread until the Download all listings in this issue as text omously while listening, disable application is stopped: “expressive listening” to reduce the fall-down risk. In effect, if the robot // Keep the application run- were subscribed to and leave the Choregraphe Memory watcher and tries to follow one of your orders // n i n g. robot in a “clean” state, as shown in Robot view so you can monitor the while moving autonomously, the application.run(); Listing 12. ALMemory events, what the robot blog mix of both movements might says, and its moves. make it fall down. Therefore, Thus, once the application is no Running Your Application 1. First, connect your robot add the code in Listing 8 before longer running, it’s important to To better see what happens when to Choregraphe, add the enabling listening. unsubscribe from everything you you run this application, use the MiddleTactilTouched and 64
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect /
WordRecognized events to 2. Touch the robot’s middle change isn’t visible in the WordRecognized event is
the Memory watcher, and tactile head sensor. The Robot view). This means that raised containing the word the COMMUNITY enable the Robot view. Then, MiddleTactilTouched event the robot is listening to what robot heard and its probabil- run your Java application. See is raised and the robot’s eye you are saying. ity, as shown in Figure 3. The Figure 2. LEDs turn navy blue (this 3. Say “forward.” The robot moves forward. JAVA IN ACTION JAVA TECH
Figure 2 Figure 4 ABOUT US
blog
Figure 3 Figure 5 65
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 13
public class VoiceCommandService extends QiService { ALMotion motion; COMMUNITY
public VoiceCommandService(Session session) { motion = new ALMotion(session); }
public void handleOrder(String order) throws CallError, InterruptedException { JAVA IN ACTION float x = 0; float y = 0; float theta = 0; if (order.equals("forward")) { x = 0.6f; Figure 6 } else if (order.equals("left")) {
theta = 0.4f; JAVA TECH 4. Say “left.” The its middle tactile head sensor } else if (order.equals("right")) { theta = -0.4f; WordRecognized event is once again. } else if (order.equals("stop")) { raised containing left and Everything seems to be working x = 0f; the robot turns left (see correctly. Figure 6 is what it should y = 0f; Figure 4). really look like. theta = 0f; 5. Try it out with the other words } else if (order.equals("faster")) { ABOUT US contained in our vocabulary: Creating a Service if (x > 0) “right,” “faster,” “slower,” or For now, the code that you wrote x += 0.2; “stop.” If you say something can be accessed only by your cur- else else, the robot tries to match rent application. Let’s say you want x -= 0.2; your input with one of the to reuse it and be able to call it from } else if (order.equals("slower")) { words it knows. another application. For this, you if (x < 0) 6. Touch the robot’s middle need to create your own service. x += 0.2; tactile head sensor again. First, create a new else The robot stops moving and class that extends from x -= 0.2; announces that it will stop QiService. In this case, call } listening (see Figure 5), and its it VoiceCommandService, motion.moveToward(x, y, theta); } eye LEDs return to their nor- as shown in Listing 13. It con- blog } mal color. tains your previously defined 7. Try saying one of the known handleOrder(String order) words; the robot does nothing. method. Download all listings in this issue as text To make it listen again, touch Then, as you did in the previous 66
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //architect / LISTING 14 LISTING 15 LISTING 16 section, create a new Application, The VoiceCommand service is public class MyRegisterServiceApplication {
connect it to your robot, and retrieve also accessible from applications COMMUNITY the created session, as shown in written in other supported pro- public static void main(String[] args) throws Exception Listing 14. This Application is gramming languages. For example, { in charge of creating and register- in Python it would look as shown in ing your VoiceCommandService Listing 16. The same example can Application application = new Application(args, for the session. The sevice also be written in C++. " t c p://n a o.l o c a l:9559"); is registered by using a DynamicObjectBuilder, which Conclusion a p plica tio n.sta r t(); JAVA IN ACTION makes the service compatible with NAOqi is a powerful framework Session session = application.session(); the other supported languages. that allows homogeneous pro- This same object allows it to adver- gramming, communication VoiceCommandService vcService = tise its methods by specifying their between services, and information new VoiceCommandService(session); signature and a brief description. sharing. This example shows how a When registering the service to the desktop Java application can inter- // Create a DynamicObjectBuilder, that will make session, you can give it any name— act with services, mainly written in // your service compatible with other supported JAVA TECH for example, VoiceCommand. C, and control the robot as it would // l a n g u a g e s. DynamicObjectBuilder objectBuilder = Last, create another do for any other supported lan- new DynamicObjectBuilder(); Application, whose goal is to guage: C++, Python, or JavaScript. vcService.init(objectBuilder.object()); demonstrate that you can call The Java NAOqi SDK is still a the advertised methods of your work in progress. We want to make // Advertise the handleOrder method contained in VoiceCommand service. For this, it more Java friendly. We know that // your VoiceCommandService service. ABOUT US you need to create an AnyObject we still have a long way to go, and // You need to specify its signature. object, which functions as a bridge we will continue improving the objectBuilder.advertiseMethod("handleOrder::v(s)", between this new Application Java bindings because we believe vcService, and your service. See Listing 15. our robots have even greater "Robot will move according to the given order: Let’s test it: potential if Java is well supported. forward, left, right, faster, slower or stop"); 1. Run MyRegisterService We hope that eventually Java will // Register the service as "VoiceCommand" Application. As long as this be directly integrated into our session.registerService("VoiceCommand", application is running, you’ll robots. objectBuilder.object()); be able to call the methods contained in your service. LEARN MORE a p plica tio n.r u n(); 2. Run ServiceConsumer } • Aldebaran’s website } Application (without stop- blog • Javadoc ping the first application). The robot starts moving forward, • Java NAOqi SDK documentation then turns to the left, and finally • libqi library Download all listings in this issue as text stops. It works! • libqi-java on GitHub 67
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015 //contact us / COMMUNITY JAVA IN ACTION
Comments. of specific Java utilities, preferably open Where? JAVA TECH We welcome your comments, correc source; and programming algorithms Comments and article proposals should tions, opinions on topics we’ve covered, implemented in Java. Articles should be be sent to me, Andrew Binstock, at and any other thoughts you feel impor in Microsoft Word or .odt format and [email protected]. tant to share with us or our readers. should run between 1,200 and 2,000 While it will have no influence on Unless you specifically tell us that your words, not including code. Listings our decision whether to publish your
correspondence is private, we reserve should be short; if necessary, break out article or letter, cookies and edible treats ABOUT US the right to publish it in our Letters snippets of 30 lines or fewer and make will be gratefully accepted by our staff to the Editor section. the rest available as a download. at Java Magazine, Oracle Corporation, 500 Oracle Parkway, MS OPL 3A, Article Proposals. Customer Service. Redwood Shores, CA 94065, USA. We welcome article proposals on all If you’re having trouble with your topics regarding Java the language; the subscription, please contact the Java Virtual Machine (JVM); languages folks at [email protected] (phone that run on the JVM that would be of +1.847.763.9635), who will do whatever interest to Java developers; discussion they can to help. blog
68
ORACLE.COM/JAVAMAGAZINE //////////////////////////////////////////////// MAY/JUNE 2015