Java EE 8 Recipes

Post on 06-Jan-2017

2,371 views 1 download

transcript

Java EE 8 RecipesPresented By: Josh JuneauAuthor and Application Developer

About MeJosh Juneau

Day Job: Developer and DBA @ Fermilab

Night/Weekend Job: Technical Writer

- Java Magazine and OTN

- Java EE 7 Recipes

- Introducing Java EE 7

- Java 8 Recipes

JSR 372 EG and JSR 378 EG

Twitter: @javajuneau

Agenda

- Take a look at big picture of Java EE 8

- Resolve a series of real life scenarios using the features of Java EE 7 and Java EE 8

Before we start. . .

Old: J2EE

Modern: Java EE

Java EE of the Past (J2EE)

Difficult to Use ConfigurationVerbose

Few Standards

Progressive Improvements

More Productive

Less Configuration

More Standards

Java EE 7 Increases Productivity Even More

and Introduces Standards for Building Modern Applications

Java EE 7 Increased Productivity

• CDI Everywhere

• JAX-RS Client API, Async Processing

• Bean Validation in EJBs and POJOs

• JSF Flows

• JMS 2.0 - Much Less Code

Java EE 7 Introduced New Standards

• WebSockets

• JSON-P

• Batch API

• Concurrency Utilities for Java EE

Who uses Java EE?

Java EE 8 Continues this Momentum

• Continued enhancements for productivity and web standards alignment

• Cloud enhancements

• Better alignment with Java SE 8

• Work towards a better platform for development of microservices

Recipes!Lots to cover…

Recipes!Statement for Completeness:

Recipes are not meant to provide comprehensive coverage of the features. Rather, they are meant to get you up and running with the new functionality quickly, providing the

details you need to know. To learn more details on any of the features covered, please refer to the online

documentation.

Let’s Cook!

How to Run

Setting up your environment for Java EE 8

• Payara 5 Branch• Clone git repository and build:

mvn clean install -DskipTests

• Clone and Build/Download latest EA of Spec• Most have git repositories

JSF 2.3JSR 372

• New features added in JSF 2.3, adding more flexibility

• Improved CDI Alignment

• PostRenderViewEvent

• WebSocket Integration and Ajax Enhancements

• Java 8 Date-Time Support

• Enhanced Components

• Much More

Problem #1

You would like to work with the Java 8 Date-Time API via your JSF application. Does not work with Java EE 7 out of the box.

Solution

Make use of the <f:convertDateTime /> tag.

How it Works

JSF 2.3 requires a minimum of Java 8, so we can make use of Java 8 goodness.

New type attribute values on <f:convertDateTime>:• localDate, localTime, localDateTime• offsetTime,offsetDateTime, zonedDateTime

Problem #2

Oftentimes, you need to work with FacesContext or another JSF artifact. It can be cumbersome to obtain the current instance, ServletContext, etc. time after time.

Problem

FacesContext context = FacesContext.getCurrentInstance();

ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

Problem

Map<String, Object> cookieMap = FacesContext.getCurrentInstance().getExternalContext().getRequestCookieMap();

Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();

Solution

Inject JSF artifacts in JSF 2.3, and inject into JSF artifacts.

Solution@Inject

private ExternalContext externalContext;

@Inject

private ServletContext servletContext;

@Inject

@ViewMap

private Map<String, Object> viewMap;

How it Works

JSF 2.3 provides default producers for many of the most commonly used JSF artifacts, therefore, we can now inject rather than hard-code.

Converters, validators and behaviors are now also injection targets.

How it Works

Bean ValidationJSR-380

New Features in Bean Validation 2.0:

• Focus on Java SE 8 Features

• Type annotations, Date-Time Validation, etc.

• Simpler Constraint Ordering on Single Properties

• Custom Payload for Constraint Violations

Problem #3

You would like to validate dates and times utilizing the Java 8 Date-Time API to ensure that they are in the past or in the future.

Solution@Future and @Past will work with Java 8 Date-Time

How it Works• Place validation constraint annotations on a field,

method, or class such as a JSF managed bean or entity class.

• When the JSF Process Validations phase occurs, the value that was entered by the user will be validated based upon the specified validation criteria. At this point, if the validation fails, the Render Response phase is executed, and an appropriate error message is added to the FacesContext. However, if the validation is successful, then the life cycle continues normally.

• Specify a validation error message using the message attribute within the constraint annotation

How it Works

Other New Features:

Type-use annotation:List<@NotNull @Email String> emails;

Mark standardized constraints with @Repeatable, eliminating the need for the usage of the @Size.List pattern.

JSON-P 1.1JSR-374

The Java API for JSON Processing is a standard for generation and processing of JavaScript Object Notation data.

JSON-P provides an API to parse, transform, and query JSON data using the object model or the streaming model.

JSON is often used as a common format to serialize and deserialize data for applications that communicate with each other over the Internet.

JSON-P 1.1

• Adds new JSON standards for JSON-Pointer and JSON-Patch

• Provides editing operations for JSON objects and arrays

• Helper classes and Java SE 8 Support

Problem #4

You would like to build a JSON object model using Java code.

We wish to create a list of current reservations.

Solution

Utilize JSON Processing for the Java EE Platform to build a JSON object model containing all of the current reservations.

Solution

How it Works

JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null.

How it WorksJava EE includes support for JSR 353, which provides an API to parse, transform, and query JSON data using the object model or the streaming model

Make use of JsonObjectBuilder to build a JSON object using the builder pattern.

Call upon the Json.createObjectBuilder() method to create a JsonObjectBuilder.

How it Works

Utilize the builder pattern to build the object model by nesting calls to the JsonObjectBuilder add() method, passing name/value pairs.

How it WorksIt is possible to nest objects and arrays.

The JsonArrayBuilder class contains similar add methods that do not have a name (key) parameter. You can nest arrays and objects by passing a new JsonArrayBuilder object or a new JsonObjectBuilder object to the corresponding add method.

Invoke the build() method to create the object.

Problem #5

You are interested in finding a specific value within a JSON document.

Solution

Utilize JSON Pointer to find the desired value.

How it Works

• Create a new JsonPointer object and pass a string that will be used for identifying a specific value.

How it Works

• Obtain the value by calling the JsonPointer.getValue() method and passing the JsonObject you wish to parse. The JsonValue will contain the value to which you had pointed.

Problem #6

You would like to perform an operation on a a specified value within a JSON document.

Solution

Utilize JSON Patch to replace a specified value within a JSON document with another value.

The original document{"baz": "qux", "foo": "bar"}The patch[ { "op": "replace", "path": "/baz", "value": "boo" }, { "op": "add", "path": "/hello", "value": ["world"] }, { "op": "remove", "path": "/foo"}]The result{"baz": "boo","hello": ["world"]}

Solution

How it Works

• JSON Document or JsonPatchBuilder

• JSON Pointer is used to find the value or section that will be patched

• A series of operations can be applied

Problem #7

You wish to parse some JSON using Java.

Solution

Use the JsonParser, which is a pull parser that allows us to process each document record via iteration.

How it Works

Parser can be created on a byte or character stream by calling upon the Json.createParser() method.

Iterate over the JSON object model and/or array, and parse each event accordingly.

JSON-BJSR-367

Java API for JSON Binding• Standardize means of converting JSON to

Java objects and vice versa• Default mapping algorithm for converting

Java classes• Draw from best of breed ideas in existing

JSON binding solutions• Provide JAX-RS a standard way to support

“application/json” for POJOs• JAX-RS currently supports JSON-P

Problem #8

You would like read in a JSON document and map it to a Java class or POJO.

Solution

Utilize default JSON binding mapping to quickly map to a POJO.

Solution

SolutionCreate JSON from Java object

SolutionCreate JSON from Java List

How it Works

• JSON-B API provides serialization and deserialization operations for manipulating JSON documents to Java

• Default mapping, with custom annotation mapping available for compile-time

• JsonConfig class for runtime mapping customizations

CDI 2.0JSR 365

• JSR is in active progress…can download WELD betas and test

• Java SE Bootstrap

• XML Configuration

• Asynchronous Events

• @Startup for CDI Beans

• Portable Extension SPI Simplification

• Small features/enhancements

Problem #9

You’d like to mark a CDI event as asynchronous.

SolutionFire the event calling upon the fireAsync() method, passing the event class.

SolutionUse @ObservesAsync to observe an asynchronous event.

How it Works

• Utilizes the Java 8 Asynchronous API to provide a streamlined approach.

• @ObservesAsync annotation added to annotate an observer method parameter so that existing observers annotated with @Observes would remain synchronous.

• fireAsync() added to the Event interface.

ConfigurationNew Spec Pending

• Standard for externalizing configuration

• Aimed at cloud-based environments

• Provide the ability to change one or more configurations that are independent/decoupled of apps...multiple configuration files

• Unified API for accessing configuration in many different environments

• Layering and overrides

Problem #10

The application that you are developing requires some external configuration values for specifying server-side paths and/or resources.

SolutionUse the standardized configuration API to retrieve the configuration values.

Suppose you have a property file with the following values:

city=Chicago

language=Java

Solution

Config config = ConfigProvider.getConfig();

String city = config.getProperty(“city”);

String language = config.getProperty(“language”);

Long val = config.getProperty(“someLong”, Long.class);

How it Works

• Define the configuration sources for an application using a config-sources.xml file, or using an api to set up at deployment time.

WebSockets

The Java API for WebSocket provides support for building WebSocket applications.

WebSocket is an application protocol that provides full-duplex communications between peers over the TCP protocol.

What about Java EE 8??

Problem #11

You wish to create a communication channel that can be used to receive messages asynchronously.

Solution

Create a WebSocket endpoint by annotating a POJO class using @ServerEndpoint, and providing the desired endpoint path.

Create a message receiver method, and annotate it with @OnMessage

Solution

How it Works

Create a WebSocket endpoint by annotating a class with @ServerEndpoint, and passing the value attribute with a desired path for the endpoint URI.

@ServerEndpoint(value=“/chatEndpoint”)

URI: ws://server:port/application-name/path

How it Works

Method annotated @OnOpen is invoked when the WebSocket connection is made.

Method annotated @OnMessage is invoked when a message is sent to the endpoint. It then returns a response.

How it Works

Specify optional Encoder and Decoder implementations to convert messages to and from a particular format.

How it WorksExample of a Decoder:

JAX-RS 2.1JSR 370

• Hypermedia API

• Reactive API

• Security API

• Support for SSE (Server Sent Events)

• Improved CDI Integration

• Support for Non-Blocking IO in Providers

Problem #12

You would like to initiate an open-ended communication channel from a server to clients. You wish to have a connection remain open to the client so that subsequent single-sided communications from the server can be sent.

SolutionCreate an SSE Resource using JAX-RS 2.1, and broadcast server messages to connected clients at will.

Solution

How it Works• Try now by downloading Jersey 2.24

• Similar to long-polling, but may send multiple messages

• Annotate resource method with @Produces(SseFeature.SERVER_SENT_EVENTS)

• Also possible to broadcast using SseBroadcaster

MVC 1.0Features of MVC 1.0:

• Action-based

• Follows suit of Spring MVC or Apache Struts

• Does not replace JSF

• No UI Components

• Model: CDI, Bean Validation, JPA

• View: Facelets, JSP, other

• Controller: Layered on top of JAX-RS

We’ve Covered A Lot

…but there is a lot more to cover!!!!

Microservices?

What is a microservice?

How to do micro services with Java EE?

We’ll get there in Java EE 9…

Learn More

Code Examples: https://github.com/juneau001/AcmeWorld

Contact on Twitter: @javajuneau