java ee 8 recipes

86
Java EE 8 Recipes Presented By: Josh Juneau Author and Application Developer

Upload: josh-juneau

Post on 06-Jan-2017

2.371 views

Category:

Technology


1 download

TRANSCRIPT

Page 1: Java EE 8 Recipes

Java EE 8 RecipesPresented By: Josh JuneauAuthor and Application Developer

Page 2: Java EE 8 Recipes

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

Page 3: Java EE 8 Recipes

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

Page 4: Java EE 8 Recipes

Before we start. . .

Old: J2EE

Modern: Java EE

Page 5: Java EE 8 Recipes

Java EE of the Past (J2EE)

Difficult to Use ConfigurationVerbose

Few Standards

Page 6: Java EE 8 Recipes

Progressive Improvements

More Productive

Less Configuration

More Standards

Page 7: Java EE 8 Recipes

Java EE 7 Increases Productivity Even More

and Introduces Standards for Building Modern Applications

Page 8: Java EE 8 Recipes

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

Page 9: Java EE 8 Recipes

Java EE 7 Introduced New Standards

• WebSockets

• JSON-P

• Batch API

• Concurrency Utilities for Java EE

Page 10: Java EE 8 Recipes

Who uses Java EE?

Page 11: Java EE 8 Recipes

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

Page 12: Java EE 8 Recipes
Page 13: Java EE 8 Recipes

Recipes!Lots to cover…

Page 14: Java EE 8 Recipes

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!

Page 15: Java EE 8 Recipes

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

Page 16: Java EE 8 Recipes

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

Page 17: Java EE 8 Recipes

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.

Page 18: Java EE 8 Recipes

Solution

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

Page 19: Java EE 8 Recipes

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

Page 20: Java EE 8 Recipes

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.

Page 21: Java EE 8 Recipes

Problem

FacesContext context = FacesContext.getCurrentInstance();

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

Page 22: Java EE 8 Recipes

Problem

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

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

Page 23: Java EE 8 Recipes

Solution

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

Page 24: Java EE 8 Recipes

Solution@Inject

private ExternalContext externalContext;

@Inject

private ServletContext servletContext;

@Inject

@ViewMap

private Map<String, Object> viewMap;

Page 25: Java EE 8 Recipes

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.

Page 26: Java EE 8 Recipes

How it Works

Page 27: Java EE 8 Recipes

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

Page 28: Java EE 8 Recipes

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.

Page 29: Java EE 8 Recipes

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

Page 30: Java EE 8 Recipes

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

Page 31: Java EE 8 Recipes

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.

Page 32: Java EE 8 Recipes

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.

Page 33: Java EE 8 Recipes

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

Page 34: Java EE 8 Recipes

Problem #4

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

We wish to create a list of current reservations.

Page 35: Java EE 8 Recipes

Solution

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

Page 36: Java EE 8 Recipes

Solution

Page 37: Java EE 8 Recipes

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.

Page 38: Java EE 8 Recipes

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.

Page 39: Java EE 8 Recipes

How it Works

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

Page 40: Java EE 8 Recipes

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.

Page 41: Java EE 8 Recipes

Problem #5

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

Page 42: Java EE 8 Recipes

Solution

Utilize JSON Pointer to find the desired value.

Page 43: Java EE 8 Recipes

How it Works

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

Page 44: Java EE 8 Recipes

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.

Page 45: Java EE 8 Recipes

Problem #6

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

Page 46: Java EE 8 Recipes

Solution

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

Page 47: Java EE 8 Recipes

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"]}

Page 48: Java EE 8 Recipes

Solution

Page 49: Java EE 8 Recipes

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

Page 50: Java EE 8 Recipes

Problem #7

You wish to parse some JSON using Java.

Page 51: Java EE 8 Recipes

Solution

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

Page 52: Java EE 8 Recipes

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.

Page 53: Java EE 8 Recipes

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

Page 54: Java EE 8 Recipes

Problem #8

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

Page 55: Java EE 8 Recipes

Solution

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

Page 56: Java EE 8 Recipes

Solution

Page 57: Java EE 8 Recipes

SolutionCreate JSON from Java object

Page 58: Java EE 8 Recipes

SolutionCreate JSON from Java List

Page 59: Java EE 8 Recipes

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

Page 60: Java EE 8 Recipes

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

Page 61: Java EE 8 Recipes

Problem #9

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

Page 62: Java EE 8 Recipes

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

Page 63: Java EE 8 Recipes

SolutionUse @ObservesAsync to observe an asynchronous event.

Page 64: Java EE 8 Recipes

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.

Page 65: Java EE 8 Recipes

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

Page 66: Java EE 8 Recipes

Problem #10

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

Page 67: Java EE 8 Recipes

SolutionUse the standardized configuration API to retrieve the configuration values.

Suppose you have a property file with the following values:

city=Chicago

language=Java

Page 68: Java EE 8 Recipes

Solution

Config config = ConfigProvider.getConfig();

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

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

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

Page 69: Java EE 8 Recipes

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.

Page 70: Java EE 8 Recipes

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??

Page 71: Java EE 8 Recipes

Problem #11

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

Page 72: Java EE 8 Recipes

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

Page 73: Java EE 8 Recipes

Solution

Page 74: Java EE 8 Recipes

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

Page 75: Java EE 8 Recipes

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.

Page 76: Java EE 8 Recipes

How it Works

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

Page 77: Java EE 8 Recipes

How it WorksExample of a Decoder:

Page 78: Java EE 8 Recipes

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

Page 79: Java EE 8 Recipes

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.

Page 80: Java EE 8 Recipes

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

Page 81: Java EE 8 Recipes

Solution

Page 82: Java EE 8 Recipes

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

Page 83: Java EE 8 Recipes

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

Page 84: Java EE 8 Recipes

We’ve Covered A Lot

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

Page 85: Java EE 8 Recipes

Microservices?

What is a microservice?

How to do micro services with Java EE?

We’ll get there in Java EE 9…

Page 86: Java EE 8 Recipes

Learn More

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

Contact on Twitter: @javajuneau