KEMBAR78
Java EE 8 Recipes | PDF
Java EE 8 Recipes
Presented By: Josh Juneau
Author and Application Developer
About Me
Josh 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 Configuration
Verbose
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
• BeanValidation 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.3
JSR 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().getExter
nalContext();
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
BeanValidation
JSR-380
New Features in BeanValidation 2.0:
• Focus on Java SE 8 Features
• Type annotations, Date-TimeValidation, etc.
• Simpler Constraint Ordering on Single Properties
• Custom Payload for ConstraintViolations
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.1
JSR-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 Works
Java 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 Works
It 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-B
JSR-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
Solution
Create JSON from Java object
Solution
Create 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.0
JSR 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.
Solution
Fire the event calling upon the fireAsync()
method, passing the event class.
Solution
Use @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.
Configuration
New 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.
Solution
Use 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 Works
Example of a Decoder:
JAX-RS 2.1
JSR 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.
Solution
Create 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_EVE
NTS)
• Also possible to broadcast using
SseBroadcaster
MVC 1.0
Features of MVC 1.0:
• Action-based
• Follows suit of Spring MVC or Apache Struts
• Does not replace JSF
• No UI Components
• Model: CDI, BeanValidation, 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

Java EE 8 Recipes

  • 1.
    Java EE 8Recipes Presented By: Josh Juneau Author and Application Developer
  • 2.
    About Me Josh Juneau DayJob: 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
  • 3.
    Agenda - Take alook 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
  • 4.
    Before we start.. . Old: J2EE Modern: Java EE
  • 5.
    Java EE ofthe Past (J2EE) Difficult to Use Configuration Verbose Few Standards
  • 6.
  • 7.
    Java EE 7Increases Productivity Even More and Introduces Standards for Building Modern Applications
  • 8.
    Java EE 7Increased Productivity • CDI Everywhere • JAX-RS Client API,Async Processing • BeanValidation in EJBs and POJOs • JSF Flows • JMS 2.0 - Much Less Code
  • 9.
    Java EE 7Introduced New Standards • WebSockets • JSON-P • Batch API • Concurrency Utilities for Java EE
  • 10.
  • 11.
    Java EE 8Continues 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
  • 13.
  • 14.
    Recipes! Statement for Completeness: Recipesare 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!
  • 15.
    How to Run Settingup 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
  • 16.
    JSF 2.3 JSR 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
  • 17.
    Problem #1 You wouldlike to work with the Java 8 Date- Time API via your JSF application. Does not work with Java EE 7 out of the box.
  • 18.
    Solution Make use ofthe <f:convertDateTime /> tag.
  • 19.
    How it Works JSF2.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
  • 20.
    Problem #2 Oftentimes, youneed to work with FacesContext or another JSF artifact. It can be cumbersome to obtain the current instance, ServletContext, etc. time after time.
  • 21.
    Problem FacesContext context = FacesContext.getCurrentInstance(); ExternalContextexternalContext = FacesContext.getCurrentInstance().getExter nalContext();
  • 22.
    Problem Map<String, Object> cookieMap= FacesContext.getCurrentInstance().getExternalContext() .getRequestCookieMap(); Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot( ).getViewMap();
  • 23.
    Solution Inject JSF artifactsin JSF 2.3, and inject into JSF artifacts.
  • 24.
    Solution @Inject private ExternalContext externalContext; @Inject privateServletContext servletContext; @Inject @ViewMap private Map<String, Object> viewMap;
  • 25.
    How it Works JSF2.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.
  • 26.
  • 27.
    BeanValidation JSR-380 New Features inBeanValidation 2.0: • Focus on Java SE 8 Features • Type annotations, Date-TimeValidation, etc. • Simpler Constraint Ordering on Single Properties • Custom Payload for ConstraintViolations
  • 28.
    Problem #3 You wouldlike to validate dates and times utilizing the Java 8 Date-Time API to ensure that they are in the past or in the future.
  • 29.
    Solution @Future and @Pastwill work with Java 8 Date-Time
  • 30.
    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
  • 31.
    How it Works OtherNew 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.
  • 32.
    JSON-P 1.1 JSR-374 The JavaAPI 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.
  • 33.
    JSON-P 1.1 • Addsnew JSON standards for JSON-Pointer and JSON-Patch • Provides editing operations for JSON objects and arrays • Helper classes and Java SE 8 Support
  • 34.
    Problem #4 You wouldlike to build a JSON object model using Java code. We wish to create a list of current reservations.
  • 35.
    Solution Utilize JSON Processingfor the Java EE Platform to build a JSON object model containing all of the current reservations.
  • 36.
  • 37.
    How it Works JSONdefines 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.
  • 38.
    How it Works JavaEE 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.
  • 39.
    How it Works Utilizethe builder pattern to build the object model by nesting calls to the JsonObjectBuilder add() method, passing name/value pairs.
  • 40.
    How it Works Itis 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.
  • 41.
    Problem #5 You areinterested in finding a specific value within a JSON document.
  • 42.
    Solution Utilize JSON Pointerto find the desired value.
  • 43.
    How it Works •Create a new JsonPointer object and pass a string that will be used for identifying a specific value.
  • 44.
    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.
  • 45.
    Problem #6 You wouldlike to perform an operation on a a specified value within a JSON document.
  • 46.
    Solution Utilize JSON Patchto replace a specified value within a JSON document with another value.
  • 47.
    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"]}
  • 48.
  • 49.
    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
  • 50.
    Problem #7 You wishto parse some JSON using Java.
  • 51.
    Solution Use the JsonParser,which is a pull parser that allows us to process each document record via iteration.
  • 52.
    How it Works Parsercan 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.
  • 53.
    JSON-B JSR-367 Java API forJSON 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
  • 54.
    Problem #8 You wouldlike read in a JSON document and map it to a Java class or POJO.
  • 55.
    Solution Utilize default JSONbinding mapping to quickly map to a POJO.
  • 56.
  • 57.
  • 58.
  • 59.
    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
  • 60.
    CDI 2.0 JSR 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
  • 61.
    Problem #9 You’d liketo mark a CDI event as asynchronous.
  • 62.
    Solution Fire the eventcalling upon the fireAsync() method, passing the event class.
  • 63.
    Solution Use @ObservesAsync toobserve an asynchronous event.
  • 64.
    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.
  • 65.
    Configuration New 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
  • 66.
    Problem #10 The applicationthat you are developing requires some external configuration values for specifying server-side paths and/or resources.
  • 67.
    Solution Use the standardizedconfiguration API to retrieve the configuration values. Suppose you have a property file with the following values: city=Chicago language=Java
  • 68.
    Solution Config config =ConfigProvider.getConfig(); String city = config.getProperty(“city”); String language = config.getProperty(“language”); Long val = config.getProperty(“someLong”, Long.class);
  • 69.
    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.
  • 70.
    WebSockets The Java APIfor 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??
  • 71.
    Problem #11 You wishto create a communication channel that can be used to receive messages asynchronously.
  • 72.
    Solution Create a WebSocketendpoint by annotating a POJO class using @ServerEndpoint, and providing the desired endpoint path. Create a message receiver method, and annotate it with @OnMessage
  • 73.
  • 74.
    How it Works Createa 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
  • 75.
    How it Works Methodannotated @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.
  • 76.
    How it Works Specifyoptional Encoder and Decoder implementations to convert messages to and from a particular format.
  • 77.
    How it Works Exampleof a Decoder:
  • 78.
    JAX-RS 2.1 JSR 370 •Hypermedia API • Reactive API • Security API • Support for SSE (Server Sent Events) • Improved CDI Integration • Support for Non-Blocking IO in Providers
  • 79.
    Problem #12 You wouldlike 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.
  • 80.
    Solution Create an SSEResource using JAX-RS 2.1, and broadcast server messages to connected clients at will.
  • 81.
  • 82.
    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_EVE NTS) • Also possible to broadcast using SseBroadcaster
  • 83.
    MVC 1.0 Features ofMVC 1.0: • Action-based • Follows suit of Spring MVC or Apache Struts • Does not replace JSF • No UI Components • Model: CDI, BeanValidation, JPA • View: Facelets, JSP, other • Controller: Layered on top of JAX-RS
  • 84.
    We’ve Covered ALot …but there is a lot more to cover!!!!
  • 85.
    Microservices? What is amicroservice? How to do micro services with Java EE? We’ll get there in Java EE 9…
  • 86.
    Learn More Code Examples:https://github.com/juneau001/AcmeWorld Contact on Twitter: @javajuneau