SlideShare a Scribd company logo
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
Java EE 8 Recipes
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

More Related Content

What's hot (18)

PDF
50 New Features of Java EE 7 in 50 minutes
Arun Gupta
 
PPTX
Top 50 java ee 7 best practices [con5669]
Ryan Cuprak
 
PPT
What's New in WebLogic 12.1.3 and Beyond
Oracle
 
PPTX
Move from J2EE to Java EE
Hirofumi Iwasaki
 
PPT
Java EE and Spring Side-by-Side
Reza Rahman
 
PDF
Java EE 7 overview
Masoud Kalali
 
PPT
Testing Java EE Applications Using Arquillian
Reza Rahman
 
PDF
Android and the Seven Dwarfs from Devox'15
Murat Yener
 
PDF
Spring Framework - Core
Dzmitry Naskou
 
PPT
Java EE 6 & Spring: A Lover's Quarrel
Mauricio "Maltron" Leal
 
PDF
jsf2 Notes
Rajiv Gupta
 
PPTX
Java EE vs Spring Framework
Rohit Kelapure
 
PDF
AAI 1713-Introduction to Java EE 7
Kevin Sutter
 
PPTX
Next stop: Spring 4
Oleg Tsal-Tsalko
 
PDF
Lecture 1: Introduction to JEE
Fahad Golra
 
ODP
OTN Developer Days - Java EE 6
glassfish
 
PDF
Spring framework
Aircon Chen
 
50 New Features of Java EE 7 in 50 minutes
Arun Gupta
 
Top 50 java ee 7 best practices [con5669]
Ryan Cuprak
 
What's New in WebLogic 12.1.3 and Beyond
Oracle
 
Move from J2EE to Java EE
Hirofumi Iwasaki
 
Java EE and Spring Side-by-Side
Reza Rahman
 
Java EE 7 overview
Masoud Kalali
 
Testing Java EE Applications Using Arquillian
Reza Rahman
 
Android and the Seven Dwarfs from Devox'15
Murat Yener
 
Spring Framework - Core
Dzmitry Naskou
 
Java EE 6 & Spring: A Lover's Quarrel
Mauricio "Maltron" Leal
 
jsf2 Notes
Rajiv Gupta
 
Java EE vs Spring Framework
Rohit Kelapure
 
AAI 1713-Introduction to Java EE 7
Kevin Sutter
 
Next stop: Spring 4
Oleg Tsal-Tsalko
 
Lecture 1: Introduction to JEE
Fahad Golra
 
OTN Developer Days - Java EE 6
glassfish
 
Spring framework
Aircon Chen
 

Viewers also liked (20)

PDF
Java EE 8 - February 2017 update
David Delabassee
 
PDF
MVC 1.0 / JSR 371
David Delabassee
 
PDF
HTML5 Media Elements
Javier Antonio Humarán Peñuñuri
 
PDF
JSR 375 Segurança em Java EE 8
Helder da Rocha
 
PPTX
Configuration for Java EE and the Cloud
Dmitry Kornilov
 
PDF
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
David Delabassee
 
PDF
New MVC 1.0 JavaEE 8 API
Trayan Iliev
 
PDF
Gráficos Vetoriais na Web com SVG
Helder da Rocha
 
PPT
Царство грибов
LotosPlay
 
PPT
Науки о природе
LotosPlay
 
PDF
Bag to school choosing the right school bag
permapleatcomau
 
PPT
Мир живых организмов
LotosPlay
 
PPT
Роль грибов
LotosPlay
 
PDF
Web based apps - Demo
actiknow
 
PPT
Ткани растений
LotosPlay
 
PPT
Прокариотическая клетка
LotosPlay
 
PDF
PMP with Rebus Business solutions
Rebus Business Solutions
 
PPT
Теория Ламарка
LotosPlay
 
PDF
Place identification paper_발표자료_summary
Namgee Lee
 
Java EE 8 - February 2017 update
David Delabassee
 
MVC 1.0 / JSR 371
David Delabassee
 
JSR 375 Segurança em Java EE 8
Helder da Rocha
 
Configuration for Java EE and the Cloud
Dmitry Kornilov
 
Java EE 8 Adopt a JSR : JSON-P 1.1 & MVC 1.0
David Delabassee
 
New MVC 1.0 JavaEE 8 API
Trayan Iliev
 
Gráficos Vetoriais na Web com SVG
Helder da Rocha
 
Царство грибов
LotosPlay
 
Науки о природе
LotosPlay
 
Bag to school choosing the right school bag
permapleatcomau
 
Мир живых организмов
LotosPlay
 
Роль грибов
LotosPlay
 
Web based apps - Demo
actiknow
 
Ткани растений
LotosPlay
 
Прокариотическая клетка
LotosPlay
 
PMP with Rebus Business solutions
Rebus Business Solutions
 
Теория Ламарка
LotosPlay
 
Place identification paper_발표자료_summary
Namgee Lee
 
Ad

Similar to Java EE 8 Recipes (20)

PDF
Jakarta EE Recipes
Josh Juneau
 
PDF
Updates to the java api for json processing for java ee 8
Alex Soto
 
PDF
Java EE 8 Overview (Japanese)
Logico
 
PPTX
What's new in the Java API for JSON Binding
Dmitry Kornilov
 
PDF
Java EE 8 - An instant snapshot
David Delabassee
 
PDF
What's coming in Java EE 8
David Delabassee
 
PDF
Json generation
Aravindharamanan S
 
PPTX
Introduction to Yasson
Dmitry Kornilov
 
PDF
112815 java ee8_davidd
Takashi Ito
 
PDF
What's Coming in Java EE 8
PT.JUG
 
PDF
Java EE 8 - An instant snapshot
David Delabassee
 
PPTX
JSON Processing and mule
Santhosh Gowd
 
PDF
What's new in Java 8
jclingan
 
PDF
Java 8
jclingan
 
PPT
Java JSON Parser Comparison
Allan Huang
 
PDF
Bas 5676-java ee 8 introduction
Kevin Sutter
 
PPTX
Java EE for the Cloud
Dmitry Kornilov
 
PPTX
Java ee 7 New Features
Shahzad Badar
 
PDF
JavaCro'15 - Java EE 8 - An instant snapshot - David Delabassee
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Jakarta EE Recipes
Josh Juneau
 
Updates to the java api for json processing for java ee 8
Alex Soto
 
Java EE 8 Overview (Japanese)
Logico
 
What's new in the Java API for JSON Binding
Dmitry Kornilov
 
Java EE 8 - An instant snapshot
David Delabassee
 
What's coming in Java EE 8
David Delabassee
 
Json generation
Aravindharamanan S
 
Introduction to Yasson
Dmitry Kornilov
 
112815 java ee8_davidd
Takashi Ito
 
What's Coming in Java EE 8
PT.JUG
 
Java EE 8 - An instant snapshot
David Delabassee
 
JSON Processing and mule
Santhosh Gowd
 
What's new in Java 8
jclingan
 
Java 8
jclingan
 
Java JSON Parser Comparison
Allan Huang
 
Bas 5676-java ee 8 introduction
Kevin Sutter
 
Java EE for the Cloud
Dmitry Kornilov
 
Java ee 7 New Features
Shahzad Badar
 
JavaCro'15 - Java EE 8 - An instant snapshot - David Delabassee
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Ad

More from Josh Juneau (8)

PDF
Migrating to Jakarta EE 10
Josh Juneau
 
PDF
Jakarta EE and MicroProfile Tech Talk
Josh Juneau
 
PDF
Jakarta EE and MicroProfile - EclipseCon 2020
Josh Juneau
 
PDF
Utilizing JSF Front Ends with Microservices
Josh Juneau
 
PPTX
Jakarta EE 8: Overview of Features
Josh Juneau
 
PDF
Lightweight Java EE with MicroProfile
Josh Juneau
 
PDF
Java EE 7 Recipes
Josh Juneau
 
PDF
Java EE 7 Recipes for Concurrency - JavaOne 2014
Josh Juneau
 
Migrating to Jakarta EE 10
Josh Juneau
 
Jakarta EE and MicroProfile Tech Talk
Josh Juneau
 
Jakarta EE and MicroProfile - EclipseCon 2020
Josh Juneau
 
Utilizing JSF Front Ends with Microservices
Josh Juneau
 
Jakarta EE 8: Overview of Features
Josh Juneau
 
Lightweight Java EE with MicroProfile
Josh Juneau
 
Java EE 7 Recipes
Josh Juneau
 
Java EE 7 Recipes for Concurrency - JavaOne 2014
Josh Juneau
 

Recently uploaded (20)

PDF
Biography of Daniel Podor.pdf
Daniel Podor
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Biography of Daniel Podor.pdf
Daniel Podor
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 

Java EE 8 Recipes

  • 1. Java EE 8 Recipes Presented By: Josh Juneau Author and Application Developer
  • 2. 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
  • 3. 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
  • 4. Before we start. . . Old: J2EE Modern: Java EE
  • 5. Java EE of the Past (J2EE) Difficult to Use Configuration Verbose Few Standards
  • 7. Java EE 7 Increases Productivity Even More and Introduces Standards for Building Modern Applications
  • 8. 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
  • 9. Java EE 7 Introduced New Standards • WebSockets • JSON-P • Batch API • Concurrency Utilities for Java EE
  • 11. 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
  • 14. 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!
  • 15. 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
  • 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 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.
  • 18. Solution Make use of the <f:convertDateTime /> tag.
  • 19. 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
  • 20. 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.
  • 21. Problem FacesContext context = FacesContext.getCurrentInstance(); ExternalContext externalContext = 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 artifacts in JSF 2.3, and inject into JSF artifacts.
  • 24. Solution @Inject private ExternalContext externalContext; @Inject private ServletContext servletContext; @Inject @ViewMap private Map<String, Object> viewMap;
  • 25. 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.
  • 27. 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
  • 28. 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.
  • 29. Solution @Future and @Past will 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 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.
  • 32. 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.
  • 33. 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
  • 34. Problem #4 You would like to build a JSON object model using Java code. We wish to create a list of current reservations.
  • 35. Solution Utilize JSON Processing for the Java EE Platform to build a JSON object model containing all of the current reservations.
  • 37. 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.
  • 38. 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.
  • 39. How it Works Utilize the builder pattern to build the object model by nesting calls to the JsonObjectBuilder add() method, passing name/value pairs.
  • 40. 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.
  • 41. Problem #5 You are interested in finding a specific value within a JSON document.
  • 42. Solution Utilize JSON Pointer to 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 would like to perform an operation on a a specified value within a JSON document.
  • 46. Solution Utilize JSON Patch to 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"]}
  • 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 wish to 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 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.
  • 53. 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
  • 54. Problem #8 You would like read in a JSON document and map it to a Java class or POJO.
  • 55. Solution Utilize default JSON binding mapping to quickly map to a POJO.
  • 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 like to mark a CDI event as asynchronous.
  • 62. Solution Fire the event calling upon the fireAsync() method, passing the event class.
  • 63. Solution Use @ObservesAsync to observe 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 application that you are developing requires some external configuration values for specifying server-side paths and/or resources.
  • 67. 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
  • 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 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??
  • 71. Problem #11 You wish to create a communication channel that can be used to receive messages asynchronously.
  • 72. 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
  • 74. 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
  • 75. 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.
  • 76. How it Works Specify optional Encoder and Decoder implementations to convert messages to and from a particular format.
  • 77. How it Works Example of 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 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.
  • 80. Solution Create an SSE Resource using JAX-RS 2.1, and broadcast server messages to connected clients at will.
  • 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 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
  • 84. We’ve Covered A Lot …but there is a lot more to cover!!!!
  • 85. Microservices? What is a microservice? 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