java ee 8: on the horizon

72
Java EE 8 On The Horizon Josh Juneau

Upload: josh-juneau

Post on 02-Aug-2015

2.860 views

Category:

Technology


0 download

TRANSCRIPT

Java EE 8 On The Horizon

Josh Juneau

About MeDay 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

- More…

JSF 2.3 Expert Group

Twitter: @javajuneau

Agenda

• Overview of the specifications that are part of Java EE 8, provide current status

• Examples of Proposed Enhancements and New Features

Java EE 8: Overview

• Alignment with Java SE 8

• Continued Enhancements for HTML5 Support

• Considerations for Ease of Use

• Extend and Improve CDI Integration

• Cloud Based Improvements

Java EE 8: Overview• JMS 2.1

• JAX-RS 2.1

• JSF 2.3

• CDI 2.0

• JSON-P 1.1

• Servlet 4.0

• Java EE Management API 2.0

New Specs

• JCache 1.0 (JSR 107)

• JSON-B 1.0 (JSR 367)

• MVC 1.0 (JSR 371)

• Java EE Security API 1.0 (JSR 375)

Updated Specifications

JMS 2.1

• JSR 368 - In early stages

• No builds available for testing, as yet.

• Planning: https://java.net/projects/jms-spec/pages/JMS21Planning

JMS 2.1• JMS 2.0 was a major overhaul

• Continuation of API Modernization

• Asynchronous Message Receipt Enhancements (SE & EE)

• Allow batches of async messages

• EE: Allow Java EE Components Other than MDB to Consume Async

• JMS Provider Portability Improvements

• Dead Message Queues

• Redelivery Behavior on JMS MDB Rollback (delays, max # consecutive)

JMS 2.1 Asynchronous Batches

• In JMS 2.0, messages delivered asynchronously by calling:

javax.jms.MessageListener onMessage(Message message)

• Define new

javax.jms.BatchMessageListener onMessages(Message[] messages)

JMS 2.1 Java EE Components

• Allow any Java EE Component to Consume Async Messages? @Stateless

public class MySessionBean {

@DestinationConsumer(mappedName = "jms/queue0")

@MessageSelector("(LostPasswordBy = 'email')")

public void sendEmailPassword(Message message) {

String email = ((TextMessage)message).getText();

String password = retrieveUserPassword(email);

... // call mailSession and send an email

}

JAX-RS 2.1

• JSR 370 - In Early Stages

• No builds available for testing

• Follow EG and Mailing Lists

JAX-RS 2.1• Hypermedia API

• Reactive API

• Security API

• Support for SSE (Server Sent Events)

• Jersey Chapter 15

• Improved CDI Integration

• Support for Non-Blocking IO in Providers

JAX-RS 2.1

• Better Prepared for Supporting Web-Based UI Front Ends

• Conditional JAXB on Runtimes

• Integration with JSON-B

• Support for CDI in Java SE

JAX-RS 2.1 Simple Resource Method

JAX-RS 2.1 Simple Broadcast Example

JSF 2.3

• JSR 372 - in active progress

• Milestones available for testing

• Read, Test, Supply Feedback

JSF 2.3• Enhanced CDI Integration

• Lifecycle Enhancements

• PostRenderViewEvent

• Java and EL API Enhancements

• Configuration Enhancements

• AJAX Enhancements

JSF 2.3 Enhanced CDI Integration

• Injection of Resources @Inject FacesContext facesContext;

@ApplicationMap

@Inject

Map applicationMap;

JSF 2.3 Enhanced CDI Integration

• Wider Support of Injection into JSF Artifacts

• javax.faces.convert.Converter

• javax.faces.validator.Validator

• javax.faces.component.behavior.Behavior

• Add “managed” attribute on the corresponding annotations

• Upgraded to CDI qualifiers

JSF 2.3 Enhanced CDI Integration

• Example of JSF 2.3 Converter with Injection @FacesConverter(value = "myConverter", managed = true)

public class MyConverter implements Converter {

@Inject

private MyService service;

@Override

public Object getAsObject(FacesContext context, UIComponent component, String value) {

// Convert string to Object here

}

}

JSF 2.3 Java and EL API Enhancements• Supporting Map and Iterable in UIData and

UIRepeat

Existing JSTL Looping of Map

<c:forEach var="entry" items="${poolMap}">

Key: <c:out value="${entry.key}"/>

Value: <c:out value="#{entry.value}"/>

</c:forEach>

JSF 2.3 Java and EL API Enhancements

• Supporting Map in UIData and UIRepeat

New Looping of Map via DataTable

<h:dataTable var="entry" value="#{poolController.poolMap}">

<h:column>#{entry.key}</h:column>

<h:column>#{entry.value}</h:column>

</h:dataTable>

CDI 2.0

• JSR 365 - in active progress

• Test Releases of Reference Implementation (Weld 3.0.0 Alphas)

• http://weld.cdi-spec.org/news/

• Follow the Expert Group

CDI 2.0• Modularity … CDI too big?

• Event System Enhancements

• Ordering of Observers and Asynchronous Events

• Improvements for Interceptors & Decorators

• Improved AOP Support, Repeatable annotations for Qualifiers and Interceptor bindings

• CDI for Java SE

• Java 8

• SPI and Context Enhancements

CDI 2.0 Event System Enhancements

• Asynchronous Events @Inject

private ExperimentalEvent<Configuration> event;

event.fireAsync(new Configuration());

• Call to event.fireAsync() returns immediately

CDI 2.0 Event System Enhancements

• How do I know when event delivery competes?

event.fireAsync(new Configuration())

.exceptionally(throwable -> DEFAULT_CONFIGURATION)

.thenAccept((config) -> master.compute(config));

CDI 2.0 Why for Java SE?

• DI is popular, and there is currently no standard

• Utilize similar wiring model with Java EE

• Easier off-server testing

JSON-P 1.1

• JSR 374 - In active progress

• Snapshots of JavaDoc and early builds available

• More Information:

• https://json-processing-spec.java.net/

• Sources: https://java.net/projects/jsonp

JSON-P 1.1• Updates to new API in Java EE 7

• New JSON Standards

• JSON-Pointer and JSON-Patch

• Editing Operations on JSON objects and arrays

• Helper Classes and Enhanced Java SE 8 support

JSON-P 1.1 Java SE 8 Support

• Stream Support

JsonArray persons;

persons.getValuesAs(JsonObject.class).stream()

.filter(x->x.getString(“age”) >= 65)

.forEach(System.out.println(x.getString(“name”)));

JSON-P 1.1 Java SE 8 Support

• JsonCollectors - Return JsonArrays or JsonObjects

JsonArray persons;

JsonArray names = persons.getValuesAs(JsonObject.class).stream()

.filter(p->getString(“age”) >= 65)

.map(p.getString(“name”))

.collect(JsonCollectors.toJsonArray());

JSON-P 1.1 JSON-Pointer

• Used to identify a specific value in a JSON document

// Create the JsonPointer

JsonPointer p = Json.createPointer(“/0/person/age”);

// Obtain value at referenced location

JsonValue v = p.getValue(persons);

JsonArray arr = p.replace(persons, 65);

JSON-P 1.1 JSON-Patch

public void shouldBuildJsonPatchExpressionUsingJsonPatchBuilder() {

JsonPatchBuilder patchBuilder = new JsonPatchBuilder();

JsonObject result = patchBuilder.add("/email", "[email protected]")

.replace("/age", 30)

.remove("/phoneNumber")

.test("/firstName", "John")

.copy("/address/lastName", "/lastName")

.apply(buildPerson());

}

Servlet 4.0

• Currently Working on Early Draft

• Join mailing list or follow expert group (JSR 369)

• Keep tabs on Ed Burn’s presentations…frequent updates

• Lots of work under the covers

Servlet 4.0• HTTP 2 Support -> Major Update

• Why do we need HTTP/2?

• Problems with HTTP/1.1

• HTTP Pipelining, Head-of-Line Blocking

• File Concatenation & Image Sprites

• Inefficient TCP

Servlet 4.0 HTTP 2

• Request/Response Multiplexing

• Binary Framing

• Stream Prioritization

• Server Push

• Socket Optimization

• Upgrade from HTTP 1.1

Servlet 4.0 Exposing HTTP 2

• Stream Prioritization

• New class Priority

• Enhance HttpServletRequest and HttpServletResponse to accommodate

• Server Push

• Not replacing WebSockets

Servlet 4.0 Newer HttpClient API - Java SE 9

• Plans to provide easy to use API

• Support both HTTP/1.1 and 2

• Builds on existing Java API Classes

Java EE Management API 2.0

• Currently working on Early Draft

• Join mailing list of JSR 373

Java EE Management API 2.0

• REST Based Interface to Supersede EJB Management APIs of JSR 77

• Monitoring and deployment as well

• SSE for Event Support (WebSockets also under consideration)

New Specifications!

MVC

• Model - View - Controller

• JSR 371

• Active Progress…download milestones

• Ozark: https://ozark.java.net/

MVC• Action-Based Web Framework for Java EE

• Follows suit of Spring MVC or Apache Struts

• Does Not Replace JSF

• Model: CDI, Bean Validation, JPA

• View: Facelets, JSP (Extensible)

• Controller: Layered on top of JAX-RS

MVC Controller Example

@Controller

@Path("/customers")

public class CustomerController {

@Inject

private Models models;

. . .

@Inject

private CustomerService customerService;

MVC Controller Example

@GET

public String listCustomers() {

models.put("customers", customerService.getCustomers());

return "customers.jsp";

}

MVC View Example

<c:forEach var="customer" items="${customers}">

<tr>

<td class="text-left">${customer.name}</td>

<td class="text-center">

<form action="${pageContext.request.contextPath}/r/customers/edit" method="POST">

<input type="hidden" name="id" value="${item.id}"/>

<button type="submit">

Edit

</button>

</form>

</td>

</tr>

</c:forEach>

MVC Custom ViewHandler

@ApplicationScoped

public class XTypeViewEngine implements ViewEngine {

@Override

public boolean supports(String view) {

return view.endsWith(“.xtype”);

}

@Override

public void processView(ViewEngineContext context)

throws ViewEngineException {

// Implementation

}

}

JSON-B

• Java API for JSON Binding

• JSR 367 - Early Draft Status

• Read the draft, join the mailing list!

• https://java.net/projects/jsonb-spec/pages/Home

JSON-B The Next Logical Step

• Standardize means of converting JSON to Java objects and vice versa…marshalling/unmarshalling

• Default mapping algorithm for converting Java classes

• Similarities with JAXB

• JAX-RS -> XML = JAXB

• JAX-RS -> JSON = JSON-B

JSON-B Other Proposed Thoughts

• Mapping subset of JSON Documents (JSON Pointer)

• Bi-Directional Mappings

JSON-B Proposed API

• Examples excerpted from Martin Grebac JavaOne 2014 Presentation

import javax.json.bind.*;

public void init(){

JsonContext context = JsonContext.newInstance()

Marshaller marshaller = context.createMarshaller();

//

}

JSON-B Proposed API - Writing

Marshaller marshaller = jsonContext.createMarshaller();

// To String

String str = marshaller.marshal(object);

// To Writer

marshaller.marshal(object, new FileWriter(“somefile.json”));

// To JSONP Parser

JsonParser parser = marshaller.marshal(object);

JSON-B Proposed API - Reading

Unmarshaller unmarshaller = jsonContext.createUnmarshaller();

// From String

MyClass myinstance = unmarshaller.unmarshal(jsonString);

// From Reader

unmarshaller.unmarshal(object, new FileReader(“somefile.json”));

JSON-B Proposed API - Custom Mapping• Utilization of annotations to map fields to JSON

Document Elements

@JsonProperty(“poolType”) public String poolType;

@JsonPropertyOrder(“poolType”,”shape”) public class Pool(){ public String poolType; public String shape; … }

{poolType : “Inground”,}

{poolType : “Inground”,shape : “Rectangle”}

JSON-B Proposed API - Much More

• Transient properties, dates, access

• Instantiation, factories, etc.

• Polymorphism and Inheritence @JsonDiscriminatorValue @JsonDiscriminatorProperty

Java EE Security• JSR 365

• Early Draft Development

• Improve Java EE platform by ensuring that the security API is useful in the modern cloud/PaaS paradigm

• Simplify, standardize, modernize

• Promotes modern concepts (EL and CDI)

Java EE Security• Current JavaEE Security Issues

• Simplify and Improve Portability

• Simple security providers

• Easy pluggability and mapping

• Enabling Existing Security Annotations for all beans

Java EE Security

• Proposed Idea Examples:

• https://github.com/javaee-security-spec/javaee-security-proposals

Java EE Security Proposed Security Provider

@SecurityProvider public class MySecurityProvider { @Inject UserService userService; @OnAuthentication // The parameters could suit the credentials mechanism being used. public Principal getPrincipal(String username, String password) { // Construct the principal using the user service. } @OnAuthorization public String[] getRoles (Principal principal) { // Construct an array of roles using the principal and user service. } }

JCache

• Java Temporary Caching API

• JSR 107 - Started in 2001

• Provides a common way for Java applications to create, access, update, and remove entries from caches

JCache• Provide applications with caching functionality…

particularly the ability to cache Java objects

• Define common set of caching concepts & facilities

• Minimize learning curve

• Maximize portability

• Support in-process and distributed cache implementations

JCache

• Support caching Java objects by-value & optionally by-reference

• Define runtime cache annotations

• Java SE and Java EE

JCache Simple Example from Specification

// resolve a cache manager

CachingProvider cachingProvider = Caching.getCachingProvider();

CacheManager cm = cachingProvider.getCacheManager();

JCache Simple Example from Specification // Configure the Cache

MutableConfiguration<String, Integer> config =

new MutableConfiguration<>()

.setTypes(String.class, Integer.class)

.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR))

.setStatisticsEnabled(true);

// Create the cache

Cache<String, Integer> cache = cacheManager.createCache("simpleCache", config);

JCache Simple Example from Specification

// Perform Operations

cache.put (key, value);

cache.remove(key);

// Obtain cache

Cache<String, Integer> cache = Caching.getCache(“simpleCache”,

String.class, Integer.class);

JCache

• Read the specification, try some of the different available implementations

• Hazelcast in Payara - Example

JCache Hazelcast

• Enable Hazelcast

./asadmin set-hazelcast-configuration --enabled=true –target=server

• Add Annotation to Long Running Methods @CacheResult

public String mySlowMethod(String input1, String input2) {

// Database Query, Obtaining JSON…

}

• Result is cached into Hazelcast using key derived from the two method parameters

Java EE 8: The Horizon is Here

• Start working with Java EE 8 today

• Tools:

• GlassFish v4.1

• Milestones

• Examples and Specification Docs

Java EE 8 Timeline

Q4 2014 Expert Groups

Q1 2015 Early Draft

Q3 2015 Public

Review

Q4 2015 Proposed Final

Draft

Q3 2016 Final

Release

Java EE.Next

Adopt-A-JSR

• Started in 2007, easy way for JUGs to get involved

• What you can do depends upon what you want to do & what spec leads are looking for

• Attend online event on May 26th

Share Feedback

Follow Expert GroupsRead early drafts/javadocTest early versions

Write or speak about the technology!

Learn More

Learn More

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

Contact on Twitter: @javajuneau