the java ee 7 platform: productivity & html5 at san francisco jug
DESCRIPTION
The Java EE 7 Platform: Productivity & HTML5 at San Francisco Java User GTRANSCRIPT
Main sponsor
The Java EE 7 Pla,orm: Produc4vity & HTML5 Arun Gupta, Java EE & GlassFish Guy blogs.oracle.com/arungupta, @arungupta
2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle.
3 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java EE 6 Platform December 10, 2009
4 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java EE 6 – Key Statistics
• 40+ Million Java EE 6 Component Downloads • #1 Choice for Enterprise Developers • #1 Application Development Platform • Fastest implementation of a Java EE release
5 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Top Ten Features in Java EE 6
1. EJB packaging in a WAR 2. Type-safe dependency injection 3. Optional deployment descriptors (web.xml, faces-config.xml)
4. JSF standardizing on Facelets 5. One class per EJB 6. Servlet and CDI extension points 7. CDI Events 8. EJBContainer API 9. Cron-based @Schedule!10. Web Profile
6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java EE 7 Revised Scope Productivity and HTML5
• Higher Productivity – Less Boilerplate – Richer Functionality – More Defaults
• HTML5 Support – WebSocket – JSON – HTML5 Forms
7 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java EE 7 – Candidate JSRs
Connector 1.6
Managed Beans 1.0 EJB 3.2
Servlet 3.1
Portable Extensions
JSF 2.2 JAX-RS 2.0
Bea
n Va
lidat
ion
1.1
JMS 2.0 JPA 2.1
EL 3.0
JTA 1.2
JSP 2.2
Interceptors 1.1 CDI 1.1 Common Annotations 1.1
Updated Major Release
New
Java Caching API (JSR 107)
Java API for WebSocket (JSR 356)
Batch Applications (JSR 352)
Java API for JSON (JSR 353)
Concurrency Utilities (JSR 236)
8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0
• Client API • Message Filters & Entity Interceptors • Asynchronous Processing – Server & Client • Hypermedia Support • Common Configuration
9 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client API - Before
String address = String.format("http://…/orders/%0$s/customer?shipped=%1$b", "10", true); !URL url = new URL(address);!HttpURLConnection conn = (HttpURLConnection) url.openConnection();!conn.setRequestMethod("GET");!conn.setDoInput(true);!conn.setDoOutput(false);! !BufferedReader br = new BufferedReader( new InputStreamReader(conn.getInputStream()));!String line;!while ((line = br.readLine()) != null) {! //. . .!}!
10 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client API - Now
// Get instance of Client Client client = ClientFactory.newClient(); // Get customer name for the shipped products String name = client.target(“../orders/{orderId}/customer”) .resolveTemplate(”orderId", ”10”) .queryParam(”shipped", ”true”) .request() .get(String.class);!
11 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client API - Now
!!// Withdraw some money Money mon = client.target("http://.../atm/{cardId}/withdrawal")! .resolveTemplate("cardId", "111122223333")! .queryParam("pin", "9876")! .request("application/json")! .post(text("50.0"), Money.class);!
12 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client API - Dynamic
!Invocation inv1 = ! client.target("http://.../atm/{cardId}/balance")…! .request().buildGet();!!!Invocation inv2 = ! client.target("http://.../atm/{cardId}/withdraw")…! .request()! .buildPost(text("50.0"));!
13 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client API - Dynamic
!Collection<Invocation> invocations = Arrays.asList(inv1, inv2);!!Collection<Response> responses = Collections.transform(! invocations, ! new F<Invocation, Response>() {! public Response apply(Invocation inv) {! return inv.invoke(); ! }! });!
14 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Filters
@Provider class LoggingFilter implements ContainerRequestFilter {! @Override public void filter(ContainerRequestContext context) { logRequest(ctx.getRequest()); // non-wrapping => returns without invoking next filter } }!
15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Entity 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;! }!}!
16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Filters & Interceptors – Client-side
Applica>on Request Filter Filter
Network Transport … … Response Filter Filter
write(…)
Writer Interceptor
… MBW
read(…) -‐ op>onal
… MBR
Writer Interceptor
Reader Interceptor
Reader Interceptor
17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Filters & Interceptors – Server-side
Response
Applica>on
Filter Filter Network
… Response Filter Filter
write(…)
… MBW Writer Interceptor
Writer Interceptor
Filter Filter … Request Request
read(…) -‐ op>onal
Reader Interceptor
… MBR Reader Interceptor
Filter Filter
Resource Matching
@PreMatching
18 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Client-side Async
Client client = ClientFactory.newClient(); Future<String> future = client.target("http://.../atm/{card}/balance") .pathParam("card", "1111222233334444") .queryParam("pin", "1234") .request("text/plain") .async() .get( new InvocationCallback<String>() { public void completed(String result) { } public void failed(InvocationException e) { } } );!
19 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Server-side Async
@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);# }! });! }!}!
20 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Common Configuration
public class MyApp extends javax.ws.rs.core.Application {! public Set<Class<?>> getClasses() {! Set<Class<?>> classes = new HashSet<…>();! …! classes.add(JsonMessageBodyReader.class);! classes.add(JsonMessageBodyWriter.class);! classes.add(JsonpInterceptor.class);! …! return classes;! }!}! public Set<Class<?>> getClasses() {!
…! classes.add(JsonFeature.class);! …!}!
21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for RESTful Web Services 2.0 Server-side content negotiation
@Path("/") class ProductResource {! @GET @Produces({"text/xml;qs=0.75", "application/json"}) public Product[] getProducts() { . . . } }!
22 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0
• Less verbose • Reduce boilerplate code • Resource injection • Connection, Session, and other objects are AutoCloseable
• Requires Resource Adapter for Java EE containers • Simplified API in both Java SE and EE
Simplify the existing API
23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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
24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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
25 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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);! }!} !
redundant and misleading arguments
26 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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
27 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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!
28 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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
29 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Sending message using JMS 1.1
@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);! }!} !
pre-create app-server specific resources
30 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Simplify the existing API
• Need to maintain backwards compatibility limits scope for change
• New methods on javax.jms.Connection: – Existing method (will remain) connection.createSession(transacted,deliveryMode)#
– New method mainly for Java SE connection.createSession(sessionMode)!
– New method mainly for Java EE connection.createSession()#
31 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Simpler API to close JMS objects
• Make JMS objects implement AutoCloseable!– Connection #– Session #– MessageProducer #– MessageConsumer #– QueueBrowser#
• Requires Java SE 7
32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Simpler API to close JMS objects
@Resource(lookup = "jms/connFactory") ConnectionFactory cf; !
@Resource(lookup="jms/inboundQueue")!Destination dest;! !public void sendMessage (String payload) throws JMSException {! try ( Connection conn = connectionFactory.createConnection(); # Session session = conn.createSession();# MessageProducer producer = session.createProducer(dest);# ){ ! Message mess = sess.createTextMessage(payload); ! producer.send(mess); ! } catch(JMSException e){ ! // exception handling ! } }!
Create closeable resources in a try-with-resources block
close() is called automatically at end of block
33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0 Introducing JMSContext and JMSProducer
@Resource(lookup = "java:global/jms/demoConnectionFactory")!ConnectionFactory connectionFactory; !!@Resource(lookup = "java:global/jms/demoQueue")!Queue demoQueue;! !public void sendMessage (String payload) {! try (JMSContext context = connectionFactory.createContext();){! context.createProducer().send(demoQueue, payload);# } catch (JMSRuntimeException ex) {! // exception handling! }!}!
close() is called automatically at end of block
JMSContext combines Connection and Session
Payload can be sent directly
No checked exceptions thrown
34 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Message Service 2.0
@Inject JMSContext context;!!
@Resource(lookup = "java:global/jms/demoQueue”) Queue demoQueue;!!public void sendMessage(String payload) {! context.createProducer().send(demoQueue, payload);!}!
Default resource definition Default resource definition
Or @JmsConnectionFactory#
13 lines è1 line#
35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0
• API to parse and generate JSON • Streaming API
– Low-level, efficient way to parse/generate JSON – Provides pluggability for parsers/generators
• Object Model – Simple, easy-to-use high-level API – Implemented on top of Streaming API
• Binding JSON to Java objects forthcoming
36 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0
• JsonParser – Parses JSON in a streaming way from input sources
• Similar to StaX’s XMLStreamReader, a pull parser – Created using
• Json.createParser(…)!• Json.createParserFactory().createParser(…)!
– Parser state events • START_ARRAY, END_ARRAY, START_OBJECT, END_OBJECT, ...
Streaming API – JsonParser and JsonGenerator
37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0 Streaming API – JsonParser {
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
38 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
START_OBJECT
Java API for JSON Processing 1.0 Streaming API – JsonParser
39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
KEY_NAME
Java API for JSON Processing 1.0 Streaming API – JsonParser
40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
VALUE_STRING
Java API for JSON Processing 1.0 Streaming API – JsonParser
41 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
VALUE_NUMBER
Java API for JSON Processing 1.0 Streaming API – JsonParser
42 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
START_ARRAY
Java API for JSON Processing 1.0 Streaming API – JsonParser
43 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{
"firstName": "John", "lastName": "Smith", "age": 25,
"phoneNumber": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}
END_ARRAY
Java API for JSON Processing 1.0 Streaming API – JsonParser
44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
{!
"firstName": "John", "lastName": "Smith", "age": 25,!
"phoneNumber": [!
{ "type": "home", "number": "212 555-1234" },!
{ "type": "fax", "number": "646 555-4567" }!
]!
}!
Iterator<Event> it = parser.iterator();!
Event event = it.next(); // START_OBJECT event = it.next(); // KEY_NAME event = it.next(); // VALUE_STRING String name = parser.getString(); // "John”
!
Java API for JSON Processing 1.0 Streaming API – JsonParser
45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0
• JsonGenerator – Generates JSON in a streaming way to output sources
• Similar to StaX’s XMLStreamWriter – Created using
• Json.createGenerator(…)!• Json.createGeneratorFactory().createGenerator(…)!
– Optionally, configured with features • E.g. for pretty printing
Streaming API – JsonParser and JsonGenerator
46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0 Streaming API – JsonGenerator
"phoneNumber": [! { "type": "home", "number": ”408-123-4567” },! { "type": ”work", "number": ”408-987-6543” }! ]!
JsonGenerator jg = Json.createGenerator(…); jg. .beginArray("phoneNumber") .beginObject() .add("type", "home") .add("number", "408-123-4567") .endObject() .beginObject() .add("type", ”work") .add("number", "408-987-6543") .endObject() .endArray(); jg.close(); !
47 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0
• JsonObject/JsonArray – JSON object and array structures – JsonString and JsonNumber for string and number values
• JsonBuilder – Builds JsonObject and JsonArray • JsonReader – Reads JsonObject and JsonArray from
input source • JsonWriter – Writes JsonObject and JsonArray to
output source
Object Model API
48 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0 DOM API – JsonReader
• Reads JsonObject and JsonArray from input source – i/o Reader, InputStream (+ encoding)
• Optionally, configured with features • Uses pluggable JsonParser!
// Reads a JSON object try(JsonReader reader = new JsonReader(io)) {!
JsonObject obj = reader.readObject();!
}!!
49 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0 DOM API – Writer
• Writes JsonObject and JsonArray to output source – i/o Writer, OutputStream (+ encoding)
• Optionally, configured with features. For e.g. pretty printing
• Uses pluggable JsonGenerator // Writes a JSON object try(JsonWriter writer = new JsonWriter(io)) {!
writer.writeObject(obj);!
}!
!
50 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for JSON Processing 1.0 Configuration
• Configuration is a set of parser/generator features – Pretty Printing, Single-Quoted strings
• Supports extensibility (custom features) • Can be used in streaming & object-model API // Writes a JSON object prettily!
JsonConfiguration config = new JsonConfiguration().withPrettyPrinting();!
try(JsonWriter writer = new JsonWriter(io, config)) { writer.writeObject(obj);!
}!
51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
• API for WebSocket Client/Endpoints – Annotation-driven (@WebSocketEndpoint) – Interface-driven (Endpoint) – Client (@WebSocketClient)
• SPI for extensions and data frames – Compression and Multiplexing – WebSocket opening handshake negotiation
• Integration with Java EE Web container
52 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0 Hello World – POJO/Annotation-driven import javax.websocket.*; @WebSocketEndpoint("/hello") public class HelloBean { @WebSocketMessage public String sayHello(String name) { return “Hello “ + name; } }!
53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0 WebSocket Annotations
Annotation Level Purpose
@WebSocketEndpoint! class Turns a POJO into a WebSocket Endpoint
@@WebSocketClient! class Turns a POJO into a WebSocket Client
@WebSocketOpen! method Intercepts WebSocket Open events
@WebSocketClose! method Intercepts WebSocket Close events
@WebSocketMessage! method Intercepts WebSocket Message events
@WebSocketPathParam! method parameter Flags a matched path segment of a URI-template
@WebSocketError! method Intercepts errors during a conversation
54 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0 @WebSocketEndpoint Attributes
value! Relative URI or URI template e.g. “/hello” or “/chat/{subscriber-level}”
decoders! list of message decoder classnames
encoders! list of message encoder classnames
subprotocols! list of the names of the supported subprotocols
55 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
@WebSocketEndpoint( value="/hello", encoders={MyMessage.class}, decoders={MyMessage.class} ) public class MyEndpoint { . . . }!
!
!
Custom Payloads
56 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
public class MyMessage implements Decoder.Text<MyMessage>, Encoder.Text<MyMessage> { private JsonObject jsonObject; public MyMessage decode(String s) { jsonObject = new JsonReader(new StringReader(s)).readObject(); return this;!
}!
public boolean willDecode(String string) { return true; // Only if can process the payload }!
!
public String encode(MyMessage myMessage) { return myMessage.jsonObject.toString(); } }!
Custom Payloads – Text
57 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
public class MyMessage implements Decoder.Binary<MyMessage>, Encoder.Binary<MyMessage> { public MyMessage decode(byte[] bytes) { . . . return this;!
}!
public boolean willDecode(byte[] bytes) { . . . return true; // Only if can process the payload }!
!
public byte[] encode(MyMessage myMessage) { . . . } }!
Custom Payloads – Binary
58 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
@WebSocketEndpoint("/chat")!
public class ChatBean {!
Set<Session> peers = Collections.synchronizedSet(…); @WebSocketOpen public void onOpen(Session peer) { peers.add(peer); } @WebSocketClose public void onClose(Session peer) { peers.remove(peer); } . . .!
Chat
59 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
. . . @WebSocketMessage#
public void message(String message, Session client) {!
for (Session peer : peers) { peer.getRemote().sendObject(message); } } }!
Chat (contd.)
60 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
• Level 1 only URI Template Matching
@WebSocketEndpoint(“/orders/{order-id}”) public class MyEndpoint { @WebSocketMessage public void processOrder( @WebSocketPathParam(“order-id”)String orderId) { . . . } }
61 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
• A parameter type that can be decoded in incoming message – String, byte[], ByteBuffer or any type for which there is a
decoder
• An optional Session parameter • 0..n String parameters annotated with @WebSocketPathParameter!
• A return type that can be encoded in outgoing message – String, byte[], ByteBuffer or any type for which there is a
encoder
Which methods can be @WebSocketMessage ?
62 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0 Hello World – Interface-driven import javax.websocket.*;!!public class HelloServer extends Endpoint { @Override public void onOpen(Session session) { session.addMessageHandler(new MessageHandler.Text() { public void onMessage(String name) { try { session.getRemote().sendString(“Hello “ + name); } catch (IOException ex) { } } }); } }!
63 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
public class MyEndpointConfig implements ServerEndpointConfiguration { String getPath() { return “/endpoint”; } Class<? extends Endpoint> getEndpointClass() { return HelloServer.class;!
} . . . }!
!
Hello World – Interface-driven Packaging
64 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java API for WebSocket 1.0
@WebSocketClient public class HelloClient { @WebSocketMessage public void message(String message, Session session) { // process message from server } } !
WebSocketContainer c = ContainerProvider.getClientContainer(); c.connectToServer(HelloClient.class, “…/hello”);!
!
Hello World Client
65 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Bean Validation 1.1
• Open: Spec, Reference Implementation, TCK • Alignment with Dependency Injection • Method-level validation
– Constraints on parameters and return values – Check pre-/post-conditions
66 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Bean Validation 1.1 Method Parameter and Result Validation
Built-in
Custom
@Future public Date getAppointment() { //. . . }!
public void placeOrder( @NotNull String productName, @NotNull @Max(“10”) Integer quantity, @Customer String customer) { //. . . }!
Need more slides here
67 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
• Suited for non-interactive, bulk-oriented and long-running tasks
• Computationally intensive • Can execute sequentially/parallel • May be initiated
– Adhoc – Scheduled
• No scheduling APIs included
68 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
• Job: Entire batch process – Put together through a Job Specification Language (XML)
• Step: Independent, sequential phase of a job – ItemReader: Retrieval of input for a step, one at a time – ItemProcessor: Business processing of an item – ItemWriter: Output of an item, chunks of items at a time
• JobOperator: Manage batch processing • JobRepository: Metadata for jobs
Batch Applications for the Java Platform 1.0 Concepts
69 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
• JobInstance: Logical Job Run • JobExecution: Single attempt to run a job • StepExecution: Single attempt to run a step
Concepts
70 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
• Chunked: Item-oriented processing – Using a reader-processor-writer pattern – Configurable check-pointing and transactions – E.g. sending monthly bank statements
• Batchlet: Task-oriented processing – Roll-your-own batch pattern – Invoke once, runs to completion, and exits – E.g., file transfer
Concepts: Types of Step
71 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
• Primary processing style – Read and Process one item – Do the above ‘n’ times (called ‘commit interval’) – Write the ‘n’ processed items – Commit the transaction
Concepts: Chunked Step
72 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
• Specifies a job, steps and directs their execution • Implemented in XML
– Referred as “Job XML”
• Supports inheritance of job, step, flow, and split
Job Specification Language
73 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
<job id=“myJob”> <step id=“init”> <chunk reader=“R” writer=W” processor=“P” /> <next on=“initialized” to=“process”/> <fail on=“initError”/> </step> <step id=“process”> <batchlet ref=“ProcessAndEmail”/> <end on=”success”/> <fail on=”*” exit-status=“FAILURE”/> </step> </job> !
Job Specification Language – Simple Job
74 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0 <step id=”sendStatements”>! <chunk reader=”AccountReader”! processor=”AccountProcessor” writer=”EmailWriter”! chunk-size=”10” />!</step>!
@ReadItem public Account readAccount() { // read account using JPA!}!!
@ProcessItem#public Account processAccount(Account account) { // calculate balance!}!!@WriteItems#
public void sendEmail(List<Account> accounts) { // use JavaMail to send email!}!!
Job Specification Language – Chunked Step
75 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0
<step id=”transferFile”>! <batchlet ref=“MyFileTransfer” />!</step>!
@Process#public void transferFile(String name) { // Transfer file!}!!
Job Specification Language: Batchlet
76 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0 Concepts: Listeners • Job listener: Interpose on batch execution
– @BeforeJob, @AfterJob
• Step listener – @BeforeStep, @AfterStep
• Chunk listener – @BeforeChunk, @AfterChunk, @BeforeCheckpoint, @AfterCheckpoint!
• Item read/process/write listener, . . .
77 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Batch Applications for the Java Platform 1.0 Concepts: Job Parallelization • Steps can be run in parallel • Parallelization models
– Partitioned • Multiple instances across multiple threads • Each thread runs the same step, unique parameters identify data • E.g., process accounts from 1-100, 101-200, etc.
– Concurrent • Steps defined by a split run concurrently across multiple threads • One step per thread
78 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• API and semantics for temporary, in-memory caching of Java objects – Object creation – Shared access – Spooling – Invalidation – Consistency across JVMs
• SPI for implementers
79 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• javax.cache.*!• Delivered as part of Java EE 7
– Immediately usable by Java EE 6, Spring and Guice – Immediately usable by any Java app
• Not a Data Grid specification – JSR 107 does not mandate a topology – JSR 347 does: builds on JSR 107
80 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• java.util.ConcurrentMap with the following additional features – Read/Write-through caching
• Using cache as the primary data source – Cache event listeners – Statistics – Transactions including isolation levels – Annotations – Generics
Key Concepts
81 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• Designed to support “local” and “distributed” caching
• Caching strategies supported – By value (default) – By reference (not suitable for “distributed” caching)
82 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• Cache Manager =>Caches • Cache => Entries • Entry => Key,Value
• CacheManager acquired via CacheManagerFactory!• CacheManagerFactory acquired via Service Provider
– META-INF/services/javax.cache.spi.CachingProvider!
Key Concepts
83 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
CacheManager cacheManager = CacheManagerFactory.getCacheManager(); or fully CacheManager cacheManager = CacheManagerFactory.getCacheManager(DEFAULT_CACHE_MANAGER_NAME, Thread.currentThread().getContextClassLoader()); !
Code Sample – Creating a CacheManager
84 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• Obtain a cache from CacheManager Cache<Integer, Date> cache = cacheManager.getCache(“testCache”);!
Code Sample – Using a Cache
85 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• Configure a cache which is set for “read-through”
CacheManager cacheManager = getCacheManager(); Cache testCache = cacheManager.createCacheBuilder(“testCache”) .setReadThrough(true) .setSize(Size.UNLIMITED) .setExpiry(Duration.ETERNAL) .build(); !
!
Code Sample – Configure a Cache
86 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Integer key = 1; cache.put(key, new Date()); !
!
Code Sample – Putting a value in a cache
87 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Date value = cache.get(key); !
!
Code Sample – Getting a value from a cache
88 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
Cache<Integer, Date> cache = cacheManager.getCache(cacheName); Integer key = 1; cache.remove(1); !
Code Sample – Removing a value from a cache
89 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
public class BlogManager { !
@CachePut(cacheName=”blogManager”) public void createEntry( @CacheKeyParam String title, @CacheValue Blog blog) {...} . . .!
Code Sample – Blog
90 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
. . . @CacheResult(cacheName="blogManager") public Blog getBlogEntry(String title) {...} !
@CacheResult(cacheName="blogManager") public Blog getEntryCached( String randomArg, @CacheKeyParam String title) {...} . . .!
Code Sample – Blog
91 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
. . . @CacheRemoveEntry(cacheName="blogManager") public void removeBlogEntry(String title) {...} !
@CacheRemoveAll(cacheName="blogManager") public void removeAllBlogs() {...}!
} !
Annotations – Blog Sample
92 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Temporary Caching API 1.0
• Terracotta – Ehcache • Oracle – Coherence • JBoss – Inifinispan • IBM – ExtremeeScale • SpringSorce – Gemfire • Google App Engine – Java memcache client • Spymemcache memcache client
Expected Implementations
93 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• Schema Generation • Unsynchronized Persistence Contexts • Converters • Bulk update/delete using Criteria!• User-defined functions using FUNCTION • Stored Procedure Query
94 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• What: Generation of database artifacts – Tables, indexes, constraints, generators, …
• Scenarios: Iterative prototyping, production, database provisioning (e.g. in cloud)
• To: Database, DDL, Both • From: O/R mapping metadata, SQL DDL scripts • When: Prior to app deployment
Schema Generation
95 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• javax.persistence.schema-generation-action!– “none”, “create”, “drop-and-create”, “drop”
• javax.persistence.schema-generation-target!– “database”, “scripts”, “database-and-scripts”
• javax.persistence.ddl-create-script-target/source!• javax.persistence.ddl-drop-script-target/source!• javax.persistence.sql-load-script-source!• . . .!
Schema Generation Properties
96 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1 Schema Generation Example from ORM Metadata
// mapped to EMPLOYEE table in default schema @Entity public class Employee {#
@Id private int id; // mapped to ID column as primary key private String name; // mapped to NAME column, VARCHAR(255) ...#
@ManyToOne // mapped to DEPT_ID foreign key column private Department dept;#
...#
}#
97 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• Specifies additional indexes • Ordering of columns must be preserved • Can be specified as part of Table, SecondaryTable, CollectionTable, JoinTable, TableGenerator
Schema Generation – @Index
@Table(indexes= {@Index(columnList=“NAME”)# @Index(columnList=“DEPT_ID”)})#@Entity public class Employee {! @Id private Integer id; ! private String name; ! ...! @ManyToOne! private Department dept;! …!}!
98 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• Overrides persistence provider’s default foreign key • Specifies foreign key constraint (or removal) • Can be specified as part of JoinColumn(s),
MapKeyJoinColumn(s), PrimaryKeyJoinColumn(s)
Schema Generation – @ForeignKey
@Entity public class Employee {! @Id private int id; ! private String name; ! ...! @ManyToOne! @JoinColumn(foreignKey=@ForeignKey(# foreignKeyDefinition= # “FOREIGN KEY (MANAGER_ID) REFERENCES MANAGER ON DELETE SET NULL”))! private Manager manager;!}!
99 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1
• Synchronized: TX are flushed to database on commit • Unsynchronized: Not synchronized with current JTA
transaction unless joinTransaction is called – Cannot do database writes – Can still call persist, merge, remove, refresh
• Applicable to container- and application-managed • Usecase
– Modeling conversations – Track persistent changes, commit only at end of conversation
Unsynchronized Persistence Contexts
100 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1 Unsynchronized Persistence Contexts Sample
@Stateful public class ShoppingCart {!
!@PersistenceContext(type=EXTENDED, synchronization=UNSYNCHRONIZED) !
EntityManager em;!
!
@PersistenceContext EntityManager dataMiningEM;!
!
Customer customer;!
Order order;!
!
public void startToShop(Integer custId) {!
customer = em.find(Customer.class, custId);!
order = new Order(); }!
!
!
101 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1 Unsynchronized Persistence Contexts Sample
!
public Collection<Book> viewCart() {!
// suggest other books based on interests!
...}!
!
// purchase the books!
public void confirmOrder() {!
em.joinTransaction(); #
customer.addOrder(order); !
}!
!
!
!
102 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1 Stored Procedure Query @Entity @NamedStoredProcedureQuery(name="topGiftsStoredProcedure”, procedureName="Top10Gifts") public class Product { . . . }!
StoredProcedreQuery query = EntityManager.createNamedStoredProcedureQuery("topGiftsStoredProcedure");!query.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT);!query.setParameter(1, "top10");!query.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN);!query.setParameter(2, 100);!// there are other setParameter methods for defining the temporal type . . .!query.execute();!String response = query.getOutputParameterValue(1);!!
103 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Persistence API 2.1 Update and Delete in Criteria CriteriaUpdate<Customer> q = cb.createCriteriaUpdate(Customer.class); Root<Customer> c = q.from(Customer.class); q.set(c.get(Customer_.status), "outstanding") .where(cb.lt(c.get(Customer_.balance), 10000)); . . .!@PersistenceContext EntityManager em; Query query = em.createQuery(q); query.executeUpdate(); !
CriteriaDelete<Customer> q = cb.createCriteriaDelete(Customer.class); Root<Customer> c = q.from(Customer.class); q.where(cb.equal(c.get(Customer_.status), "inactive"), cb.isEmpty(c.get(Customer_.orders))); . . . !
UPDATE Customer c!SET c.status = 'outstanding'!WHERE c.balance < 10000!
DELETE FROM Customer c WHERE c.status = 'inactive' AND c.orders IS EMPTY!
104 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
• @Singleton!• @Asynchronous!• @Schedule!• Portable JNDI Name • EJBContainer.createEJBContainer!• EJB 3.1 Lite
EJBs Today
105 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enteprise JavaBeans 3.2 Updates: Opt-in Transactions in SFSB Lifecycle Callbacks
@Stateful public class HelloBean { @PersistenceContext(type=PersistenceContextType.EXTENDED) private EntityManager em;!
!@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)#
@PostConstruct# public void init() { . . . }! @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) @PreDestroy#
public void destroy () { . . . }!
106 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2 Updates: Opt-out passivation of Stateful Session Beans
@Stateful(passivationCapable=false)#public class HelloBean {! private NonSerializableType ref = …;!! …!}!
107 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
@Stateless public class Bean implements Foo, Bar { }!
Updates: Simplified Rules for Local/Remote Client Views
@Local @Stateless public class Bean implements Foo, Bar { }!
@Remote @Stateless public class Bean implements Foo, Bar { }!
Local
Remote
108 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
@Remote public interface Foo { . . . } public interface Bar { . . . } @Stateless public class Bean implements Foo, Bar { }!
Updates: Simplified Rules for Local/Remote Client Views
Remote
109 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
• Enhanced list of standard activation-config properties – destinationLookup – connectionFactoryLookup – clientId – subscriptionName – shareSubscriptions
Updates: Alignment with JMS 2.0
110 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
• Embeddable container implements Autocloseable!• Removed restriction to use java.io package • Thread context in Singleton is guaranteed to be
thread-safe • . . .
Updates: Miscellaneous
111 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
• Asynchronous session bean • Non-persistent EJB Timer service
More Features in EJB.Lite
112 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Enterprise JavaBeans 3.2
• Optional features – EJB 2.1 and earlier Entity Bean Component Contract for CMP
and BMP – Client view of an EJB 2.1 Entity Bean – EJB QL: Query Language for CMP Query Methods – JAX-RS-based Web service endpoint and client
• Specification split into Core and Optional – Easy to read
Pruning
113 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
• Non-blocking I/O • Protocol Upgrade • Security Enhancements
114 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
public class TestServlet extends HttpServlet protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletInputStream input = request.getInputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = input.read(b)) != -1) { . . . } } }!
Non-blocking IO - Traditional
115 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
• Two new listeners – ReadListener!– WriteListener!
• Register using ServletInputStream and ServletOutputStream!
Non-blocking I/O – New APIs
116 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
• ServletInputStream!– public void setReadListener(ReadListener listener)!
– public boolean isFinished()!– public boolean isReady()!
• ServletOutputStream!– public setWriteListener(WriteListener listener)!– public boolean canWrite()!
Non-block I/O: New APIs
117 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
public interface ReadListener extends EventListener { public void onDataAvailable(); pubic void onAllDataRead(); public void onError(); }!
public interface WriteListener extends EventListener { public void onWritePossible(); public void onError(); }!
Non-blocking I/O Listeners
118 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
AsyncContext context = request.startAsync(); ServletInputStream input = request.getInputStream(); input.setReadListener( new MyReadListener(input, context)); !
Non-blocking I/O: doGet Code Sample
119 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
@Override public void onDataAvailable() { try { StringBuilder sb = new StringBuilder(); int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); System.out.println("--> " + data); } } catch (IOException ex) { . . . } } . . . !
Non-blocking I/O: MyReadListener Code Sample
120 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
. . . @Override public void onAllDataRead() { context.complete(); } @Override public void onError(Throwable t) { t.printStackTrace(); context.complete(); } !
Non-blocking I/O: MyListener Code Sample
121 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1
• <T extends HttpUpgradeHandler> T HttpServletRequest.upgrade(Class<T> class) throws IOException;
• HttpUpgradeHandler!– init(WebConnection wc);!– destroy();!
HTTP Protocol Upgrade Mechanism
122 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Servlet 3.1 Security Enhancements
123 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Provide concurrency capabilities to Java EE application components – Without compromising container integrity
• Support simple (common) and advanced concurrency patterns
Goals
124 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Provide consistency between Java SE and Java EE concurrency programming model – Extend the Concurrency Utilities API (JSR 166)
• java.util.concurrent package • Largely by providing a managed version of java.util.concurrent.ExecutorService!
Goals
125 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Manageable version of java.util.concurrent.ExecutorService – Lookup using JNDI (No CDI ??)
• Java EE components create task classes – Implement java.lang.Runnable or java.util.concurrent.Callable!
• Submitted using submit or invoke methods • Multiple (configurable) executors are permitted
ManagedExecutorService
126 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Recommended to bind in java:comp/env/concurrent subcontext
<resource-env-ref> <resource-env-ref-name> concurrent/BatchExecutor </resource-env-ref-name> <resource-env-ref-type> javax.enterprise.concurrent.ManagedExecutorService </resource-env-ref-type> </resource-env-ref>!
Defining ManagedExecutorService using JNDI
127 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
public class TestServlet extends HTTPServlet { @Resource(name=“concurrent/BatchExecutor”) ManagedExecutorService executor; Future future = executor.submit(new MyTask()); class MyTask implements Runnable { public void run() { . . . // task logic } } } !
Submit Tasks to ManagedExecutorService using JNDI
128 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
class MyTask implements Callable<Long> { public Long call() { . . .} } class MyTask2 implements Callable<Account> { } ArrayList<Callable> tasks = new ArrayList<>(); tasks.add(new MyTask()); tasks.add(new MyTask2()); List<Future<Object>> res = executor.invokeAll(tasks);!
Submitting multiple tasks
129 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0 ManagedExecutorService using CDI
130 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• ThreadFactory: Reference to ManagedThreadFactory!• Thread Use: Short vs long-running tasks, pooled vs
daemon • Hung Task Threshold: Time before task is considered
hung • PoolInfo
– Core Size: Minimum number of threads – Maximum Size: Maximum number of threads (unbounded) – Keep Alive: TTL for idle threads if > core size – Work Queue Capacity: Inbound buffer size (unbounded)
ManagedExecutorService Configuration
131 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Reject Policy: Policy if a task is rejected by executor – Abort: Throw an exception when rejected – Retry and Abort: Automatically submit to another instance and
abort if it fails
• Run Location: Distributable or Local • Contextual Callback: Boolean indicating whether
container context propagated to threads or not
ManagedExecutorService Configuration
132 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0 Server-Managed Thread Pool Executor Component Relship
133 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Adds delay and periodic task running capabilities provided to ManagedExecutorService
• Accessible via javax.enterprise.concurrent.ManagedScheduledExecutorService JNDI reference
• Tasks submitted using submit, invokeXXX or scheduleXXX methods
ManagedScheduledExecutorService
134 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
public class TestServlet extends HTTPServlet { @Resource(name=“concurrent/LoggerExecutor”) ManagedScheduledExecutorService executor; Future future = executor.schedule( new MyTask(), 5, TimeUnit.SECONDS);!
ManagedScheduledExecutorService Sample
135 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0 ContextService
136 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
• Provides a method for creating threads for execution in a managed environment
• Lookup using JNDI <resource-env-ref> <resource-env-ref-name> concurrent/LoggerThreadFactory </resource-env-ref-name> <resource-env-ref-type> javax.enterprise.concurrent.ManagedThreadFactory </resource-env-ref-type> </resource-env-ref>!
ManagedThreadFactory
137 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Concurrency Utilities for Java EE 1.0
@Resource(“concurrent/LoggerThreadFactory”) ManagedThreadFactory threadFactory;#
LoggerTask task = new LoggerTask(); Thread thread = threadFactory.newThread(task); LoggerTask implements Runnable { public void run() { . . . } }!
ManagedThreadFactory Sample
138 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
JavaServer Faces 2.2
• @FlowScoped!• HTML5 Friendly Markup Support
– Pass through attributes and elements
• Cross Site Request Forgery Protection • Loading Facelets via ResourceHandler!• File Upload Component • Multi-templating
139 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
JavaServer Faces 2.2
• Queue control for Ajax requests • File Upload component (Non-Ajax & Ajax) • Injection in all JSF artifacts – including converters &
validators • @FaceletsResourceResolver!• Instantiating composite components in Java • . . .
140 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Contexts & Dependency Injection 1.1
• Embedded mode to startup outside Java EE container • Global ordering of interceptors and decorators • API for managing built-in contexts • Send Servlet events as CDI events • . . .
141 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Transaction API 1.2
• Declarative transactions outside EJB – Based on CDI interceptors
• Add annotation and standard values to javax.transaction package
142 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Transaction API 1.2
public @interface Transactional { TxType value() default TxType.REQUIRED }!
public enum TxType { REQUIRED, REQUIRED_NEW, MANDATORY, SUPPORTS, NOT_SUPPORTED, NEVER }!
!
!
143 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java Transaction API 1.2
public class ShoppingCart {!
...!
@Transactional public void checkOut() {...}!
...!
}!
144 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Many other improvements . . .
• EL 3.0: Lambda expressions, Collection, Operators, …
145 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
4.0 Java EE 7 – Implementation Status
download.java.net/glassfish/4.0/promoted/
146 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Java EE 8 and Beyond Standards-based cloud programming model
• Deliver cloud architecture • Multi tenancy for SaaS
applications • Incremental delivery of JSRs • Modularity based on Jigsaw
Java EE 7
PaaS Enablement
Multitenancy
NoSQL
JSON-B
Concurrency Cloud
Storage
Thin Server Architecture
147 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Call to Action
• Java EE 7 Transparent Expert Groups – javaee-spec.java.net
• Java EE 7 Reference Implementation – glassfish.org
• The Aquarium – blogs.oracle.com/theaquarium
148 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Transparency
• Oracle’s Java EE 7 JSRs are run in the open on java.net – http://javaee-spec.java.net – One project per spec – e.g., jpa-spec, jax-rs-spec, jms-spec…
• Publicly viewable Expert Group mail archive – Users observer list gets copies of all Expert Group emails
• Publicly viewable download area • Publicly viewable issue tracker • Commitment to update to JCP 2.8 Process
149 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Adopt-a-JSR
• Initiative by JUG leaders to get involved in a JSR • Promote JSR to wider Java community • What can I do ?
– Review spec and javadocs – Build applications – Contribute to RI, samples, docs – Talk at JUG/conferences – Blog – . . .
What is it ?
150 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Adopt-a-JSR How do I get started ? – glassfish.org/adoptajsr
151 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Adopt-a-JSR Participating JUGs
152 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Status and Schedule
• All JSRs up and running
• All Early Drafts, several Public Reviews
• Final release target: Q2 2013
153 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
GlassFish Roadmap
2009 2010 2011
GlassFish Server 3.1.2 • Bug Fixes • Incremental features
GlassFish Server 3.1 • Centralized administration • Clustering / HA • GlassFish Server Control
2012
GlassFish Server 4 • Java EE 7 • Productivity • HTML5
GlassFish v3 • Java EE 6 support • Single instance • GlassFish Enterprise Mgr
GlassFish Server 3.0.1 • Oracle branding • Oracle platform support • Oracle interoperability
GlassFish Server 3.1.1 • Bug fixes • Updated components • Incremental features
2013
154 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
Call to Action
• Java EE 7 Expert Group – javaee-spec.java.net
• Java EE 7 Reference Implementation – glassfish.org
• The Aquarium – blogs.oracle.com/theaquarium
• Adopt-a-JSR – glassfish.org/adoptajsr
155 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.