Presentation What’s New in the Java EE 7 Platform

Java EE 7 continues the simplification of the APIs for accessing container services while broadening the range of services available. This platform overview focuses on the following areas:

• Extension of the platform to encompass emerging Web technologies such as WebSocket and JSON, which provide the underpinnings for HTML5 support in Java EE, as well as the HTTP client API added by JAX-RS

• Simplified alignment of managed beans by the leveraging of CDI injection and interceptors to include new JTA declarative transactions, method-level validation, and constructor injection

• Enhancements for ease of use, including simplified JMS APIs, the new batch API, expanded resource definition facilities, and the pruning of superseded technologies

Speakers


PDF: slides.pdf

Slides

Java EE 7

Java EE 7 What’s New in the Java EE Platform ! ! ! David Delabassee Oracle #DV13 #JavaEE7 @delabassee

The following is intended to outline our general product direction. It

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.

Agenda

Agenda A look at some of the important new features of Java EE 7 #DV13 #JavaEE7 @delabassee

Java EE 7 momentum

Java EE 7 momentum YOU Adopt a JSR GlassFish 89 PROMOTED BUILDS 19 JUGs Active and transparent mailing lists 22 JSRs ADOPTED 26 ACTIVE PROJECTS ACTIVE JSRs 14 SPEC LEADS 16 COMPANIES 32 EXPERTS 187

Java EE 7 Themes

Java EE 7 Themes ENTERPRISE EDITION MEETING ENTERPRISE DEMANDS DEVELOPER PRODUCTIVITY Java EE 7 • • • More annotated POJOs Less boilerplate code Cohesive integrated platform #DV13 #JavaEE7 • • • • WebSockets JSON Servlet 3.1 NIO REST • • • Batch Concurrency Simplified JMS

Java EE 7 JSRs

Java EE 7 JSRs New or Updated • • • • • • • JPA 2.1 JAX-RS 2.0 EJB 3.2 JMS 2.0 Servlet 3.1 EL 3.0 JSF 2.2 • • • • • • CDI 1.1 Bean Validation 1.1 WebSocket 1.0 JSON-P 1.0 Batch Applications 1.0 Concurrency Utilities 1.0 ! !

Java EE 7 JSRs

Java EE 7 JSRs Maintenance Releases • • • • • • • Common Annotations 1.2 JTA 1.2 Interceptors 1.2 Connector 1.7 JSP 2.3 JASPIC 1.1 JACC 1.4 • JavaMail 1.5 • Web Services 1.4 ! !

JSON Processing 1.0

JSON Processing 1.0 • API to parse and generate JSON • Streaming API (javax.json.stream) - Low-level, efficient way to parse/generate JSON - Similar to StAX API in XML world • Object Model API (javax.json) - Simple, easy to use high-level API - Similar to DOM API in XML world

JSON Processing 1.0

JSON Processing 1.0 Streaming API : Parsing • Created using -­‐ Json.createParser(…)   -­‐ Json.createParserFactory().createParser(…)   • Parses JSON in streaming way from input sources     Event  event  =  parser.next();   //START_OBJECT       event  =  parser.next();       //  KEY_NAME       event  =  parser.next();       //  VALUE_STRING   • Parser state events -­‐ START_OBJECT,  END_OBJECT,  START_ARRAY,  END_ARRAY,   KEY_NAME,  VALUE_STRING,  VALUE_NUMBER,  …

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser {            “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser START_OBJECT {            “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser KEY_NAME {            “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser VALUE_STRING {            “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser VALUE_NUMBER {            “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser {   START_ARRAY          “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Streaming Parser {   END_ARRAY          “firstName”:  “John”,    “lastName”:  “Smith”,    “age”:  25,            “phoneNumber”:  [                          {    “type”:  “home”,    “number”:    “212  555-­‐1234”  },                          {    “type”:  “fax”,    “number”:    “646  555-­‐4567”  }              ]   }

JSON Processing 1.0

JSON Processing 1.0 Using Streaming API to generate JSON JsonGenerator  gen  =  Json.createGenerator…          .writeStartObject()                .write("firstName",  "John")                  .write("lastName",  "Smith")                  .write("age",  25)                  .writeStartArray(“phones”)                        .writeStartObject()                    .write(“type",  “home")                                .write(“nber”,  “222555-­‐123”))                        .writeEnd()                        .writeStartObject()  …    .writeEnd()                .writeEnd()          .writeEnd();     {     “firstName”:“John”,     “lastName”:“Smith”,     “age”:25,        “phones”:  [       {“type”:“home”,         “nber”:“22555-­‐123”  },       {“type”:“fax”,         “nber”:“64555-­‐456”  }     ]   }

JSON Processing 1.0

JSON Processing 1.0 Object Model API • JsonObject/JsonArray - JSON object and array structures - JsonString and JsonNumber for string and number values • JSON builders - Build JsonObject and JsonArray • JsonReader - Reads JsonObject and JsonArray • JsonWriter - Writes JsonObject and JsonArray

JSON Processing 1.0

JSON Processing 1.0 Object Model API JsonObject  value  =  Json.createObjectBuilder()            .add("firstName",  "John")            .add("lastName",  "Smith")            .add("age",  25)            .add(“phones",  Json.createArrayBuilder()                  .add(Json.createObjectBuilder()                 .add(“type",  “home")                        .add(“nber”,  “22555-­‐123”))                .add(“Json.createObjectBuilder()                  .add(“type",  “fax")                        .add(“nber”,  “64555-­‐456”)))        .build();   {     “firstName”:“John”,     “lastName”:“Smith”,     “age”:25,        “phones”:  [       {“type”:“home”,         “nber”:“22555-­‐123”  },       {“type”:“fax”,         “nber”:“64555-­‐456”  }     ]   }

Java API for WebSocket 1.0

Java API for WebSocket 1.0 • Bidirectional full-duplex messaging - Over a single TCP connection • Annotation-based or interface-based programming model • Server and Client WebSocket Endpoints - Annotated: @ServerEndpoint, @ClientEndpoint - Programmatic: Endpoint • Integrated with Java EE web container - Simple packaging and deployment as wars or jars • Highly configurable

Java API for WebSocket 1.0

Java API for WebSocket 1.0 Main API classes • EndPoint - Intercepts WebSocket lifecycle events • MessageHandler - Handles incoming message for EndPoint • Session - Represents the active conversation • Remote EndPoint - Represents the other end of the conversation

WebSocket EndPoints

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

WebSocket EndPoints as POJOs

WebSocket EndPoints as POJOs Annotated client EndPoint ! @ClientEndpoint   public  class  MyClient  {     !        @OnOpen          public  void  onOpen(Session  session)  {                    session.getBasicRemote().sendText(“Hello”);          }   !        @OnMessage          public  void  onMessage(String  text,  Session  session)  {                      System.out.println("Message  from  the  server  :  "  +  text);          }     ! }  

WebSocket EndPoints as POJOs

WebSocket EndPoints as POJOs Annotated server EndPoint (1/2) ! @ServerEndpoint(“/chat")   public  class  ChatServer  {     !          static  Set  peers  =  Collections.synchronizedSet(…);   ! !          @OnOpen            public  void  onOpen(Session  peer)  {                      peers.add(peer);            }   …  

WebSocket EndPoints as POJOs

WebSocket EndPoints as POJOs Annotated server EndPoint (2/2) ! …          @OnMessage          public  void  onMessage  (String  message,  Session  client)  {                      for  (Session  peer  :  peers)  {                              peer.getBasicRemote().sendText(message);                    }              }                    @OnClose          public  void  onClose(Session  peer)  {                    peers.remove(peer);          }   }  

Java API for RESTful Web Services 2.0

Java API for RESTful Web Services 2.0 JAX-RS 2.0 • Client API • Filters and Interceptors • Asynchronous Processing • Hypermedia • Validation • …

JAX-RS 1.1

JAX-RS 1.1 “Client API” ! …   URL  url  =  new  URL(“http://…/atm/balance”);     HttpURLConnection  conn  =  (HttpURLConnection)  url.openConnection();   conn.setDoInput(true);     conn.setDoOutput(false);     conn.setRequestMethod("GET");     BufferedReader  br  =  new  BufferedReader(                                          new  InputStreamReader(conn.getInputStream()));     String  line;     while  ((line  =  br.readLine())  !=  null)  {                  //…     }  

JAX-RS 2.0

JAX-RS 2.0 New Client API ! ! Client  client  =  ClientFactory.newClient();   ! String  name  =  client.target("http://…/orders/")                                          .request()                                          .get(String.class);   …  

JAX-RS 2.0

JAX-RS 2.0 New Client API ! ! Client  client  =  ClientFactory.newClient();   ! WebTarget  target  =  client.target("http://…/orders/{orderId}/cust")                                                    .register(LoggingFilter.class);   ! String  name  =  target.resolveTemplate(“orderId”,  “10”)                                          .request(“text/plain”)                                          .get(String.class);   …  

JAX-RS 2.0

JAX-RS 2.0 New Client API …   Future  entityFuture  =  target()                                          .path("http://.../resource/")                                          .request()                                          .async()                                          .get(new  InvocationCallback()  {                                                  @Override                                                  public  void  completed(String  response)  {…}                                                  @Override                                                  public  void  failed(Throwable  throwable)  {…}                                                  });   …  

JAX-RS 2.0

JAX-RS 2.0 Bean Validation ! ! @Path("/")   class  MyResourceClass  {                @POST            @Consumes(MediaType.APPLICATION_FORM_URLENCODED)            public  void  registerUser(                      @NotNull  @FormParam("firstName")  String  firstName,                      @NotNull  @FormParam("lastName")  String  lastName,                      @Email  @FormParam("email")  String  email)  {  …  }            …   }  

Managed Beans Alignment

Managed Beans Alignment Cohesive, integrated model Java EE 7 • CDI is core component model • CDI enabled by default • Expanded use of CDI Interceptors - Transactional interceptors - Method-level validation interceptors • New CDI scopes - @TransactionScoped   - @FlowScoped

Transactional Interceptors

Transactional Interceptors Annotations and semantics defined in JTA 1.2 ! @Inherited   @InterceptorBinding   @Target({TYPE,  METHOD})   @Retention(RUNTIME)   public  @interface  Transactional  {          TxType  value()  default  TxType.REQUIRED;          Class[]  rollbackOn()  default  {};          Class[]  dontRollbackOn()  default  {};   }   ! @Transactional(rollbackOn={SQLException.class},                                dontRollbackOn={SQLWarning.class})   public  class  ShoppingCart  {…}  

Bean Validation 1.1

Bean Validation 1.1 Method-level Validation ! @Stateless   public  class  OrderService  {      …        @ValidOrder        public  Order  placeOrder(              @NotNull  String  productName,              @Max(10)  int  quantity,              @NotNull  String  customerName,              @Address  String  customerAddress)  {            …      }   }  

Interceptor Ordering

Interceptor Ordering Well-defined priority ordering • Interceptor.Priority.PLATFORM_BEFORE = 0 • Interceptor.Priority.LIBRARY_BEFORE = 1000 - Platform-defined interceptors to be executed at beginning of interceptor chain Transactional interceptors: Interceptor.Priority.PLATFORM_BEFORE+200 Intended for use by extension libraries • Intended for application-defined interceptors Interceptor.Priority.LIBRARY_AFTER = 3000 • Interceptor.Priority.PLATFORM_AFTER = 4000 • Bean Validation defined interceptors: Interceptor.Priority.PLATFORM_AFTER+800 Interceptor.Priority.APPLICATION = 2000 -

Resource Definition Metadata

Resource Definition Metadata • - Specifies resources needed by application Enhances configurability in Java EE apps Facilitates provisioning in cloud environments ! @DataSourceDefinition  (     name=“java:app/jdbc/myDB”,     className=“oracle.jdbc.pool.OracleDataSource”,     isolationLevel=TRANSACTION_REPEATABLE_READ,   !   initialPoolSize=5)   @Stateless   public  class  MySessionBean  {     @Resource(lookup=“java:app/jdbc/myDB”)     DataSource  my  DB;     …   }  

Resource Definition Metadata

Resource Definition Metadata • - New in Java EE7 JMSConnectionFactoryDefinition JMSDestinationDefinition MailSessionDefinition ConnectionFactoryDefinition AdministeredObject

Default Resources

Default Resources • java:comp/DefaultDataSource JMS • java:comp/DefaultJMSConnectionFactory • Concurrency Utilities java:comp/DefaultManagedExecutorService JDBC/JPA - java:comp/DefaultManagedScheduledExecutorService java:comp/DefaultManagedThreadFactory java:comp/DefaultManagedContextService

Simplification through Pruning

Simplification through Pruning • Process defined in Java EE 6 • Optional APIs as of Java EE 7 - Platform version N defines feature as “Proposed Optional” Platform version N+1 determines whether to make feature Optional EJB Entity Beans (CMP, BMP, EJB QL) JAX-RPC JAXR Deployment (JSR 88)

Java Message Services 2.0

Java Message Services 2.0 • • • • • New JMS Simplified API Less code, less boilerplate Fewer objects to manage Increased developer productivity “Classic API” has also been improved

JMS 2.0

JMS 2.0 • - Simplifications include…. New JMSContext interface Use of CDI injection; new TransactionScope AutoCloseable JMSContext, Connection, Session, … Use of runtime exceptions Method chaining on JMSProducer Simplified message sending …

JMS 1.1

JMS 1.1 Sending a message in the JMS 1.1 “classic” API ! @Resource(lookup  =  “java:global/jms/myConnectionFactory”)   ConnectionFactory  connectionFactory;     @Resource(lookup  =  “java:global/jms/myQueue”)   Queue  queue;     ! public  void  sendMessage(String  text)  {        try  {                Connection  connection  =  connectionFactory.createConnection();                Session  session  =  connection.createSession(false,  Session.AUTO_ACKNOWLEDGE);                MessageProducer  messageProducer  =  session.createProducer(queue);                TextMessage  textMessage  =  session.createTextMessage(text);                messageProducer.send(textMessage);        }  finally  {                connection.close();        }  catch  (JMSException  ex)    {…}   }  

JMS 2.0

JMS 2.0 Sending a message using Simplified API and JMSContext ! @Resource(lookup  =  “java:global/jms/myConnectionFactory”)   ConnectionFactory  connectionFactory;     ! @Resource(lookup  =  “java:global/jms/myQueue”)   Queue  queue;     ! public  void  sendMessage(String  text)  {        try  (JMSContext  context  =    connectionFactory.createContext();)  {          context.createProducer().send(queue,  text);        }  catch  (JMSRuntimeException  ex)  {  …  }   }  

JMS 2.0

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

JMS 2.0

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

Concurrency Utilities for Java EE 1.0

Concurrency Utilities for Java EE 1.0 • • • Provides asynchronous capabilities to Java EE components Extension of Java SE Concurrency Utilities API Provides managed objects for submitting tasks and obtaining managed threads -­‐ ManagedExecutorService   -­‐ ManagedScheduledExecutorService   -­‐ ManagedThreadFactory   -­‐ ContextService

Concurrency Utilities for Java EE 1.0

Concurrency Utilities for Java EE 1.0 ! public  class  AccountTask  implements  Callable  {      …      public  AccountInfo  call()  {      //  task  logic      }      …   }   ! @Resource   ManagedExecutorService  myExecutor;   …   Future  acctFuture  =  myExecutor.submit(new  AccountTask(…));   AccountInfo  accountInfo  =  acctFuture.get();  //  Wait  for  the  results   …  //  Process  the  results  

Batch Application for the Java Platform

Batch Application for the Java Platform • Designed for non-interactive, bulk-oriented and long• • running tasks Sequential, parallel, and/or decision-based batch execution Processing styles - Item-oriented (“chunked”) - Task-oriented (“batchlet”)

Batch API 1.0

Batch API 1.0 Key Concepts • Job: entire batch process - Defined through XML Job Specification Language • Step: independent, sequential phase of a job • JobOperator: interface for managing job processing • JobRepository: information about past and present jobs Job Operator Job Step ItemReader ItemProcessor Job Repository ItemWriter

Batch API 1.0

Batch API 1.0 Job Steps Chunked step: Item-oriented processing • - ItemReader/ItemProcessor/ItemWriter pattern Configurable checkpointing and transactions • Batchlet: Task-oriented processing • Job can include both types of steps - Roll-your-own batch pattern Runs to completion and exits ItemReader

Batch API 1.0

Batch API 1.0 JSL                                                                                                                                                                                                                 ItemReader                                                                                                                

Batch API 1.0

Batch API 1.0 API ! @Named   public  class  MyItemProcessor  implements  ItemProcessor  {   !        @Inject          private  JobContext  jobContext;   !        public  Object  processItem(Object  obj)  throws  Exception  {                  PayrollInputRecord  inputRecord  =  (PayrollInputRecord)  obj;                  PayrollRecord  payrollRecord  =    new  PayrollRecord();   !                int  base  =  inputRecord.getBaseSalary();                  float  tax  =  base  *  27  /  100.0f;   !                payrollRecord.setEmpID(inputRecord.getId());                  payrollRecord.setBase(base);                  payrollRecord.setTax(tax);                  return  payrollRecord;          }     }   ItemReader

Java Persistence API 2.1

Java Persistence API 2.1 Schema Generation Generation of database tables, indexes, constraints, etc. Designed for flexibility • • - • Scenarios: prototyping; production; provisioning environments Generate from object/relational metadata (annotations and/or XML) Generate from bundled SQL DDL scripts; also SQL load scripts Generate directly into database Generate into SQL DDL scripts ItemReader Process controlled by metadata or runtime properties

Java EE 7 Themes

Java EE 7 Themes ENTERPRISE EDITION MEETING ENTERPRISE DEMANDS DEVELOPER PRODUCTIVITY Java EE 7 • • • More annotated POJOs Less boilerplate code Cohesive integrated platform #DV13 #JavaEE7 • • • • WebSockets JSON Servlet 3.1 NIO REST • • • Batch Concurrency Simplified JMS

But also…

But also… • • • • • • EJB 3.2 Expression Language 3.0 Servlet 3.1 JavaServer Faces 2.2 Java Connector 1.7 …

Transparency in JSR processes

Transparency in JSR processes • http://java.net/projects/javaee-spec/pages/Home Publicly viewable Expert Group mailing archives • Users observer lists get copies of all Expert Group emails • • Public download areas, JIRAs Wikis, source repositories, etc. at the group discretion • ItemReader Commitment to JCP 2.8/2.9 processes • java.net used for all Oracle-led JSRs ➡

DOWNLOAD

DOWNLOAD Java EE 7 SDK oracle.com/javaee ! GlassFish 4.0 Full Platform or Web Profile glassfish.org #DV13 #JavaEE7 @delabassee