The Java EE 7 Platform: Productivity & HTML5 at San Francisco JUG
Upcoming SlideShare
Loading in...5
×
 

The Java EE 7 Platform: Productivity & HTML5 at San Francisco JUG

on

  • 13,667 views

The Java EE 7 Platform: Productivity & HTML5 at San Francisco Java User G

The Java EE 7 Platform: Productivity & HTML5 at San Francisco Java User G

Statistics

Views

Total Views
13,667
Views on SlideShare
2,516
Embed Views
11,151

Actions

Likes
3
Downloads
68
Comments
0

17 Embeds 11,151

http://javadev.ru 9746
http://marakana.com 782
https://thenewcircle.com 296
http://www.javadev.ru 97
http://javadev.org 97
http://www.javadev.org 85
http://webcache.googleusercontent.com 16
http://translate.googleusercontent.com 16
https://www.google.ru 3
http://mrkn.co 3
http://yandex.ru 3
http://tester.amalama.ru 2
http://replica-31.search.km 1
http://cc.bingj.com 1
http://hghltd.yandex.net 1
http://prlog.ru 1
http://crcl.to 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

The Java EE 7 Platform: Productivity & HTML5 at San Francisco JUG The Java EE 7 Platform: Productivity & HTML5 at San Francisco JUG Presentation Transcript

  • Main sponsorThe  Java  EE  7  Pla,orm:  Produc4vity  &  HTML5  Arun  Gupta,  Java  EE  &  GlassFish  Guy  blogs.oracle.com/arungupta,  @arungupta  
  • 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.2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java EE 6 Platform December 10, 20093 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 release4 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 Profile5 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 Forms6 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java EE 7 – Candidate JSRs JAX-RS Java Caching API JSP 2.2 JSF 2.2 2.0 EL 3.0 (JSR 107) PortableExtensions Bean Validation 1.1 Concurrency Utilities Servlet 3.1 (JSR 236) Common Batch Applications Interceptors 1.1 CDI 1.1 (JSR 352)Annotations 1.1 Java API for JSON Managed Beans 1.0 EJB 3.2 (JSR 353)Connector Java API for WebSocket JPA 2.1 JTA 1.2 JMS 2.0 (JSR 356) 1.6 New Major Updated Release 7 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 Configuration8 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) {! //. . .! }!9 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);!10 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);!11 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"));!12 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(); ! }! });!13 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
     }
 }!14 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;! }! }!15 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for RESTful Web Services 2.0 Filters & Interceptors – Client-side write(…)   Writer   Interceptor   … Writer   Interceptor   MBW   Request   Filter   … Filter   Applica>on   Transport   Network   Response   Filter   … Filter   read(…)  -­‐  op>onal   MBR   Reader   Interceptor   … Reader   Interceptor  16 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for RESTful Web Services 2.0 Filters & Interceptors – Server-side read(…)  -­‐  op>onal   Reader   Interceptor   … Reader   Interceptor   MBR   @PreMatching Request   Filter   Filter   Resource   Matching   Filter   … Filter   Request  Network   Applica>on   Response   Filter   … Filter   Filter   Filter   Response   write(…)   MBW   Writer   Interceptor   … Writer   Interceptor   17 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for RESTful Web Services 2.0 Client-side AsyncClient 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) {
 }
 }
 );! 18 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);# }! });! }!}!19 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);! …! }!20 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() {
         . . .
     }
 }!21 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 Simplify the existing API •  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 EE22 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);! 13 lines of messageProducer.send(textMessage);# } finally {! code just connection.close();! to send a }! } catch (JMSException ex) {! message Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);! }! } !23 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 Sending message using JMS 1.1 must create several intermediate objects @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);! }! } !24 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 Sending message using JMS 1.1 redundant and @Resource(lookup = "java:global/jms/demoConnectionFactory")! ConnectionFactory connectionFactory;! misleading ! arguments @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);! }! } !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;! boilerplate ! @Resource(lookup = "java:global/jms/demoQueue")! code 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);! }! } !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 {# must close connection.close();# }# resources } catch (JMSException ex) {! after use! Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);! }! } !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);! all methods } finally {! throw checked connection.close();! }! exceptions } catch (JMSException ex) {! Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);! }! } !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;# pre-create app- # server specific @Resource(lookup = "java:global/jms/demoQueue")# resources 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);! }! } !29 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()#30 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 731 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 Simpler API to close JMS objects Create closeable resources in a try- @Resource(lookup = "jms/connFactory")
 with-resources block 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); ! close() is called producer.send(mess); ! automatically } catch(JMSException e){ ! at end of block // exception handling ! }
 }!32 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 JMSContext Introducing JMSContext and JMSProducer combines Connection and Session @Resource(lookup = "java:global/jms/demoConnectionFactory")! ConnectionFactory connectionFactory; ! ! Payload @Resource(lookup = "java:global/jms/demoQueue")! can be sent Queue demoQueue;! directly ! public void sendMessage (String payload) {! try (JMSContext context = connectionFactory.createContext();){! context.createProducer().send(demoQueue, payload);# } catch (JMSRuntimeException ex) {! // exception handling! }! close() is called }! automatically No checked at end of block exceptions thrown33 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Message Service 2.0 Default resource definition Default resource definition Or @JmsConnectionFactory# @Inject
 JMSContext context;! ! @Resource(lookup = "java:global/jms/demoQueue”)
 Queue demoQueue;! ! public void sendMessage(String payload) {! context.createProducer().send(demoQueue, payload);! }! 13 lines è1 line#34 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 forthcoming35 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser and JsonGenerator •  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, ...36 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" } ] }37 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser START_OBJECT { "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.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser { KEY_NAME "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }39 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser { VALUE_STRING "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }40 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser { VALUE_NUMBER "firstName": "John", "lastName": "Smith", "age": 25, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }41 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, START_ARRAY "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }42 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" } END_ARRAY ] }43 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" }! ]! }! 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”44 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonParser and JsonGenerator •  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 printing45 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Streaming API – JsonGenerator
 JsonGenerator jg = Json.createGenerator(…);
"phoneNumber": [! 
 { 
 jg.
 "type": "home", 
 .beginArray("phoneNumber")
 "number": ”408-123-4567”
 .beginObject() 
 },! .add("type", "home") 
 {
 .add("number", "408-123-4567") 
 "type": ”work", 
 .endObject() 
 "number": ”408-987-6543”
 .beginObject() 
 }! .add("type", ”work") 
 ]! .add("number", "408-987-6543") 
 .endObject() 
 .endArray();
 jg.close(); !46 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for JSON Processing 1.0 Object Model API •  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 source47 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();! }! !48 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);! }! !49 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);! }!50 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 container51 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Hello World – POJO/Annotation-drivenimport javax.websocket.*;

@WebSocketEndpoint("/hello")
public class HelloBean {

 @WebSocketMessage
 public String sayHello(String name) {
 return “Hello “ + name;
 }
}!52 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 method @WebSocketPathParam! Flags a matched path segment of a URI-template parameter @WebSocketError! method Intercepts errors during a conversation53 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 @WebSocketEndpoint Attributes Relative URI or URI template value! 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 subprotocols54 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Custom Payloads @WebSocketEndpoint(
 value="/hello",
 encoders={MyMessage.class},
 decoders={MyMessage.class}
 )
 public class MyEndpoint {
 . . .
 }! !55 ! Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Custom Payloads – Text 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();
 }
56 }! © 2012, Oracle and/or its affiliates. All rights reserved. Copyright
  • Java API for WebSocket 1.0 Custom Payloads – Binary 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) {
 . . .
 }
57 }! © 2012, Oracle and/or its affiliates. All rights reserved. Copyright
  • Java API for WebSocket 1.0 Chat @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);
 }
 
 . . .!58 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Chat (contd.) . . .
 
 @WebSocketMessage# public void message(String message, Session client) {! for (Session peer : peers) {
 peer.getRemote().sendObject(message);
 }
 }
 }!59 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 URI Template Matching •  Level 1 only @WebSocketEndpoint(“/orders/{order-id}”)
 public class MyEndpoint {
 @WebSocketMessage
 public void processOrder(
 @WebSocketPathParam(“order-id”)String orderId) {
 . . .
 }
 }60 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Which methods can be @WebSocketMessage ? •  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 a61 encoder 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) {
 }
 } 
 });
 }
 }!62 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java API for WebSocket 1.0 Hello World – Interface-driven Packaging public class MyEndpointConfig implements ServerEndpointConfiguration {
 String getPath() {
 return “/endpoint”;
 }
 
 Class<? extends Endpoint> getEndpointClass() {
 return HelloServer.class;! }
 
 . . .
 }! ! Copyright © 2012, Oracle and/or its affiliates. All rights reserved.63
  • Java API for WebSocket 1.0 Hello World Client @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”);! !64 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-conditions65 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Bean Validation 1.1 Method Parameter and Result Validation Need more slides here public void placeOrder( 
 @NotNull String productName,
Built-in @NotNull @Max(“10”) Integer quantity,
Custom @Customer String customer) { 
 //. . .
 }! @Future
 public Date getAppointment() {
 //. . .
 }!66 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 included67 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Concepts •  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 jobs68 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Concepts •  JobInstance: Logical Job Run •  JobExecution: Single attempt to run a job •  StepExecution: Single attempt to run a step69 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Concepts: Types of Step •  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 transfer70 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Concepts: Chunked Step •  Primary processing style –  Read and Process one item –  Do the above ‘n’ times (called ‘commit interval’) –  Write the ‘n’ processed items –  Commit the transaction71 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Job Specification Language •  Specifies a job, steps and directs their execution •  Implemented in XML –  Referred as “Job XML” •  Supports inheritance of job, step, flow, and split72 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Job Specification Language – Simple Job <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> !73 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Job Specification Language – Chunked Step<step id=”sendStatements”>! @ReadItem
 <chunk reader=”AccountReader”! public Account readAccount() {
 processor=”AccountProcessor”
 // read account using JPA! writer=”EmailWriter”! }! chunk-size=”10” />! !</step>! @ProcessItem# public Account processAccount(Account account) {
 // calculate balance! }! @WriteItems# ! public void sendEmail(List<Account> accounts) {
 // use JavaMail to send email! }! ! 74 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Batch Applications for the Java Platform 1.0 Job Specification Language: Batchlet <step id=”transferFile”>! <batchlet ref=“MyFileTransfer” />! </step>! @Process# public void transferFile(String name) {
 // Transfer file! }! !75 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, . . .76 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 thread77 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 implementers78 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 10779 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Key Concepts •  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 –  Generics80 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)81 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Key Concepts •  Cache Manager =>Caches •  Cache => Entries •  Entry => Key,Value •  CacheManager acquired via CacheManagerFactory! •  CacheManagerFactory acquired via Service Provider –  META-INF/services/javax.cache.spi.CachingProvider!82 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Creating a CacheManager CacheManager cacheManager = CacheManagerFactory.getCacheManager(); or fully CacheManager cacheManager = CacheManagerFactory.getCacheManager(DEFAULT_CACHE_M ANAGER_NAME, Thread.currentThread().getContextClassLoader()); !83 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Using a Cache •  Obtain a cache from CacheManager Cache<Integer, Date> cache = 
 cacheManager.getCache(“testCache”);!84 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Configure a Cache •  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(); ! !85 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Putting a value in a cache Cache<Integer, Date> cache =
 cacheManager.getCache(cacheName);
 Integer key = 1;
 cache.put(key, new Date()); ! !86 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Getting a value from a cache Cache<Integer, Date> cache =
 cacheManager.getCache(cacheName);
 Date value = cache.get(key); ! !87 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Removing a value from a cache Cache<Integer, Date> cache =
 cacheManager.getCache(cacheName);
 Integer key = 1;
 cache.remove(1); !88 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Blog public class BlogManager { ! @CachePut(cacheName=”blogManager”)
 public void createEntry(
 @CacheKeyParam String title,
 @CacheValue Blog blog) {...}
 
 . . .!89 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Code Sample – Blog . . .
 
 @CacheResult(cacheName="blogManager") 
 public Blog getBlogEntry(String title) {...} ! 
 @CacheResult(cacheName="blogManager") 
 public Blog getEntryCached(
 String randomArg, 
 @CacheKeyParam String title) {...}
 
 . . .!90 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Annotations – Blog Sample . . .
 
 @CacheRemoveEntry(cacheName="blogManager") 
 public void removeBlogEntry(String title) {...} 
 ! @CacheRemoveAll(cacheName="blogManager") 
 public void removeAllBlogs() {...}! } !91 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Temporary Caching API 1.0 Expected Implementations •  Terracotta – Ehcache •  Oracle – Coherence •  JBoss – Inifinispan •  IBM – ExtremeeScale •  SpringSorce – Gemfire •  Google App Engine – Java memcache client •  Spymemcache memcache client92 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 Query93 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Persistence API 2.1 Schema Generation •  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 deployment94 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Persistence API 2.1 Schema Generation Properties •  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! •  . . .!95 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;# ...# }#96 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Persistence API 2.1 Schema Generation – @Index •  Specifies additional indexes •  Ordering of columns must be preserved •  Can be specified as part of Table, SecondaryTable, CollectionTable, JoinTable, TableGenerator @Table(indexes= {@Index(columnList=“NAME”)# @Index(columnList=“DEPT_ID”)})# @Entity public class Employee {! @Id private Integer id; ! private String name; ! ...! @ManyToOne! private Department dept;! …! }!97 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Persistence API 2.1 Schema Generation – @ForeignKey •  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) @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;! }!98 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Persistence API 2.1 Unsynchronized Persistence Contexts •  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 conversation99 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(); }! !100 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); ! }! ! ! !101 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);! !102 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); 
 UPDATE Customer c! q.set(c.get(Customer_.status), "outstanding")
 SET c.status = outstanding!  .where(cb.lt(c.get(Customer_.balance), 10000));
 WHERE c.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)));
 DELETE FROM Customer c
 . . .
 WHERE c.status = inactive
 ! AND c.orders IS EMPTY!103 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 EJBs Today •  @Singleton! •  @Asynchronous! •  @Schedule! •  Portable JNDI Name •  EJBContainer.createEJBContainer! •  EJB 3.1 Lite104 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 () { . . . }!105 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 = …;! ! …! }!106 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 Updates: Simplified Rules for Local/Remote Client Views @Stateless
 public class Bean implements Foo, Bar {
 }! Local @Local @Stateless
 public class Bean implements Foo, Bar {
 }! Remote @Remote @Stateless
 public class Bean implements Foo, Bar {
 }!107 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 Updates: Simplified Rules for Local/Remote Client Views @Remote
 public interface Foo { . . . }
 
 public interface Bar { . . . }
 
 Remote @Stateless
 public class Bean implements Foo, Bar {
 }!108 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 Updates: Alignment with JMS 2.0 •  Enhanced list of standard activation-config properties –  destinationLookup –  connectionFactoryLookup –  clientId –  subscriptionName –  shareSubscriptions109 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 Updates: Miscellaneous •  Embeddable container implements Autocloseable! •  Removed restriction to use java.io package •  Thread context in Singleton is guaranteed to be thread-safe •  . . .110 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 More Features in EJB.Lite •  Asynchronous session bean •  Non-persistent EJB Timer service111 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Enterprise JavaBeans 3.2 Pruning •  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 read112 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 •  Non-blocking I/O •  Protocol Upgrade •  Security Enhancements113 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking IO - Traditional 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) {
 . . .
 }
 }
 }!114 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking I/O – New APIs •  Two new listeners –  ReadListener! –  WriteListener! •  Register using ServletInputStream and ServletOutputStream!115 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-block I/O: New APIs •  ServletInputStream! –  public void setReadListener(ReadListener listener)! –  public boolean isFinished()! –  public boolean isReady()! •  ServletOutputStream! –  public setWriteListener(WriteListener listener)! –  public boolean canWrite()!116 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking I/O Listeners 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();
 }!117 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking I/O: doGet Code Sample AsyncContext context = request.startAsync();
 ServletInputStream input = request.getInputStream();
 input.setReadListener(
 new MyReadListener(input, context)); !118 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking I/O: MyReadListener Code Sample @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) {
 . . .
 }
 }
 . . .
119 ! Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Non-blocking I/O: MyListener Code Sample . . .
 @Override
 public void onAllDataRead() {
 context.complete();
 }
 
 @Override
 public void onError(Throwable t) {
 t.printStackTrace();
 context.complete();
 } !120 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 HTTP Protocol Upgrade Mechanism •  <T extends HttpUpgradeHandler> T HttpServletRequest.upgrade(Class<T> class) throws IOException;
 •  HttpUpgradeHandler! –  init(WebConnection wc);! –  destroy();!121 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Servlet 3.1 Security Enhancements122 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Goals •  Provide concurrency capabilities to Java EE application components –  Without compromising container integrity •  Support simple (common) and advanced concurrency patterns123 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Goals •  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!124 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedExecutorService •  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 permitted125 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Defining ManagedExecutorService using JNDI •  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>!126 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Submit Tasks to ManagedExecutorService using JNDI 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
 }
 }
 }
127 ! Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Submitting multiple tasks 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);!128 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedExecutorService using CDI129 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedExecutorService Configuration •  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 size130 –  Work Queue Capacity: Inbound buffer size (unbounded) Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedExecutorService Configuration •  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 not131 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 Server-Managed Thread Pool Executor Component Relship132 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedScheduledExecutorService •  Adds delay and periodic task running capabilities provided to ManagedExecutorService •  Accessible via javax.enterprise.concurrent.ManagedSchedul edExecutorService JNDI reference •  Tasks submitted using submit, invokeXXX or scheduleXXX methods133 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedScheduledExecutorService Sample public class TestServlet extends HTTPServlet {
 @Resource(name=“concurrent/LoggerExecutor”)
 ManagedScheduledExecutorService executor;
 
 Future future = executor.schedule(
 new MyTask(),
 5,
 TimeUnit.SECONDS);!134 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ContextService135 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedThreadFactory •  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>!136 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Concurrency Utilities for Java EE 1.0 ManagedThreadFactory Sample @Resource(“concurrent/LoggerThreadFactory”)
 ManagedThreadFactory threadFactory;# 
 LoggerTask task = new LoggerTask();
 Thread thread = threadFactory.newThread(task);
 
 LoggerTask implements Runnable {
 public void run() { . . . }
 }!137 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-templating138 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 •  . . .139 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 •  . . .140 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 package141 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
 }! !142 ! Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java Transaction API 1.2 public class ShoppingCart {! ...! @Transactional
 public void checkOut() {...}! ...! }!143 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Many other improvements . . . •  EL 3.0: Lambda expressions, Collection, Operators, …144 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java EE 7 – Implementation Status 4.0 download.java.net/glassfish/4.0/promoted/145 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Java EE 8 and Beyond Standards-based cloud programming model •  Deliver cloud architecture Storage NoSQL •  Multi tenancy for SaaS JSON-B Multitenancy Java EE 7 applications Concurrency Cloud PaaS •  Incremental delivery of JSRs Enablement Thin Server Architecture •  Modularity based on Jigsaw146 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/theaquarium147 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 Process148 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Adopt-a-JSR What is it ? •  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 –  . . .149 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Adopt-a-JSR How do I get started ? – glassfish.org/adoptajsr150 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • Adopt-a-JSR Participating JUGs151 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 152 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • GlassFish RoadmapGlassFish v3 GlassFish Server 3.1 GlassFish Server 3.1.2•  Java EE 6 support •  Centralized administration •  Bug Fixes•  Single instance •  Clustering / HA •  Incremental features•  GlassFish Enterprise Mgr •  GlassFish Server Control 2009 2010 2011 2012 2013 GlassFish Server 3.0.1 GlassFish Server 3.1.1 GlassFish Server 4 •  Oracle branding •  Bug fixes •  Java EE 7 •  Oracle platform support •  Updated components •  Productivity •  Oracle interoperability •  Incremental features •  HTML5 153 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/adoptajsr154 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.
  • 155 Copyright © 2012, Oracle and/or its affiliates. All rights reserved.