45,59 €
Build a variety of real-world applications by taking advantage of the newest features of Java 9
This book is for Java developers who are already familiar with the language. Familiarity with more advanced topics, such as network programming and threads, would be helpful, but is not assumed.
Java is a powerful language that has applications in a wide variety of fields. From playing games on your computer to performing banking transactions, Java is at the heart of everything.
The book starts by unveiling the new features of Java 9 and quickly walks you through the building blocks that form the basis of writing applications. There are 10 comprehensive projects in the book that will showcase the various features of Java 9. You will learn to build an email filter that separates spam messages from all your inboxes, a social media aggregator app that will help you efficiently track various feeds, and a microservice for a client/server note application, to name a few. The book covers various libraries and frameworks in these projects, and also introduces a few more frameworks that complement and extend the Java SDK.
Through the course of building applications, this book will not only help you get to grips with the various features of Java 9, but will also teach you how to design and prototype professional-grade applications with performance and security considerations.
This is a learn-as-you-build practical guide to building full-fledged applications using Java 9. With a project-based approach, we'll improve your Java skills. You will experience a variety of solutions to problems with Java.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 554
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: July 2017
Production reference: 1250717
ISBN 978-1-78646-019-6
www.packtpub.com
AuthorJason Lee
Copy Editor
Zainab Bootwala
Reviewer
Dionisios Petrakopoulos
Project Coordinator
Prajakta Naik
Commissioning Editor
Kunal Parikh
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Rekha Nair
ContentDevelopmentEditor
Lawrence Veigas
Graphics
Abhinash Sahu
Technical Editor
Abhishek Sharma
Production Coordinator
Nilesh Mohite
Jason Lee has been writing software professionally for over 20 years, but his love for computers started over a decade earlier, in the fourth grade, when his dad brought home a Commodore 64. He has been working with Java for almost his entire career, with the last 12+ years focused primarily on Enterprise Java. He has written in-house web applications and libraries, and also worked on large, more public projects, such as the JavaServer Faces reference implementation Mojarra, GlassFish, and WebLogic Server.
Jason is currently the President of the Oklahoma City Java Users Group, and is an occasional speaker at conferences. Ever the technology enthusiast, his current interests include cloud computing, mobile development, and emerging JVM languages.
Apart from work, Jason enjoys spending time with his wife, Angela, and his two sons, Andrew and Noah. He is active in the music ministry of his local church, and enjoys reading, running, martial arts, and playing his bass guitar.
Dionisios Petrakopoulos has worked in several companies using different technologies and programming languages, such as C, C++, Java SE, Java EE, and Scala, as a senior software engineer for the past 15 years. His main interest is the Java ecosystem and the various facets of it. His other area of interest is information security, especially cryptography. He holds a BSc degree in computer science and an MSc degree in information security, both from Royal Holloway, University of London. He is also the technical reviewer of the book Learning Modular Java Programming by Packt.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/178646019X. If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Introduction
New features in Java 8
Lambdas
Streams
The new java.time package
Default methods
New features in Java 9
Java Platform Module System/Project Jigsaw
Process handling API
Concurrency changes
REPL
Projects
Process Viewer/Manager
Duplicate File Finder
Date Calculator
Social Media Aggregator
Email filter
JavaFX photo management
A client/server note application
Serverless Java
Android desktop synchronization client
Getting started
Summary
Managing Processes in Java
Creating a project
Bootstrapping the application
Defining the user interface
Initializing the user interface
Adding menus
Updating the process list
Summary
Duplicate File Finder
Getting started
Building the library
Concurrent Java with a Future interface
Modern database access with JPA
Building the command-line interface
Building the graphical user interface
Summary
Date Calculator
Getting started
Building the library
A timely interlude
Duration
Period
Clock
Instant
LocalDate
LocalTime
LocalDateTime
ZonedDateTime
Back to our code
A brief interlude on testing
Building the command-line interface
Summary
Sunago - A Social Media Aggregator
Getting started
Setting up the user interface
Setting up the controller
Writing the model class
Finishing up the controller
Adding an image for the item
Building the preferences user interface
Saving user preferences
Plugins and extensions with the Service Provider Interface
Resource handling with try-with-resources
Adding a network - Twitter
Registering as a Twitter developer
Adding Twitter preferences to Sunago
OAuth and logging on to Twitter
Adding a model for Twitter
Implementing a Twitter client
A brief look at internationalization and localization
Making our JAR file fat
Adding a refresh button
Adding another network - Instagram
Registering as an Instagram developer
Implementing the Instagram client
Loading our plugins in Sunago
Summary
Sunago - An Android Port
Getting started
Building the user interface
Android data access
Android services
Android tabs and fragments
Summary
Email and Spam Management with MailFilter
Getting started
A brief look at the history of email protocols
JavaMail, the Standard Java API for Email
Building the CLI
Building the GUI
Building the service
Summary
Photo Management with PhotoBeans
Getting started
Bootstrapping the project
Branding your application
NetBeans modules
TopComponent - the class for tabs and windows
Nodes, a NetBeans presentation object
Lookup, a NetBeans fundamental
Writing our own nodes
Performing Actions
Services - exposing decoupled functionality
PhotoViewerTopComponent
Integrating JavaFX with the NetBeans RCP
NetBeans preferences and the Options panel
Adding a primary panel
Adding a secondary panel
Loading and saving preferences
Reacting to changes in preferences
Summary
Taking Notes with Monumentum
Getting started
Microservice frameworks on the JVM
Creating the application
Creating REST Services
Adding MongoDB
Dependency injection with CDI
Finish the notes resource
Adding authentication
Building the user interface
Summary
Serverless Java
Getting started
Planning the application
Building your first function
DynamoDB
Simple Email Service
Simple Notification Service
Deploying the function
Creating a role
Creating a topic
Deploying the function
Testing the function
Configuring your AWS credentials
Summary
DeskDroid - A Desktop Client for Your Android Phone
Getting started
Creating the Android project
Requesting permissions
Creating the service
Server-sent events
Controlling the service state
Adding endpoints to the server
Getting conversations
Sending an SMS message
Creating the desktop application
Defining the user interface
Defining user interface behavior
Sending messages
Getting updates
Security
Securing the endpoints
Handling authorization requests
Authorizing the client
Summary
What is Next?
Looking back
Looking forward
Project Valhalla
Value types
Generic specialization
Reified generics
Project Panama
Project Amber
Local-Variable Type Inference
Enhanced enums
Lambda leftovers
Looking around
Ceylon
Kotlin
Summary
The world has been waiting for Java 9 for a long time. More specifically, we've been waiting for the Java Platform Module System, and Java 9 is finally going to deliver it. If all goes as planned, we'll finally have true isolation, giving us, potentially, smaller JDKs and more stable applications. That's not all that Java 9 is offering of course; there is a plethora of great changes in the release, but that's certainly the most exciting. That said, this book is not a book about the module system. There are plenty of excellent resources that can give you a deep dive into the Java Platform Module System and its many implications. This book, though, is a much more practical look at Java 9. Rather than discussing the minutiae of the release, as satisfying as that can be, what we'll do over the next few hundred pages is look at different ways all of the great changes in recent JDK releases--especially Java 9--can be applied in practical ways.
When we're done, you'll have ten different projects that cover a myriad of problem areas, from which you can draw usable examples as you work to solve your own unique challenges.
Chapter 1, Introduction, gives a quick overview of the new features in Java 9, and also covers some of the major features of Java 7 and 8 as well, setting the stage for what we'll be using in later chapters.
Chapter 2, Managing Process in Java, builds a simple process management application (akin to Unix's top command), as we explore the new OS process management API changes in Java 9.
Chapter 3, Duplicate File Finder, demonstrates the use of the New File I/O APIs in an application, both command line and GUI, that will search for and identify duplicate files. Technologies such as file hashing, streams, and JavaFX are heavily used.
Chapter 4, Date Calculator, shows a library and command-line tool to perform date calculations. We will see Java 8's Date/Time API exercised heavily.
Chapter 5, Sunago - A Social Media Aggregator, shows how one can integrate with third-party systems to build an aggregator. We'll work with REST APIs, JavaFX, and pluggable application architectures.
Chapter 6, Sunago - An Android Port, sees us return to our application from Chapter 5, Sunago - A Social Media Aggregator.
Chapter 7, Email and Spam Management with MailFilter, builds a mail filtering application, explaining how the various email protocols work, then demonstrates how to interact with emails using the standard Java email API--JavaMail.
Chapter 8, Photo Management with PhotoBeans, takes us in a completely different direction when we build a photo management application using the NetBeans Rich Client Platform.
Chapter 9, Taking Notes with Monumentum, holds yet another new direction. In this chapter, we build an application--and microservice--that offers web-based note-taking similar to several popular commercial offerings.
Chapter 10, Serverless Java, moves us into the cloud as we build a Function as a Service system in Java to send email and SMS-based notifications.
Chapter 11, DeskDroid - A Desktop Client for Your Android Phone, demonstrates a simple approach for a desktop client to interact with an Android device as we build an application to view and send text messages from our desktop.
Chapter 12, What's Next?, discusses what the future might hold for Java, and also touches upon two recent challengers to Java's preeminence on the JVM--Ceylon and Kotlin.
You need the Java Development Kit (JDK) 9, NetBeans 8.2 or newer, and Maven 3.0 or newer. Some chapters will require additional software, including Scene Builder from Gluon and Android Studio.
This book is for beginner to intermediate developers who are interested in seeing new and varied APIs and programming techniques applied in practical examples. Deep understanding of Java is not required, but a basic familiarity with the language and its ecosystem, build tools, and so on is assumed.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The Java architects have introduced a new file, module-info.java, similar to the existing package-info.java file, found at the root of the module, for example at src/main/java/module-info.java."
A block of code is set as follows:
module com.steeplesoft.foo.intro { requires com.steeplesoft.bar; exports com.steeplesoft.foo.intro.model; exports com.steeplesoft.foo.intro.api; }
Any command-line input or output is written as follows:
$ mvn -Puber install
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In the New Project window, we select Maven then NetBeans Application."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Java-9-Programming-Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/Java9ProgrammingBlueprints_ColorImages.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In the process of erecting a new building, a set of blueprints helps all related parties communicate--the architect, electricians, carpenters, plumbers, and so on. It details things such as shapes, sizes, and materials. Without them, each of the subcontractors would be left guessing as to what to do, where to do it, and how. Without these blueprints, modern architecture would be almost impossible.
What is in your hands--or on the screen in front of you--is a set of blueprints of a different sort. Rather than detailing exactly how to build your specific software system, as each project and environment has unique constraints and requirements, these blueprints offer examples of how to build a variety of Java-based systems, providing examples of how to use specific features in the Java Development Kit, or JDK, with a special focus on the new features of Java 9 that you can then apply to your specific problem.
Since it would be impossible to build an application using only the new Java 9 features, we will also be using and highlighting many of the newest features in the JDK. Before we get too far into what that entails, then, let's take a brief moment to discuss some of these great new features from recent major JDK releases. Hopefully, most Java shops are already on Java 7, so we'll focus on version 8 and, of course, version 9.
In this chapter, we will cover the following topics:
New features in Java 8
New features in Java 9
Projects
Java 8, released on March 8, 2014, brought arguably two of the most significant features since Java 5, released in 2004--lambdas and streams. With functional programming gaining popularity in the JVM world, especially with the help of languages such as Scala, Java adherents had been clamoring for more functional-style language features for several years. Originally slated for release in Java 7, the feature was dropped from that release, finally seeing a stable release with Java 8.
While it can be hoped that everyone is familiar with Java's lambda support, experience has shown that many shops, for a variety of reasons, are slow to adopt new language versions and features, so a quick introduction might be helpful.
While lambdas and streams are extremely important game-changing updates, with Java 8, we were given another long-awaited change that was, at least in some circles, just as exciting: a new date/time API. Anyone who has worked with dates and times in Java knows the pain of java.util.Calendar and company. Clearly, you can get your work done, but it's not always pretty. Many developers found the API too painful to use, so they integrated the extremely popular Joda Time library into their projects. The Java architects agreed, and engaged Joda Time's author, Stephen Colebourne, to lead JSR 310, which brought a version of Joda Time (fixing various design flaws) to the platform. We'll take a detailed look at how to use some of these new APIs in our date/time calculator later in the book.
Before turning our attention to Java 9, let's take a look at one more significant language feature: default methods. Since the beginning of Java, an interface was used to define how a class looks, implying a certain type of behavior, but was unable to implement that behavior. This made polymorphism much simpler in a lot of cases, as any number of classes could implement a given interface, and the consuming code treats them as that interface, rather than whatever concrete class they actually are.
One of the problems that have confronted API developers over the years, though, was how to evolve an API and its interfaces without breaking existing code. For example, take the ActionSource interface from the JavaServer Faces 1.1 specification. When the JSF 1.2 expert group was working on the next revision of the specification, they identified the need to add a new property to the interface, which would result in two new methods--the getters and setters. They could not simply add the methods to the interface, as that would break every implementation of the specification, requiring the maintainers of the implementation to update their classes. Obviously, this sort of breakage is unacceptable, so JSF 1.2 introduced ActionSource2, which extends ActionSource and adds the new methods. While this approach is considered ugly by many, the 1.2 expert group had a few choices, and none of them were very good.
With Java 8, though, interfaces can now specify a default method on the interface definition, which the compiler will use for the method implementation if the extending class does not provide one. Let's take the following piece of code as an example:
public interface Speaker { void saySomething(String message); } public class SpeakerImpl implements Speaker { public void saySomething(String message) { System.out.println(message); } }
We've developed our API and made it available to the public, and it's proved to be really popular. Over time, though, we've identified an improvement we'd like to make: we'd like to add some convenience methods, such as sayHello() and sayGoodbye(), to save our users a little time. However, as discussed earlier, if we just add these new methods to the interface, we'll break our users' code as soon as they update to the new version of the library. Default methods allow us to extend the interface and avoid the breakage by defining an implementation:
public interface Speaker { void saySomething(String message); default public void sayHello() { System.out.println("Hello"); } default public void sayGoodbye() { System.out.println("Good bye"); } }
Now, when users update their library JARs, they immediately gain these new methods and their behavior, without making any changes. Of course, to use these methods, the users will need to modify their code, but they need not do so until--and if--they want to.
As with any new version of the JDK, this release was packed with a lot of great new features. Of course, what is most appealing will vary based on your needs, but we'll focus specifically on a handful of these new features that are most relevant to the projects we'll build together. First up is the most significant, the Java Module System.
Despite being a solid, feature-packed release, Java 8 was considered by a fair number to be a bit disappointing. It lacked the much anticipated Java Platform Module System (JPMS), also known more colloquially, though not quite accurately, as Project Jigsaw. The Java Platform Module System was originally slated to ship with Java 7 in 2011, but it was deferred to Java 8 due to some lingering technical concerns. Project Jigsaw was started not only to finish the module system, but also to modularize the JDK itself, which would help Java SE scale down to smaller devices, such as mobile phones and embedded systems. Jigsaw was scheduled to ship with Java 8, which was released in 2014, but it was deferred yet again, as the Java architects felt they still needed more time to implement the system correctly. At long last, though, Java 9 will finally deliver this long-promised project.
That said, what exactly is it? One problem that has long haunted API developers, including the JDK architects, is the inability to hide implementation details of public APIs. A good example from the JDK of private classes that developers should not be using directly is the com.sun.*/sun.* packages and classes. A perfect example of this--of private APIs finding widespread public use--is the sun.misc.Unsafe class. Other than a strongly worded warning in Javadoc about not using these internal classes, there's little that could be done to prevent their use. Until now.
With the JPMS, developers will be able to make implementation classes public so that they may be easily used inside their projects, but not expose them outside the module, meaning they are not exposed to consumers of the API or library. To do this, the Java architects have introduced a new file, module-info.java, similar to the existing package-info.java file, found at the root of the module, for example, at src/main/java/module-info.java. It is compiled to module-info.class, and is available at runtime via reflection and the new java.lang.Module class.
So what does this file do, and what does it look like? Java developers can use this file to name the module, list its dependencies, and express to the system, both compile and runtime, which packages are exported to the world. For example, suppose, in our preceding stream example, we have three packages: model, api, and impl. We want to expose the models and the API classes, but not any of the implementation classes. Our module-info.java file may look something like this:
module com.packt.j9blueprints.intro { requires com.foo; exports com.packt.j9blueprints.intro.model; exports com.packt.j9blueprints.intro.api; }
This definition exposes the two packages we want to export, and also declares a dependency on the com.foo module. If this module is not available at compile-time, the project will not build, and if it is not available at runtime, the system will throw an exception and exit. Note that the requires statement does not specify a version. This is intentional, as it was decided not to tackle the version-selection issue as part of the module system, leaving that to more appropriate systems, such as build tools and containers.
Much more could be said about the module system, of course, but an exhaustive discussion of all of its features and limitations is beyond the scope of this book. We will be implementing our applications as modules, though, so we'll see the system used--and perhaps explained in a bit more detail--throughout the book.
In prior versions of Java, developers interacting with native operating system processes had to use a fairly limited API, with some operations requiring resorting to native code. As part of Java Enhancement Proposal (JEP) 102, the Java process API was extended with the following features (quoting from the JEP text):
The ability to get the pid (or equivalent) of the current Java virtual machine and the pid of processes created with the existing API.
The ability to enumerate processes on the system. Information on each process may include its pid, name, state, and perhaps resource usage.
The ability to deal with process trees; in particular, some means to destroy a process tree.
The ability to deal with hundreds of subprocesses, perhaps multiplexing the output or error streams to avoid creating a thread per subprocess.
We will explore these API changes in our first project, the Process Viewer/Manager (see the following sections for details).
As was done in Java 7, the Java architects revisited the concurrency libraries, making some much needed changes, this time in order to support the reactive-streams specification. These changes include a new class, java.util.concurrent.Flow, with several nested interfaces: Flow.Processor, Flow.Publisher, Flow.Subscriber, and Flow.Subscription.
With that brief and high-level overview of what new features are available to use, what do these blueprints we'll cover look like? We'll build ten different applications, varying in complexity and kind, and covering a wide range of concerns. With each project, we'll pay special attention to the new features we're highlighting, but we'll also see some older, tried and true language features and libraries used extensively, with any interesting or novel usages flagged. Here, then, is our project lineup.
We will explore some of the improvements to the process handling APIs as we implement a Java version of the age old Unix tool--top. Combining this API with JavaFX, we'll build a graphical tool that allows the user to view and manage processes running on the system.
This project will cover the following:
Java 9 Process API enhancements
JavaFX
As a system ages, the chances of clutter in the filesystem, especially duplicated files, increases exponentially, it seems. Leveraging some of the new File I/O libraries, we'll build a tool to scan a set of user-specified directories to identify duplicates. Pulling JavaFX back out of the toolbox, we'll add a graphical user interface that will provide a more user-friendly means to interactively process the duplicates.
This project will cover the following:
Java File I/O
Hashing libraries
JavaFX
With the release of Java 8, Oracle integrated a new library based on a redesign of Joda Time, more or less, into the JDK. Officially known as JSR 310, this new library fixed a longstanding complaint with the JDK--the official date libraries were inadequate and hard to use. In this project, we'll build a simple command-line date calculator that will take a date and, for example, add an arbitrary amount of time to it. Consider the following piece of code for example:
$ datecalc "2016-07-04 + 2 weeks" 2016-07-18 $ datecalc "2016-07-04 + 35 days" 2016-08-08 $ datecalc "12:00CST to PST" 10:00PST
This project will cover the following:
Java 8 Date/Time APIs
Regular expressions
Java command-line libraries
One of the problems with having accounts on so many social media networks is keeping tabs on what's happening on each of them. With accounts on Twitter, Facebook, Google+, Instagram, and so on, active users can spend a significant amount of time jumping from site to site, or app to app, reading the latest updates. In this chapter, we'll build a simple aggregator app that will pull the latest updates from each of the user's social media accounts and display them in one place. The features will include the following:
Multiple accounts for a variety of social media networks:
Read-only, rich listings of social media posts
Links to the appropriate site or app for a quick and easy follow-up
Desktop and mobile versions
This project will cover the following:
REST/HTTP clients
JSON processing
JavaFX and Android development
Given the size and scope of this effort, we'll actually do this in two chapters: JavaFX in the first, and Android in the second.
Managing email can be tricky, especially if you have more than one account. If you access your mail from more than one location (that is, from more than one desktop or mobile app), managing your email rules can be trickier still. If your mail system doesn't support rules stored on the server, you're left deciding where to put the rules so that they'll run most often. With this project, we'll develop an application that will allow us to author a variety of rules and then run them via an optional background process to keep your mail properly curated at all times.
A sample rules file may look something like this:
[ { "serverName": "mail.server.com", "serverPort": "993", "useSsl": true, "userName": "[email protected]", "password": "password", "rules": [ {"type": "move", "sourceFolder": "Inbox", "destFolder": "Folder1", "matchingText": "[email protected]"}, {"type": "delete", "sourceFolder": "Ads", "olderThan": 180} ] } ]
This project will cover the following:
JavaMail
JavaFX
JSON Processing
Operating System integration
File I/O
The Java Development Kit has a very robust assortment of image handling APIs. In Java 9, these were augmented with improved support for the TIFF specification. In this chapter, we'll exercise this API in creating an image/photo management application. We'll add support for importing images from user-specified locations into the configured official directory. We'll also revisit the duplicate file finder and reuse some of the code developed as a part of the project to help us identify duplicate images.
This project will cover the following:
The new
javax.imageio
package
JavaFX
NetBeans Rich Client Platform
Java file I/O
Have you ever used a cloud-based note-taking application? Have you wondered what it would take to make your own? In this chapter, we'll create such an application, with complete front and backends. On the server side, we'll store our data in the ever popular document database, MongoDB, and we'll expose the appropriate parts of the business logic for the application via REST interfaces. On the client side, we'll develop a very basic user interface in JavaScript that will let us experiment with, and demonstrate how to use, JavaScript in our Java project.
This project will cover the following:
Document databases (MongoDB)
JAX-RS and RESTful interfaces
JavaFX
JavaScript and Vue 2
Serverless, also known as function as a service (FaaS), is one of the hottest trends these days. It is an application/deployment model where a small function is deployed to a service that manages almost every aspect of the function--startup, shutdown, memory, and so on, freeing the developer from worrying about such details. In this chapter, we'll write a simple serverless Java application to see how it might be done, and how you might use this new technique for your own applications.
This project will cover the following:
Creating an Amazon Web Services account
Configuring AWS Lambda, Simple Notification Service, Simple Email Service, and DynamoDB
Writing and deploying a Java function
With this project, we'll change gears a little bit and focus specifically on a different part of the Java ecosystem: Android. To do this, we'll focus on a problem that still plagues some Android users--the synchronization of an Android device and a desktop (or laptop) system. While various cloud providers are pushing us to store more and more in the cloud and streaming that to devices, some people still prefer to store, for example, photos and music directly on the device for a variety of reasons, ranging from cost for cloud resources to unreliable wireless connectivity and privacy concerns.
In this chapter, we'll build a system that will allow users to synchronize music and photos between their devices and their desktop or laptop. We'll build an Android application that provides the user interface to configure and monitor synchronization from the mobile device side as well as the Android Service that will perform the synchronization in the background, if desired. We will also build the related components on the desktop--a graphical application to configure and monitor the process from the desktop as well as a background process to handle the synchronization from the desktop side.
This project will cover the following:
Android
User interfaces
Services
JavaFX
REST
We have taken a quick look at some of the new language features we will be using. We have also seen a quick overview of the projects we will be building. One final question remains: what tools will we be using to do our work?
The Java ecosystem suffers from an embarrassment of riches when it comes to development tools, so we have much to choose from. The most fundamental choice facing us is the build tool. For our work here, we will be using Maven. While there is a strong and vocal community that would advocate Gradle, Maven seems to be the most common build tool at the moment, and seems to have more robust, mature, and native support from the major IDEs. If you do not have Maven already installed, you can visit http://maven.apache.org and download the distribution for your operating system, or use whatever package management system is supported by your OS.
For the IDE, all screenshots, directions, and so forth will be using NetBeans--the free and open source IDE from Oracle. There are, of course, proponents of both IntelliJ IDEA and Eclipse, and they're both fine choices, but NetBeans offers a complete and robust development out-of-the-box, and it's fast, stable, and free. To download NetBeans, visit http://netbeans.org and download the appropriate installer for your operating system. Since we are using Maven, which IDEA and Eclipse both support, you should be able to open the projects presented here in the IDE of your choice. Where steps are shown in the GUI, though, you will need to adjust for the IDE you've chosen.
At the time of writing, the latest version of NetBeans is 8.2, and the best approach for using it to do Java 9 development is to run the IDE on Java 8, and to add Java 9 as an SDK. There is a development version of NetBeans that runs on Java 9, but, as it is a development version, it can be unstable from time to time. A stable NetBeans 9 should ship at roughly the same time as Java 9 itself. In the meantime, we'll push forward with 8.2:
To add Java 9 support, we will need to add a new Java platform, and we will do that by clicking on
Tools
|
Platforms
.
This will bring up the
Java Platform Manager
screen:
Click on
Add Platform...
on the lower left side of your screen.
We want to add a
Java Standard Edition
platform, so we will accept the default and click on
Next
.
On the
Add Java Platform
screen, we will navigate to where we've installed Java 9, select the JDK directory, and click on
Next
.
We need to give the new Java Platform a name (NetBeans defaults to a very reasonable JDK 9) so we will click on
Finish
and can now see our newly added Java 9 option.
With the project SDK set, we're ready to take these new Java 9 features for a spin, which we'll start doing in Chapter 2, Managing Processes in Java.
In this chapter, we've taken a quick look at some of the great new features in Java 8, including lambdas, streams, the new date/time package, and default methods. From Java 9, we took a quick look at the Java Platform Module System and Project Jigsaw, the process handling APIs, the new concurrency changes, and the new Java REPL. For each, we've discussed the what and why, and looked at some examples of how these might affect the systems we write. We've also taken a look at the types of project we'll be building throughout the book and the tools we'll be using.
Before we move on, I'd like to restate an earlier point--every software project is different, so it is not possible to write this book in such a way that you can simply copy and paste large swathes of code into your project. Similarly, every developer writes code differently; the way I structure my code may be vastly different from yours. It is important, then, that you keep that in mind when reading this book and not get hung up on the details. The purpose here is not to show you the one right way to use these APIs, but to give you an example that you can look at to get a better sense of how they might be used. Learn what you can from each example, modify things as you see fit, and go build something amazing.
With all of that said, let's turn our attention to our first project, the Process Manager, and the new process handling APIs.
Typically speaking, it is much better if a build can be reproduced without requiring the use of a specific IDE or some other proprietary tool. Fortunately, NetBeans offers the ability to create a Maven-based JavaFX project. Click on File | New Project and select Maven, then JavaFX Application:
Next, perform the following steps:
Click on
Next
.
Enter
Project Name
as
ProcessManager
.
Enter
Group ID
as
com.steeplesoft
.
Enter
Package
as
com.steeplesoft.processmanager
.
Select
Project Location
.
Click on
Finish
.
Consider the following screenshot as an example:
Once the new project has been created, we need to update the Maven pom to use Java 9:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> <configuration> <source>9</source> <target>9</target> </configuration> </plugin> </plugins> </build>
Now, with both NetBeans and Maven configured to use Java 9, we're ready to start coding.
When building the user interface for a JavaFX application, you can do it in one of two ways: code or markup. To keep our code smaller and more readable, we'll build the user interface using FXML--the XML-based language created specifically for JavaFX to express user interfaces. This presents us with another binary choice--do we write the XML by hand, or do we use a graphical tool? Again, the choice is a simple one--we'll use a tool, Scene Builder, which is a WYSIWYG tool originally developed by Oracle and now maintained and supported by Gluon. We will, however, also be looking at the XML source so that we can understand what's being done, so if you don't like using a GUI tool, you won't be left out.
Installing and using Scene Builder is, as you would expect, pretty straightforward. It can be downloaded from http://gluonhq.com/labs/scene-builder/. Once installed, you need to tell NetBeans where to find it, which can be done in the Settings window, under Java | JavaFX, as you can see in the following screenshot:
We are now ready to create the FXML file. Under the resources directory in the Project View, create a new folder called fxml, and in that folder, create a file called procman.fxml, as follows:
<BorderPane xmlns="http://javafx.com/javafx/8.0.60" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.steeplesoft.procman.Controller"> </BorderPane>
BorderPane is a container that defines five regions--top, bottom, left, right, and center, giving us a fairly coarsely-grained control over where on the form the controls should appear. Typically, with BorderPane, each area uses a nested container to provide the finer-grained control often necessary. For our needs, this level of control will be perfect.
The primary concern of the user interface is the list of processes, so we'll start with the controls for that. From Scene Builder, we want to click on the Controls section on the accordion on the left, then scroll down to TableView. Click on this and drag it to the CENTER region on the form, as shown here in this screenshot from Scene Builder: