Java EE 7 overview

93
Java EE 7: What’s New in the Java EE Platform JDays 2013 Masoud Kalali @MasoudKalali ORACLE

description

The Java EE 7 specification has evolved quite a lot since the early days of the specification. One one hand, Java EE 7 continues the ease of development push that characterized prior releases by bringing further simplification to enterprise development. On the other hand, Java EE 7 tackle new emerging requirements such as HTML 5 support. Last but not least, Java EE 7 also adds new, APIs such as the REST client API in JAX-RS 2.0, WebSockets, JSON-P, JMS 2, Batch Processing, etc. This session will give an technical overview of the Java EE 7 platform. GlassFish 4.0, the world first Java EE 7 Application Server, will be used to demonstrate some of the Java EE 7 features.

Transcript of Java EE 7 overview

Page 1: Java EE 7 overview

Java EE 7: What’s New in the Java EE Platform

JDays 2013 Masoud Kalali @MasoudKalali ORACLE

Page 2: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 2

Agenda

A look at some of the important new features of Java EE 7

Page 3: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 3

Java EE 7 Themes

§  Batch §  Concurrency §  Simplified JMS

§  More annotated POJOs §  Less boilerplate code §  Cohesive integrated

platform

DEVELOPER PRODUCTIVITY

§  WebSockets §  JSON §  Servlet 3.1 NIO §  REST

MEETING ENTERPRISE DEMANDS

Java EE 7

Page 4: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 4

Java EE 7 JSRs New or Updated

§  JPA 2.1 §  JAX-RS 2.0 § EJB 3.2 §  JMS 2.0 § Servlet 3.1 § EL 3.0 §  JSF 2.2

§ CDI 1.1 § Bean Validation 1.1 § WebSocket 1.0 §  JSON 1.0 § Batch Applications 1.0 § Concurrency Utilities 1.0

Page 5: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 5

Java EE 7 Maintenance Releases

§ Common Annotations 1.2 §  JTA 1.2 §  Interceptors 1.2 § Connector 1.7 §  JSP 2.3 §  JASPIC 1.2 §  JACC 1.4 §  JavaMail 1.5 § Web Services 1.4

Page 6: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 6

JSON Processing 1.0

Page 7: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 7

JSON Processing 1.0

§ API to parse and generate JSON § Streaming API (javax.json.stream)

–  Low-level, efficient way to parse/generate JSON –  Similar to StAX API in XML world

§ Object model API (javax.json) –  Simple, easy to use high-level API –  Similar to DOM API in XML world

Page 8: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 8

JSON Processing 1.0

§ Created using –  Json.createParser(…) –  Json.createParserFactory().createParser(…)

§ Parses JSON in streaming way from input sources Event event = parser.next(); //START_OBJECT event = parser.next(); // KEY_NAME event = parser.next(); // VALUE_STRING

§ Parser state events –  START_OBJECT, END_OBJECT, START_ARRAY, END_ARRAY,

KEY_NAME, VALUE_STRING, VALUE_NUMBER, …

Streaming API: Parsing

Page 9: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 9

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser

Page 10: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 10

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser

START_OBJECT

Page 11: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 11

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser KEY_NAME

Page 12: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 12

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser VALUE_STRING

Page 13: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 13

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser VALUE_NUMBER

Page 14: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 14

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser

START_ARRAY

Page 15: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 15

JSON Processing 1.0

{ “firstName”: “John”, “lastName”: “Smith”, “age”: 25, “phoneNumber”: [ { “type”: “home”, “number”: “212 555-1234” }, { “type”: “fax”, “number”: “646 555-4567” } ] }

Streaming Parser

END_ARRAY

Page 16: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 16

JSON Processing 1.0

JsonGenerator gen = Json.createGenerator… .writeStartObject() .write("firstName", "John") .write("lastName", "Smith") .write("age", 25) .writeStartArray(“phones”) .writeStartObject() .write(“type", “home") .write(“number”, “222 555-1234”)) .writeEnd() .writeStartObject() … .writeEnd() .writeEnd() .writeEnd();

Using Streaming API to generate JSON { "firstName": "John", "lastName": "Smith", "age": 25, “phones" : [ { “type”: “home”, “number”: “ 222 555-1234” }, { “type”: “fax”, “number”: “ 646 555-4567” } ] }

Page 17: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 17

JSON Processing 1.0

§  JsonObject/JsonArray – JSON object and array structures –  JsonString and JsonNumber for string and number values

§  JSON builders – build JsonObject and JsonArray §  JsonReader – reads JsonObject and JsonArray §  JsonWriter – writes JsonObject and JsonArray

Object Model API

Page 18: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 18

JsonReader § Reads JsonObject and JsonArray from input source § Uses pluggable JsonParser

JsonReader reader = new JsonReader(io));

JsonObject obj = reader.readObject();

Page 19: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 19

JsonWriter § Writes JsonObject and JsonArray to output source § Uses pluggable JsonGenerator

JsonWriter writer = new JsonWriter(io));

writer.writeObject(obj);

Page 20: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 20

WebSockets 1.0

Page 21: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 21

Java API for WebSocket 1.0 § Bidirectional full-duplex messaging

–  Over a single TCP connection § Annotation-based or interface-based programming model § Server and Client WebSocket Endpoints

–  Annotated: @ServerEndpoint, @ClientEndpoint –  Programmatic: Endpoint

§  Integrated with Java EE web container § Highly configurable § Simple packaging and deployment as wars or jars

Page 22: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 22

Java API for WebSocket 1.0

§ Endpoint –  intercepts websocket lifecycle events

§ MessageHandler –  handles incoming messages for endpoint

§ Session –  represents the active conversation

§ RemoteEndpoint –  represents the other end of the conversation

Main API classes

Page 23: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 23

WebSocket Endpoints

public class MyClient extends Endpoint { public void onOpen(Session session, EndpointConfig ec) { session.addMessageHandler(new MessageHandler.Whole<String>() { public void onMessage(String text) { System.out.println("Message came from the server : " + message”); } } session.getBasicRemote().sendText("Hello!"); } public void onClose(Session session, CloseReason closeReason) { super.onClose(session, closeReason); } }

Programmatic API

Page 24: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 24

WebSocket Endpoints as POJOs

@ClientEndpoint public class MyClient { @OnOpen public void onOpen(Session session) { session.getBasicRemote().sendText(“Hello”); } @OnMessage public void onMessage(String text, Session session) { System.out.println("Message came from the server : " + message); } }

Annotated client endpoint

Page 25: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 25

WebSocket Endpoints as POJOs

@ServerEndpoint("/chat") public class ChatServer { static Set<Session> peers = Collections.synchronizedSet(…); @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnMessage public void onMessage (String message, Session client) { for (Session peer : peers) { peer.getBasicRemote().sendObject(message); } } @OnClose public void onClose(Session peer) { peers.remove(peer); } }

Annotated server endpoint

Page 26: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 26

JAX-RS 2.0

Page 27: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 27

Java API for RESTful Web Services (JAX-RS) 2.0

§ Client API § Asynchronous Processing § Filters and Interceptors § Validation

Page 28: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 28

JAX-RS 1.1

URL url = new URL("http://. . ./atm/balance"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true); conn.setDoOutput(false); conn.setRequestMethod("GET"); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = br.readLine()) != null) { //. . . }

Previous Client API

Page 29: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 29

JAX-RS 2.0 JAX-RS 2.0 Client API

Client client = ClientFactory.newClient();

WebTarget webTarget= client.target(new URI(TARGET_URI)) ;

webTarget.request().post(Entity.text(message));

Page 30: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 30

JAX-RS 2.0

JAX-RS 2.0 Client API

Client client = ClientFactory.newClient(); String name= client.target("http://.../orders/{orderId}/customer") .resolveTemplate(“orderId”, “10”) .queryParam("pin", "9876") .request() .get(String.class);

Page 31: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 31

Async Processing

§  Server API support –  Off-load I/O container threads

§  Long-running operations –  Efficient asynchronous event processing

§  Suspend while waiting for an event §  Resume when event arrives

–  Leverage Servlet 3.x async support (if available)

§  Client API support –  Asynchronous request invocation API

§  Future<RESPONSE>, InvocationCallback<RESPONSE>  

Page 32: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 32

Async Processing: Server-side

@Path("/async/longRunning") public class MyResource { @GET public void longRunningOp(@Suspended AsyncResponse ar) { ar.setTimeoutHandler(new MyTimoutHandler()); ar.setTimeout(15, SECONDS); Executors.newSingleThreadExecutor().submit(new Runnable() { public void run() { … ar.resume(result); } }); } }

Page 33: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 33

Async Processing: Client-side

WebTarget target = client.target("http://.../balance”)… // Start async call and register callback Future<?> handle = target.request().async().get( new InvocationCallback<String>() { void complete(String balance) { … } void failed(InvocationException e) { … } }); // After waiting for too long… if (!handle.isDone()) handle.cancel(true);

Page 34: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 34

Filters & Interceptors

§ Customize JAX-RS request/response processing –  Use Cases: Logging, Compression, Security, Etc.

§  Introduced for client and server APIs § Replace existing proprietary support

–  Provided by most JAX-RS 1.x implementations §  All using slightly different types or semantics

Motivation

Page 35: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 35

Filters & Interceptors

§ Non-wrapping filter chain

–  Filters do not invoke next filter in the chain directly

–  managed by the JAX-RS runtime § Each filter decides to proceed or

break the chain

Filter each incoming/outgoing message

§ Request è Request –  ContainerRequestFilter,  ClientRequestFilter  

§ Response è Response –  ContainerResponseFilter,  ClientResponseFilter

§ Server-side specialties –  @PreMatching,  DynamicFeature

Page 36: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 36

Filters & Interceptors

public class RequestLoggingFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { log(requestContext); // non-wrapping => returns without invoking the next filter } ... }

A Logging Filter Example

Page 37: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 37

Filters & Interceptors

§  Invoked ONLY when/if entity reading/writing occurs

–  Performance boost

§ Wrapping interceptor chain –  Each interceptor invokes the next

one in the chain via context.proceed()  

Intercept entity providers

§ MessageBodyReader interceptor –  ReaderInterceptor interface

§ MessageBodyWriter interceptor –  WriterInterceptor interface

Page 38: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 38

Filters & Interceptors

public class GzipInterceptor implements ReaderInterceptor { @Override Object aroundReadFrom(ReaderInterceptorContext ctx) { InputStream old = ctx.getInputStream(); ctx.setInputStream(new GZIPInputStream(old)); // wrapping => invokes the next interceptor Object entity = ctx.proceed(); ctx.setInputStream(old); return entity; } }

A GZip Reader Interceptor Example

Page 39: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 39

JAX-RS 2.0

@Path("/") class MyResourceClass { @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void registerUser( @NotNull @FormParam("firstName") String firstName, @NotNull @FormParam("lastName") String lastName, @Email @FormParam("email") String email) { ... } … }

Bean Validation

Page 40: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 40

CDI 1.1

Page 41: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 41

CDI: Default enabling Finer scanning control

§ Possible values: all, annotated, none § The annotated is set as the default, scan @*Scoped annotated § all behaves like in Java EE 6 (default if not set) <beans ... version="1.1" bean-discovery-mode="all">! <alternatives>! <class>org.agoncal.book.MockGenerator</class>! </alternatives>!</beans>!

Page 42: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 42

CDI: @Vetoed Veto the processing of the class or package

@Vetoed!

public class NonProcessedBean { ...!

}!

!

package-info.java @Vetoed!

package com.non.processed.package;!

Page 43: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 43

Interceptor 1.2

Page 44: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 44

Interceptors: AroundConstruct Interceptor associated with a constructor

public class LoggingInterceptor {!! @AroundConstruct! private void init(InvocationContext ic) throws Exception{! logger.fine("Entering constructor");! ic.proceed();! logger.fine("Exiting constructor");! }!! @AroundInvoke! public Object logMethod(InvocationContext ic) ... {! // ...! }!}!

Page 45: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 45

Interceptors: @Priority Prioritizing interceptor bindings

§ PLATFORM_BEFORE (0), LIBRARY_BEFORE (1000), APPLICATION (2000), LIBRARY_AFTER (3000), PLATFORM_AFTER (4000)

§ Lower the priority, earlier the invocation!

@Interceptor!@Loggable!@Priority(Interceptor.Priority.LIBRARY_BEFORE + 10)!public class LoggingInterceptor {!! @AroundInvoke! ...!}!

Page 46: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 46

Default Resources

Page 47: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 47

Resource Definition Metadata

§ Specifies resources needed by application –  Enhances configurability in Java EE 7 apps –  Facilitates provisioning in cloud environments –  Java EE 6 introduced DataSourceDefinition

@DataSourceDefinition ( name=“java:app/jdbc/myDB”, className=“oracle.jdbc.pool.OracleDataSource”, isolationLevel=TRANSACTION_REPEATABLE_READ, initialPoolSize=5) @Stateless public class MySessionBean { @Resource(lookup=“java:app/jdbc/myDB”) DataSource my DB; … }

Page 48: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 48

Resource Definition Metadata

§  Java EE 7 adds: –  JMSConnectionFactoryDefinition –  JMSDestinationDefinition –  MailSessionDefinition –  ConnectionFactoryDefinition –  AdministeredObjectDefinition

Page 49: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 49

Default Resources

§  JDBC/JPA: java:comp/DefaultDataSource §  JMS: java:comp/DefaultJMSConnectionFactory § Concurrency Utilities:

–  java: comp/DefaultManagedExecutorService –  java: comp/DefaultManagedScheduledExecutorService –  java: comp/DefaultManagedThreadFactory –  java: comp/DefaultManagedContextService

Preconfigured resources for use by application

Page 50: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 50

JMS 2.0

Page 51: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 51

Java Message Service 2.0

§ Less code, less boilerplate § Fewer objects to manage §  Increased developer productivity §  “Classic API” has also been improved

New JMS Simplified API targeted at ease of development

Page 52: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 52

JMS 2.0

§ New JMSContext interface § Use of CDI injection; new TransactionScope § AutoCloseable JMSContext, Connection, Session, … § Use of runtime exceptions § Method chaining on JMSProducer § Simplified message sending

Simplifications include….

Page 53: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 53

JMS 1.1: Sending a message @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }

13 lines of code just to send a message

Page 54: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 54

JMS 1.1: Sending a message @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }

must create several intermediate objects

Page 55: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 55

JMS 1.1: Sending a message @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }

boilerplate code

Page 56: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 56

JMS 1.1: Sending a message @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }

must close resources after use!

Page 57: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 57

JMS 1.1: Sending a message @Resource(lookup = "java:global/jms/demoConnectionFactory") ConnectionFactory connectionFactory; @Resource(lookup = "java:global/jms/demoQueue") Queue demoQueue; public void sendMessage(String payload) { try { Connection connection = connectionFactory.createConnection(); try { Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(demoQueue); TextMessage textMessage = session.createTextMessage(payload); messageProducer.send(textMessage); } finally { connection.close(); } } catch (JMSException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }

all methods throw checked exceptions

Page 58: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 58

Simplifying the JMS API

§ Simplify existing JMS 1.1 API where it won't break compatibility § Define new simplified API requiring fewer objects

–  JMSContext, JMSProducer, JMSConsumer §  In Java EE, allow JMSContext to be injected and managed by the

container

Strategy

Page 59: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 59

JMS 2.0

@Resource(lookup = “java:global/jms/myConnectionFactory”) ConnectionFactory connectionFactory; @Resource(lookup = “java:global/jms/myQueue”) Queue queue; public void sendMessage(String text) { try (JMSContext context = connectionFactory.createContext();) { context.createProducer().send(queue, text); } catch (JMSRuntimeException ex) { … } }

Sending a message using Simplified API and JMSContext

Page 60: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 60

JMS 2.0

@Inject @JMSConnectionFactory(““java:global/jms/myConnectionFactory”) JMSContext context; @Resource(lookup = “java:global/jms/myQueue”) Queue queue; public void sendMessage(String text) { context.createProducer().send(queue, text); }

Even simpler….

Page 61: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 61

JMS 2.0

@Inject JMSContext context; @Resource(lookup = “java:global/jms/myQueue”) Queue queue; public void sendMessage(String text) { context.createProducer().send(queue, text); }

Even simpler still….

Page 62: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 62

JMS 2.0: New API features

Page 63: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 63

Delivery delay

§ Allows a JMS client to schedule the future delivery of a message § New method on old MessageProducer

§ New method on the new JMSProducer

§ Sets minimum time in ms from that a message should be retained by the messaging system before delivery to a consumer

§ Why? If the business requires deferred processing, e.g. end of day

public JMSProducer setDeliveryDelay(long deliveryDelay)

public void setDeliveryDelay(long deliveryDelay)

Page 64: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 64

Async send

§  Send a message and return immediately without blocking until an acknowledgement has been received from the server.

§  Instead, when the acknowledgement is received, an asynchronous callback will be invoked

§  New methods on MessageProducer

§  Feature also available on JMSProducer §  Why? Allows thread to do other work whilst waiting for the acknowledgement

messageProducer.send(message,completionListener)

Page 65: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 65

Async send

§ Application specifies a CompletionListener instance

public interface CompletionListener { void onCompletion(Message message); void onException(Message message, Exception exception); }

Page 66: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 66

Better handling of "poison" messages

§  JMS 1.1 defines an optional JMS defined message property JMSXDeliveryCount.

–  When used, this is set by the JMS provider when a message is received, and is set to the number of times this message has been delivered (including the first time). The first time is 1, the second time 2, etc

§  JMS 2.0 will make this mandatory § Why? Allows app servers and applications to handle "poisonous"

messages better

Make JMSMXDeliveryCount mandatory

Page 67: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 67

Multiple consumers on a topic subscription

§ Allows scalable consumption of messages from a topic subscription –  multiple threads, multiple JVMs

§ New methods needed for non-durable subscriptions

§ Existing methods used for durable subscriptions

§ Also available on JMSContext

MessageConsumer messageConsumer= session.createSharedConsumer(topic,sharedSubscriptionName);

MessageConsumer messageConsumer= session.createDurableConsumer(topic,durableSubscriptionName);

Page 68: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 68

Concurrency Utilities for Java EE 1.0

Page 69: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 69

Concurrency Utilities for Java EE 1.0

§ Extension of Java SE Concurrency Utilities API § Provides managed objects for submitting tasks and obtaining managed

threads –  ManagedExecutorService –  ManagedScheduledExecutorService –  ManagedThreadFactory –  ContextService

Provides asynchronous capabilities to Java EE components

Page 70: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 70

Concurrency: ManagedExecutor

@Resource ManagedExecutorService executor; !ManagedExecutorService executor = (ManagedExecutorService) ctx .lookup("java:comp/DefaultManagedExecutorService");!

Default ManagedExectuor

Page 71: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 71

Concurrency: ManagedExecutor

<web-app … version="3.1">! <resource-env-ref>! <resource-env-ref-name>! concurrent/myExecutor! </resource-env-ref-name>! <resource-env-ref-type>! javax.enterprise.concurrent.ManagedExecutorService! </resource-env-ref-type>! </resource-env-ref>!</web-app>!

Specify in web.xml

Page 72: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 72

Concurrency: ManagedScheduledExecutor

§ Managed version of ScheduledExecutorService!§ Submit delayed or periodic tasks

@Resource ManagedScheduledExecutorService executor;!

Page 73: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 73

Concurrency: ManagedScheduledExecutor

InitialContext ctx = new InitialContext(); ManagedScheduledExecutorService executor = (ManagedScheduledExecutorService)ctx.lookup( "java:comp/DefaultManagedScheduledExecutorService"); !

§ Can be defined in web.xml as well

Access using JNDI

Page 74: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 74

Concurrency: ManagedScheduledExecutor

§ executor.schedule(new MyCallableTask(), 5, TimeUnit.SECONDS);!

§ executor.scheduleAtFixedRate(new MyRunnableTask(), 2, 3, TimeUnit.SECONDS);!

§ executor.scheduleWithFixedDelay(new MyRunnableTask(), 2, 3, TimeUnit.SECONDS);!

Page 75: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 75

Concurrency: ManagedThreadFactory

§ Extends ThreadFactory @Resource(name = "DefaultManagedThreadFactory") ManagedThreadFactory factory; ManagedThreadFactory factory = (ManagedThreadFactory) ctx.lookup("java:comp/DefaultManagedThreadFactory");

Page 76: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 76

Concurrency: ManagedThreadFactory

§ Thread thread = factory.newThread(new MyTask());

§ ((ManageableThread)thread).isShutdown();

Page 77: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 77

Concurrency: DynamicProxy

§ Create dynamic proxy objects, adds contextual information available for applications running in Java EE environment

§ Classloading, JNDI, Security, …

Page 78: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 78

Concurrency: DynamicProxy

@Resource ContextService service; Runnable proxy = service.createContextualProxy(new MyRunnable(), Runnable.class); Future f = executor.submit(proxy);!

Page 79: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 79

Batch Applications for the Java Platform 1.0

Page 80: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 80

Batch Applications for the Java Platform 1.0

§ Designed for non-interactive, bulk-oriented and long-running tasks § Sequential, parallel, and/or decision-based batch execution § Processing styles

–  Item-oriented: ItemReader, ItemProcessor, ItemWriter interfaces –  Task-oriented: Batchlet interfaces

Page 81: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 81

Batch 1.0

§  Job: entire batch process –  Defined through XML Job Specification Language

§ Step: independent, sequential phase of a job §  JobOperator: interface for managing job processing §  JobRepository: information about past and present jobs

Key concepts

Job Repository

Job Operator Job Step ItemReader

ItemWriter

ItemProcessor

Page 82: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 82

Batch 1.0

§ Chunked step: Item-oriented processing –  ItemReader/ItemProcessor/ItemWriter pattern –  Configurable checkpointing and transactions

§ Batchlet: Task-oriented processing –  Roll-your-own batch pattern –  Runs to completion and exits

§  Job can include both types of steps

Job steps

Page 83: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 83

Batch 1.0

<job id="myJob" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0"> <step id="step1" next="step2"> <chunk item-count="3"> <reader ref="myItemReader"></reader> <processor ref="myItemProcessor"></processor> <writer ref="myItemWriter"></writer> </chunk> </step> <step id="step2" next=“step3”> <batchlet ref="myBatchlet"/> </step> <step id="step3" > <chunk item-count="3"> <reader ref="myOtherItemReader"></reader> <processor ref="myOtherItemProcessor"></processor> <writer ref="myOtherItemWriter"></writer> </chunk> </step> </job>

Job specification language

Page 84: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 84

EJB 3.2

Page 85: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 85

EJB 3.2 new features and improvments

§ Singleton Session Beans § EJB 3.1 Lite:

§  Includes non-persisted TimerService §  Local asynchronous invocation of session beans

Page 86: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 86

Java Persistence API 2.1

Page 87: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 87

Java Persistence API 2.1

§ Generation of database tables, indexes, constraints, etc. § Designed for flexibility

–  Scenarios: (iterative) prototyping; production; provisioning environments –  Generate from object/relational metadata (annotations and/or XML) –  Generate from bundled SQL DDL scripts; also SQL load scripts –  Generate directly into database –  Generate into SQL DDL scripts

§ Process controlled by metadata or runtime properties

Schema generation

Page 88: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 88

JPA 2.1

<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/

XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name=“samplePU" transaction-type="JTA"> <jta-data-source>jdbc/mypu</jta-data-source> <properties> <property name="javax.persistence.schema-generation.database.action" value="none" /> <property name="javax.persistence.schema-generation.scripts.action" value=“drop-and-create"/> <property name="javax.persistence.schema-generation.scripts.create-target" value=”//temp/create.sql"/

> <property name="javax.persistence.schema-generation.scripts.drop-target" value=“/temp/drop.sql"/> </properties> </persistence-unit> </persistence>

Schema generation into scripts

Page 89: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 89

JPA 2.1

<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/

XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name=“samplePU" transaction-type="JTA"> <jta-data-source>jdbc/mypu</jta-data-source> <properties> <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> <property name="javax.persistence.schema-generation.create-source" value="script"/> <property name="javax.persistence.schema-generation.drop-source" value="script"/> <property name="javax.persistence.schema-generation.create-script-source" value="META-INF/create.sql"/> <property name="javax.persistence.schema-generation.drop-script-source" value="META-INF/drop.sql"/> <property name="javax.persistence.sql-load-script-source" value="META-INF/load.sql"/> </properties> </persistence-unit> </persistence>

Schema generation from scripts

Page 90: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 90

JPA 2.1

§ Stored procedure support: @NamedStoredProcedureQuery § Dynamically Defining Named Queries § Enhancements To Queries § @Converter and @Convert(…)

Some more features

Page 91: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 91

Java EE 7 Summary

§  Batch §  Concurrency §  Simplified JMS

§  More annotated POJOs §  Less boilerplate code §  Cohesive integrated

platform

DEVELOPER PRODUCTIVITY

§  WebSockets §  JSON §  Servlet 3.1 NIO §  REST

MEETING ENTERPRISE DEMANDS

Java EE 7

Page 92: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 92

DOWNLOAD Java EE 7 SDK

oracle.com/javaee

GlassFish 4.0 Full Platform or Web Profile

glassfish.org

Page 93: Java EE 7 overview

Copyright © 2012, Oracle and/or its affiliates. All rights reserved. 93

? Questions…