//NOVEMBER/DECEMBER 2014 /
THE INTERNET OF THINGS JAVA IS EVERYWHERE 13 29 20 HENRIK STÅHL INDUSTRIAL AUTOMATION JAVA: THE NEXT ON JAVA AND IOT WITH ROBOTS GENERATION
ORACLE.COM/JAVAMAGAZINE //table of contents /
13 20 29 COMMUNITY JAVA: THE NEXT ROBOTS MAKE JAVA DEVELOPMENT GENERATION FACTORIES Teach kids to code SMARTER and give them tools Keba’s systems help FOR THE INTERNET for success. usher in the next OF THINGS industrial revolution. JAVA IN ACTION Oracle’s Henrik Ståhl discusses the Internet of Things for Java developers.
Internet
of Things JAVA TECH
New theme icon. See how it works.
COVER ART BY LINDY GROENING
COMMUNITY JAVA TECH 45 55
03 35 Embedded Rich Client ABOUT US From the Editor New to Java A Smart-Home Platform Building Castles in the Sky 05 Code Java on the Raspberry Pi for the Mass Market Use JavaFX 3D to model historical Java Nation BlueJ brings Java SE 8 development Eclipse SmartHome bridges the gap treasures and more. JavaOne recap, plus news, directly to the Raspberry Pi. between tech-savvy users and average 62 people, events, and books 38 users to provide a smart-home platform Rich Client for everyone. Java Architect A Bridge from Java 2D to JavaFX 25 50 JCP Executive Series jdeps, Compact Profiles, Profit from the easy migration path The Java Advantage for IoT and Java Modularity Embedded provided by FXGraphics2D. Freescale’s Maulin Patel discusses the A look at the future of Java modularity The Device I/O API 67 Internet of Things (IoT) and how the JCP 41 A standard API for peripherals and Fix This helps to facilitate evolving technologies. low-level hardware control just arrived Take our JAX-RS code challenge! Java Architect for Oracle Java SE Embedded. JDK 8u20 Improves Performance, blog JAVA IN ACTION Security, and Manageability 34 Learn how to better control managed IoT Developer Challenge Winner systems that run multiple rich internet Lhings Connected Table applications. 01
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 EDITORIAL PUBLISHING Editor in Chief Publisher Caroline Kvitka Jennifer Hamilton +1.650.506.3794 COMMUNITY Community Editor Associate Publisher and Audience Yolande Poirier Development Director Java in Action Editor Karin Kinnear +1.650.506.1985 Michelle Kovac ADVERTISING SALES Technology Editor President, Sprocket Media Tori Wieldt Kyle Walkenhorst +1.323.340.8585 Contributing Writer Western and Central US, LAD, and Kevin Farnham Canada, Sprocket Media 3 Billion Contributing Editors Tom Cometa +1.510.339.2403 Claire Breen, Blair Campbell, Eastern US and EMEA/APAC, Kay Keppler, Karen Perkins Sprocket Media IN ACTION JAVA DESIGN Mark Makinney +1.805.709.4745 Devices Run Java Senior Creative Director Advertising Sales Assistant Francisco G Delgadillo Cindy Elhaj +1.626.396.9400 x 201 Senior Design Director Mailing-List Rentals Suemi Lam Contact your sales representative. Design Director RESOURCES Richard Merchán Oracle Products
Contributing Designers +1.800.367.8674 (US/Canada) TECH JAVA Jaime Ferrand, Diane Murray, Oracle Services ATMs, Smartcards, POS Terminals, Blu-ray Players, Arianna Pucherelli +1.888.283.0591 (US) Production Designers Sheila Brennan, Kathy Cygnarowicz Oracle Press Books Set Top Boxes, Multifunction Printers, PCs, Servers, oraclepressbooks.com Routers, Switches, Parking Meters, Smart Meters, Lottery Systems, Airplane Systems, IoT Gateways, ARTICLE SUBMISSION ABOUT US If you are interested in submitting an article, please e-mail the editors. Programmable Logic Controllers, Optical Sensors, SUBSCRIPTION INFORMATION Subscriptions are complimentary for qualified individuals who complete the Wireless M2M Modules, Access Control Systems, subscription form. MAGAZINE CUSTOMER SERVICE Medical Devices, Building Controls, Automobiles… [email protected] Phone +1.847.763.9635 PRIVACY Oracle Publishing allows sharing of its mailing list with selected third parties. If you prefer that your mailing address or e-mail address not be included in this program, contact Customer Service.
Copyright © 2014, Oracle and/or its affiliates. All Rights Reserved. No part of this publication may be reprinted or otherwise reproduced without permission from the editors. JAVA MAGAZINE IS PROVIDED ON AN “AS IS” BASIS. ORACLE EXPRESSLY DISCLAIMS ALL WARRANTIES, WHETHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ORACLE BE LIABLE FOR ANY DAMAGES OF ANY KIND ARISING FROM YOUR USE OF OR RELIANCE ON ANY INFORMATION PROVIDED HEREIN. The #1 Development Platform information is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied blog upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Java Magazine is published bimonthly with a free subscription price by Oracle, 500 Oracle Parkway, MS OPL-3C, Redwood City, CA 94065-1600. Digital Publishing by GTxcel 02
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //from the editor / COMMUNITY JAVA IN ACTION
ava is everywhere. As the Internet of Things (IoT) moves from hype to reality, we’re seeing embedded Java used in a wide range of applications, from industrial automation systems and medical imaging devices to Jconnected vehicles and smart meters. Haven’t you heard? Java is the glue. Internet JAVA TECH In our interview with Oracle’s Henrik Ståhl, we discuss the opportunities and challenges of Things that the IoT presents for Java developers, and how changes in Java SE and Java ME (and their embedded versions) make it easier to reassemble and strip down code for smaller devices. We have lots of additional IoT content in this issue as well: we talk toFreescale’s Maulin Patel about the IoT and Java, profileIoT Developer Challenge winner Lhings Connected Table, and show you how robots make fac- tories smarter. Plus, Vinicius Senger introduces the Device I/O API, Kai Kreuzer brings us the latest on smart ABOUT US homes, and Michael Kölling shows us how to program in Java on the Raspberry Pi. We also take a look at the developers of tomorrow in “Java: the Next Generation.” I’ve been talking to kids at various programming events for the last few months, and I am inspired. These kids are brave, bold, and so smart. They do not fear technology; they embrace it. I’m thrilled to see so many pro- grams around the world that are teaching young people to code and helping them to //send us your feedback / create their futures. We’ll review all suggestions for future improvements. BIO Caroline Kvitka, Editor in Chief Depending on volume, some messages might not get a direct reply. blog
PHOTOGRAPH BY BOB ADLER 03
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014
// java nation / JavaOne 2014 / COMMUNITY JAVAONE TAKES SAN FRANCISCO
The 19th JavaOne celebrated IN ACTION JAVA momentum in the Java platform, innovation, and strong community. Devoxx4Kids kicked things off a day early, when 150 kids got hands-on and had fun with programming,
robotics, and engineering. The open- TECH JAVA ing Strategy keynote established Oracle’s commitment to building a strong and flexible Java platform that will enable IT professionals to adapt to rapid technological change, from the Internet of Things (IoT) to more-
powerful enterprise systems. ABOUT US Oracle’s Peter Utzschneider said Java has shown strong growth this year, with 80 new Java user groups (JUGs) established and a transpar- ent and accessible Java Community Process (JCP). Java SE 8, released in March 2014, has changed the land- scape for Java developers, thanks to lambda expressions and their ability to reduce the need for boilerplate code, said Oracle’s Georges Saab. blog Utzschneider stressed that the A bird’s-eye view ongoing integration of embedded of Duke’s Café Java with the rest of the platform is enabling developers who have basic
PHOTOGRAPH BY HARTMANN STUDIOS 05
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation / JavaOne 2014 / COMMUNITY
From left to
right: Mark IN ACTION JAVA Watch the Strategy keynote. Reinhold, John Rose, James Java skills to use those skills in Gosling, and the embedded space and the grow- Brian Goetz ing IoT. Later, Oracle’s Cameron Purdy emphasized how the Java plat- TECH JAVA form is continuously evolving TECHNICAL KEYNOTE toward end-to-end capabilities. The Technical keynote was held in two parts: one include value classes. Look to Project Valhalla and He acknowledged the help of the that followed the Strategy keynote and a second Project Panama for more information, he said. community and emphasized that that preceded the Community keynote. Oracle’s In part two, Reinhold gathered a panel of Java Java EE 7, the only standards-based Mark Reinhold reflected on Java as it nears its luminaries, including James Gosling, onstage to platform for enterprise develop- 20th birthday about ways it can keep going for take questions. When asked when Java would ABOUT US ment, is continuing to drive down another 20 years. He addressed the challenges of become obsolete, Gosling confessed that for a the costs of building and maintain- enhancing Java’s ability to scale down, improve decade he has been expecting Java’s demise, but ing applications. He pointed out security, evolve more easily, improve startup that Java is a kind of organism grounded in the that the JCP Executive Committee performance, and scale up to large systems. To community that is well understood and flexible has unanimously approved the address these issues, Java 9 is focused on Project and has strong staying power. roadmap to Java EE 8—which was Jigsaw, which is “an attempt to design and imple- drawn up directly from the survey Watch the ment a standard module system for the Java SE responses of 4,500 Java developers. Technical platform and use that to modularize the platform keynote. Purdy observed that for Java EE 7, 19 itself—and applications,” he said. Jigsaw will have JUGs made valuable contributions a profound impact on how large Java systems are by adopting 14 JSRs, and he called built and maintained and improve developer per- for that kind of community partici- blog formance and productivity, Reinhold said. pation going forward. Next, Brian Goetz offered a vision of Java extending to Java 9 and beyond that would
PHOTOGRAPHS BY HARTMANN STUDIOS 06
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation / JavaOne 2014 /
Bruno Paul Perrone
Maisonnier COMMUNITY JAVA IN ACTION JAVA NullPointers
Rock JavaOne TECH JAVA COMMUNITY KEYNOTE
At the JavaOne Community keynote, Java ABOUT US Evangelist James Weaver gathered a large group of innovators, who showed off Java-based projects—everything from programs that teach Andra Kay kids to code to automated vehicle testing sys- The NullPointers, the unofficial Java community band, rocked JavaOne at the tems that can save lives. JCP party and later in the week at Duke’s Robotics was a key theme. Some highlights: in the United States, and showed a video about Café. The band is made up entirely of Andra Kay, director at Silicon Valley Robotics, his automated vehicle testing system with an JavaOne community members. said, “By 2020 your household robot will be advanced braking system that could save lives— your house.” a first step toward cars with full autonomy. Bruno Maisonnier, CEO at Aldebaran, a world The Community keynote ended with the tra- leader in humanoid robots, presented a video ditional T-shirt toss (or catapult), led byJames showing robots teaching children mathematics Gosling. It was the perfect ending to a great blog in schools. week of information sharing, learning, and Paul Perrone of Perrone Robotics lamented the community building. 30,000 deaths from auto accidents each year Watch the Community keynote.
PHOTOGRAPHS BY HARTMANN STUDIOS 07
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation / JavaOne 2014 /
JCP Awards COMMUNITY The Java Community Process (JCP) presented GEEKS the 10th annual JCP Awards and celebrated its
RIDE ON 15th birthday at a gather- IN ACTION JAVA The Geek Bike Ride tradi- ing atop the Hilton Hotel tion continued at JavaOne on Monday night. with 35 riders from nine Heather VanCura received the award for JCP countries. Riders sported Program Member of the jerseys designed by com- Year for her leadership in TECH JAVA munity members in Brazil the Adopt-a-JSR program, and enjoyed a sunny day of which provides a mecha- heart-pumping activity. nism for Java user groups (JUGs) and individuals to easily contribute to JSRs and encourages grassroots participation in crafting ABOUT US Otávio Gonçalves de Santana (top), Heather VanCura (top the future of Java. and bottom), and Michael The Most Significant JSR Lagally (bottom) was awarded to JSR 360, Connected Limited Device Configuration (CLDC) 8, which brings language features, including generics, enumerations, and try-with-resources, from Java SE into Java ME. Michael Lagally was recognized as Outstanding Spec Lead for his efforts in spearheading JSR 360. Otávio Gonçalves de Santana was awarded Outstanding Adopt-a-JSR Participant for his work on blog JSR 354, Java Money and Concurrency—specifically in migrating the codebase from Java 7 to Java 8.
BIKE RIDE PHOTOGRAPH BY KEVIN NILSON; JCP PHOTOGRAPHS BY BOB LARSEN 08
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation / COMMUNITY
Subramaniam.” Each UJUG meet- ing has two pre- sentations, and the presenter schedule is already filled into IN ACTION JAVA late 2015. Meetings typi- cally start with the traditional pizza, and they often end with a trip to TECH JAVA the local pub for those interested. FEATURED JAVA USER GROUP “Yes, there’s good beer in Utah!” Porter exclaims. He adds that each UJUG meeting is unique. “Something new is tried each month to improve networking and for just plain
UTAH JAVA USERS GROUP ABOUT US fun—we had a paper airplane competition The Utah Java Users Group (UJUG) was mation technology and software development last month.” founded in 1998 by Ben Galbraith and Glen firms along the Wasatch Front in north central If you’re a Java developer who loves skiing or Lewis. The group is currently led by Jason Utah that is “leading the world in innovative the great outdoors, you may want to consider Porter and supported by board members Don memory process technology. . .and data analy- the Silicon Slopes next time you’re seeking Bogardus, Mike Bylund, and Chris Hansen. sis,” according to CNBC. new work. “There’s a healthy startup com- UJUG currently has about 1,000 members. Porter notes that, indeed, the Silicon Slopes munity and a trend for big out-of-state shops Meetings, which are normally held on the phenomenon has had an enormously positive to open local development centers,” says third Thursday of each month, typically draw effect on UJUG’s growth and vivacity. “Silicon Porter. “Developer unemployment in Utah is from 80 to 180 attendees. Slopes has seen a tech boom, and Java is the down to 1.5 percent, with salaries continuing If this level of participation surprises you language of choice in all the major shops, to rise (the latest trend is highway recruiting (because Utah is in the bottom 20 percent of and most of the smaller ones,” he says. “This billboards). All the energy in the ecosystem blog the United States in population density), that makes for great local presenters, and we makes for great UJUG meetings, and a tan- probably means you haven’t heard of “Silicon also get visits from out-of-towners, includ- gible excitement in the community.” Slopes” (@SiliconSlopes), the cluster of infor- ing Jason Van Zyl, Gavin King, and Venkat Learn more at UJUG’s Meetup site.
SKIING PHOTOGRAPH BY MIKE SCHIRF/GETTY IMAGES 09
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation /
JAVA CHAMPION PROFILE
BRUNO GHISI COMMUNITY
Java SE puter and program- Ghisi: I love program- my career and take ming language? ming and still do it it to the next level. Updates Ghisi: My first com- as a hobby. I used Great opportunities puter was a 486 PC. to surf, but now I also came from blog- Oracle has released Java I put Linux on it, and enjoy jogging and ging and doing open
SE Development Kit 8 started program- cooking more. source development. IN ACTION JAVA Update 25 (JDK 8u25) ming simple scripts. Java Magazine: What Java Magazine: What and Java SE 7u71 and My first real pro- happens on your are you looking for- Java SE 7u72. gramming language typical day off work? ward to in the com- JDK 8u25 includes was Java. Ghisi: I definitely stay ing years? important security Java Magazine: What with my friends and Ghisi: For the
fixes. Read ther elease was your first profes- family, sometimes past three years, TECH JAVA notes and download sional programming going to the beach. I I have been CTO the update. job? love barbecues, and I [and cofounder] of Bruno Ghisi is Ghisi: Florianópolis, Java SE 7u71 and Java I worked for a also like to travel. Resultados Digitais. an open source a southern Brazil Ghisi: SE 7u72 include impor- mobile company that What We have a product developer, tech- island. Java Magazine: tant security fixes. Read was writing some side effects of your called RD Station, nology blogger, Java Magazine: When the release notes and nice Java ME appli- career do you enjoy which is an online
and cofounder of and how did you first ABOUT US download the update. cations in a period the most? marketing platform, Resultados Digitais, become interested Java SE 7u71 is a Critical when there were no I meet a lot and more than 1,200 an online marketing in computers and Ghisi: Patch Update (CPU), smartphones or app of people that I’ve clients. I love what company. He became programming? which contains fixes to stores. The UIs were long admired. I do. I work with a a Java Champion in Ghisi: My father was security vulnerabilities simple, and net- fantastic team, and September 2007, involved in the first Java Magazine: and critical bugs. Java working was terrible. Has being a Java we have awesome while he was com- computer science SE 7u72 is a Patch Set We ported some of Champion changed customers. For the pleting his under- class at the Federal Update (PSU), which con- the first social net- anything for you coming years, I hope graduate degree at University of Santa tains all of the security works such as Orkut with respect to your to keep learning, the Federal University Catarina, and intro- fixes in the CPUs released (before Facebook) daily life? experience new chal- of Santa Catarina, duced me to main- up to that version, as well and Fotolog to Definitely. I lenges, and probably Brazil. frames at his job Ghisi: as additional noncritical mobile devices. was pretty young have a baby as well. Java Magazine: when I was a child. blog fixes. Learn more about Where did you What Java Magazine: What when I became a Java You can find Bruno CPU and PSU releases. Java Magazine: grow up? was your first com- do you enjoy for fun Champion, and being Ghisi on Twitter as and relaxation? one helped to guide @brunogh. 10
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation / COMMUNITY JAVA IN ACTION JAVA JAVA TECH JAVA ABOUT US
Codemotion share everything about the Groovy and EVENTS NOVEMBER 21–22 Grails ecosystems. MADRID, SPAIN Jfokus FEBRUARY 2–4 This conference is open to users of all Riga Dev Day STOCKHOLM, SWEDEN languages and platforms. It offers full-day JANUARY 22, 2015 Jfokus has run for eight years and is the largest annual workshops, keynotes, conference ses- RIGA, LATVIA Java developer conference in Sweden. Conference topics sions, and hackathons across eight tracks. This event is a joint project by Google include Java SE and Java EE, front end and web, mobile, Developer Group Riga, Java User Group continuous delivery and DevOps, Internet of Things, cloud Groovy & Grails eXchange Latvia, and Oracle User Group Latvia. By and big data, future and trends, alternative Java Virtual DECEMBER 11–12 and for software developers, it focuses on blog Machine (JVM) languages, and agile development. LONDON, ENGLAND 25 of the most-relevant topics and tech- This two-day conference brings together nologies for that audience. Tracks include industry-leading experts and develop- JVM and web development, databases, ers from around the world to learn and DevOps, and case studies. PHOTOGRAPH BY EDWARD STOJAKOVIC/FLICKR 11
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java nation /
JAVA BOOKS COMMUNITY JAVA IN ACTION JAVA
SOA WITH JAVA MASTERING LAMBDAS: RESTFUL JAVA WEB SERVICES PROFESSIONAL JAVA EE JAVA EE APPLICATIONS ON By Thomas Erl, Andre Tost, JAVA PROGRAMMING IN A SECURITY DESIGN PATTERNS ORACLE JAVA CLOUD Satadru Roy, Philip Thomas, Raj MULTICORE WORLD By René Enríquez and By Murat Yener and By Harshad Oak Balasubramanian, David Chou, By Maurice Naftalin Andrés Salazar C. Alex Theedom Oracle Press, September 2014 and Thomas Plunkett Oracle Press, November 2014 Packt Publishing, July 2014 Wiley, December 2014 Learn how to build highly JAVA TECH JAVA Prentice Hall, June 2014 This Oracle Press book pro- This book will serve as a Professional Java EE Design available, scalable, secure, Java has evolved into an vides a complete ground- practical companion for Patterns is the perfect distributed applications exceptional platform for ing in the theory of lambda you to learn about com- companion for anyone who on Oracle Java Cloud with building web-based enter- expressions and the ratio- mon vulnerabilities when wants to work more effec- Java Champion Harshad prise services. In SOA with nale for their introduc- using RESTful services. You tively with Java EE. It’s the Oak. He leads you through Java, Thomas Erl and sev- tion and use in practice. It will gain indispensable only resource that covers the entire Java EE cloud- eral world-class experts reviews a simple Java code knowledge of the tools you both the theory and appli- based application life- ABOUT US guide readers in mastering fragment iterated over a can use to implement and cation of design patterns cycle, from development the principles, best prac- collection, poses differ- test security on your appli- in solving real-world prob- to deployment. Filled tices, and Java technolo- ent challenges, and then cations.RESTful Java Web lems. The authors guide with real-world examples, gies required to design and delves into the fundamen- Services Security covers readers through the funda- ready-to-use code, and deliver high-value services tals of syntax and basic the finer details of setting mental and advanced fea- best practices,Java EE and service-oriented solu- use. Maurice Naftalin rec- up RESTful services—for tures of Java EE 7, present- Applications on Oracle tions. The book is appro- ommends best practices example, implementing ing patterns throughout Java Cloud is an invaluable priate for any technical for adding lambda expres- RESTEasy, securing trans- and demonstrating how resource for anyone look- professional whose aim is sions to an existing library mission protocols such they are used in day-to- ing to meet the growing to design and implement and explores the changing as OAuth, and integrating day problem solving. demand for cloud-based web-based service- Collections Framework. OAuth with RESTEasy. development skills. oriented architectures and blog enterprise solutions with Java technologies.
12
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY
Oracle’s Henrik Ståhl JAVA DEVELOPMENT discusses the Internet of Things for Java developers. FOR THE INTERNET OF THINGS BY TIMOTHY BENEKE JAVA IN ACTION
Internet of Things
he Internet of Things (IoT) is JAVA TECH poised to blow into our daily lives and make many of the things we interact with Tmore efficient, faster, and more fun. Analysts predict that by 2020 there
will be 50 billion devices wirelessly ABOUT US connected to each other and making smart decisions for us. We’re seeing early adoption in healthcare, includ- ing lifestyle health devices, patient monitoring, and home healthcare. Another big area is telematics in the automotive industry—not to men- tion home automation. Suffice it to say that everything from our homes to healthcare to the workplace will change due to the IoT. For Java developers, many oppor- blog tunities and questions present them- selves. How can they deploy their present skills to better apply them to IoT development? What changes PHOTOGRAPHY BY NAME HERE 13
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY
in the Java platform should future IoT developers know about? What are the security issues? We met up with Henrik Ståhl, vice president of product management for Java and the IoT at Oracle, to discuss JAVA IN ACTION these and other issues.
Java Magazine: What is Oracle doing to help Java developers enter the IoT space? Ståhl: Java developers can already use their skills to develop back-end appli- JAVA TECH cations for the IoT. We want them to also be able to develop software on the various devices that constitute the devices—the things in the IoT—using the same language, the same APIs, and compact runtimes suitable for the ABOUT US embedded space, which in the past has involved a steep learning curve for everyone who ventures into it. Instead, developers have had to learn low-level does not currently exist in the embed- to make them as compatible with each Henrik Ståhl at work languages that impede productivity ded space. other—and with the mainstream Oracle at Oracle’s Stockholm, and lead to relatively high maintenance To achieve this vision, it is vital that JDK 8—as possible. Sweden, office costs. Now, because embedded devel- we get to a common programming To get toward this goal while achiev- opment often includes integration with model across all devices, regardless ing low memory and disk footprints, various types of specialized peripherals of size or device capabilities. With the we have introduced the concept of and sensors, it will likely always require release of Oracle Java ME Embedded 8 Compact Profiles in Java SE 8. These some amount of low-level program- and Oracle Java SE Embedded 8, we give developers a choice of deploying ming. We are not aiming to replace have made the features that developers the entire set of Java SE APIs, or one of blog that, but rather to enable an application are used to in Java available on embed- three different subsets that are incre- developer to work in Java, freeing up the ded platforms with as little as a couple mentally smaller. These subsets have system developer to focus only on the of hundred kilobytes of memory. A been selected very carefully to match hardware enablement. This distinction major goal of these two releases was what APIs are needed for common use 14
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY JAVA IN ACTION Watch the video: Java Embedded for IoT
ded gateways. This brings the Java ME Raspberry Pi. Our traction in the micro- APIs much closer, but not quite on par, controller space is more limited to JAVA TECH with Java SE. We plan to continue this date, but with the release of Oracle Java development and are looking at things ME Embedded 8 we believe that our missing from Java ME such as lambdas, platform is well suited to meet market reflection, and better integration with demands. And so, we think that with native code. enough energy and support coming These embedded Java platforms are from the Java community and Oracle, ABOUT US the number one thing that we are pro- we can get Java developers to start Ståhl (center) shows a cases such as running an OSGi [Open viding to embedded developers. focusing on embedded. This brings an demo to colleagues Klara Service Gateway initiative] stack. The And as we include tools—for example, immediate benefit to the IoT because Ward and Erik Helin. Compact Profiles are a stepping-stone on the Java ME side so that it catches up Java greatly facilitates key device-side toward more-granular modularity that with the likes of Java SE—it will be really requirements such as communica- will be introduced with Project Jigsaw in easy for the 9 million Java developers tions, integration, security, and a flex- Java SE 9. to start taking on embedded projects, ible application model. The notion of As for Oracle Java ME Embedded 8, which is something that we are obvi- having billions of things out there on we have come a very long way from its ously trying to encourage. We have seen constrained form factors means that roots as a platform for feature phones. very good uptake of Java already in the we need programming models to push The APIs and the application deploy- higher-end devices, such as wireless business logic to the network edge and ment model have been massively modules (small chips that integrate a make decisions at the perimeter of the blog updated to fit their target to run on low-power CPU, some memory, and a network as opposed to centralizing all small embedded devices, including 3/4G modem for communications) and communication behind the customer medium- to high-end microcontrollers, larger SoCs [systems on a chip] includ- firewall and the cloud. So, the embed- smart sensors, and small embed- ing the popular hobbyist-targeted ded Java platform is only going to 15
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 DEVELOPING ON DEVICES
“Java developers can already use their skills to develop COMMUNITY back-end applications for the IoT. We want them to also be able to develop software on the various devices that constitute the devices in the IoT.” , JAVA IN ACTION
become more important moving for- have a retail application, you ward, as Java developers start to key in can now extend that retail on the IoT. application to iBeacon and do Java Magazine: What’s happening with proximity marketing. If you Java ME? have an application that does JAVA TECH Ståhl: We released Java ME 8 and we input payment or serves up are planning another release in 2015, ads for automobile custom- where you will see a lot of incremen- ers, you can now extend that tal enhancements that build on the all the way to the automobile capabilities of the Java ME 8 platform. and actually start getting back You’re going to see additional platform information from its various ABOUT US support, improved runtime perfor- systems that will allow you to mance—all of the things that we’re offer a pretty good mainte- focusing on or that we have focused on nance plan. tion. It’s necessary but insufficient to Ståhl talks with colleague in Java SE 8. You are also going to see And if you want to better orches- derive value from the use cases. It’s Stefan Särne. uptake in the field by hardware manu- trate the subsystems in a building, really the rest of the application that facturers that integrate Java ME directly you can now do that by tying in to the becomes more valuable. For example, a in their devices, greatly increasing the HVAC system and the lighting system, retail application—from Oracle or from adoption rate. and doing that across vendors with a somewhere else—becomes much more Java Magazine: What do you want Java standard platform such as Java. The valuable when you can use it to do developers to understand as they apply ability to connect to edge devices—for proximity-based marketing or provide their skills in an embedded context? example, an actuator, a valve, or what- proximity-based offers depending on Ståhl: With our embedded platforms, ever, depending on the use case—and where somebody is in a store. blog Oracle is enabling all of the applica- control these systems is one of the key So embedded Java becomes the tions in the Oracle portfolio and all of enablers of the IoT. enabling technology. For developers the applications being built by the Java I am quick to caution that it’s not who pay attention, this will allow them community to talk to the IoT. So if you necessarily the biggest value proposi- to tap into an entirely new class of appli- 16
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY
cations that extend existing solutions. the same device. This has been hugely Ståhl: The IoT introduces risk on a Java Magazine: What key features of beneficial to Java for server applica- number of levels. There are three dif- Java make it a good fit for the IoT? tions. But it is even more important ferent approaches that we’re taking, Ståhl: What’s important about Java for embedded because there is such and we’re relying on standards wher- is the abstraction and portability that a massive diversity of hardware archi- ever possible to make sure we provide the runtime environment provides. tectures, operating systems, peripher- a proven solution. JAVA IN ACTION Organizations that need to deploy als, and so on. The simple benefit of First, there is a vulnerability on the Ståhl notes that in devices as part of an IoT solution can being able to reuse application code device itself. So, for example, if you the IoT space, security decouple their applications and librar- is in itself a very strong argument for had a vending machine to hook up to repeatedly comes ies from specific devices, enabling Java. Of course, the rich set of standard the internet and you could use that to up as an underlying reuse of code between different devices APIs and the predictable development access other systems, then harden- limiting concern. and between different generations of cycle and lifetime of the Java platform ing that system at the edge is hugely itself are also strong important. This is further aggravated by JAVA TECH arguments. the fact that the devices are often not Another benefit of the physically secure and—even worse—in runtime environment is some cases, they are under the physi- encapsulation. The fact cal control of the entity most interested that we’re running within in hacking into them. I often use smart the JVM [Java Virtual meters as an example: The person ABOUT US Machine] and restricting in whose house the smart meter is the developer from doing installed is the person who benefits things that are not per- most from hacking it. formed via some well- Second, the middle piece of secu- defined API means that rity is data transmission, where we are we’re providing an addi- relying on internet standards; encrypt- tional layer of security. ing things on the edge and then on the In the IoT space, security back end; and sending the data over repeatedly comes up the encrypted channel. With traditional as the underlying limit- internet security, we have a concern ing concern that people that there’s a man in the middle who’s have about jumping into going to intercept something and replay blog this industry. it as an attack. With the IoT, the concern Java Magazine: Tell us is more that you think you’re talking to a more about security and smart toaster in your house when really the IoT. you’re talking to a hacker in his mom’s 17
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY
has not been modified or standpoint, and that is not going to tampered with on the way, change. Oracle’s belief is that by con- and that only authorized tinuing to invest in these areas, Java individuals have access will remain vibrant, the community to it? will remain engaged with Oracle, and Of course, all of these Oracle and the community will con- JAVA IN ACTION areas have to be managed tinue to have a creative and beneficial such that an administra- ongoing relationship. I would like to tor—or, in the case of per- finally put to rest the FUD [fear, uncer- sonal data, an individual— tainty, and doubt] about Java being can control the security a legacy language and platform. The configuration, the authen- reality is that Java is rejuvenating itself tication, and the authori- across the board with new innovation JAVA TECH zation through policies. and new growth in community activity. Java Magazine: Any This includes the addition of new Java final thoughts for Java user groups, and an unprecedented developers? rate of adoption of Java 8 including in Ståhl: Oracle is redoubling hot areas such as the cloud and, yes, its efforts to keep Java the IoT. Developers have the tools and ABOUT US vibrant and is continuing a commitment from Oracle and the to honor its commitment community to do everything possible Ståhl says that Oracle basement. That’s the big concern. to add new productivity features— to make them successful. is redoubling its efforts Third is data security. This goes back for example, things such as lambda MORE ON TOPIC: to keep Java vibrant to basic concepts such as privacy, data expressions—across the board, includ- and is continuing to integrity, and accountability for and ing in the embedded computing space, Internet add new productivity of Things features. auditability of access to sensitive data. down the road. It’s a big commitment. If you carry around a medical sensor, But in this age where there are a ton which reads your vitals, you don’t want of new languages being created, and Timothy Beneke is a freelance writer and data from it to be available to anyone a ton of new runtimes that are pop- editor who has written extensively about except your healthcare provider and ping up all over the place, the reality Java. His articles, which cover a wide your close friends and family. With is that our biggest customers always range of topics, have appeared in Mother blog today’s complex infrastructures and come back to Java. And the reason Jones and the East Bay Express. business models, how can you make that’s happening is because of the sure that data read from a sensor ends continued investment that we make in LEARN MORE up in the right back-end system, that it Java from a performance and security • “Navigate the Internet of Things” 18
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014
At Java programming workshops at Oracle headquarters and JavaOne, kids got hands-on with coding, robotics, COMMUNITY and more. JAVA IN ACTION JAVA TECH ABOUT US
ids are coding. They are creating animations, modifying Minecraft, Kbuilding LEGO Mindstorms, pro- gramming NAO robots, and more. And JAVA: they are doing it in Java. With the number of computer sci- ence jobs on the rise, making sure the blog THE NEXT GENERATION next generation can fill these positions is critical. According to the organization Teach kids to code and give them tools for success. BY CAROLINE KVITKA code.org, there will be 1 million more PHOTOGRAPHS BY ORACLE/RON SELLERS, HARTMANN STUDIOS computer science jobs than computer 20
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY JAVA IN ACTION JAVA TECH
Kids at the Create the Future Java Workshop talk with Caroline Kvitka.
At the Devoxx4Kids science students in the United States accomplishes the entire solution to ters in Redwood Shores, California, for ABOUT US event before alone by 2020. the problem.” the Create the Future Java Workshop. JavaOne, kids chose Whether kids are destined for careers However, only 1 in 10 schools in the Over three days, they learned to pro- from workshops in in computer science or something United States offers computer science gram in Alice 2.0 and Alice 3.0, and in programming, robotics, and engineering. outside of technology, programming classes, according to code.org, which Java on LEGO Mindstorms. skills are useful in many parts of their wants US schools to follow the example Alice 2.0 focuses on logical and com- lives, says Wanda Dann, associate pro- set by China, the UK, and Vietnam, putational thinking skills and program- fessor at Carnegie Mellon University where coding classes are offered as ming fundamentals, while Alice 3.0 and director of the Alice program. Alice early as elementary school. emphasizes object-oriented concepts is a tool that focuses on storytelling That’s where extracurricular pro- and a full transition to the Java pro- in a 3-D environment to teach kids grams come in. Although opportunities gramming language. LEGO Mindstorms the basic concepts of object-oriented for kids to learn to code were limited combines building LEGO robots with programming. just a few years ago, today programs programming. blog “Learning to program actually is abound and kids (and sometimes their “We have used Java as our tool for learning to decompose a problem parents) are flocking to them. implementation, and we write our into simpler steps,” Dann says. “And In August, 672 kids between the ages code so that after students have used PHOTOGRAPH BY HARTMANN STUDIOS by accomplishing those steps, one of 13 and 18 came to Oracle headquar- Alice they can go into a classroom 21
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 where Java is being taught and feel must be a priority in a society where “We need to train our kids in tech-
comfortable that they understand technology is becoming more and more nology, and have them stay engaged in COMMUNITY what those statements do because important,” says Daniel de Luca, world- technology at an early age. If we catch they actually have seen them before,” wide manager of the Devoxx4Kids ini- them raw and show them it’s fun, it’s Dann says. “I think one tiative, which started in 2012 in Belgium possible, they won’t be scared,” adds of the reasons that Java with programming workshops for kids. Arun Gupta of Devoxx4Kids Bay Area. is so well liked as a pro- The program aims to teach and inspire And from the looks of the San Cool Tools for Kids gramming language for kids about computer programming Francisco event, the kids did have fun. Scratch teaching younger students while they are having fun. Since its “It’s been really cool . . . I really liked A drag-and-drop programming tool, is because it is possible founding, Devoxx4Kids has shared its it,” says Tim Gonzales, a 14-year-old JAVA IN ACTION Scratch teaches young kids how to to model everyday kinds curriculum with Java user groups and participant from San Francisco who program interactive stories, games, of objects. Students other organizations around the world. plans to pursue a career in technol- and animations. can then relate to those To date, more than 80 Devoxx4Kids ogy. “The door to opportunity is so Greenfoot objects, which makes it workshops have taken place, with open. I just need to find out my passion This visual and interactive integrated easier for them to see how 2,500 participants. within technology.” Programs such as development environment (IDE) the skills they’re learning JAVA TECH teaches object orientation with Java. in computer program- BlueJ ming are usable in many This standalone Java IDE is used to different career paths,” teach the beginnings of programming. she adds. More recently, the SnapCode next generation of Java ABOUT US Featured at the JavaOne Community developers got a taste keynote, SnapCode is a new, free tool of programming at a for building Java applications with Devoxx4Kids day the simple drag and drop. Saturday before JavaOne San Francisco. At this event, a collaboration with Oracle Academy, 150 kids, ages 10 to 18, got hands-on and had fun with programming, robotics, and engineer- ing. Topics included Alice, Arduino, Greenfoot, LEGO Mindstorms, Minecraft Modding, NAO humanoid blog robot, Python, Raspberry Pi gaming, and Scratch. Kids attended four ses- sions of their choice. Twenty-one girls from the organization Black Girls Code participated in the Devoxx4Kids PHOTOGRAPH BY HARTMANN STUDIOS “Teaching children how to program event at JavaOne. 22
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 Left: Kids took a stretching break at the Devoxx4Kids COMMUNITY event. Below: Chris Hollinger of Oracle Academy talked about Alice at the Create the Future Java Workshop. JAVA IN ACTION JAVA TECH ABOUT US
Devoxx4Kids can help him get where he atmosphere,” says Black Girls Code needs to go, he adds. Founder Kimberly Bryant. Of the Devoxx4Kids attendees, 21 were girls from the San Francisco chap- AROUND THE WORLD ter of Black Girls Code, an organiza- Computer programs for kids are pop- tion that seeks to introduce girls from ping up all over the world. In the underserved communities to computer Philippines, JEDI4KiDS educates chil- science and technology with a goal to dren to be more creative using comput- increase their representation in the ers and provides them the opportunity STEM (science, technology, engineer- to learn computer programming in a Kids and organizers talk about their ing, and mathematics) fields. “The fun and interactive manner. experience at the Devoxx4Kids event. blog event was a wonderful opportunity for JEDI4KiDS is part of the larger JEDI our students to experience a wide array initiative, which provides free and of technology tools in a youth-friendly open source computer science and IT
PHOTOGRAPHS BY HARTMANN STUDIOS, ORACLE/RON SELLERS 23
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 More Organizations COMMUNITY Girls Who Code This US-based nonprofit organiza- tion works to educate, inspire, and equip high school girls with the skills and resources to pursue opportuni- ties in computing fields.
CoderDojo JAVA IN ACTION CoderDojo is a global network of volunteer-led, independent, free computer programming clubs for young people between 7 and 17 who learn how to code; develop websites,
apps, programs, and games; and JAVA TECH explore technology. Maker Kids The Toronto, Canada–based Maker Kids builds maker learning activities for kids and educators and runs one of the world’s only “makerspaces” for kids. Curriculum and training are ABOUT US available to educators, parents, and interested adults in any location. Hour of Code Daniel de Luca, training to colleges and universities. they can solve problems. If there is This global programming move- worldwide manager JEDI4KiDS was developed when the something they don’t like, they can fix of Devoxx4Kids (top ment is reaching tens of millions of JEDI founders realized that there was a or change it. If there is something they row, center, in white), need to teach programming at an early wish they had, they can create it.” students in every country. Hour of and Arun Gupta Code takes place during Computer of Devoxx4Kids age. The program offers one-day work- The momentum around exposing Science Education Week, December Bay Area (top row, shops in Greenfoot, LEGO Mindstorms, more kids to computer technology 8 to 14, 2014. Hour of Code offers second from right) and Scratch in partnership with opens the door to a bright future—both one-hour tutorials in more than 30 with Devoxx4Kids Devoxx4Kids. for Java and the next generation of Java languages for ages 4 and up. day participants, “Coding allows children to think cre- developers, technologists, and creative blog volunteers, and atively and use their brains in a way minds. NAO robots. they have never imagined,” says Gerald Concha, founding partner of JEDI4KiDS. Caroline Kvitka is editor in chief of “It allows them to feel confident that Java Magazine. PHOTOGRAPH BY ORACLE/RON SELLERS 24
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 Maulin Patel with team members Greg Hemstreet and Mary Thomas at Freescale’s Austin, Texas, headquarters. COMMUNITY JAVA IN ACTION JAVA TECH ABOUT US
JCP Executive Series Internet The Java Advantage for IoT of Things aulin Patel manages the global Freescale’s Maulin Patel discusses the Internet of Things (IoT) and how Software and Applications team blog for the Microcontrollers group at the JCP helps to facilitate evolving technologies. BY STEVE MELOAN M Freescale, a leader in embedded process- ing solutions. He oversees the engineer- PHOTOGRAPHY BY PAUL S. HOWELL ing focus of Freescale’s IoT strategy. With 25
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY more than 25 years of experience in of focus, while maintain- software engineering, he has held vari- ing the broad-based appli- ous leadership roles at IBM, Intel, NXP cability that has defined the Semiconductors, Conexant Systems, and Java ecosystem. Trident Microsystems. Patel earned a Since joining the JCP, we’ve bachelor’s degree in electrical engineer- been able to engage with tech- ing from SP University in India and a nology partners toward influ- JAVA IN ACTION master’s degree in electrical engineer- encing key elements of Java ing from Kansas State University. In architectural JSRs. We were addition, he holds 11 patents in a vari- also influential in some of the ety of software fields such as system JSRs related to Java 8. management, reliability, availability, Java Magazine: Can you give and serviceability. us some more detail on your JAVA TECH involvement with various JSRs? Java Magazine: What motivated you to Patel: I have contributed to join the JCP [Java Community Process], JSR 358 and JSR 364 as an and how has that involvement ben- Executive Committee mem- efited your company and your work ber. JSR 358 focuses on a within the company? number of important changes Patel: For more than two years we’ve and adjustments to the JCP, ABOUT US been engaged with Oracle through the including revision of the Java JCP. That partnership has been very Specification Participation fruitful toward ensuring that our prod- Agreement [JSPA], which ucts work seamlessly with a variety of is crucial to broadening industry partners in the IoT space. participation. believe we arrive at compromises and Patel says that “Java Java provides a framework for our The focus of JSR 364 is to broaden JCP creative solutions that best suit the provides a framework end-to-end IoT schema, consisting participation by defining new -mem entire community. for our end-to-end IoT schema.” of edge (sensor endpoints), gateway bership classes, modifying existing Java Magazine: What are some of your (communications layer), and cloud. Our membership categories, and ensuring most pressing areas of concern in portfolio plays in all of these segments. appropriate intellectual property com- evolving the IoT space and Java? One of the primary motivating fac- mitments from JCP members. Patel: Key areas of focus for us are the tors in joining the JCP has been to Executive Committee member dis- footprint, the power scheme manage- blog contribute our IoT expertise and experi- cussions represent a broad range of ment, and data security across the ence along with other industry leaders. voices, including large companies such entire domain, end to end. Security Our goal is to ensure that Java evolves as IBM, SAP, Intel, HP, and Oracle, issues are of paramount importance in a way that is beneficial to our area as well as a host of smaller players. I at this stage of the IoT’s development, 26
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 PATEL ON SECURITY “Security issues are of paramount importance at this COMMUNITY stage of the IoT’s development, specifically the interplay between Java and the IoT framework.” JAVA IN ACTION
consistent architecture that all plays As a functional body, the JCP is work- together seamlessly. That’s a huge ing well. But we need to make partici- advantage. You can begin data collec- pation easier for individuals who may tion with Java ME, move to Java SE for not be affiliated with large corporations. JAVA TECH gateway services, and move to Java EE Many of these developers have brilliant for data management and process- IoT and Java-related ideas and expertise ing. This frees Java IoT developers from to contribute. Also, Java user groups worrying about hardware dependencies span the globe. We need to incentiv- and allows them to create applications ize this amazing pool of talent to bring much more quickly. more JSRs to the table.
The Java platform also ensures data The JCP is still a bit complex and time ABOUT US Patel says that the specifically the interplay between Java security across the entire vertical span. consuming. JSRs 348, 358, and 364 Java architecture and the IoT framework. The entire Java It is built in as an integrated architec- have improved things greatly, but we’re allows customers community needs to become more tural attribute. With all the data hack- constantly trying to improve efficiency to create vertical applications that span aware of IoT issues, because growth is ing we constantly hear about, security and inclusiveness, while preserving the data collection at edge going to be substantial. And the whole is on people’s minds. Java security integrity of the processes. nodes, to gateways, Java ecosystem will be strengthened by integrity will continue to evolve through Java Magazine: What are your thoughts and up to the cloud. adding additional effort and attention the JSR process. It’s a very dynamic set about attracting existing Java develop- to these areas. of activities. ers who are not very familiar with the Java Magazine: What are some of the Java Magazine: Are there any changes IoT space? advantages Java brings to the table for you would like to see in the JCP? Patel: That’s a good question, and IoT developers? Patel: This topic was addressed at something that should be a topic of Patel: The Java architecture allows any the last meeting of the Executive conversation within the Executive blog customer to create vertical applications Committee. We were discussing ways Committee. Expert Java developers that span data collection at the edge to bring new voices from the IoT per- will want to become involved in the nodes, to the gateway communica- spective into the Executive Committee IoT domain, because it’s one of the tion layer, and up to the cloud, using a through the election process. most exciting application areas right 27
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 PATEL ON THE JVM “In the world of IoT development, COMMUNITY now. And it’s poised for there is sometimes the JCP community. There are still connectivity issues to explosive growth. But I do And I think we’re gener- be dealt with in making this happen. A think the importance of a concern that ally doing a good job of common connectivity framework and IoT should be reinforced the JVM will be achieving those goals. architecture will be essential. Multiple at events such as JavaOne In the world of IoT devel- connectivity standards are out there— and Oracle OpenWorld, an impediment opment, there is some- Wi-Fi, Bluetooth, and ZigBee, for JAVA IN ACTION with keynote addresses to efficiency. But times a concern that the instance. Wi-Fi is becoming the most and sessions. That would evolving Java JVM [Java Virtual Machine] prevalent, but it’s not the de facto stan- be a great forum for this will be an impediment to dard. Connectivity needs to be ubiqui- kind of promotion. standards are efficiency. But evolving tous, highly reliable, and well organized. I would compare IoT making Java ME Java standards are mak- And as I’ve mentioned, security is right now to the initial ing Java ME applications another concern of primary impor- JAVA TECH phase of the smartphone applications very very efficient. tance. Customers must be able to trust app market. There was efficient.” It’s also important to that their data is secure for IoT applica- some initial resistance, consider overall system tions to really proliferate and become and nobody knew exactly cost. This is where the a part of daily life. The evolution of Java how things would evolve. Java platform excels. Java through the JCP will be a key element in But apps very quickly became a multi- development saves time and promotes that success formula.
billion-dollar market. I believe that will reusability. These are huge advantages ABOUT US
happen for IoT as well. in the broader scheme. MORE ON TOPIC: Java Magazine: Could you discuss the Java Magazine: Do you have any closing Internet interplay between standards and inno- remarks? of Things vation in the world of Java and the JCP? Patel: If we deploy IoT to the lowest Patel: Too much rigidity can be the common denominator in the human enemy of innovation. But we also need population, that means the household. Steve Meloan is a former C/UNIX soft- well-crafted standards to attract devel- For instance, if you were driving to ware developer who has covered the web opers around a common framework. work and you had forgotten to set your and the internet for such publications as Millions of developers worldwide are home alarm, you could pull over and Wired, Rolling Stone, Playboy, SF Weekly, affected by the standards developed do that on your smartphone. And you and the San Francisco Examiner. He re- through the JCP. The platform must could check surveillance cameras to cently published a science-adventure function as an integrated totality. make sure all was well, and then adjust novel, The Shroud, and regularly contrib- blog And it does. But it must also be flex- the thermostat or close the garage utes to The Huffington Post. ible enough and nimble enough to door. Those myriad devices must be respond to dynamic market forces. seamlessly connected all the way to LEARN MORE We talk about that frequently within the cloud. • Freescale’s Internet of Tomorrow Tour 28
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 Keba Software Developer Hannes Bachmayr sketches COMMUNITY out some code at company headquarters in Linz, Austria. JAVA IN ACTION
Internet of Things
ew industries have seen as much JAVA TECH change and upheaval in the last F decade as the manufacturing sec- tor. Today’s modern factories bear little resemblance to the mills, plants, and assembly lines that defined industrial production throughout the twentieth ABOUT US century. Steady advancements in tech- nology and increasing globalization have transformed not only our facto- ries, but our manufacturing workforce as well. Take a tour of a modern auto- mobile plant, for example, and you will see more robots than people. Routine production and assembly operations ROBOTS MAKE are performed by computer-driven machines. The factory workers who remain are mostly highly skilled techni- cians, designers, and engineers. blog FACTORIES SMARTER Many of these machines are Keba’s systems help usher in the next industrial revolution. BY DAVID BAUM equipped with advanced sensors that give them an uncanny awareness of PHOTOGRAPHY BY TON HENDRIKS their operating environments, as part of 29
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 COMMUNITY
KEBA AG keba.com Headquarters: Linz, Austria
Employees: JAVA IN ACTION 900 Revenue: €181 million Java technologies used:
Java SE 6, Java SE 7, JAVA TECH and Java SE 8 with JavaFX, OSGi, and Eclipse e4 ABOUT US
the rapidly growing Internet of Things The intellectual capital in these ver- Keba AG, an engineering firm based Keba software (IoT)—physical objects with network satile factory environments doesn’t lie in Linz, Austria, that designs and pro- engineering team connectivity that can send and receive so much with the equipment as with duces high-tech equipment for the members (from left data. In a modern factory, sensors not the software that controls it—a per- industrial, energy, and banking sectors, to right) Hannes Bachmayr, Florian Erler, only guide the machines, but also pro- vasive fabric of instructions that binds is in the vanguard of these modern Martin Fischer, Fabian vide information to fine-tune the opera- each robot to the global supply chain. factory developments. In the field of Schöppl, and Robert tion as a whole. For example, if the heat Collecting and analyzing real-time pro- industrial automation, Keba has built Pöchtrager share ideas. blog or humidity on a production line varies duction data dictates many aspects of products for controlling injection mold- outside of an acceptable range, that line the manufacturing cycle, from sourcing ing machines and robotic systems. In can report this condition and adjust its materials and customizing products to the energy sector it is well known for activities automatically. interacting with partners. its climate control systems and elec- 30
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 tric vehicle charging stations. Keba thing from motion controllers to keyless architect in Keba’s industrial depart-
also develops bank terminals, parcel security systems. ment who works closely with Bachmayr. COMMUNITY machines, lottery terminals, and cus- “We are the guys setting up the soft- “All of the controls are based on Java. tom hardware and software systems ware that enables people to interact When a user clicks Generate, KeStudio governing their use. with machines,” says Hannes Bachmayr, creates the Java code that controls the For the last several years, Keba’s soft- a software developer at Keba special- machines. And when they click the Start ware engineers have been immersed izing in these human-machine connec- button, KeStudio fires up Java appli- in the development of a Java-based tions. “Many of our important software cations that govern a robot’s control, environment for human-machine components are based on Java.” sensory feedback, and information- interfaces (HMIs) that operate the processing capabilities.” JAVA IN ACTION activities of all types of industrial equip- GLOBAL CONNECTIONS, Some of Keba’s products are powered ment. One popular system, dubbed LOCAL CONTROL by multipurpose hardware devices such From left to right: Fabian Schöppl, Marion KeStudio View Edit, is a point-and-click According to a report issued by the as the CP-36 system KeControl C3. This Lindenmair, Hannes environment that guides engineers McKinsey Global Institute, the expense versatile platform can be programmed as they develop HMIs for robots and of owning and operating industrial to control 3-D printers, presses, and
Bachmayr, and Martin JAVA TECH Fischer chat over coffee other systems. Application engineers robots has fallen by as much as 50 other machine tools using the KeStudio at Keba. of Keba use KeStudio to design every- percent compared to human labor since environment. KeControl C3 is powered 1990. This is due in part to sheer effi- by an Intel processor and runs Windows, ciency: Machines can operate around Linux, and other operating systems. the clock and achieve unusually high “Java is perfect for this multiplatform precision in production and assem- system because we can compile appli- bly processes. They don’t talk back or cations once and run them everywhere,” ABOUT US require a coffee break, and many of Bachmayr says. “Java also makes it easy them can work in a lights-out environ- to move applications from one comput- ment, saving energy costs. ing environment to another.” Many of these machines are con- To ensure that Keba’s hardware and trolled by HMI applications that dictate software environments are compatible how they behave, such as positioning with global manufacturing standards, a robotic arm in an injection molding Keba’s software engineers pay close machine or training an infrared sen- attention to the proceedings of theOPC sor to follow a heat source. KeStudio Foundation, an industry consortium makes it easy to create HMI applica- chartered with ensuring compatibil- tions by shielding product design- ity among various types of industrial ers and hardware engineers from the equipment. Adhering to OPC (which blog underlying code. stands for object linking and embedding “KeStudio is easy to use because you for process control) standards is espe- don’t need to understand program- cially important for the work Keba does ming,” says Fabian Schöppl, a software with German automotive manufactur- 31
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 ers, many of which are part of Industrie
4.0, a project sponsored by the German COMMUNITY government to encourage the creation of “smart factories.” An important standards body for Industrie 4.0 and the IoT, OPC helps ensure compat- ible communication among industrial equipment and processes.
DAWN OF AN INDUSTRIAL ERA JAVA IN ACTION Manufacturing consultants at Germany Trade & Invest, a government agency within the Federal Republic of Germany, From Industry 1.0 to 4.0 believe Industrie 4.0 will First industrial revolution: Use of pave the way for a fourth JAVA TECH mechanical production facilities industrial revolution driven by water and steam power. over the next couple of Second industrial revolution: decades. As they see it, the Introduction of division of labor and first industrial revolution, Keba’s Fabian Schöppl and Josef Milt test out a demo application. mass production with the help of which extended from the electrical energy. late eighteenth century to ABOUT US Third industrial revolution: Infusion the mid-nineteenth cen- As we stand on the threshold of a sonal communication and interaction. of information technology to further tury, was defined by the fourth industrial revolution, we can Similar movements are afoot in the automate production. shift from handcrafted expect a manufacturing panacea that US with the Smart Manufacturing Fourth industrial revolution: The goods to mechanical pro- will combine today’s ubiquitous com- Leadership Coalition, a nonprofit orga- dawn of cyberphysical systems to duction methods. The munication networks with the equip- nization of manufacturers, suppliers, facilitate interaction between the second industrial revolu- ment in smart factories. Germany and technology companies that is sup- virtual and physical worlds. tion gained momentum at Trade & Invest is encouraging the ported by a consortium of universities, the start of the twentieth development of technologies that can government agencies, and laboratories. (Source: German Research Center century with refined meth- independently exchange information The aim of this coalition is to foster col- for Artificial Intelligence) ods for industrial assembly and manage their own industrial laborative R&D practices and encourage and the mass production processes. Researchers use the term the formation of advocacy groups that of products. Industrial cyberphysical systems to describe this can enhance manufacturing intelli- blog revolution #3 started in the late 1960s interplay between the virtual and phys- gence via common standards and plat- with the rise of electronics and the con- ical worlds. These systems facilitate forms and shared infrastructure. sequent infusion of information tech- these connections in much the same Industrial giant GE uses slightly dif- nology into industrial processes. way that the internet transformed per- ferent terminology to describe today’s 32
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 the machines. This type of selected Java for its ease of migra-
workforce, united by com- tion and platform independence, and COMMUNITY mon projects and inter- because it has tons of plugins and ests rather than location, third-party tools,” he states. He adds points to another impor- that the Keba team especially appreci- tant attribute of today’s ates multitouch support with JavaFX, advanced manufacturing a software platform the team uses for companies: their ability creating rich desktop clients. “Java is an to break down geographic easy programming language to learn. boundaries and create Oracle is behind it, which benefits the JAVA IN ACTION a smoothly function- community, and it’s part of a steady ing global workforce. For progression of new technologies such example, Bachmayr’s dis- as the Leap Motion Controller and other tributed team of software modern input devices. We compared engineers includes science Java with .NET on multiple criteria, and partners at the Software Java won out 12 to 9.” JAVA TECH Competence Center Despite differences in location, ter- Hagenberg in northern minology, and equipment standards, Austria and independent Java unites Keba’s software engineers researchers at Johannes and, by extension, paves the way for Hannes Bachmayr manufacturing opportunities and Kepler University. An additional software the factories of tomorrow. “We have demonstrates a upheavals. During a presentation at engineering team in other countries licensed Java Virtual Machines for ARM ABOUT US touchscreen system. the D-Eleven conference in May 2013, handles the finer nuances of Eclipse and versions 5 and 7 so we can easily install CEO Jeffrey Immelt said GE pioneered JavaFX development. our applications on robotic devices the “Industrial Internet” to combine “We get together every three to six with no modification at all,” concludes the positive effects of two transforma- weeks to present ideas, meet custom- Bachmayr. “Java runs on hundreds of tive revolutions: the myriad machines, ers, and discuss requirements,” says mobile devices, operating systems, facilities, fleets, and networks that Bachmayr. “In the interim we structure and embedded devices, so it was the arose from the Industrial Revolution, our development process based on well- obvious solution for these industrial and the more recent advances in com- structured increments called sprints.” applications.” puting, information, and communica- tion systems that characterized the VERSATILE SOFTWARE MORE ON TOPIC: Internet Revolution. FOR A NEW ERA Internet One of GE’s goals is to bring design- Bachmayr is adamant about the ben- of Things blog ers, suppliers, and production engineers efits of using Java for creating HMIs, together to design and test goods vir- and he has built a European team that David Baum writes about innovative tually, without requiring them to be in reflects tremendous depth of experi- businesses, emerging technologies, and close proximity to either the materials or ence with the Java ecosystem. “We compelling lifestyles. 33
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 The Lhings team at JavaOne in San Francisco (from left to right): José Antonio Lorenzo, COMMUNITY David Peñuela, and José Pereda
message welcoming the user is sent to his or her mobile phone, and the Raspberry Pi that controls the workspace Watch the Lhings Connected JAVA IN ACTION implements the user’s pref- Table in action. erences (illumination, docu- ments, printing preferences, and potentially anything else that could be controlled by an IoT device). When the workday is over, the worker scans JAVA TECH Internet the RFID card over the tabletop and the of Things workspace returns to its default state, awaiting its next user. IoT Developer Challenge Winner The Lhings platform receives infor- FAST FACTS mation from internet-connected The Lhings Connected devices, remotely controls them, and Table lets users cus- ABOUT US Lhings Connected Table lets users build logic to make the tomize their work- spaces by defining devices work together. “Lhings allowed A custom office, wherever you are BY KEVIN FARNHAM preferences for poten- us to develop the first prototype in only tially anything that can two weeks,” says Lorenzo. be controlled by an IoT he Lhings Connected Table new areas,” explains Lhings CTO José “The IoT is totally changing the device (for example, integrates embedded Java, the Antonio Lorenzo. “We thought about way people interact with their envi- desktop lighting). T Raspberry Pi, and the Lhings travelers who work in distinct locations ronment,” he adds. “The table is an Preferences are stored cloud library with a set of connected each day and how convenient it would example of IoT that goes beyond the in the cloud, and are devices (RFID cards, lighting, a coffee- be if their office workspace could be most-obvious examples. It provides available around the maker, and more) to provide a custom- replicated around the world.” an integral experience in which sev- world at any work- ized office environment that’s transfer- The Lhings Connected Table is a step eral devices work together to achieve a space where the Lhings Connected Table rable to any location. Lhings was one of in that direction. The table lets a user log common goal, offering the user a cus- blog platform is installed. three IoT Developer Challenge winners in to a shared workspace using an RFID tomized workspace; delocalizing the in the professional category. card. The user ID information is trans- desktop; and offering a set of services Lhings is a contraction “We wanted to explore how IoT ferred to the Lhings cloud platform, the that make working simpler, convenient, of Links things. [Internet of Things] could be applied to user’s preferences are retrieved, a text and more productive.” PHOTOGRAPH BY BOB ADLER/GETTY IMAGES 34
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //new to java / Part 1 Code Java on the Raspberry Pi COMMUNITY BlueJ brings Java SE 8 development directly to the Raspberry Pi.
MICHAEL KÖLLING ava programming directly website—when it comes to the hard-float API and opti- Writing Java for the BIO Jon the Raspberry Pi? Is it programming—states that mizing many other parts, Java Raspberry Pi JAVA IN ACTION possible? the computer is “a capable then became viable. It runs When the Raspberry Pi was Yes, it is! If you want to find little device that enables very well (within the restric- launched, the founders had a out how, read on. people of all ages to explore tions of the platform), and clear vision: They wanted kids The Raspberry Pi probably computing, and to learn how the Raspberry Pi Foundation to start tinkering with com- does not need much intro- to program in languages like started to include Oracle’s puters and with program- duction anymore among Scratch and Python.” Scratch JDK in its software stack (the ming again. The family com- JAVA TECH readers of Java Magazine. It is and Python? What? No Java? Raspbian images distrib- puter, so the thinking went, a small, roughly credit card– How can this be? uted to run the Raspberry Pi) is too precious; parents won’t size computer (see Figure 1) by default. let young aspiring program- that plugs into your monitor Java on the Raspberry Pi So all is well, then? Not mers play with it for fear that and keyboard. Most often, it The issue here is that you can quite. they will muck things up. No is used for electronics proj- easily develop Java the
for ABOUT US ects or to learn about pro- Raspberry Pi, but much less gramming. And it is cheap— so on the Raspberry Pi. you can get one for around In the early days of the US$40. Raspberry Pi, you could install Various Java enthusiasts and run OpenJDK. OpenJDK have done amazing things was not optimized very well with the Raspberry Pi— for the platform, and per- look, for example, at Simon formance was too poor for Ritter’s “Carputer” project. many tasks. As a result, the It connects the Raspberry Pi Raspberry Pi Foundation did to your car using Java. A few not promote Java much for minutes with your favorite the Raspberry Pi. blog Internet web browser will enable you Then, in the fall of 2013, of Things to discover various other Oracle released a JDK opti- cool projects. mized for the Raspberry Pi PHOTOGRAPH BY JOHN BLYTHE Figure 1 Yet the official Raspberry Pi ARM platform. Making use of 35
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //new to java / LISTING 1 experimentation allowed. libraries to access the hardware sudo apt-get update &&
The solution: Give kids their own, components alone is a stumbling COMMUNITY cheap computer that they can play block that will put an end to many sudo apt-get install oracle-java8-installer with all they want. What if they attempts at tinkering. delete half the operating system? As a result, until now Java devel- Download all listings in this issue as text No problem—reinstall and start opment for the Raspberry Pi took again. Experiment, play, tinker, and place on a separate computer. learn to program. The program was developed on a the hardware components of the not, you might want to start here.) It’s a great idea, except that for standard laptop or desktop, and Raspberry Pi. Make sure that your Raspberry Pi is Java, it does not work well. Java the completed executable was Thus, with BlueJ installed, you connected to the internet. JAVA IN ACTION development typically takes place then transferred to and run on can now program the Raspberry Pi We will use Java SE 8 and BlueJ in an integrated development the Raspberry Pi. This constituted using Java SE 8 and using all the for the following examples. Most environment (IDE), for development for the standard Java/BlueJ examples that likely, you do not need to install example, NetBeans IDE, BLUEJ FOR PI Raspberry Pi, but not on were previously available for stan- Java—if you got your Raspberry Pi Eclipse, IntelliJ IDEA, the Raspberry Pi. dard desktops. Your Raspberry Pi within the last year, Java SE 8 will or something like it. With BlueJ version While this is a viable can finally replace your desktop. be preinstalled on your system. If JAVA TECH None of these popu- 3.14, you can now workflow for knowl- But you can also do more than your system is older, you can install lar IDEs runs accept- program in Java edgeable hobbyists and that. You can create interactive Java SE 8 by opening a terminal ably on the Raspberry enthusiasts, it misses objects that represent hardware and typing the command shown in Pi; they are all too big SE 8 directly on the original vision. components connected to the Listing 1. and resource hungry to the Raspberry Pi. Rather than being able Raspberry Pi, such as buttons or If you are not sure whether make using them on the to use the Raspberry Pi LEDs, and have a more interac- Java is installed (or which version ABOUT US Raspberry Pi a realistic instead of the full com- tive and experimental setup for is installed), type the following proposition. puter, you now need this kind of development than command: Of course, you can always use a to use it in addition to your main ever before. plain-text editor and command- machine. More, not less, hardware For the rest of this article, and java -version line compiler. But apart from the was now needed. continuing in a future article in the fact that this is not how modern next issue of Java Magazine, we After making sure that you have software development works—and, Writing Java on the Raspberry Pi will explore installing and using Java, you are ready to download therefore, not what we should To change all this, BlueJ for the BlueJ, from BlueJ basics to exciting BlueJ. Open your web browser, go teach our kids—it is also not con- Raspberry Pi has now been interactions with the Raspberry Pi to bluej.org, and download the ducive to learning. Too many acci- released. hardware. Ubuntu/Debian Linux version of dental complexities are put into the The latest BlueJ release (with the BlueJ. (You can also use this direct path of young learners, leading to fortuitous version number 3.14) Download and Installation download link, but if you read this blog frustration and failure, rather than has been optimized to run well on For the purpose of this article, it is long after the initial publication of to experimentation and excite- the small computer directly. It also assumed that you have a Raspberry this issue of Java Magazine, it would ment. Setting up the CLASSPATH includes a library by default, Pi4J, Pi and you have already figured out be better to check the BlueJ site for correctly for the inevitably required which enables access directly to how to set it up and get started. (If newer versions.) 36
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //new to java /
Once you have downloaded the class diagram of the current project IDEs, but it can also do more. In desktop machine, the Raspberry
file, install BlueJ using the following in its main window (see Figure 2). BlueJ, you can interactively instan- Pi can do more. Because of its COMMUNITY command: tiate individual objects and call exposed hardware, you can also Getting Some Sample Programs individual methods. This enables start playing with other physical sudo dpkg -i bluej-314.deb If you are new to BlueJ or to Java much easier testing, tinkering, and I/O devices: LEDs, buttons, motors, programming, you can download experimentation. and so on. Then start BlueJ by typing the some more sample programs from These BlueJ features have been In the next issue of Java following: the BlueJ book website—look for described in previous issues of Magazine, we will continue this dis- the “Book Projects” link. Java Magazine, and you can start cussion of BlueJ on the Raspberry JAVA IN ACTION bluej there to learn more. The July/ Pi and explore some examples of Getting Started with BlueJ August 2012 and the September/ combining BlueJ’s interactivity with After BlueJ starts, you can open If you are not familiar with BlueJ, October 2012 issues include an the Raspberry Pi’s peripherals to an existing project or create a new it is worth spending a little bit of introduction to BlueJ, and theMay/ start interactive programming with one. Some sample projects are time finding out what it can do June 2014 and July/August 2014 LEDs, buttons, and more. included in the examples folder for you. It is a standard Java IDE, issues discuss the interactive fea- under /usr/share/doc/bluej. With so you can write all the Java pro- tures of BlueJ in more detail. Conclusion JAVA TECH a project open, BlueJ will display a grams that you can write in other Another good starting point is the It was high time to bring Java to the BlueJ book website. The first two Raspberry Pi as a first-class citizen. chapters of Objects First with Java External Java development with are freely downloadable for evalu- the Java executable transferred to ation and provide a good introduc- and run on the Raspberry Pi is fine tion. And, of course, you can always for many electronics hobbyists, but ABOUT US get the full book if you get hooked. it does not allow kids to practice their programming skills on the Making Use of the Raspberry Raspberry Pi itself. Pi Hardware With BlueJ version 3.14, you can So far, we have only looked at the now program in Java SE 8 directly original promise of the Raspberry on the Raspberry Pi—no second Pi: using it to replace your desktop computer is needed. computer. We have used BlueJ in
the same way we would have used MORE ON TOPIC: it on other platforms. We have seen Internet how you can now do Java program- of Things ming on the Raspberry Pi without blog a second computer. Your options for learning to program with the LEARN MORE Raspberry Pi now include Java. • BlueJ Figure 2 But in addition to replacing the • Raspberry Pi 37
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect /
jdeps, Compact Profiles, and COMMUNITY Java Modularity A look at the future of Java modularity BEN EVANS JAVA IN ACTION
BIO n “Exploring Java 8 file an application needs test for the usage of internal ber of libraries use the well- IProfiles,” we explored the to run under; to identifying APIs by user code. This is known sun.misc.Unsafe class. idea of Compact Profiles— developer code that makes easily accomplished by using Having said that, the reduced versions of the calls into the undocumented, the -jdkinternals switch. This -jdkinternals switch is a useful Java runtime environment internal JDK APIs; to helping can easily be scripted into a sanity check for developers JAVA TECH (JRE) designed for smaller- trace transitive dependencies. very useful form via a shell who develop libraries and free footprint deployments, such In its simplest form, jdeps script such as the one shown and open source software. as headless or server-only takes a class or package and in Listing ,3 which identifies Code that is designed for use deployments. provides a brief list of pack- any usage of internal APIs in by other developers (espe- This article continues ages that are the dependen- any .jar file contained in the cially by developers who are the discussion of Compact cies for that class or package, current directory or any of its external to your organization) ABOUT US Profiles and digs deeper as shown in Listing 1. subdirectories. should stick to the public APIs into what can be achieved The -cp option, as usual, This technique for finding unless doing otherwise is using the jdeps tool. It also provides a classpath to use internal API usages works absolutely necessary. describes developments to find the appropriate class best for library code, for the Otherwise, if you rely on an across the landscape of or package. The -P switch simple reason that most internal API that changes or is Compact Profiles and better (shown in Listing )2 shows applications will very likely removed from a new version modularization of the JDK. which profile is needed for a rely on a framework or library of Java, users of your code will class (or package) to run. that depends on an internal be unable to upgrade to the The jdeps Tool jdeps also has the ability to API somewhere. new Java version until you Let’s start by revisitingjdeps , delve deeper into dependen- For example, the Netty release a new version of your which is a static analysis tool cies. The -v and -V switches library depends on the inter- library that works around the for examining the dependen- show dependencies to the nal implementation of Java’s changed or removed API. blog cies of packages or classes. level of individual classes and X.509 security libraries, Some limited support for The tool can be used in a packages, respectively. Logback depends on low- detecting the use of internal number of different ways, One of the most important level details of sun.reflect APIs is also now provided by PHOTOGRAPH BY JOHN BLYTHE from identifying which pro- things that jdeps can do is to .Reflection, and a large num- javac, the Java compiler, which 38
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect / LISTING 1 LISTING 2 LISTING 3 currently flags the use of some, or other Java API that does not $ jdeps -cp $HOME/projects/scales/target/classes
but not all, internal APIs by default. necessarily contain a complete COMMUNITY :$JAVA_HOME/jre/lib/rt.jar javac emits a warning if it detects implementation of all the relevant :$M2_REPO/javax/inject/javax.inject/1/javax.inject-1.jar the usage of any internal API from a Java technology. Under normal :$M2_REPO/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar list of internal APIs that were added circumstances, using a Stripped :$M2_REPO/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7.jar to the JDK before JDK 6. Implementation would not be com.scales.svc.SimulationService While this is helpful, one area appropriate or desirable, because /Users/ben/projects/scales/target/classes -> where tooling could do more to the whole point of Java standards is /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/ support library (and application) to provide a stable, unfragmented Home/jre/lib/rt.jar JAVA IN ACTION developers is by analyzing depen- platform that developers and busi- /Users/ben/projects/scales/target/classes -> dencies. This could be achieved nesses can rely upon. /Users/ben/.m2/repository/javax/ws/rs/javax.ws.rs-api/ by using something similar to the Instead, the primary use case for 2.0/javax.ws.rs-api-2.0.jar jdeps tooling interface to build a Stripped Implementation is to /Users/ben/projects/scales/target/classes -> tree views of the dependencies of provide a solution for a Java appli- /Users/ben/.m2/repository/javax/inject/javax.inject/1/ particular packages and classes. By cation that does not want to rely on javax.inject-1.jar doing such an analysis, developers the existence of a Java environment /Users/ben/projects/scales/target/classes -> JAVA TECH could make their users aware of key on a target machine, and instead /Users/ben/.m2/repository/org/slf4j/slf4j-api/1.7.7/ facts, such as the following: wants to bundle a private environ- slf4j-api-1.7.7.jar com.scales.svc (classes) ■■ This code is guaranteed to be ment, the precise specifications of -> java.lang rt.jar API-safe, uses no internal APIs, which are known. -> java.time rt.jar and can be cleanly upgraded. As it stands, the only way to do -> java.time.format rt.jar ■■ This code can be run under this is by bundling a complete JRE. -> java.util rt.jar ABOUT US a Compact Profile, such as Even the smallest Compact Profile -> javax.inject javax.inject-1.jar compact1, and requires very little (compact1) is around 11 MB, which -> javax.ws.rs javax.ws.rs-api-2.0.jar in the way of core dependencies. can be a large overhead, espe- -> javax.ws.rs.core javax.ws.rs-api-2.0.jar The NetBeans IDE already has cially for embedded deployments. -> org.slf4j slf4j-api-1.7.7.jar limited support for Compact For applications that have a GUI, Profiles, but only via manual selec- there’s no current option but to tion and a rebuild. There is clearly bundle the full JRE, because the Download all listings in this issue as text scope for a more sophisticated and current Compact Profiles do not complete profile analysis plugin. subset the GUI classes in the JRE. This is the problem that Stripped changes to licensing and testing are the future of Java modularity. Java Stripped Implementations Implementations aim to solve by well under way and expected to be SE 8 has only just been released, There have also been some devel- providing a mechanism through completed soon. but there have already been some blog opments on another subject men- which standards producers can announcements about the content tioned in the last article: the con- define how stripping can work for Java and Modularity of the Java SE 9 release. cept of a Stripped Implementation, their particular standards. Now Finally, let’s take a look beyond Java Chief Architect Mark which is essentially a reduced JRE that Java SE 8 is out, the necessary Compact Profiles, and look into Reinhold announced the return 39
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect / LISTING 4 of modularity in a batch of Java that will deliver full modularity. The ben$ pwd
Enhancement Proposals (JEPs) that first of these JEPs is, unsurprisingly, COMMUNITY make up the first announced fea- JEP 201. The second is JEP 200, /Users/ben/projects/openjdk/jdk9/jdk/src ben$ ls tures that are intended to become which aims to describe and set out bsd java.rmi jdk.charsets part of Java SE 9. the module structure without actu- jdk.jconsole jdk.security.auth This batch includes JEP 201, titled ally implementing it. The summary demo java.scripting jdk.compiler jdk.jdi “Modular Source Code.” Despite of this JEP says, jdk.snmp the name, this JEP does not intro- “Define a modular structure for java.base java.security.acl jdk.crypto.ec duce modularity in any sense that the JDK. Make minimal assump- jdk.jdwp.agent jdk.zipfs JAVA IN ACTION is visible to a developer of Java tions about the module system java.corba java.security.jgss jdk.crypto.mscapi applications, and the OpenJDK 9 that will be used to implement jdk.jvmstat linux builds as they stand have no trace that structure.” java.desktop java.security.sasl jdk.crypto.pkcs11 of modularity in the binaries. Within those minimal assump- jdk.localedata sample Instead, JEP 201 is a first step that tions is the idea that any mod- java.instrument java.smartcardio jdk.deploy.osx has implemented some necessary ule that starts with java is one jdk.naming.dns solaris housekeeping and has rearranged that will be governed by the Java java.logging java.sql jdk.dev JAVA TECH the layout of the OpenJDK source Community Process (JCP) and by jdk.naming.rmi tree, so that it is now in modules. Java Specification Requests (JSRs). java.management java.sql.rowset jdk.hprof.agent This JEP has already been com- For developers unfamiliar with the jdk.rmic java.naming java.xml.crypto jdk.httpserver pleted and is integrated into the standardization process, what this jdk.runtime JDK 9 source repositories. Let’s look means is that the modules are java java.prefs jdk.attach jdk.jcmd at how these new modules are laid those that are intended to be por- jdk.sctp ABOUT US out in the OpenJDK 9 source direc- table across Java implementations tory (see Listing ).4 (in a future world, in which Java has Download all listings in this issue as text Inside each module, the directory been fully modularized). structure has also been rearranged, In contrast, the modules we with one interesting side effect. see that start with jdk represent toward a more modular future, be expected, with further updates The code that was historically com- internal implementations that are but we still have a long way to go from the platform team as Project mon between UNIX-like operating specific to OpenJDK. JEP 200 is still before we see a fully modularized Jigsaw progresses and the modu- systems was contained in a direc- in development, but we can see JRE. In particular, the build process larity train starts to pick up steam tory called solaris. With this reorga- the first traces of it in the deliv- needs to be updated to produce again. nization, this confusing (and rather ery of JEP 201, where the big split modular binary artifacts (and the legacy) name has been changed to between java modules and jdk end of a monolithic rt.jar), and the the more accurate . modules is obvious. class-loading subsystem needs to blog unix LEARN MORE Reinhold also announced a new become aware of modules as a pri- version of Project Jigsaw, the proj- Conclusion mary mechanism for loading code • jdeps ect aiming to deliver a modular JDK. The arrival of Compact Profiles and into a Java process. In the coming • JEP 201: Modular Source Code His vision is of four fairly large JEPs jdeps represents a great first step months, a great deal of activity is to • JEP 200: The Modular JDK 40
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect /
JDK 8u20 Improves Performance, COMMUNITY Security, and Manageability Learn how to better control managed systems that run multiple rich internet applications. JAVA IN ACTION
ollowing the Java 8 release to such administrators, the Oracle Java Mission Control. vendor, the permission level, Fearlier this year, Java SE Java Advanced Management The functionality of and the number of times the Development Kit 8, Update Console and the Microsoft Advanced Management application has been run—is 20 (JDK 8u20) continues to Windows Installer Enterprise Console 1.0 can be boiled also provided, all of which improve upon the significant JRE Installer, along with other down to two areas. It directly can be gathered from a large JAVA TECH ERIK COSTLOW AND advances made in the Java SE important improvements in tracks usage data for Java number of clients across ERIC RENAUD platform. As the latest minor the JDK 8u20 release. applications, and it enables an enterprise. release of Oracle’s administrators to act on How is this accomplished? BIO implementation of REDUCE RISK Advanced that data in a guided man- It’s done by way of the Usage Java SE, JDK 8u20 By using the Management ner. Using the Advanced Tracker, a Java feature that was architected, Console Management Console results enables the Java clients on ABOUT US in part, to provide Advanced First, let’s address in a more easily controlled the desktops within an enter- enterprise system Management the Advanced and more secure environ- prise to report RIA and JRE administrators with Management ment that provides an usage data. The usage data the ability to better Console, Console. It is avail- improved end user experi- gathered (including the type control managed administrators able in the Oracle ence, as we will see below. of virtual machine start, the systems on which Java SE Advanced A primary benefit of the date and time of the start, the users run multiple can reduce products, which Advanced Management host name and IP address, rich internet appli- security provide enterprises Console is the ability to learn the application name, and cations (RIAs), spe- concerns by and independent which RIAs (Java applets and much more) is stored in a cifically Java applets software vendors Java Web Start applications) normalized database for and Java Web Start effectively (ISVs) with sup- are being run in an enter- performance reasons, which applications. creating port and special- prise as well as which Java means that a single Usage blog In this article, ized tools such runtime environments (JREs) Tracker can handle a large we will explore whitelists and as the Advanced are used. Additional infor- number of clients. the two new tools blacklists. Management mation—such as the loca- (As an aside, the Usage ERIC RENAUD PHOTOGRAPH BY VOLTAIRE YAP most beneficial Console and tion of each application, the Tracker is off by default. It is 41
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect /
enabled by creating the proper- be in place for reporting to 3. Visualization: The Advanced Figure 2 shows a view of the
ties file
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect /
deployment rule sets, which creating whitelists and blacklists.
provides administrators with An important item to note is how COMMUNITY the ability to specify that an guided rule creation and packag- application be run with a ing support greatly simplify devel- different JRE version than the oping deployment rule sets. The version specified in the appli- Advanced Management Console cation itself. can also be used to determine Figure 2 Deployment rule sets also which rules and rule sets an appli- offer a secure way of manag- cation matches, helping system ing compatibility with older administrators understand the JAVA IN ACTION versions of Java. By using a impact of installing a particular rule deployment rule set, the lat- set prior to actually testing the rule est and most secure version set in user environments. During acts as a proxy to allow only the guided creation of deployment “known to be safe” applica- rule sets, Usage Tracker data iden- tions to run with older, com- tifies applications by certificate JAVA TECH patible JRE ver- hash and by location. sions. As a result, TRACK AND ACT In addition, a com- most applications parison tool is available use the current, The functionality to verify rules against secure JRE and of Advanced tracked data, thus older JREs are enabling easier test- Management ABOUT US Figure 3 limited to run- ing. While administra- ning “known to Console 1.0 can tors can always create sions can be used to launch them. trol over a more secure network be safe” applications. be boiled down deployment rule sets An additional advantage is that the infrastructure. Similarly, a deployment by hand using a text end user experience is enhanced, There are many uses for the rule can be deployed to two areas. editor, these new tools because the Deployment Rule Advanced Management Console, that causes the “last It directly tracks greatly reduce the time Set feature can also control which but its main advantages are that known to run” JRE to and effort required and security prompts users see. it equips administrators with a be used for a particular usage data for make the process far As illustrated in Figure 3, the tool set to match applications to application while keep- Java applications, less error-prone. Advanced Management Console’s desired JREs, to maintain a record ing all the other appli- and it enables In summary, the UI provides administrators with of the deployment rule sets that cations on up-to-date Advanced Management the ability to create deployment are deployed, and to gather data JREs. Thus, by using the administrators to Console enables system blog rules and deployment rule sets about applications that are run in Advanced Management act on that data in a administrators to easily and store them in the Advanced the enterprise. Console, administra- identify RIAs and JREs, Management Console’s database, In JDK 8u20, a new “force” tors can reduce security guided manner. and it provides tools for thereby achieving greater con- feature was added for use with concerns by effectively controlling the com- 43
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //java architect /
patibility and availability of older 64- and 32-bit systems, this new standard Windows Installer, such Conclusion
Java installations through deploy- installer provides a number of as silent installations and upgrades, While the enhancements and COMMUNITY ment rule sets in a scalable manner benefits for system administrators low-privileged installations, and optimizations in JDK 8u20 are across the enterprise, all of which who customize or manage software self-repair capabilities. Other com- numerous and impactful, it is the results in a streamlined experience in the enterprise at scale. Unlike mon features—such as rolling back new tools it provides in Oracle for users. Figure 4 shows a view of the basic installer that most users unsuccessful installations, repairing Java SE Advanced products that some rules and rule sets that have obtain from Java.com or Oracle broken installations, and installing add the luster to this release. The been deployed in the Advanced Technology Network, this installer over existing broken installations— new tools make it easier for sys- Management Console. is built around customization and are all available with the Microsoft tem administrators to identify and integration with various desk- Windows Installer Enterprise control client installations at scale. JAVA IN ACTION Microsoft Windows Installer top management products such JRE Installer. Integrated with the Administrators at organizations Enterprise JRE Installer as the Microsoft System Center installer is the Java Uninstall tool, that want either the tools or associ- The new Microsoft Windows Configuration Manager (SCCM), and which provides the option to ated commercial support should Installer Enterprise JRE Installer it provides automated, consistent remove older versions of Java from consider using Oracle Java SE integrates into various desktop installation of the JRE across all the a system. Advanced products. management tools, making it eas- desktops in an enterprise. Oracle Java Mission Control (fea- JAVA TECH ier to customize and roll out differ- System administrators who use Other Improvements tured in the July/August 2014 issue ent Java SE versions. the Microsoft Windows Installer JDK 8u20 also provides enhance- of Java Magazine) continues to be Available in the Oracle Java SE Enterprise JRE Installer can use ments that improve performance, available as a commercial feature Advanced products for Windows every capability provided by the such as a reduced memory foot- in the Oracle Java SE Advanced print, several patches geared products. The new version, Oracle to next-generation CPUs, Java Mission Control 5.4, is bundled ABOUT US and improved support for with JDK 8u20 and includes several garbage-first (G1) garbage enhancements to improve usability. collection for long-running Advanced Management Console applications. and Oracle Java Mission Control For G1 garbage collection, require an Oracle Java SE Advanced the newly added String dedu- product license for production plication capability described use, but each tool is available for in JDK Enhancement download for development and Proposal (JEP) 192 does not evaluation purposes from Oracle actually deduplicate the Technology Network. String objects; it deduplicates only their backing character blog arrays. However, the result- ing optimization is elegant, LEARN MORE removes inefficiency, and • JDK 8u20 Update Release Notes Figure 4 results in heap reduction. • Oracle Java SE Advanced 44
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded /
A Smart-Home Platform for the COMMUNITY Mass Market Eclipse SmartHome bridges the gap between tech-savvy users and average users to provide a KAI KREUZER smart-home platform for everyone. JAVA IN ACTION
BIO
here are plenty of smart- Smart-home technology is ■■ The high-end market for The mass market in Thome offerings on the often regarded as a subset of luxury homes, in which cost between these two segments market, but most are tailored the IoT—the part that deals does not matter and home- is going to be conquered from toward certain use cases with consumer products for owners have professional the ground up. Just as per- JAVA TECH and a fixed set of supported the home. Luckily, Gartner installers customize every- sonal computers were initially devices. The Java-powered mentionsconnected home thing to their needs. In assembled by nerds and were open source project openHAB as a separate category that is this segment, smart-home then adapted for the average (open Home Automation still in the innovation phase. technology is often coupled consumer, the same is likely Bus) has established itself as We can, therefore, expect with alarm systems and to happen for smart-home a Swiss army knife for real- more public awareness about private security services. technology. ABOUT US izing overarching use cases. smart homes in the future. Because installers require openHAB has attracted a Previously addressing only And this year was not short training and prefer tested large community of DIY users. tech-savvy users, it has fur- on related news with Google and reliable solutions, this The project serves as a cen- ther evolved into the new buying Nest, Apple introduc- segment is usually not tral integration point where Eclipse SmartHome project, ing HomeKit, and Samsung where innovation happens. different home automation which has a flexible platform acquiring SmartThings. It is ■■ The “do it yourself” (DIY) systems and protocols can that allows building mass- going to be an exciting future. market, in which tech- be combined into one over- market solutions. savvy people love spend- arching solution that pro- 2014 is the year of the An Emerging Market ing their time but not too vides uniform user interfaces Internet of Things (IoT). But let’s begin with what is much of their money. This across all devices and, more According to Gartner, hype currently available. Smart- group usually comes up importantly, a possibility to about the IoT is currently home technology has existed with creative and inno- define automation logic that blog Internet at a peak, which means the for a few decades already, but vative ideas and prefers bridges all gaps. All this is of Things market has huge expecta- it has never found its way into systems that can be eas- done through textual configu- tions that soon might give the mass market. There are ily changed, reconfigured, ration and scripting, which is PHOTOGRAPH BY TON HENDRIKS way to some disillusionment. actually two main segments: and adapted. flexible and powerful for the 45
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded / COMMUNITY JAVA IN ACTION JAVA TECH
Figure 1 Figure 2
tech-savvy user but daunting for covers not only com- paramount requirement is that transforms ephem-
Connectivity Persistence ABOUT US the average user. To address this munication via a certain protocol the framework offers flexible eral events into permanent infor- problem and broaden the potential or a proprietary interface among mechanisms for implementing mation. Persistence can be pro- user base, the code for the open- devices or systems, it also deals logic. This requirement can be vided through local databases or HAB framework was contributed to with making the gateway accessible reached only by using some kind cloud services, and the data can the Eclipse Foundation in early 2014 in a homogenous way for client of programming language. be used for reports or charts or as an initial seed for the Eclipse applications. Just as the framework User interfaces (UIs) are the visual for inferring automation actions. SmartHome project. expects other systems to provide component of a smart-home solu- Such persistence services must open APIs, it itself exposes its func- tion. To appeal to users, it is impor- be configurable with respect to A Home Gateway Stack tionality through a REST API. tant that UIs offer a consistent way which data should be collected (for The Eclipse SmartHome project Automation is all about rules of accessing devices and visualizing example, every changed value) and is meant to be a software frame- and the smart parts of a smart the current state of devices. Ideally, with which kind of strategy (for work tailored for home gateways. It home. In essence, this is the code there is one UI to address all needs, example, at a fixed frequency). blog provides APIs and services for four that brings the whole system to not a plethora of different apps. As All these aspects were addressed categories: connectivity, automa- life. Homes are extremely indi- a result, such a UI must be generic in a textual way in openHAB, as tion, user interfaces, and persis- vidualistic, and no two setups enough to easily adapt to new kinds can be seen in Figure 2. For Eclipse tence (see Figure 1). will ever look alike. Therefore, a of devices and use cases. SmartHome, completely new APIs 46
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded / LISTING 1 LISTING 2 LISTING 3 and services have been developed is quite complex, and it does not public class MyDiscoveryService
with the goal of enabling the cre- make sense that every device bind- COMMUNITY ation of easy-to-use setup and ing comes with its own implemen- extends AbstractDiscoveryService { configuration tools that are com- tation or bundled library, but there patible with end user needs. So is already a shared UPnP discovery private static final int SCAN_TIMEOUT = 5; // in seconds what exactly are the challenges for service in place. Developers can private static final ThingTypeUID MY_THINGTYPE = achieving this goal? hook into this service to participate new ThingTypeUID("my:thingtype"); in analyzing the received informa- Architectural Challenges tion and to derive discovery results public MyDiscoveryService() throws IllegalArgumentException { JAVA IN ACTION One major task when setting up a from it. super(Collections.singleton(MY_THINGTYPE), SCAN_TIMEOUT); system is to define all the devices This shared service builds on top } that are supposed to be part of the of the open source jUPnP library solution. The most user-friendly and simply hands discovered UPnP protected void startScan() { way is obviously autodiscovery. devices over to the participants, // do something to get hold of the thing Nonetheless, users might not want which only have to implement a // ... to use every device that is avail- simple interface. A real-life imple- DiscoveryResult result = DiscoveryResultBuilder JAVA TECH able on the network, so they should mentation for the Philips Hue sys- .create(new ThingUID("my:thingtype:1")) have a chance to approve the use of tem is shown in Listing 2, which .withLabel("My great device") each device. In Eclipse SmartHome, demonstrates how easy it is to add .withProperty("ip", "10.0.0.1") .build(); this is done through an inbox, support for a new device without thingDiscovered(result); which keeps track of discovered having to deal with the inherent } things and adds them to the sys- complexity of the UPnP protocol. } ABOUT US tem only upon manual approval. Discovering and identifying An important design goal is to devices is not enough, though. To make life for developers as simple enable the system to make use as possible, and a good way to of the devices, the devices’ func- achieve this is to offer abstract tionality must be described in a superclasses. Listing 1 is an exam- formal way. ple implementation of a discovery Eclipse SmartHome defines a service that shows what developers Java object model for this and pro- have to implement in order to pro- vides an XML schema and parser as vide a discovery mechanism for a a default mechanism for describing dedicated type of device they want things. Listing 3 shows an example to support. description for an LED bulb. Since a blog A common way to discover common ontology for all the things IP-enabled devices on the network in a smart home is an ongoing topic is through Universal Plug and Play of research, this model is based Download all listings in this issue as text (UPnP). The UPnP specification on a capabilities-based approach, 47
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded /
vides some context to applications Eclipse SmartHome comes with Building Commercial Solutions
and to rule logic. an Xtend-based scripting language. As a pure framework, Eclipse COMMUNITY In addition to devices, all kinds of However, in order for scripts to be SmartHome’s scope is limited to services (such as persistence and interpreted at runtime, a rather functional categories. Because it notifications) usually require some large number of third-party librar- is a Java software stack that uses user configuration. To cater to the ies is required, which is not ideal for Open Service Gateway initiative extensibility of solutions, generic embedded use. (OSGi) for modularization, build- configuration UIs are required. Java SE 8 comes to the rescue: ing a home gateway (such as the Describing configuration proper- It ships with the very perfor- one shown in Figure 3) requires ties as HTML5 input types already mant JavaScript engine, Nashorn. the rest of the stack to be defined JAVA IN ACTION Figure 3 covers important aspects such as a Nashorn compiles JavaScript down as well. Eclipse SmartHome offers type system, “required” flags, and to Java bytecode and, thus, can run a wide variety of options here; all which allows describing new kinds input constraints. scripts directly on the Java Virtual it requires is a Java SE 7–compliant of things without having to extend Nonetheless, a metadata facility Machine (JVM). Nashorn further- JVM and an OSGi R4.2 framework the existing model. has to provide options to also group more comes with a transparent implementation. A general problem for applica- and order properties, so that a nice mapping from Java to JavaScript Typically, a home gateway with JAVA TECH tions is to know the semantics of a layout can be achieved. Also, special code and vice versa. It is, there- an embedded ARM CPU runs a device. When bundling hardware properties, such as geo-locations fore, a perfect match for a future Linux OS with the JDK and a small- for a given use case, this is simple: or OAuth2 access tokens, require rule engine. footprint OSGi frame- The software can expect that the very special widgets, such as an Having scripting capa- NERDS FIRST work, which can be an user uses the bundled devices (for embedded map or an external web bilities is not enough for Just as personal open source framework, example, a switchable socket for flow. It is, therefore, a big challenge a mass-market solution, such as Apache Felix, or a ABOUT US controlling a lamp). to cover these requirements in a though. Instead, scripts computers commercial one, such as But for a general-purpose solu- way that addresses all relevant use need to be param- were initially the implementation from tion, the context is often unknown, cases while keeping the implemen- etrizable, so that they can assembled by ProSyst. However, remote and it cannot be statically defined tation complexity for configuration be created by develop- management of the by the device description. Only the UIs at an acceptable level. ers and then reused by nerds and were gateway—for example, users know what they have plugged consumers. Such param- then adapted applying updates, doing into a switchable socket. If the The Power of Scripts etrizable scripts can be backups, or providing device is a refrigerator, it obviously Automation rules can be highly regarded as rule tem- for the average remote access—is out of should not be included in an all-off individualistic, and very often the plates that serve a certain consumer, the scope. Various commer- scenario, while a lamp should be best settings are found only by trial use case, but which can cial offerings can be cho- included. Eclipse SmartHome sug- and error. This makes it important be individually adapted. same is likely sen for that functionality. gests a simple but powerful solu- to have short round-trip cycles— Such an infrastructure is to happen for Because the footprint of blog tion to this problem: Functionalities code compilation and deployment going to be introduced smart-home the software stack always can be tagged with tags such as should not be necessary in order to in Eclipse SmartHome matters, Java SE 8 brings “light,” “security,” and “energy” so apply a new set of rules. Scripting in conjunction with Java technology. a new and elegant way that this rough categorization pro- languages can accomplish this. SE 8 and Nashorn. of reducing it: Compact 48
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded /
mass market. QIVICON comes
with its own UIs that make use of COMMUNITY the Eclipse SmartHome APIs. This
allows QIVICON to keep its unique By and for the Java community look and feel, but to still benefit from the extensibility of the under- lying framework. A few companies are currently working on Eclipse SmartHome–based gateways, too. Find the Most Qualifi ed Java JAVA IN ACTION Conclusion Eclipse SmartHome is a modern Professionals for Your Company’s Future Figure 4 framework whose strength is a modular architecture that provides Profiles. Compact Profiles reduce APIs tailored to the expectations Introducing the Java Magazine Career the JVM library to the parts that are of developers. Abstracting device JAVA TECH essential for an embedded solution. descriptions and their semantics is Opportunities section – the ultimate All AWT, Swing, and other headful the most crucial part for allowing parts are stripped out, which cuts multipurpose solutions to be built technology recruitment resource. the size easily by more than 50 on top of the framework. Such percent. In conjunction with Oracle solutions additionally benefit from Place your advertisement and gain Java SE Embedded, this results in the existing developer community immediate access to our audience of top IT ABOUT US a very small and lightweight JVM, and from the framework’s cus- which still allows Java SE applica- tomizability. As Figure 4 shows, professionals worldwide including: corporate tions to be run on it. The goal of even smart telephone booths can and independent developers, IT managers, Eclipse SmartHome is to be com- be realized with it. Leveraging pliant with the compact2 profile. Java SE 8 features in the future architects and product managers. (The compact1 profile requires JAXB will make it even more powerful for the JAX-RS–powered REST API, and attractive. so it would not be feasible.) One of the first companies to MORE ON TOPIC: integrate Eclipse SmartHome in Internet a commercial home gateway is of Things For more information or to place your Deutsche Telekom. Its QIVICON recruitment ad or listing contact: blog platform is clearly targeted at the [email protected] mass market as a self-installable LEARN MORE solution. It has an easy setup pro- • openHAB cess, so it is a perfect fit for the • Eclipse SmartHome 49
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded /
The Device I/O API COMMUNITY A standard API for peripherals and low-level hardware control just arrived for Oracle Java SE Embedded. JAVA IN ACTION VINICIUS SENGER f you recall the history of most-popular database ven- asynchronous receiver/ between our Device I/O and Java, you might remem- dors, so this is a great success transmitter (UART), and so BIO I Pi4J. Pi4J is (and will remain) ber that in the beginning, story for the Java Community on. The number and types of much richer in functionality, each database had its own Process (JCP). single-board computers are but was really intended for access API, and if you needed However, now we have a growing fast, and each type the Raspberry Pi and not for to migrate to another data- similar problem using Java provides a different API for other platforms. We have been base implementation, it was SE in the embedded space, using its GPIO pins. discussing with Robert Savage JAVA TECH necessary to learn that data- where there is a need to Naturally, for each different (Pi4J author and frequent base’s API and refactor all access and control many dif- board, a new Java API needs contributor on this forum) the database access code. To ferent low-level devices using to be designed. A popular how to handle this overlap solve this problem, JDBC was interfaces such as general- example is the Pi4J project, and the current thoughts are launched in 1997 to specify purpose input/output (GPIO), which is a nice API for the that Device I/O may be the how vendors should imple- inter-integrated circuit bus Raspberry Pi that allows you
right place to handle the basic ABOUT US ment their drivers. Nowadays, (I2C), serial peripheral inter- to manipulate GPIO pins and I/O with Pi4J as a rich layer on JDBC is implemented by the face (SPI) bus, universal use I2C, SPI, and UART com- top. We have a similar thread ponents. But if you want to going with some of the LeJOS migrate to another board, you (Java on Lego Mindstorms) will need to rewrite all your community members.” GPIO access code. This is all very exciting for In May 2014, Oracle the embedded Java commu- Vice President of Product nity, because the Connected Management in the Java Limited Device Configuration Platform Group Henrik Ståhl (CLDC) for Java ME and also announced the Device I/O Java SE are target platforms API and also made some for embedded projects with blog Internet comments about overlap single-board computers or of Things between the Pi4J project and microcontrollers. In prac- Vinicius Senger demonstrates the Device I/O API with home automation devices. the Device I/O API: tice, if you have a Java ME or “There is some overlap Java SE project that reads an 50
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded / LISTING 1 I2C sensor using the Device I/O and collaborate; the official web- hg clone http://hg.openjdk.java.net/dio/dev
API, your code will be 100 per- site is https://wiki.openjdk.java COMMUNITY cent portable to different target .net/display/dio/Main. There is an boards such as the Raspberry Pi, amazing team supporting and writ- Download all listings in this issue as text BeagleBone Black, UDOO, and doz- ing this API. ens of other boards. This article will present Device Getting Started with the Device code by typing the command Raspberry Pi. I/O API details, code for a practical I/O API and the Raspberry Pi shown in Listing 1. Inside the dev directory, you will project, and also some examples of You can start playing with the You might need to install the find the following subdirectories: JAVA IN ACTION industry applications. Device I/O API and the Raspberry GNU Compiler Collection (GCC) or ■■ /dev/src, which contains the Java Pi today, because Oracle is writing some additional tools, but typing and C native code Device I/O API Features the implementation for Linux with the following commands should ■■ /dev/test, which contains the test The Device I/O API abstraction is hard-float support and is testing be enough to build a Device suite very complete and includes sup- the implementation with Raspberry I/O project for most Raspbian ■■ /dev/build, which contains all port for analog-to-digital con- Pi boards (based on the BCM2835 distributions: the compiled files, the linux.so verters (ADCs), digital-to-analog system on a chip [SoC]). You will library, and the .jar files JAVA TECH converters (DACs), AT command need the following items: export PI_TOOLS=/usr ■■ /dev/build/deviceio, which con- devices, counters, GPIO pins, I2C ■■ One Raspberry Pi, Model A, B, export JAVA_HOME=
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded / LISTING 2 LISTING 3 LISTING 4 LISTING 5 all the base source package javamagazine.dio;
code for the Device I/O COMMUNITY API that can be shared import jdk.dio.DeviceConfig; with other platforms, import jdk.dio.DeviceManager; while the subdirec- se import jdk.dio.gpio.GPIOPin; tory contains specific import jdk.dio.gpio.GPIOPinConfig; classes and native code for the Oracle Java SE public class LedBlink { Embedded platform. JAVA IN ACTION The main package for public static void main(String[] args) throws Exception { the Device I/O API is GPIOPin pin = null; jdk.dio, and you will pin = (GPIOPin) DeviceManager.open(18); find all the interface System.out.println("Blinking LED"); definitions insideshare/ Figure 1 for (int x = 0; x < 20; x++) { classes/jdk/dio. pin.setValue(x % 2 == 0);
Thread.sleep(1000); JAVA TECH Writing Your First } Device I/O Application pin.close(); To run your first applica- } } tion using the Device I/O API, you will need the following: Download all listings in this issue as text ABOUT US ■■ Any standard Java class with a main method ■■ java.policy, which is ■■ One resistor (220 ohms) ments shown in Listing .3 a file that contains ■■ A protoboard and male-female To make things easy, you can the permissions wire install Device I/O files in your configuration You can wire your protoboard as Java runtime environment (JRE), ■■ dio.jar, which contains Figure 2 shown in Figure 1 and Figure 2. because we have the directory the Java Device I/O As you can see, the code in /dev/build/deviceio prepared to API itself version of the well-known embed- Listing 2 is very simple. We have install dio.jar and libdio.so in your ■■ libdio.so, which contains native ded Hello World program. the DeviceManager class as a start- JRE, and it includes libdio.so in lib/ code In terms of hardware, you will ing point to establish a connection ext/arm and dio.jar in lib/ext. To ■■ dio.properties, which contains need the following: between the Java object named do this, just type the command blog board-specific configuration (for ■■ A Raspberry Pi, any model pin and the physical device, in this shown in Listing .4 Then, you the Raspberry Pi) ■■ An SD card case, GPIO pin number 18. won’t need to specify dio.jar and Let’s write the code for using a ■■ A power supply (5 volts, 1 amp) To run the application, you must the additional library path (see ■■ blinking LED with an embedded One LED run the command with the argu- Listing ).5 52
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded / LISTING 6 LISTING 7 LISTING 8 LISTING 9 LISTING 10 LISTING 11 Your jar file must PORTABLE CODE access a restricted set echo 18 > /sys/class/gpio/unexport specify a manifest of devices that you COMMUNITY .mf with the Java class In practice, if you must specify in the main method. Net- have a Java ME or gpio.policy file. Listing 8 Beans IDE does that Java SE project that shows an example pol- automatically. 2 icy file that grants all Tip: If you interrupt reads an I C sensor the permissions for your application with- using the Device I/O GPIO pin 18. out executing the To finish, let’s see JAVA IN ACTION pin.close() method, API, your code will what the Raspberry Pi the pin will remain in be 100 percent properties file looks exported state and like (see Listing ).9 This you will not be able to portable to file declares and con- use it again until you different target figures all the devices “unexport” it manu- we have on our board,
boards such as JAVA TECH ally by running the from pins to watchdog command shown in the Raspberry Pi, timers, UART devices, Listing .6 BeagleBone Black, and so on. The device We could also numbers will vary specify additional pin UDOO, and dozens according to the board configurations beyond of other boards. or SoC you are using, the pin number, for so you must check the ABOUT US example, signal direc- data sheet and manu- tion (for instance, als if you are going to Download all listings in this issue as text input only), mode (for instance, use another board or SoC. pull-up or pull-down), and so on. Let’s look at the sample code in Device I/O API Demos Listing 10. You should see your LED The Device I/O API is very com- Listing ,7 which could replace the The Device I/O source code blinking on port 18. plete and covers most low-level code inside the main method in includes a sample application that devices, from PWMs to DACs to Listing 2. uses an LED and an SPI imple- The Device I/O API: Beyond Pins ADCs. The way you establish a Because we already know how to mentation for the MCP3008 ADC. The Device I/O API supports much connection with various devices use libdio.so and dio.jar as external You will find the generated .jar file more than GPIO pins; most of the is quite similar. For each type of libraries and as part of our JRE, in the build/jar directory: popular device communication device, you need to use the specific let’s look inside the gpio.policy standards are supported. Listing 11 interface shown in Table 1. blog policy file and the Raspberry Pi /dev/build/jar/dio-samples.jar shows the code for reading a GPS properties file. sensor using UART communication The API, DIY, and the Industry The security policy allows the To run this application, you through Raspberry Pi pins 8 (RX) We are living in an exciting time for Java Virtual Machine (JVM) to can use the command shown in and 10 (TX). the embedded space as a result of 53
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //embedded /
for the future of embedded Java, INTERFACE DESCRIPTION
similar to what JDBC was for the COMMUNITY jdk.dio.adc.ADCChannel ANALOG-TO-DIGITAL CONVERTER SUPPORT Java platform. jdk.dio.atcmd.ATDevice MODEM/CELLULAR SUPPORT Conclusion jdk.dio.counter.PulseCounter PULSE COUNTER SUPPORT This is just the beginning for jdk.dio.dac.DACChannel DIGITAL-TO-ANALOG CONVERTER SUPPORT embedded Java. Much more will come from the community, com- jdk.dio.gpio.GPIOPin DIGITAL PIN SUPPORT panies, and universities. If we look JAVA IN ACTION jdk.dio.i2cbus.I2CDevice I2C BUS SUPPORT again to the Java EE platform, after JDBC many persistence frameworks jdk.dio.power.PowerManaged POWER MANAGEMENT SUPPORT were created and now we have a jdk.dio.pwm.PWMChannel PULSE-WIDTH MODULATION SUPPORT standard for persistence frame- works: Java Persistence API. The jdk.dio.spibus.SPIDevice SPI SUPPORT same might happen in the embed- jdk.dio.uart.UART UART RX AND TX COMMUNICATION SUPPORT ded space; once the standard API JAVA TECH for Device I/O control is done, we jdk.dio.watchdog.WatchdogTimer SUPPORT FOR WATCHDOG TIMER THAT FORCES RESTART might see more and more frame- Table 1 works for devices in the embedded space, making it even easier to work decreases in hardware prices, the The hardware industry now has with hardware, boards, devices, availability of open source hard- many small, midsize, and startup and embedded Java. ABOUT US ware, the Internet of Things (IoT), companies; it is not like in the past Now—what will you create with startups, a resurgence of “do it when you could count on your fin- Oracle Java SE Embedded and the yourself” (DIY) projects, and the gers the number of hardware com- Device I/O API? Maker Movement. There is defi- panies. It’s predictable that many nitely an explosion of possibilities successful products will comprise MORE ON TOPIC: that goes much further than the custom hardware, code from the Internet mobile phone market. You can cre- community, and the cloud. of Things ate a gadget to solve a particular Java EE is very reliable and popu- problem using sensors, motors, lar for server-side development, big LEARN MORE lights, and so on, and doing that data, the web, cloud, and service- is becoming popular. As Arduino’s oriented architecture (SOA), and • OpenJDK page for the Device I/O Mássimo Banzi said: there are now many standards in project blog “. . . hardware becomes like a use. Now it’s time to work with • Video: Accessing HW Devices Using piece of culture that you share and standards and implementations for Java ME 8 Device I/O API you build upon, like it was a song or embedded devices. The Device I/O • Download the code shown in the a poem.” API is definitely an important step video demo 54
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
Building Castles in the Sky COMMUNITY Use JavaFX 3D to model historical treasures and more.
n the last few years, recon- presents a JavaFX project texturized the 3-D model. characteristics of the scene JOSÉ PEREDA I struction algorithms that uses 3-D models pro- This article focuses on the can be extracted. JAVA IN ACTION for 3-D real objects have vided by Óscar Cosido Cobos visualization tool, JavaFX 3D, Photogrammetry is a BIO received significant attention, and his team at the Training which was used as the visual- technique for obtaining not only for artificial intel- and Employment Center ization framework for display- two- or three-dimensional ligence but also as tools for (CEFEM) for the City Council ing the 3-D model and navi- metric information from applications in fields such of Santander in Cantabria, gating through it. By using photographic images. as medicine, manufactur- Spain. Cosido and his team the JavaFX 3D API, you can Photogrammetry is, there- JAVA TECH ing, robotics, and archeology were able to generate all develop your own applications fore, a technology that can that require 3-D modeling of the digital documenta- for targeting and customizing provide dimensional aspects real environments. tion, including the main 3-D some of the usual capabilities when using images to recon- When geomatic engineer- objects, for the Menéndez of commercial software. struct a given scene. By using ing is applied to the recon- Pelayo Library, a historical oblique processing tech- struction of cities, historic building opened to the public Reverse Engineering niques for 3-D reconstruction, ABOUT US buildings, or museums, digi- in 1923. They did this using Techniques an object is reconstructed tal documentation reverse engineering Neither digital images nor by identifying (in at least —such as an inven- GET A VISUAL and a hybridization analog images are metric. In two images, and preferably tory of the buildings of technologies and other words, we cannot derive three) the points and lines and sites—is gener- JavaFX 3D can techniques such as measurements of the objects that form the physiognomy of ated. Then, with the be used as the geographic informa- that are displayed nor can we the object. use of visualization tion systems (GIS), derive the distances between Usually, a 3-D modeling tools, georeferenced visualization artificial vision, ter- them. We can visualize, inter- project starts with the topo- and scaled virtual framework restrial photogram- pret, and analyze, but we graphic work, in which total tours can be cre- metry, and flight cannot exploit the objects stations are employed to set ated, allowing you for displaying with microdrones. metrically. Computer stereo several main control points to “walk” through a 3-D model Then they postpro- vision is the extraction of and form a network. To cre- blog the areas while and navigating cessed the data for 3-D information from digital ate the graphic and photo- sitting in front of point cloud optimi- images. Through multiple graphic documentation of an your computer. through it. zation, orthorecti- images of a scene taken from object, an essential step is the PHOTOGRAPH BY BOB ADLER/ GETTY IMAGES This article briefly fied the images, and different viewpoints, the 3-D calibration of the camera. For 55
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
that, a template such as the one already provides a clear view of the briefly show what can be achieved. a 3-D shape is stored, including the
shown in the left side ofFigure 1 modeled object) of the inside of the Step 1. Importing the model. 3-D coordinates of all the vertices, COMMUNITY is used. This process involves cal- Menéndez Pelayo Library building. The JavaFX 3D graphics APIs pro- two-dimensional texture coor- culating the transformation that vide nodes that represent 3-D dinates, faces, and optional face relates the instrumental coordi- 3-D Modeling with JavaFX objects from a common base class, smoothing groups. nates with the photocoordinates. The JavaFX 3D graphics APIs pro- Shape3D, and four concrete sub- Material is an abstract class The right side of Figure 1 shows a vide a general-purpose 3-D graph- classes: Sphere, Box, and Cylinder, with one concrete class called shot from the camera. ics library for the JavaFX platform. which are predefned 3-D primi- PhongMaterial that controls the sur- Once everything is in place, it’s Since the launch of Java SE 8, a true tive shapes, andMeshView , a user- face material. The drawMode enum JAVA IN ACTION time to shoot photos. This requires 3-D scene is available with lights, defned shape that defnes a surface has two constants: LINE for a wire- the object to be divided into smaller cameras, materials, and basic with the specifed 3-D mesh data. frame drawing or FILL for a solid parts to shoot. In addition to the 3-D objects. Access to dedicated The Mesh abstract class and its drawing. cullFace determines which images taken around the object at graphics processing unit (GPU) TriangleMesh concrete subclass are side of the face is not rendered ground level, oblique and zenith hardware allows 3-D rendering where the geometric information of (BACK or FRONT), while NONE allows aerial images taken from flying a with great performance. drone over the object can be used. Besides the official documen- JAVA TECH Finally, once the characteristic tation, there are many good points of the images are obtained, a resources out there for learn- triangulation has to be performed. ing about JavaFX 3D, including The result will be a series of 3-D the book I coauthored (JavaFX 8: points corresponding to the sur- Introduction by Example) and the faces of the object. For this phase, new , as well as many
Pro JavaFX 8 ABOUT US a combination of Voronoi diagrams blogs and presentations from con- and Delaunay triangulation tech- ferences. In addition, there is the niques is used. 3DViewer application, which you The last step for obtaining the 3-D can fnd in the OpenJFX project, as Figure 1 model of an object is to obtain the well as other experimental mate- corresponding points in the rest of rial under the project’s Toys folder. the images. By knowing the points But the best way to learn is to of the base image, it is possible get your hands dirty hacking some to find the epipolar lines in other code. So now we’ll explore a simple images using the fundamental application intended to be a multi- matrix and a correlation between model 3-D viewer and manipula- the intensity of a point in the image tor. You can fnd all the code and blog and its surroundings. Figure 2 some simple 3-D models that were shows the white model (a model donated by Cosido and his team in the early stages, which is not in my repository. At the end of the Figure 2 fully colored or texturized yet, but article, we’ll use their real models to 56
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client / LISTING 1 LISTING 2 both sides to be rendered. Note (OBJ, Maya, 3D Studio Max, Collada, mtllib chair.mtl
that the same material is shared and FXML) can be imported into COMMUNITY among multipleShape3D nodes. a JavaFX scene by the import- v -2.0226 -0.3300 -0.3345 Complex 3-D models—such as ers available with the 3DViewer v -2.0226 0.0000 -0.3345 those shown in Figure 3, which application. ... shows, from left to right, a wire- We’ll focus on the common open vn -1.0000 0.0000 -0.0000 framed model, a solid model, and format OBJ and its MTL material vn 1.0000 0.0000 -0.0000 a solid model with texture—can’t format. Listing 1 shows an excerpt ... be generated easily with just 3-D of the chair.obj file for the model vt 1.0000 1.0000 0.0000 JAVA IN ACTION primitives, because they are made shown in Figure 3, where a chair vt 0.0000 1.0000 0.0000 of complex meshes. In order to from the library is shown in a JavaFX display these models in a JavaFX subscene after the file is imported g Chair01 scene (or SubScene), we need a and different options are selected. usemtl Material__64 way to import all the information In Listing 2, you can see how an s off and reconstruct the JavaFX model. .obj 3-D model can be imported f 1/1/1 2/2/1 3/3/1 4/4/1 Usually this is accomplished by using ObjImporter from the usemtl FrontCol JAVA TECH loading the meshes that define 3DViewer application to cre- f 5/5/2 4/6/2 3/7/2 those models. ate objects based on triangular f 5/8/2 6/9/2 7/10/2 There are no loaders for any of meshes. Note that you can also ... the common 3-D file formats in the select PolyObjImporter, in case JavaFX 3D APIs, but some of them you have polygonal meshes with ABOUT US
blog
Download all listings in this issue as text Figure 3 57
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client / LISTING 3 LISTING 4
public class Library { ... COMMUNITY private final ObservableList
public Library(){ Model3D modelBuildingOut = new Model3D("lib_Walls.obj","Library Walls"); modelBuildingOut.importObj(); JAVA IN ACTION models.add(modelBuildingOut);
Model3D modelChair1=new Model3D("chair.obj","Chair - 1"); Affine affineChair=new Affine(); affineChair.prependTranslation(2,4.13,-12); affineChair.prependScale(0.14,0.14,0.14);
modelChair1.setAffine(affineChair); JAVA TECH modelChair1.importObj(); modelChair1.setPickable(true); models.add(modelChair1); ... } } Figure 4 ABOUT US
faces consisting of more than four is scaled down and translated to sides. This is the case in Figure 4, its final location. which shows several columns of Using the prepend methods the library, which are imported causes the transformations to with PolygonMeshView after the file take place in the provided order Download all listings in this issue as text lib_Columns.obj is imported. because, from a mathematical Step 2. Manipulating the models. point of view, operations are per- When adding different models to formed on the left of the transfor- minimum Y coordinate is -4.13 m, tion. This means that new transfor- a multimodel application, some of mation matrix (this is called pre- it’s moved up 4.13 m), and then it mations are performed relative to the models might require scaling, multiplication) and referred always is scaled down with a 0.14 factor to the current object’s coordinate ori- translating, or rotating to locate to the global coordinate system. a final height of 1.20 m. gin. While this is the preferred tech- blog them in the correct position. For In Listing ,3 the chair is first trans- Note that by using append meth- nique in JavaFX, both multiplication this, an Affine class is provided lated using its actual dimensions ods instead, operations would techniques are implemented in the for every model, as shown in (because the original height of be performed on the right of the JavaFX 3D APIs, so you can use what Listing ,3 in which the chair model the chair’s model is 8.43 m and its matrix, the so-called postmultiplica- is best suited for your problem. 58
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client / LISTING 5 LISTING 6
private final EventHandler
} JAVA TECH } else if (event.getEventType() == MouseEvent.MOUSE_DRAGGED) { mousePosX = event.getSceneX(); mousePosY = event.getSceneY(); Figure 5 ... // update model location In the ContentModel class shown of the final model, as shown in ... ABOUT US in Listing 4, a subscene is created Figure 5. } else if (event.getEventType() == containing a main group, root3D, Step 3. Moving the models. MouseEvent.MOUSE_RELEASED) { with lights and a second group Several listeners are added to the cursor.set(Cursor.DEFAULT); named group3D. This one contains subscene, so it becomes respon- } the axes and a third group with sive to user input, mainly input }; as many groups as models, each provided through a mouse. The of them containing their meshes main responses consist of camera loaded. Note that Java SE 8 movements. For that, MOUSE_ Download all listings in this issue as text streams are used to create these PRESSED, MOUSE_DRAGGED, and groups based on a sequential MOUSE_RELEASED mouse events stream of the 3DModel collection, are listened to in order to trigger slowing down (CTRL key pressed) or Result() is the key for obtaining and note also that a Comparator camera rotations (left mouse but- speeding up (ALT key pressed). the selected node on the scene. blog can be used to sort the way the ton pressed), zooming (right mouse MOUSED_PRESSED events can The PickResult class, which is part meshes are added. button pressed), or panning (mouse also be used to select a model of the javafx.scene.input package, A TreeTableView is used to display wheel pressed), with some modi- from the scene and move it allows mouse, gesture, or touch the hierarchy of groups and meshes fications of that behavior, such as around. For that, event.getPick events to return information about 59
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
the user’s pick result, such as the els can be marked as pickable
intersected node, the intersected or not pickable, so they can be COMMUNITY point in the local coordinate sys- moved around the scene or pre- tem of the picked node, or the vented from being moved. distance from the camera to the ■■ While moving the camera, a intersection. Listing 5 shows how balance is required between the pick result can be used to providing detailed visualization move models around the scene. and ensuring usability, especially Note that models are moved freely when dealing with big models. without checking possible inter- For that reason, textures are JAVA IN ACTION sections with other models. unloaded while rotating, pan- In the video below, you can see a ning, or zooming the scene, as demo of the application, including shown in Listing .6 several implemented features that Missing features in the applica- are worth mentioning: tion, for example, light or camera ■■ Picking can be used to identify manipulation, can be added easily. JAVA TECH the node and select its tree item At this point, you are invited to con- in the TreeTableView. tribute creating pull requests with ■■ Selecting a mesh tree item on more-advanced features. the TreeTableView highlights the real mesh. Loading the Real Model ■■ In the settings titled pane, -mod Finally, we’ll use the developed Figure 6 ABOUT US
application to load and visualize the resulting in a 143 MB.obj file and 90 complex model of the Menéndez MB in texture images. Pelayo Library created by Óscar Cosido and HELP IS HERE Conclusion his team. New capabilities JavaFX 3D technology is Figure 6 shows the mature enough to enable outside view of the build- in Java SE 8 the development of tools ing, with 10,556 meshes (mainly lambdas for the geometric pro- and 1.5 million triangles, cessing of complex mod- which results in a 132 and streams) els obtained by reverse MB .obj file and 32 MB in help to deal engineering. It provides a blog texture images. Figure 7 with big hier- way to navigate a virtual shows the interior of the model and establishes José Pereda gives an overview of his article and demos library, with 2,841 meshes archical models. the basis for the future the JavaFX 3D tool. and 2.4 million triangles, development of tools for 60
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
COMMUNITY Learn Java 8 From the Source JAVA IN ACTION Oracle University
JAVA TECH New Java SE 8 training and certification
Available online or in the classroom Figure 7
managing 3-D objects in a thank Óscar Cosido and Taught by Oracle experts virtual world as part of a 3-D the students who attended ABOUT US information system. the “GIS and 3D Heritage 100% student satisfaction program New capabilities in Java Modeling” workshop orga- SE 8 (mainly lambdas and nized by the City Council streams) really help to deal of Santander. Also, special with big hierarchical models. thanks goes to Esteban Still, work has to be done Sainz Vidal, director of the to provide JavaFX 3D APIs CEFEM, for the support and for building more-powerful help he offered. tools for rendering, lighting, shadowing, model move- ment, and the usual features Learn More one can find in 3-D model- blog ing software. LEARN MORE Acknowledgements • OpenJFX project The author would like to • Menéndez Pelayo Library 61
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
A Bridge from Java 2D to JavaFX COMMUNITY Profit from the easy migration path provided by FXGraphics2D.
he JavaFX Canvas is an library, JFreeChart, which based on the Java 2D API, and chart on a JavaFX Canvas via DAVID GILBERT Timage node that can be uses the Java 2D API exclu- it avoids the need to rewrite FXGraphics2D. JAVA IN ACTION added to a scene to display sively for rendering. To solve already working code. BIO high-quality text and graph- this problem we created the This article provides an About the FXGraphics2D ics. It has an “immediate FXGraphics2D project, an overview of FXGraphics2D, Project mode” drawing API that open source “bridge” from including a demo and some The FXGraphics2D project is resembles the HTML5 Canvas the Java 2D API to JavaFX. It performance benchmarking. small and open source. The API, and it provides a feature provides an easy migration Figure 1 shows the JFreeChart library consists of a single JAVA TECH set that is comparable to that path for applications that are library being used to render a class (FXGraphics2D.java) provided by the Java 2D API, the standard vector graphics API in Java SE since JDK 1.2. The Canvas node provides a powerful additional capability ABOUT US for developers creating JavaFX user interfaces. As developers migrate their applications from Swing to JavaFX, though, they might encounter a problem. The JavaFX Canvas API is differ- ent than the Java 2D API and does not provide a compat- ibility layer. Consequently, existing code based on the Java 2D API can require sig- blog nificant rework. My company, Object Refinery Limited, faced this Figure 1 exact problem with our 62
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
that extends the Java 2D API’s Java Image I/O API. With appropri- mation about shapes or their
Graphics2D class and is licensed ate third-party libraries—for exam- properties (color, line style, and COMMUNITY using a very liberal BSD-style ple, Batik, iText, and JFreeSVG—it is so on) after they have been ren- license. We chose this license to also possible to export to Scalable dered. Immediate mode rendering ensure that there are no obstacles Vector Graphics (SVG), Portable requires less memory space for anyone who wants to use this Document Format (PDF), and other when rendering complex graph- Figure 2 code. The source code is hosted at formats easily. ics that have many elements. The GitHub. The download During the last JavaFX Canvas node introduces We create an instance of includes additional decade and a half, a an immediate mode rendering TeXFormula using the following KEEP YOUR CODE JAVA IN ACTION files, including some lot of code has been option for JavaFX applications that string to define the formula that we demo applications. Migrating to JavaFX written to use the Java require it. want JLaTeXMath to render: can be a lot easier 2D API—open source About the Java 2D examples include A Demonstration " x=\\f r a c{-b \\p m \\s qr t API if you don’t need to JFreeChart, JGraphX, To demonstrate FXGraphics2D, {b^2-4ac}}{2a}" The Java 2D API is the throw away a lot of and JLaTeXMath, and we will use the open source vector graphics API there are many more. JLaTeXMath library, whose stated If you are familiar with LaTeX, JAVA TECH that has been part existing code. This main purpose is “to display math- you will understand what this of the Java standard article demonstrates Retained Mode ematical formulas written in somewhat-cryptic string of char- library since JDK 1.2 that FXGraphics2D Versus Immediate LaTeX.” JLaTeXMath renders its acters specifies. If not, but you are was released in 1999. Mode output via the Java 2D API, making curious about LaTeX, here is a good Among other things, it is a robust solution In JavaFX, the graphics it a perfect candidate for use with starting point. is the graphics engine model is scene-based, FXGraphics2D. Our simple demo Next, we create an instance of that allows you to ABOUT US that powers Swing. which means objects application will produce the out- FormulaCanvas (a subclass of the The Java 2D API is a keep your tried-and- are added to a scene put shown in Figure 2. JavaFX Canvas class; see Listing )2 transparent, feature- tested Java 2D code and rendering is man- You can download JLaTeXMath that handles the creation of an complete, and fast and incorporate it into aged by the JavaFX here. For this demo, we are using FXGraphics2D instance and man- API that is available runtime. Objects can jlatex-1.0.3.jar. In Listing 1 you ages the rendering of a TeXFormula. to all Java application JavaFX applications. be updated at any time can see the code for our JavaFX For this rendering, we create a developers, on both and, because JavaFX demo application. There are sev- TeXIcon from the TeXFormula that the client side and the retains state informa- eral important things to note in was passed to the constructor. server side, and on all tion, the scene can be the code. This icon object can be used easily Java-supported platforms. automatically rendered again with- In the start() method, the first in Swing because it implements Graphics that are compliant out programmer intervention. thing we do is preload the fonts the Icon interface, but for our with the Java 2D API can be eas- JavaFX is sometimes referred that are required by JLaTeXMath. (JavaFX) purposes, a more inter- blog ily exported directly as images in to as being a retained mode API. These fonts are included in the esting item is theBox object that Portable Network Graphics (PNG), Java 2D, on the other hand, is an jlatex-1.0.3.jar file, but they are not is returned by the TeXIcon getBox() Joint Photographic Experts Group immediate mode graphics API; it available to JavaFX until we load method. Box is an abstract class in (JPEG), and other formats using the does not retain any state infor- them using Font.loadFont(). JLaTeXMath that declares the fol- 63
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client / LISTING 1 LISTING 2 LISTING 3 lowing draw() method: very important, because in JavaFX, 1/**
drawing operations on the canvas COMMUNITY 2 * A demo using FXGraphics2D and JLaTeXMath. Requires jlatex-1.0.3.jar. public abstract void draw( are not executed immediately but 3 */ Graphics2D g2, float x, are queued for later execution. 4public class FXGraphics2DDemo extends Application { float y); When the canvas surface is cleared in this way, anything that was 5 This method renders the content previously in the queue can be 6 @Override 7 public void start(Stage stage) throws Exception { of the Box—the graphical output discarded because, logically, it 8 Font.loadFont(getClass().getResourceAsStream( derived from the TeXFormula—at a can no longer affect the out- 9"/org/scilab/forge/jlatexmath/fonts/base/jlm_cmmi10.ttf"), 1); JAVA IN ACTION specific x( , y) location. Now, because put. Without the clearRect() call, this content is drawn to an arbitrary the drawing queue continues 10 Font.loadFont(getClass().getResourceAsStream( 11"/org/scilab/forge/jlatexmath/fonts/maths/jlm_cmsy10.ttf"), 1); Graphics2D instance, we have an to grow—you would want this opportunity to render the formula to happen only if you were add- 12 Font.loadFont(getClass().getResourceAsStream( 13"/org/scilab/forge/jlatexmath/fonts/latin/jlm_cmr10.ttf"), 1); to a JavaFX Canvas simply by supply- ing to the output rather than 14 ing an instance of FXGraphics2D to regenerating it.
15 TeXFormula f = new TeXFormula( JAVA TECH this draw() method. Second, the code in Listing 3 16"x=\\frac{-b \\pm \\sqrt {b^2-4ac}}{2a}"); The FormulaCanvas class draws the content of the box (our also takes care of creating formula in the demo) to the 17 FormulaCanvas canvas = new FormulaCanvas(f); 18 StackPane stackPane = new StackPane(); the FXGraphics2D instance FXGraphics2D instance (g2). and connecting it to its own Here, JLaTeXMath will generate a 19 stackPane.getChildren().add(canvas); 20 // Bind canvas size to stack pane size. GraphicsContext. This wiring sequence of Java 2D API calls that 21 canvas.widthProperty().bind(stackPane.widthProperty()); needs to be done only once, in the FXGraphics2D instance will ABOUT US the constructor. translate directly to the equivalents 22 canvas.heightProperty().bind(stackPane.heightProperty()); 23 stage.setScene(new Scene(stackPane)); Canvas drawing is triggered for the JavaFX Canvas (actually, the 24 stage.setTitle("FXGraphics2DDemo.java"); when the width or height prop- GraphicsContext for the Canvas). 25 stage.setWidth(300); erties are modified, because we This is where FXGraphics2D does 26 stage.setHeight(100); based our FormulaCanvas on the its job. If you didn’t already run the resizable canvas example posted demo, please try it now. 27 stage.show(); online by Dirk Lemmermann. For The demo requires that you have 28 } 29 this demo, the resizing capability the two jar files,jlatexmath-1.0.3.jar 30 public static void main(String[] args) { is not strictly required, because and fxgraphics2d-1.1.jar, on your the output is static. However, the classpath. First arrange the files in a 31 launch(args); technique is useful to know about. working directory as follows: 32 } The actual canvas drawing is 33 blog 34} handled by the code shown in lib/jlatexmath-1.0.3.jar Listing .3 Two things happen here. lib/fxgraphics2d-1.1.jar First, a clearRect() call is performed src/demo/FXGraphics2DDemo.java Download all listings in this issue as text for the whole of the canvas. This is src/demo/FormulaCanvas.java 64
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
Create an empty directory directly to a Swing JPanel ver-
named build alongside the lib and sus rendering to a JavaFX Canvas COMMUNITY src directories, and then com- via FXGraphics2D—and so both pile the demo using the following the translation overhead and the command: graphics engine change are com- bined in one measure. javac -sourcepath src -cp We would expect the transla- lib/jlatexmath-1.0.3.jar: tion overhead to be minimal in lib/fxgraphics2d-1.1.jar terms of CPU time—particularly as JAVA IN ACTION -d build a percentage of overall rendering src/demo/FXGraphics2DDemo.java time—and small in terms of mem- ory space. The impact on memory . . . and run the demo with usage is likely to be the greater of the two overheads, since the call- java -cp build: ing code will create Java 2D objects lib/jlatexmath-1.0.3.jar (shapes, paths, colors, strokes, JAVA TECH demo.FXGraphics2DDemo fonts, and so on) that will, in many cases, be copied to equivalent Performance JavaFX objects. For most applica- A key question that you might tions, this should not be a big issue. Figure 3 already be asking is “how does The switch from the Java 2D FXGraphics2D perform?” There rendering pipeline to the JavaFX In fact, the one benchmark that rather than for 2-D charts. ABOUT US are two aspects to consider. rendering pipeline is more inter- I found online suggests that the To ensure that anyone can run First, there is the overhead of the esting. I found surprisingly little two graphics engines have roughly the benchmarks locally, the bench- on-the-fly translation between information online regarding the equivalent performance, which is marks require only the free evalua- Java 2D API calls and the equiva- relative performance of these not surprising. tion.jar file for Orson Charts, which lent JavaFX Canvas API calls— graphics engines. You might We wrote two benchmark you can download. surely there will be some cost expect the newer JavaFX code to programs, one for JavaFX The benchmark programs create here. Second, there is the impact be faster, but bear in mind that the (TestPerformanceFX.java) and a frame, display a 3-D chart, and of using the JavaFX rendering Java 2D API has been the focus of a an equivalent program for Swing then rotate the chart for 1,000 pipeline versus the Java 2D pipe- good deal of optimization over the (TestPerformanceSwing.java). You frames. The first 500 frames are line. Could this bring some gains? years. Moreover, JavaFX is required can download the source code for considered the warm-up phase to It would take some careful to perform one or two tricks (for these programs from GitHub. The allow the just-in-time (JIT) com- benchmarking to separately mea- example, shadow effects) that benchmark programs render 3-D piler to work some magic, and the blog sure these two aspects and, for the Java 2D API is not required charts using Orson Charts, a com- second 500 frames are timed. now, I have not done that. The to perform. This can restrict the mercial library that is similar in Figure 3 shows a screenshot from benchmark used here compares available options for optimization style to JFreeChart (it has the same the JavaFX version (itself a nice the performance of rendering in certain cases. author: me) but is for 3-D charts example of what can be done 65
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 //rich client /
RUN JAVAFX WITH FXGRAPHICS2D SWING WITH JAVA 2D COMMUNITY 1 18,491 MILLISECONDS 17,623 MILLISECONDS 2 18,636 MILLISECONDS 17,342 MILLISECONDS 3 18,736 MILLISECONDS 17,429 MILLISECONDS AVERAGE 18,621 MILLISECONDS 17,465 MILLISECONDS Table 1 JAVA IN ACTION
with FXGraphics2D). gin. Unless your application has I ran this benchmark on a recent very strict performance require- (mid-2014) Apple MacBook Pro ments, this margin is not likely to with a high-density display on JRE be an issue. You should, of course, 1.8.0_11. run your own performance tests Table 1 shows the results. Note with a workload that is repre- JAVA TECH that you must run the JavaFX sentative of your application and benchmark with the following Java target platforms. Virtual Machine (JVM) option: Conclusion -Djavafx.animation.fullspeed= Migrating to JavaFX can be a true lot easier if you don’t need to ABOUT US throw away a lot of existing code. Without that option, you’ll get This article demonstrates that some impressive but misleading FXGraphics2D is a robust solution results, because the JavaFX ren- that allows you to keep your tried- dering engine will populate the and-tested Java 2D code and incor- rendering queue more quickly than porate it into JavaFX applications. the capped frame rate, and some The FXGraphics2D code is free to frames will be dropped, thanks to download, and the license is busi- the clearRect() call described previ- ness friendly. There are no obstacles ously. For nonbenchmark use, this to using this solution for your own might be what you want. JavaFX applications. As you can see in Table 1, the blog FXGraphics2D rendering is—for this particular configuration, at LEARN MORE least—slower than the same code • FXGraphics2D project in Java 2D, but not by a large mar- • JFreeChart 66
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014 // fix this / COMMUNITY In the September/October 2014 issue, Assuming that the REST service is accessible on http://localhost:8080/ Cyril Lapinte gave us code that was not making TestREST/demo, what do you think will happen when an HTTP POST request is effective use of streams. sent to the service with a text (e.g. Duke) as the HTTP message body payload?
The correct answer is #3: Use the noneMatch() public abstract class ParentResource { method instead of counting the number of filtered @POST
@Consumes(MediaType.TEXT_PLAIN) IN ACTION JAVA results from the inner stream. This will terminate the inner @Produces(MediaType.TEXT_PLAIN) stream as soon as a match is found, meaning that the number is public abstract String greet(String name); not prime. This will reduce the amount of work done in the inner } stream pipeline considerably. @Path("/demo") public class ChildResource extends ParentResource { This issues challenge comes from Abhishek Gupta, a senior identity @Override and access engineer, who gives us a JAX-RS problem. @Consumes({MediaType.TEXT_PLAIN, MediaType.TEXT_XML}) TECH JAVA public String greet(String name) { Hint: The ChildResource class return "Hello " + name + " !"; overrides @Consumes } on the greet method. 1 THE PROBLEM } The JAX-RS API (JSR 311) allows us to create resource implementations by inheriting from parent classes decorated WHAT S THE FIX? 3 ABOUT US with JAX-RS metadata annotations. This lets us enjoy all 1) The invocation results in an HTTP 500 error the benefits of inheritance and isolate the usage of JAX-RS and is fixed by putting the @Path("/demo") annotation on the annotations within a single parent class. ParentResource instead of the ChildResource class. 2) The client gets back "Hello Duke!" as the message along with an HTTP 200 2 THE CODE response code. The ParentResource class is a simple POJO decorated with JAX-RS annotations. Because it is abstract, it has to be 3) The invocation results in an HTTP 404 error and is fixed by including extended by a subclass in order to be utilized. ChildResource is the @POST annotation on the overridden greet method of the the subclass that inherits from the ParentResource and provides ChildResource class. an implementation for its one and only abstract method: greet. 4) The application fails to deploy. blog GOT THE ANSWER?
ART BY I-HUA CHEN Look for the answer in the next issue. Or submit your own code challenge! 67
ORACLE.COM/JAVAMAGAZINE //////////////////////////////// NOVEMBER/DECEMBER 2014