JAX-RS 39 | JAVA INTERFACES 47 | FANTOM 53

SEPTEMBER/OCTOBER 2016

magazine

By and for the Java community Devices and IoT

INTERACTING 14 WITH SENSORS CONTROLLING CNC ROUTING 24 FROM A RASPBERRY PI

IOT AND 32 THE CLOUD

ORACLE.COM/JAVAMAGAZINE //table of contents /

14 24 32 RASPBERRY PI– USING THE CLOUD INTERACTING WITH SENSORS CONTROLLED CNC WITH IOT ROUTER By Eric Bruno ON INTEL’S GALILEO BOARD By Stephen Chin By pushing device control and Programming the Raspberry Pi analytics into an IoT-specific to manage cutting, carving, cloud, devices can be remotely and routing operations managed and operated.

By Gastón Hillar Capturing and responding to data are the heart and soul of IoT. Here’s how to do both with Java on an inexpensive board that uses an x86 processor.

COVER ART BY I-HUA CHEN

04 11 47 58 From the Editor JVM Language Summit 2016 New to Java Fix This Appreciating Limited Choice in Recapping a small annual conference The Evolving Nature of Interfaces By Simon Roberts Languages: The more prescriptive that dives deeply into the JVM By Michael Kölling Our latest code quiz a language is in the details, the 12 Understanding multiple inheritance and 23 easier it is to code productively. Java Books the role of Java 8’s default methods Java Proposals of Interest 06 Review of Companion 53 JEP 293: Revising the format Letters to the Editor 39 JVM Languages of command-line options Comments, questions, suggestions, Enterprise Java Fantom Programming Language 64 and kudos By Brian Frank User Groups JAX-RS.next: A First Glance A language that runs on the JVM and 09 By Sebastian Daschner Danish JUG JavaScript VMs and delivers excellent Events A look at what’s coming next in UI-building capabilities 65 Upcoming Java conferences and events JAX-RS 2.1 Contact Us Have a comment? Suggestion? Want to submit an article proposal? Here’s how. 01

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 EDITORIAL PUBLISHING Editor in Chief Publisher Andrew Binstock Jennifer Hamilton +1.650.506.3794 Managing Editor Associate Publisher and Audience Claire Breen Development Director Copy Editors Karin Kinnear +1.650.506.1985 Karen Perkins, Jim Donahue Audience Development Manager Get Java Technical Reviewer Jennifer Kurtz Stephen Chin ADVERTISING SALES DESIGN Sales Director Senior Creative Director Tom Cometa Francisco G Delgadillo Account Manager Mark Makinney Certified Design Director Richard Merchán Account Manager Senior Designer Marcin Gamza Arianna Pucherelli Advertising Sales Assistant Designer Cindy Elhaj +1.626.396.9400 x 201 Oracle University Jaime Ferrand Mailing-List Rentals Senior Production Manager Contact your sales representative. Sheila Brennan Production Designer RESOURCES Kathy Cygnarowicz Oracle Products +1.800.367.8674 (US/Canada) * Oracle Services Upgrade & Save 35% +1.888.283.0591 (US)

ARTICLE SUBMISSION Get noticed by hiring managers If you are interested in submitting an article, please email the editors. SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the Learn from Java experts subscription form. MAGAZINE CUSTOMER SERVICE [email protected] Phone +1.847.763.9635 Join online or in the classroom PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or email address not be included in this program, contact Connect with our Java Customer Service. certification community Copyright © 2016, 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. Opinions expressed by authors, editors, and interviewees—even if they are Oracle employees—do not necessarily reflect the views of Oracle. The information is intended to outline our general product direction. It is intended for information purposes only, and may not Save 35% when you upgrade or advance your existing Java certification. Offer expires December 31, 2016. Click for further details, terms, and conditions. be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly and made available at no cost to qualified subscribers by Oracle, 500 Oracle Parkway, MS OPL-3A, Redwood City, CA 94065-1600. 02

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016

//from the editor /

Java in the Cloud

Appreciating Limited Choice Oracle Cloud delivers high-performance and in Languages battle-tested platform The more prescriptive a language is in the details, and infrastructure services the easier it is to code productively. for the most demanding Java apps.

ur coverage of JDK Enhancement Proposals command-line switches should be included in Oracle Cloud. O (JEPs) in this issue examines a recent pro- style guides for the language. If the Java team Built for modern app dev. posal to standardize the syntax of command-line had specified a standard convention for switches Built for you. arguments for tools that ship in the JDK. As the when it released the language (in the same way proposal points out in support of its core concern, that it recommended initial capitals for class presently there are multiple ways of asking for names and all capitals for constants), this small help from the command line. And if you happen annoyance would not exist. The more a language to guess wrong when using a given tool, you need can formalize small details, the easier it is to get to circle through the variety of possibilities. These things done. can vary from –help to --help to -?. And then But in an ideal world, even this solution is there’s the unmentioned last resort, which is to insufficient. I strongly believe that the abundance Start here: run the program with no arguments and see what of Java style guides is itself a limitation. I’d far developer.oracle.com kind of information you get in the error message. prefer that there be one consistent set of recom- I wholly support this standardization, but mendations that was universally followed. For I’d go much further. In my view, the syntax of example, writing out definitive guidelines for the #developersrule

PHOTOGRAPH BY BOB ADLER/GETTY IMAGES 04

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //from the editor /

location of opening braces, size tions of an integer. As a result, there are additional constraints. The convenience and benefits of indents, tabs vs. spaces, how porting C from one platform For example, the executable code of such strictures that ensure to stagger or not stagger if/else to another was extraordinarily after any if statement must be uniform syntax are widely rec- sequences, Javadoc’s numerous tedious. Java solved these prob- enclosed in braces, even it if con- ognized. This is evident in the formatting options, and so forth. lems. Data items had fixed sizes tains only a single line. Many other choice of most modern develop- Obviously, this would apply to across platforms, and code could conventional items are defined by ment organizations to prescribe higher-level concerns as well: fully be run on multiple platforms what is known as “idiomatic Go.” their own “house style” for code, expanded imports vs. wildcards, without modification. The happy result is that all Go code which is frequently enforced in the sequence of import state- C’s lack of standardization looks the same. Reading and writ- code reviews, so that all develop- ments and variable declarations, caused so much pointless activ- ing it is easy. ers use the same conventions. But and so on. By having a fixed set of The lack of standardization these styles conflict with each guidelines, every Java listing would of details during the last few other for lack of a single, unified be consistent and not require re- years has been an issue in Java set of conventions. examination to adjust to a given Most modern development in small but annoying ways, If the world were all Java, I individual’s or site’s style. organizations prescribe beyond command-line syntax. For think it would not be too onerous Curiously enough, in a certain their own “house style” example, the three variants of the to put up with the differences, way, Java’s initial appearance on annotation for indicating a field although the time lost in doing so the scene addressed what, at the for code, which is frequently should not be null: @NonNull, is lost for no good reason. time, was a tremendous laxity in enforced in code reviews. But @Nonnull, and @NotNull. The But in an increasingly poly- language that made some tasks these styles conflict with each first of these was used by Check- glot world in which other lan- exceedingly tedious. The principal style and FindBugs, the last of guages (JavaScript, HTML, and language before Java was C. It was other for lack of a single, unified them by Java EE 6 and the IntelliJ so on) play significant roles, the purposely designed from a radi- set of conventions. IDE. The result was that if you lack of enforced coding standards cally nonprescriptive perspective. coded in one environment and in Java and especially across those Even today, after many rounds of moved to a different development languages combine to create a standardization, C has numerous environment, you had to change sustained and pointless drag on places where behavior is unde- your code or your toolchain to productivity. fined or left up to the implemen- ity that when the original team get your expected level of null- tation to define. In the mid-’90s from AT&T Bell Labs developed a checking. This is, of course, the Andrew Binstock, Editor in Chief when Java first appeared, C was new language, Go, they chose a exact antithesis of Java’s vaunted [email protected] far looser. An integer could be highly prescriptive implementa- portability, when switching IDEs @platypusguy more or less anything the com- tion. There is one formalized cod- is enough to make code behave piler defined it to be, with—if I ing style for Go, and all code is differently. Fortunately, Java 8’s recall correctly—a minimum of expected to use that style. A code use of the Checker framework has Coming in November: 16 bits of width. 16, 32, and 64 bits formatter is bundled with the Go now consolidated the convention our special issue on JUnit 5. were all legitimate implementa- distribution. In the language itself, around @NonNull. 05

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //letters to the editor /

JAVA 9’S NEW REPL 43 | NIO.2 49 | ADVANCED GENERICS 56 | JRUBY 62 The Limitations of JSON-P The editors add: “JSON-P is part of the Java EE stan- ENTERPRISE JAVA The article by David Delabassée titled “Using the Java dard and has an elegant parsing interface; in addition, for JSON Processing” in the July/August 2016 issue it’s fast. When JSON-B is finalized, we’ll cover it inJava does not mention significant problems with the JSON-P Magazine as well. Jackson and GSON both represent good JULY/AUGUST 2016 standard, which is poorly designed, and the reference choices for developers needing JSON serialization now.” implementation, which is poorly implemented. I believe the standard is poorly designed because The Practice of Small Classes 17 25 31 37 neither of the two APIs in the standard support pars- With respect to your editorial in the July/August issue, JSF 2.3 JASPIC JSON-P JAVAMAIL WHAT’S AUTHENTICATION PROCESS DATA AUTOMATE COMING? FOR CONTAINERS EASILY ALERTS FROM JAVA EE APPS ing and serialization of plain old Java objects (POJOs) “The Problem of Writing Small Classes,” I second your

ORACLE.COM/JAVAMAGAZINE to and from JSON, the natural fit for an object- idea and argumentation about writing small classes JULY/AUGUST 2016 oriented language. in any “normal” code project. But when it comes to JSON parsers and serializers written with the web development (servlets) or when writing a RESTful JSON-P API are too big, require too many API calls, API, I always find it quite painful to externalize lots of and are too fragile, requiring extensive changes if the pure (RESTful) logic just to stay within my own limits. structure of the JSON to be processed changes. Just as an example, I have a REST resource class I believe the reference implementation is poorly called ItemResource. I define several methods that implemented because in my use case, converting make use of different media types and define several thousands of Java objects to JSON strings of 500 to request mappings and request methods (using Spring, 50,000 characters each, a program using the Jackson but it would be the same with pure Java EE). API’s object model converted a real data set to JSON an So, alone with the imports, injections, method astounding 10 times faster than one using the object definitions, annotations, and logging plus the pure model API in the JSON-P reference implementation. calls to business (Entity) classes and some Java 8 The presumably more efficient streaming API in JSON-P stream processing (mostly one-liners), I easily reach would have required unmaintainable code in which the 200 lines of code or more. API calls to open JSON arrays and objects were often I start to believe in the best of both worlds— widely separated from the API calls to close them. trying to keep it simple and small but still binding So, I believe you should discuss alternative JSON semantic units together. A class should still be a class, processing libraries such as Jackson and GSON. and if we divide this more and more into smaller —Jeffrey S. Mayo parts we could end up with one-method classes or Norcross, Georgia endless delegations to deeper classes. I tend to not limit myself to a hard number of David Delabassée responds: “In the article, I discuss lines, but take other measures in metrics plugins such marshaling: ‘Note that binding (that is, marshaling of as method complexity and try to take the separation Java objects to JSON documents and vice versa) will be of concerns seriously. addressed in a related API, the Java API for JSON Binding —Alex Hepp (JSON-B), which is currently being defined in JSR 367.’” Germany 06

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //letters to the editor /

Why Monospaced Fonts? In your editorial in the July/August issue, you men- tion that the code font is under discussion. Why not use a nice sans-serif proportional font like Tahoma or any other open font? Most important: Do syntax highlighting! Monospaced fonts for modern code samples are 13 Billion completely old-fashioned and totally horrible. Nobody needs to have columns vertically aligned anymore as Devices Run Java was useful in COBOL and Fortran times. The advantage of syntax highlighting is obvious. It is so much easier to see keywords, constants, com- ments, and so on with little effort. Which scheme is used for colors, italics, and font weight is highly sub- jective, of course. ATMs, Smartcards, POS Terminals, Blu-ray Players, —Hubert Kauker Set Top Boxes, Multifunction Printers, PCs, Servers, Germany Routers, Switches, Parking Meters, Smart Meters, Andrew Binstock responds: “I can see no possible benefit Lottery Systems, Airplane Systems, IoT Gateways, from giving up monospaced fonts for coding. I would note that every reputable website and publisher uses monospace. Programmable Logic Controllers, Optical Sensors, In addition, so does just about every developer I know—by Wireless M2M Modules, Access Control Systems, which I mean every developer whose code I’ve seen. “Syntax highlighting is not ideal. The first reason Medical Devices, Building Controls, Automobiles… is that every reader has a different preferred scheme. Moreover, given our generally short printed listings (with downloadable code available for the entire codebase), the benefit would be small while the effort and cost required would be significant.” #1 Development Platform Contact Us We welcome comments, suggestions, grumbles, kudos, article proposals, and chocolate chip cookies. All but the last two might be edited for publication. Write to us at [email protected]. For other ways to reach us, see the last page of this issue. 07

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 Coming this fall to selected /ARM devices AOT-Compiled Java for ARM Starring: Your Java app and the Excelsior JET Runtime From version 11.3, Excelsior JET will begin supporting Java SE 8 on ARM-based platforms

Get Your Early Access Copy Now Registration-Free Download

LICENSEE

LICENSEE //events / Desert Code Camp JavaDay Kiev OCTOBER 8 OCTOBER 14–15 CHANDLER, ARIZONA KIEV, UKRAINE Desert Code Camp is a free, JavaDay Kiev will feature more developer-based conference than 50 sessions on topics built on community content ranging from the core JVM that promises “No Fluff: platform and Java SE (Java 8) Only Code.” Topics scheduled to JVM languages to big data for the Java track include and NoSQL. Five keynotes bots, Amazon Echo, and are slated, and more than language user interfaces; 1,000 developers are expected getting started with Apache to attend this year’s event. Kafka; and microservices with Juergen Hoeller, cofounder and Spring Boot. project lead of the open source Spring Framework, is scheduled JAX London to speak. OCTOBER 10 AND 13, WORKSHOPS O’Reilly Software Architecture OCTOBER 11–12, CONFERENCE Conference LONDON, ENGLAND OCTOBER 18–19, TRAINING JAX London is a four-day event OCTOBER 19–21, TUTORIALS for cutting-edge software AND CONFERENCE LONDON, ENGLAND Devoxx Belgium NOVEMBER 7–11 engineers and enterprise- ANTWERP, BELGIUM level professionals, bringing This year, the O’Reilly Soft- ware Architecture Conference Devoxx Belgium is dedicated to deep learning this year, touching on top- together the world’s leading is exploring evolutionary ics such as quantum computing and machine learning. Tracks will cover innovators in the fields of Java, architecture to reflect the methodology; Java language skills; cloud, containers, and infrastructure; microservices, continuous broadening of the field, server-side Java; and more. An estimated 3,500 developers will choose delivery, and DevOps. Speakers encompassing disciplines such from more than 200 sessions, including one-hour conference talks, include Klara Ward, Oracle’s as DevOps. Topics will include three-hour hands-on labs, informal presentations, a program for kids, Java Mission Control principal strategies for meeting business and more. developer, and Raoul-Gabriel Urma, coauthor of Java 8 goals, developing leadership in Action. skills, and making the concep-

PHOTOGRAPH BY ERIC HUYBRECHTS/FLICKR 09

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //events /

esting speakers, core developers for JDK 9 and cover concurrency of popular open source technolo- updates, HTTP/2, unified logging, gies, and professionals willing to G1 garbage collector, Scala, and share their knowledge and experi- Reactive Streams. ences. Former Oracle Technology Evangelist Simon Ritter is W-JAX scheduled to present “JDK 9: Big NOVEMBER 7 AND 11, WORKSHOPS Changes to Make Java Smaller.” NOVEMBER 8–10, CONFERENCE MUNICH, GERMANY Devoxx Morocco The W-JAX conference is focused NOVEMBER 1, UNIVERSITY DAY on Java, architecture, and soft- NOVEMBER 2–3, CONFERENCE ware innovation. More than 160 CASABLANCA, MOROCCO presentations on technologies Devoxx Morocco is the place to and languages—ranging from go for learning, networking, and Java, Scala, and Android to web sharing experiences about Java, programming, agile develop- related technologies, and soft- ment models, and DevOps—are ware craftsmanship. This year, planned. (No English page available.) more than 1,500 developers are expected, 150 sessions are slated, O’Reilly Software Architecture tual jump from software devel- noncommercial conference in and activities are planned for chil- Conference oper to architect. Java-specific northern Germany for Java devel- dren ages 9 to 15. NOVEMBER 13–14, TRAINING highlights include a session opers and decision-makers. With NOVEMBER 14–16, TUTORIALS devoted to fault-tolerant pro- more than 25 presentations in QCon AND CONFERENCE gramming with Hystrix and led parallel tracks and a diverse pro- NOVEMBER 7–9, CONFERENCE SAN FRANCISCO, CALIFORNIA by Pivotal’s Matt Stine, a cloud- gram, the event also provides net- NOVEMBER 10–11, WORKSHOPS Like its European counterpart, the native Java primer with Pivotal’s working opportunities. (No English SAN FRANCISCO, CALIFORNIA California version of this confer- Josh Long, and a presentation on page available.) Billed as a practitioner-driven ence will explore evolutionary best practices in the use of con- software conference, QCon is architecture. Presentations of tainers by Red Hat’s Mark Little. VOXXED Days Thessaloniki designed for technical team interest to Java developers include OCTOBER 21 leads, architects, engineering “An Introduction to Reactive Java Forum Nord THESSALONIKI, GREECE directors, and project managers. Applications, Reactive Streams, OCTOBER 20 The inaugural VOXXED Days event Tracks include an overview of and Options for the JVM” with HANOVER, GERMANY in Thessaloniki is a developer Java 9 hosted by QCon Chair Wes ThirdChannel’s Stephen Pember, Java Forum Nord is a one-day, conference that promises inter- Reisz that will focus on prepping and “Clone Clone Make: A Better PHOTOGRAPH BY BENBENW/FLICKR 10

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //events / //event recap /

Way to Build,” led by IBM’s microservices and enterprise Java Dan Heidinga. experts. (No English page available.)

Topconf ConFoo JVM Language Summit 2016 NOVEMBER 15, WORKSHOPS DECEMBER 5–7 For the past nine years, Oracle (and earlier, Sun) has NOVEMBER 16–18, CONFERENCE VANCOUVER, CANADA been sponsoring a small gathering of Java experts whose TALLIN, ESTONIA This multitechnology conference primary work is on the JVM. The roughly 150 attendees Java and the JVM, reactive archi- for web developers features ses- gather to discuss the JVM and JVM languages. tectures, sustainable develop- sions on Java and JVM. Scheduled Unlike most conferences, at this summit there is ment, and big data highlight this topics include Java 9; caching; only a single track, attended by all the participants. year’s conference. Couchbase machine-learning models with Over three days, many sessions of surpassing inter- Developer Advocate Laurent Java- and Spark-based tools; est are presented. All of them are recorded. The videos Doguin will present a practical Docker and Java; and writing bet- for the 2016 summit are posted on YouTube. This year’s example of RxJava, and ter streams with Java 8. summit in early August saw particular focus on Java 9 MATHEMA Software Senior and post–Java 9 releases. Consultant Thomas Künneth Special Note: Event Cancellation As for JVM languages, you can find videos of ses- will discuss current approaches sions on implementation details and upcoming features to Java on mobile devices. QCon Rio OCTOBER 5–7 for Kotlin and Scala. And there are sessions that focus Java Enterprise Summit RIO DE JANEIRO, BRAZIL on standalone technical topics: immutable collections, NOVEMBER 28–30 The organizers report: “Faced , use of Intel vector instructions, and so forth. BERLIN, GERMANY with an unstable political and While the sessions are technically demanding, you do not need deep knowledge of the JVM to follow What does a state-of-the-art economic environment . . . we along. However, as you’ll see in the videos, you do need enterprise Java application look considered it prudent to cancel our some fluency with the terminology of JVM functions like? Which APIs are useful? What edition of QCon 2016. We empha- and features. are the roles of various web and size that this decision does not The conference is held in July or August at Oracle’s JavaScript frameworks? And how affect the preparation of QCon campus in Santa Clara, California. While attendance is important is standard Java EE São Paulo 2017.” intentionally kept low, developers working on JVM top- today? These and many other ics can apply to attend on the conference’s home page. questions will be discussed at this Have an upcoming conference Attendance is generally opened 60 days before the next year’s Java Enterprise Summit. A you’d like to add to our listing? summit begins. The home page also includes links to large training event is held con- Send us a link and a description of the videos of sessions from previous summits. Enjoy the currently with the Micro Services your event four months in advance deep dives! —Andrew Binstock Summit, hosting 24 power work- at [email protected]. shops with well-known German

11

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 // java books /

JAVA PERFORMANCE COMPANION By Charlie Hunt, Monica Beckwith, et al. Addison-Wesley

This book’s title—in which The discussion of G1 starts tion, it provides very detailed Companion is the operative with an introduction compar- analysis of core dumps when word—indicates its primary ing garbage collectors, followed programs lock up or suffer fatal mission: a supplement to the by a deep dive into its internals. exceptions. This data supple- highly regarded classic on And, finally, there are explana- ments that provided by jhat, the JVM performance tuning, Java tions (and recommendations) mainstay JDK analyzer of heap Performance, by Charlie Hunt regarding the various configura- dump files. and Binu John. However, that tion options that can be set by an Finally, an appendix reviews book first appeared toward the admin. The writing is clear but performance-related command- end of 2011 and has not been does make occasional references line options that have been added updated by a second edition. to the original book. It’s best to to the JVM since the original book So, this new volume provides read this volume as an adjunct to appeared. Each switch enjoys information on the central per- that work, although for readers several paragraphs of explanation formance topic that came after familiar with JVM innards, it can and recommendations on its use. 2011: the G1 garbage collector. be read by itself. Although a US$50 cover price While G1, which is a standard The second half of the book for a 150-page book seems more part of Java releases since JDK 7, is dedicated to the Java Service- than a tad on the expensive side, update 4, has been designed to ability Agent (SA), a little-known the information in this slim vol- require only a few options (after debugging utility in the JDK. The ume will be valuable enough to which the garbage collector will SA attaches to a running process sites that need top performance sort out its ideal configuration), and takes a complete snapshot, that the price should represent certain workloads can benefit which it translates into human- no obstacle. With that in mind, I from an admin’s additional readable format. It includes full have no difficulty recommend- tuning through switches and stack and heap info, plus data on ing this book unreservedly. runtime parameters. the running processes. In addi- —Andrew Binstock

12

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 Programming Devices

n this issue, our feature articles focus sending commands to it from a Raspberry on how to program devices. The Pi board. CNC routers are devices that devices range from small, single- shape hardware items by grinding down purpose hardware items to complex or cutting a piece of material into the machines. When hooked together, right shape. They’re like 3-D printers Itypically via the cloud, they form the except that they remove material from Internet of Things (IoT). Much of IoT a block rather than iteratively build up programming consists of raw data pro- the product from new material. As this cessing: you gather data from the device, article shows, once a connection to the and you send it commands. The biggest device is established, the primary task is challenges are accessing the device and getting data from the device and send- knowing the command sequence that ing it new commands. The Java code translates into specific actions. Learn for managing these two activities is how to do most of this, add a little back- remarkably straightforward. The author, end processing in the cloud, and you’re Stephen Chin, wrote a similar article in most of the way there. our May/June 2015 issue explaining how This issue has three articles that to interact with an electronic scale from a build on each other to show how this Raspberry Pi. kind of programming is done in Java. The For the IoT to become a reality, first article, by Gastón Hillar page( 14), devices need to share data and typically shows the basics of accessing a device—in will do so by funneling the data from this case, an inexpensive Intel-based IoT multiple devices to a cloud instance. Our board—and using its features by querying third article on IoT (page 32) shows how sensors and turning on various pins that this works on a cloud platform as a ser- light an LED. If you’re not terribly famil- vice custom-made for such data and for iar with Java access to hardware, this is controlling devices remotely. the article to start with. It’s an ideal hob- In addition, you’ll find our regular byist project: instructive and useful, and assortment of Java articles: in-depth it can be completed in a single afternoon. tutorials, explorations of JVM languages, The second article (page 24) dem- book reviews, letters we’ve received, and onstrates how to control a CNC router by of course, our Java quiz.

ART BY I-HUA CHEN 13

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things / Interacting with Sensors on Intel’s x86 Galileo Board Capturing data and responding to it are the heart and soul of IoT. Here’s how it works GASTÓN HILLAR with Java and an inexpensive board that uses an x86 processor.

n this article, I develop and explain a project that measures ators. Both are part of the Intel IoT Development Kit. You can Iambient light and dims a red, green, blue (RGB) LED in download Intel System Studio IoT Edition from Intel’s IoT site. response. This way, you can see how to interact with ana- One of the main problems you can face when you start log inputs and pulse width modulation (PWM) outputs using a new IoT project with Java is that the versions for the upm Java SE 8. I use the latest versions of the Intel IoT Development and mraa libraries included in Intel System Studio IoT Edition Kit, which includes support for Java. I take advantage of must match the versions of these libraries installed in the both the upm and mraa libraries, which provide high-level version of Yocto Poky Linux that is running on the Intel interfaces for controlling the Intel Galileo Gen 2 board—an Galileo Gen 2 board. Unfortunately, I had many problems Arduino-compliant x86 chip based on the Pentium architec- when using the synchronization features included in the ture. I also show how to control wired electronic components, IDE and, therefore, I suggest first updating the libraries in sensors, and actuators. the IDE and then in the board as separate operations. Select Intel(R) IoT | Libraries Update… in the main menu for the Prerequisites IDE and follow the steps to install the latest available versions The Intel Galileo Gen 2 board boots the Yocto Poky Linux for the libraries. image, which is the latest version of the Intel Galileo microSD Once the board has finished the boot process with the card Linux image. You can download the microSD card Linux operating system image and is connected latest version of the Yocto Poky image for Galileo from the to your LAN through the Ethernet port, the DHCP server will Intel website. have assigned the board an IP address. You will need this IP For development, I use the Intel System Studio IoT address later. There are many ways for you to retrieve the Edition software. It is an -based IDE that makes it easy assigned address. For example, if you have access to the web to create a new IoT project with Java as the main program- interface for your DHCP server, you can use it to retrieve the ming language. I also use the latest available versions of both IP assigned to the device with the MAC address that matches the mraa and upm libraries. The mraa library is a low-level the one printed on a label in the board. skeleton library for communication on Linux platforms, and You can also discover the board and its services on the upm is a set of libraries for interacting with sensors and actu- LAN automatically through the zero-configuration network- 14

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

ing implementation. In Windows, you can use the free whether the environment is dark, and this example doesn’t Bonjour Browser for Windows. In OS X, you can use the free have problems with latencies (that is, delays in reporting the Bonjour Browser for OS X. dimming of light). Just make sure you take into account accu- Both applications display the available Bonjour services, racy and latency if you need to sense ambient light in a more and you just need to pay attention to those named galileo. complex project. The IP address displayed for the SSH service named galileo is The photoresistor is a variable resistor whose resistance the one you can use to establish a connection with the board. value changes based on the ambient light intensity. When the Then, use your favorite SSH terminal tool to connect to ambient light intensity increases, the resistance of the photo- Yocto Linux running on the Intel Galileo Gen 2 board by using resistor decreases and vice versa. the previously retrieved IP address, the root user, and a blank The board makes it possible to read voltage values password. Then, execute the following commands in the through the analog input pins. I use a voltage divider con- SSH terminal: figuration that includes the photoresistor as one of its two resistors. The voltage divider outputs a high voltage value opkg update when the photoresistor receives a high amount of light, and it opkg install mraa outputs a low voltage value when the photoresistor receives a opkg install upm small amount of light or no light at all. The Intel Galileo Gen 2 board allows you to use only six Then, click Create an IoT Project and select Java Project of the digital I/O pins as PWM output pins. These six pins are in the IDE. I’ll use AmbientLightAndLed as the project name. labeled with a tilde symbol (~), which reflects a prefix to the Enter the connection name and the IP address for your Intel number on the board. Galileo Gen 2 board. This way, the IDE will provide you with I use the analog pin labeled A0 to connect the positive an environment that will upload and run the project to the side (+) of the voltage divider that includes the photoresistor. specified board. In the console, you will see the output gener- In addition, I use the following PWM-enabled pins to control ated by the project, and you can run commands in a terminal. the brightness level of an RGB LED: However, as always, once you learn how things work, you ■■ Pin ~6 is connected to the anode pin for the red component will find it easier to generate your own scripts and run your of the RGB LED. own commands to upload the generated JAR file and run it. ■■ Pin ~5 is connected to the anode pin for the green component The IDE provides an integrated debugging experience that is of the RGB LED. extremely useful when you start working with the mraa and ■■ Pin ~3 is connected to the anode pin for the blue component upm libraries in Java. of the RGB LED. You need the following parts to work with this example: Wiring the Electronic Components ■■ A photoresistor. A photoresistor is an electronic component also known as a ■■ A 10,000Ω (10 kΩ) resistor with 5 percent tolerance. The light-dependent resistor (LDR) or photocell. It is not the best color bands for the resistor are brown, black, orange, component for sensing ambient light with high levels of and gold. accuracy. However, the component is useful for determining ■■ A common cathode 5 mm RGB LED. 15

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

■■ Three 270Ω resistors with 5 percent tolerance. The color age divider built from the photoresistor and a 10 kΩ resistor bands for the resistor are red, violet, brown, and gold. with 5 percent tolerance. The photoresistor is wired to the Figure 1 shows the previously mentioned electronic com- IOREF pin. I am using the board’s default configuration and, ponents connected to a breadboard, the necessary wirings, therefore, the IOREF voltage is 5V. The 10 kΩ resistor is wired and the wirings from the Intel Galileo Gen 2 board to the to GND. breadboard. (I created the original diagram with the popu- lar Fritzing multiplatform application. The Fritzing file is Coding a Class to Dim an LED by Using PWM included in the code bundle related to this article, which is Once you finish all the necessary wiring, you need to write available in the Java Magazine download area. Java code to determine whether you are in a dark environ- There are three PWM-capable GPIO (general-purpose ment and then control the brightness of the three colors of input/output) pins: ~6, ~5, and ~3. Each of them is connected the RGB LED based on the ambient light value. The code reads to a 270Ω resistor and wired to an anode pin for each LED the result of converting a resistance value into a voltage, and color. The common cathode is connected to ground (GND). then transforms this analog value into its digital representa- The analog input pin labeled A0 is connected to the volt- tion. The code maps the digital value to a voltage value, and then it maps this voltage value to a darkness or ambient light measurement value. In order to keep the code easier to read and understand, the next Java classes I explain won’t perform checks on the results of each operation performed. However, in a final version of the example, you should check the result of each call to a method of an instance of the different mraa classes and make sure that the returned value is equal to mraa.Result.SUCCESS. I am going to create the following three classes: ■■ VariableBrightnessLed: This class represents an LED con- nected to the board, and it will allow me to control its brightness level. ■■ VoltageInput: This class represents a voltage source con- nected to an analog input pin in the board, and it will allow me to map the raw values read from the analog input into voltage values. ■■ SimpleLightSensor: This class represents a light sensor, and it will allow me to transform a voltage value, measured with a VoltageInput instance, into a light measurement Figure 1. The electronic components connected to a breadboard and and description. wired to the Intel Galileo Gen 2 board Then, I will create a BoardManager class that creates instances 16

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

of the VariableBrightnessLed and SimpleLightSensor classes, } else if (validBrightnessLevel < 0){ and will interact with them. Finally, I will create a master validBrightnessLevel = 0; class, called AmbientLightAndLed, which coordinates the } operations of the previously explained classes. float convertedLevel = First, I create a new VariableBrightnessLed class that validBrightnessLevel / 255f; represents an LED connected to the board that can have a this.pwm.write(convertedLevel); brightness level from 0 to 255 inclusive. The following code this.brightnessLevel = validBrightnessLevel; lines show the import statements that I use for all the classes System.out.format( and the code for the new class: "%s LED connected to PWM Pin #%d " + "set to brightness level %d.%n", import mraa.Aio; this.name, import mraa.Pwm; this.gpioPin, validBrightnessLevel); class VariableBrightnessLed { } private final int gpioPin; private final String name; public int getBrightnessLevel() { private final Pwm pwm; return this.brightnessLevel; private int brightnessLevel; }

public int getGpioPin() { public VariableBrightnessLed(int gpioPin, return this.gpioPin; String name) { } this.name = name; } this.gpioPin = gpioPin; this.pwm = new Pwm(gpioPin); When I create an instance of the VariableBrightnessLed class, this.pwm.period_us(700); it is necessary to specify the GPIO pin number to which the this.pwm.enable(true); LED is connected in the gpioPin int argument and a name for // Set the initial brightness level to 0 the LED in the name String argument. The constructor creates this.setBrightnessLevel(0); a new mraa.Pwm instance with the received gpioPin as its pin } argument, saves its reference in the pwm field, and calls its period_us method to configure the PWM period to 700 micro- public void setBrightnessLevel( seconds (700 µs). This way, the output duty cycle will deter- int brightnessLevel) { mine the percentage of the 700 µs period during which the int validBrightnessLevel = brightnessLevel; signal is in the on state. if (validBrightnessLevel > 255) { For example, a 0.10 (10 percent) output duty cycle means validBrightnessLevel = 255; that the signal is on during 70 µs of the 700 µs period. 17

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

Then, the constructor calls the Finally, the code saves the valid brightness level in the The class declares pwm.enable method with true as a brightnessLevel field, which is read-only accessible through a method that parameter to set the enable status the getBrightnessLevel method. The last line prints details translates a of the PWM-enabled pin and about the brightness level set to the LED identified with a allow the code to start setting name and wired to a specific pin number. The line is printed brightness level the output duty-cycle percentage with System.out.format, and it is possible to see the output from 0 to 255 for the PWM pin with calls to the when you run the generated JAR file through the IDE or by (inclusive) into the pwm.write method. running commands through SSH on Yocto Linux running on Finally, the constructor the board. I’ll dive deep on the benefits of printing useful appropriate output calls the setBrightnessLevel information later. duty-cycle value for method with 0 as the value for the PWM pin. the brightnessLevel argument. Measuring Ambient Light via Analog Input This way, the constructor sets the Now, I create a new VoltageInput class that represents a volt- brightness level to 0 for the LED age source connected to an analog input pin on the board. The wired to the specified pin number following lines show the code for this new class: and turns off the LED. Specifically, the call turns off a specific color component of the RGB LED. class VoltageInput { The class declares a setBrightnessLevel method that private final int analogPin; translates a brightness level from 0 to 255 (inclusive) into private final Aio aio; the appropriate output duty-cycle value for the PWM pin. The method receives a brightness level int value in the public VoltageInput(int analogPin) { brightnessLevel argument. this.analogPin = analogPin; First, the code makes sure that the brightness level is this.aio = new Aio(analogPin); a value between 0 and 255 (inclusive). If the value is out of // Configure the ADC range, the code uses either the lower-level or the upper- // (short for Analog-to-Digital Converter) level value and saves it in the validBrightnessLevel // resolution to 12 bits (0 to 4095) local variable. this.aio.setBit(12); Then, the code calculates the required output duty- } cycle percentage for the PWM pin to represent the bright- ness level as a float value between 1.0f and 0.0f (100 percent public float getVoltage() { and 0 percent). It is necessary to divide the valid brightness long rawValue = this.aio.read(); level (validBrightnessLevel) by 255f. The code saves the float voltageValue = value in the convertedLevel variable. The next line calls the rawValue / 4095f * 5f; this.pwm.write method with the convertedLevel variable for return voltageValue; the percentage argument and sets the output duty cycle for } the pin configured as the PWM output to convertedLevel. 18

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

public int getAnalogPin() { I have a class that allows me to retrieve a voltage return analogPin; value from a voltage source. Now, I will create a new Simple } LightSensor class that represents the photoresistor, which } is included in the voltage divider and wired to an analog pin of the board. The new class uses the previously coded When I create an instance of the VoltageInput class, it is VoltageInput class that reads and transforms an analog necessary to specify, in the analogPin int argument, the input. The new class allows me to transform a voltage value analog pin number to which the voltage source is connected. into a light measurement and description. The following lines The constructor saves the received analog pin number in show the code for this new class: the analogPin field, which is read-only accessible through the getAnalogPin method. Then, the constructor creates a class SimpleLightSensor { new mraa.Aio instance with the received analogPin as its pin // Light-level descriptions argument, saves its reference in the aio field, and calls its public static final String setBit method to configure the analog-to-digital converter LL_EXTREMELY_DARK = "Extremely dark"; (ADC) resolution to 12 bits. This way, the ADC will provide public static final String 4,096 possible values (212 = 4096) to represent from 0V to 5V. A LL_VERY_DARK = "Very dark"; 0 value read from the ADC represents 0V, and 4095 means 5V. public static final String It is necessary to apply a linear function to convert the LL_JUST_DARK = "Just dark"; raw values read from the analog pin and map them to the public static final String corresponding input voltage values. Thus, the code multiplies LL_SUNNY_DAY = "Like a sunny day"; the raw value read from the analog pin by 5 and divides it by // Maximum voltages that determine the light level 4095 to obtain the input voltage value from the raw value. private static final float As I am using 12 bits of resolution, the detected values will EXTREMELY_DARK = 2.1f; have a step of 5V / 4095 = 0.001220012V, that is, approximately private static final float 1.22 millivolts. VERY_DARK = 3.1f; The VoltageInput class declares a getVoltage method private static final float that calls the this.aio.read method to retrieve the raw value JUST_DARK = 4.05f; from the analog pin and saves it in the rawValue long vari- able. The code saves the value in this variable to make it private final VoltageInput voltageInput; easy to debug and understand how the code works. Then, the private float measuredVoltage = 0f; method calculates the result of dividing rawValue by 4,095 private String lightLevel = and multiplying it by 5, and saves it to the floatvoltageValue SimpleLightSensor.LL_SUNNY_DAY; variable. Finally, the method returns the value of the voltageValue variable. This way, the method returns the public SimpleLightSensor(int analogPin) { voltage value, converted from the raw value retrieved by the this.voltageInput = this.aio.read method. new VoltageInput(analogPin); 19

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

this.measureLight(); the environment is very dark. If } the retrieved voltage is lower than The new class 4.05V, the environment is just barely allows me to public void measureLight() { dark. These values work with a spe- transform a voltage this.measuredVoltage = cific photoresistor; you might have this.voltageInput.getVoltage(); to check the voltage values that value into a light if (this.measuredVoltage < determine specific environments in measurement and SimpleLightSensor.EXTREMELY_DARK) { your own configuration. It is neces- description. this.lightLevel = sary to change only the values of the SimpleLightSensor.LL_EXTREMELY_DARK; class fields. } else if (this.measuredVoltage < The main goal for the Simple SimpleLightSensor.VERY_DARK) { LightSensor class is to convert a this.lightLevel = quantitative value (a voltage value) into a qualitative value (an SimpleLightSensor.LL_VERY_DARK; ambient light description). The class declares the following } else if (this.measuredVoltage < four class fields with the descriptions for the light levels: SimpleLightSensor.JUST_DARK) { ■■ LL_EXTREMELY_DARK this.lightLevel = ■■ LL_VERY_DARK SimpleLightSensor.LL_JUST_DARK; ■■ LL_JUST_DARK } else { ■■ LL_SUNNY_DAY this.lightLevel = When I create an instance of the SimpleLightSensor class, SimpleLightSensor.LL_SUNNY_DAY; I need to specify in the analogPin argument, which is the } analog pin number to which the voltage divider that includes } the photoresistor is connected. The constructor creates a new VoltageInput instance with the received analogPin argu- public String getLightLevel() { ment and saves its reference in the voltageInput field. The return this.lightLevel; next line calls the measureLight method that transforms } the voltage value retrieved with the VoltageInput instance } (this.voltageInput) into a description of the light level. The class declares the measureLight method, which saves The class defines the following three class fields, which specify the voltage value retrieved by calling the this.voltageInput the maximum voltage values that determine each light level. .getVoltage method in the measuredVoltage field. Then, ■■ EXTREMELY_DARK: 2.1V the next lines use the previously explained class fields to ■■ VERY_DARK: 3.1V determine whether the value of the measuredVoltage field is ■■ JUST_DARK: 4.05V lower than the maximum voltages that determine each light If the retrieved voltage is lower than 2.1V, the environment level. The code sets the appropriate value for the lightLevel is extremely dark. If the retrieved voltage is lower than 3V, field according to the measured voltage value. Then, it is 20

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

possible to access the light level description by calling the } getLightLevel method. public void updateLedsBasedOnLight() { Controlling One Input and Three Outputs with a String lightLevel = Board Manager this.lightSensor.getLightLevel(); Now, I will create a new BoardManager class that creates an switch (lightLevel) { instance of the previously coded SimpleLightSensor class and case SimpleLightSensor.LL_EXTREMELY_DARK: three instances of the VariableBrightnessLed class. This way, this.setRGBBrightnessLevel(255); there is one instance of the VariableBrightnessLed class for break; each color component of the RGB LED. The class fires actions case SimpleLightSensor.LL_VERY_DARK: when the ambient light changes. Specifically, the class adjusts this.setRGBBrightnessLevel(128); the brightness for the three color components of the RGB LED break; based on the measured ambient light. The following lines case SimpleLightSensor.LL_JUST_DARK: show the code for this new class: this.setRGBBrightnessLevel(64); break; class BoardManager { default: public final SimpleLightSensor lightSensor; this.setRGBBrightnessLevel(0); public final VariableBrightnessLed redLed; break; public final VariableBrightnessLed greenLed; } public final VariableBrightnessLed blueLed; } } public BoardManager() { this.lightSensor = The BoardManager class declares the following four fields that new SimpleLightSensor(0); the constructor initializes: this.redLed = ■■ lightSensor: An instance of SimpleLightSensor, which new VariableBrightnessLed(6, "Red"); represents the photoresistor included in the voltage divider this.greenLed = connected to the analog pin labeled A0. new VariableBrightnessLed(5, "Green"); ■■ redLed: An instance of VariableBrightnessLed, which rep- this.blueLed = resents the red component of the RGB LED connected to the new VariableBrightnessLed(3, "Blue"); GPIO pin labeled ~6. } ■■ greenLed: An instance of VariableBrightnessLed, which represents the green component of the RGB LED connected public void setRGBBrightnessLevel(int value) { to the GPIO pin labeled ~5. this.redLed.setBrightnessLevel(value); ■■ blueLed: An instance of VariableBrightnessLed, which rep- this.greenLed.setBrightnessLevel(value); resents the blue component of the RGB LED connected to this.blueLed.setBrightnessLevel(value); the GPIO pin labeled ~3. 21

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things /

The setRGBBrightnessLevel method calls the set // The measured light level has changed BrightnessLevel method for the three VariableBrightness lastlightLevel = newLightLevel; Led instances with the value received as an argument. This System.out.format( way, the three color components of the RGB LED are set to "Measured light level: %s%n", the same brightness level through a single call. newLightLevel); The updateLedsBasedOnLight method retrieves the board.updateLedsBasedOnLight(); light-level description from the SimpleLightSensor instance } and calls the previously explained setRGBBrightnessLevel try { method to set the brightness level for the three components Thread.sleep(1000); of the RGB LED based on the measured light. If it is extremely } catch (InterruptedException e) { dark, the brightness level System.err.format( is set to 255. If it is very "Sleep interruption: %s", The main goal for the dark, the brightness level e.toString()); SimpleLightSensor class is set to 128. If it is just } is to convert a quantitative dark, the brightness level } is set to 64. Otherwise, the } value (a voltage value) into a brightness level is set to 0, } qualitative value (an ambient which means the RGB LED light description). is completely off. The class declares the main method that is executed when I Now, I will write code upload and launch the project on the board. First, the method that uses the BoardManager initializes the lastLightLevel local variable with an empty class to measure the String and creates an instance of the BoardManager class ambient light and set the brightness for the three color named board. Then, the method runs a loop forever. components of the RGB LED based on the measured ambi- The loop calls the board.lightSensor.measureLight ent light. The following lines show the code for the new method to update the ambient light measurement. The next AmbientLightAndLed class: line saves the light-level description retrieved with the call to board.lightSensor.getLightLevel in the newLightLevel public class AmbientLightAndLed { local variable. If the new light level is different from the last public static void main(String[] args) { recorded ambient light level, the code updates the value for String lastlightLevel = ""; the lastLightLevel variable, prints the measured light level, BoardManager board = new BoardManager(); and calls the board.updateLedsBasedOnLight method. while (true) { You can run the example and use a flashlight or your board.lightSensor.measureLight(); smartphone to move light over the photoresistor. You should String newLightLevel = see the printed messages and see that the RGB dims and board.lightSensor.getLightLevel(); finally turns off. After you reduce the light in the environ- if (newLightLevel != lastlightLevel) { ment, the RGB LED increases its brightness. 22

ORACLE.COM/JAVAMAGAZINE //////////////////////////////// SEPTEMBER/OCTOBER 2016 //internet of things / //java proposals of interest /

Listening for transport dt_socket at address: 8009 Red LED connected to PWM Pin #6 set to brightness level 0. Green LED connected to PWM Pin #5 set to brightness level 0. FEATURED JDK ENHANCEMENT PROPOSAL Blue LED connected to PWM Pin #3 set to brightness level 0. Measured light level: Extremely dark Red LED connected to PWM Pin #6 set to brightness level 255. Green LED connected to PWM Pin #5 set to brightness level 255. JEP 293: Revising the Format Blue LED connected to PWM Pin #3 set to brightness level 255. Measured light level: Extremely dark Red LED connected to PWM Pin #6 set to brightness level 128. of Command-Line Options Green LED connected to PWM Pin #5 set to brightness level 128. Blue LED connected to PWM Pin #3 set to brightness level 128. This recent enhancement proposal suggests that the Figure 2. Console messages JDK tools that are run from the command line should share a common syntax for passed-in arguments. As the Figure 2 is an example of the output shown in the console document points out, at present JDK tools don’t share a window of the IDE. The console window displays all the mes- common syntactical convention for switches. For exam- sages I printed, which makes it easy for me to understand ple, the help command, which most readers will agree what should happen with the components. should be consistent across all tools, varies between -?, -help, and --help. Conclusion While JEP 293 primarily advocates uniformity in This simple example demonstrates that you can take advan- future command-line JDK products, it also suggests tage of Java SE 8 to create high-level code that interacts with that a useful format to adopt would be the set of GNU IoT components on the Intel Galileo Gen 2 board. The mraa syntax conventions, described in large part in getopt(3). and upm libraries are regularly updated, and combining them These conventions use a single hyphen for single-letter with Java makes it easy to leverage your existing knowledge options (which can be combined) and a double hyphen to undertake IoT projects that interact with different kinds of for the so-called “long” options. Although this choice inputs, outputs, sensors, displays, and actuators.