Java EE 7 Overview Hamed Hatami h_hatami@isc.iranet.net January 2014 from Iran JUG.

Post on 25-Dec-2015

222 views 0 download

Transcript of Java EE 7 Overview Hamed Hatami h_hatami@isc.iranet.net January 2014 from Iran JUG.

Java EE 7 Overview

Hamed Hatami

h_hatami@isc.iranet.net

January 2014

from Iran JUG

Hamed Hatami @ 2014

Agenda

Overview

A Taste of API Changes

Looking Ahead

Hamed Hatami @ 2014

Java EE 7 Launch Last Month June 2013

Hamed Hatami @ 2014

Java EE 7 - Major Themes in Context

2014 - Future2013 - Future1998-2004

Enterprise Java Platform

Robustness

Web Services J2EE

20 specs

Java EE 7

2005-2012

Ease ofDevelopment

Lightweight

Developer Productivity & HTML5

32 specs

EE 5, EE 6

28 specs

Hamed Hatami @ 2014

Java EE 7 – Past, Present, Future

Hamed Hatami @ 2014

Java EE 7 – Themes

Hamed Hatami @ 2014

Java EE 7 - JSRs

Connector 1.6

Connector 1.6

Managed Beans 1.0Managed Beans 1.0 EJB 3.2EJB 3.2

Servlet 3.1Servlet 3.1

PortableExtension

s

PortableExtension

s

JSF 2.2JSF 2.2 JAX-RS 2.0

JAX-RS 2.0

JMS 2.0JMS 2.0JPA 2.1JPA 2.1

EL 3.0EL 3.0

JTA 1.2JTA 1.2

JSP 2.2JSP 2.2

Interceptors 1.1Interceptors 1.1 CDI 1.1CDI 1.1Common Annotations 1.1

Common Annotations 1.1

Concurrency Utilities(JSR 236)

Concurrency Utilities(JSR 236)

Batch Applications(JSR 352)

Batch Applications(JSR 352)

Java API for JSON(JSR 353)

Java API for JSON(JSR 353)

Java API for WebSocket(JSR 356)

Java API for WebSocket(JSR 356)

Updated

MajorRelease

New

Hamed Hatami @ 2014

Java EE Web Profile Enhancements

• The Java Enterprise Edition Web Profile was introduced in Java EE 6

• Most Web applications have significant requirements in the areas oftransaction management, security, and persistence.

• but are not supported by standalone servlet containers.

• Web Profile is provided with pre-installed, pre-integrated, fully testedWeb infrastructure features.

• The Java EE 7 Web Profile adds support for HTML5 with WebSockets,JSON, JAX-RS 2.0, and more.

Hamed Hatami @ 2014

JSR 343: Java Message Service 2.0

• API modernization using dependency injection

• Delivery delay, async send, MDB alignment, JMS resource definition

• Fixes, clarifications

Hamed Hatami @ 2014

JMS - Old API

@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); }}

Hamed Hatami @ 2014

JMS 2 - Simplified API

@Injectprivate JMSContext context;

@Resource(mappedName = "jms/inboundQueue")private Queue inboundQueue;

public void sendMessage (String payload) { context.createProducer().send(inboundQueue, payload);}

Hamed Hatami @ 2014

JMS 2/Java EE 7

@JMSConnectionFactoryDefinition( name="java:global/jms/demoConnectionFactory", className= "javax.jms.ConnectionFactory", description="ConnectionFactory to use in demonstration")

@JMSDestinationDefinition( name = "java:global/jms/demoQueue", description = "Queue to use in demonstration", className = "javax.jms.Queue", destinationName="demoQueue")

Hamed Hatami @ 2014

JMS 2/EJB 3.2

@MessageDriven(activationConfig = { @ActivationConfigProperty( propertyName = "destinationType", propertyValue = "javax.jms.Queue"), @ActivationConfigProperty( propertyName = "destinationLookup", propertyValue = "jms/OrderQueue"), @ActivationConfigProperty( propertyName = "connectionFactoryLookup", propertyValue = "jms/MyConnectionFactory")})public class OrderListener implements MessageListener { ... public void onMessage(Message message) { ... } ...}

Hamed Hatami @ 2014

Why WebSocket?

• HTTP is half duplex

• HTTP is verbose

• Hacks for Server Push • Polling • Long Polling • Comet/Ajax

• Complex, Wasteful, Inefficient

Hamed Hatami @ 2014

HTTP Communication

Hamed Hatami @ 2014

Polling

Hamed Hatami @ 2014

Long Polling

Hamed Hatami @ 2014

HTTP Streaming (Comet)

Hamed Hatami @ 2014

WebSocket to rescue

• TCP based, bi-directional, full-duplex messaging

• Capable of sending both UTF-8 string and binary frames in anydirection at the same time

• Operating from a single socket across the web

• As part of HTML5, the application of the client interface will becomenative to all modern browsers

• To establish a Web Socket connection, the browser or client simplymakes a request to the server for an upgrade from HTTP to a WebSocket

Hamed Hatami @ 2014

Java API for WebSocket

@ServerEndpoint(”/chat”)public class ChatServer {

Set<Session> peers = ...

@OnOpenpublic void onOpen(Session peer) {peers.add(peer);}

@OnClosepublic void onClose(Session peer) {peers.remove(peer);}...

Hamed Hatami @ 2014

Java API for WebSocket

@OnMessagepublic void message(String message, Session client)throws IOException { for (Session session : peers) { if (!session.equals(client)) { session.getRemote().sendObject(message); } } }}

Hamed Hatami @ 2014

JSON (JavaScript Object Notation)

•JSON is a lightweight data-interchange format. It is easy for humans to read and write.

• It is easy for machines to parse and generate.

• It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.

• JSON is a text format that is completely language independent but uses conventions that are familiar to programmers.

Hamed Hatami @ 2014

Why we need another API?

• JSON has become a defacto data transfer standard specially for RESTful Web Services.

• Java applications use different implementations to consume and process JSON data.

• There should be standardized Java API for JSON so that applications do not need to bundle the implementation libraries.

• API to parse, generate, transform, query JSON

• Binding JSON to Java objects forthcoming.

Hamed Hatami @ 2014

Java API for JSON Processing

JsonArray value = Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234") ) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567") ).build();

[{"type": "home”,"number": "212 555-1234"},{"type": "fax”,"number": "646 555-4567"}]

Hamed Hatami @ 2014

JSR 338: Java API for RESTful Web Services 2.0

• Client API

• Message Filters & Entity Interceptors

• Asynchronous Processing – Server & Client

• Hypermedia Support

• Content negotiation

Hamed Hatami @ 2014

JAX-RS 2

// Get instance of ClientClient client = ClientBuilder.newClient();

// Get customer name for the shipped productsString name = client.target(“../orders/{orderId}/customer”) .pathParam(”orderId", ”10”) .queryParam(”shipped", ”true”) .request() .get(String.class);

Hamed Hatami @ 2014

JAX-RS 2 / Logging Filter

public class RequestLoggingFilter implements ContainerRequestFilter {

@Overridepublic void filter(ContainerRequestContext requestContext) { log(requestContext); // Non-wrapping => returns without invoking next filter }...}

Hamed Hatami @ 2014

JSR 339: Java Persistence API 2.1

The new features can be described with the following short list:

• Automatic schema generation

• Stored procedure mapping

• Unsynchronized persistence context

• Criteria Bulk updates and deletes

• JOIN using the ON condition

• Support for downcast in JPQL

• Support for Functions in JPQL

• CDI listeners in Entity classes

• Dynamically defined named queries

Hamed Hatami @ 2014

JPA 2.1 / Schema Generation Properties

• javax.persistence.schema-generation.[database|scripts].action “none”,“create”, “drop-and-create”, “drop”

• javax.persistence.schema-generation.scripts.[create|drop]-target

• javax.persistence.schema-generation.[create|drop]-script-source

• javax.persistence.sql-load-script-source

• javax.persistence.schema-generation.[create|drop]-source “metadata”,“script”, “metadata-then-script”, “script-then-metadata”

Hamed Hatami @ 2014

JPA 2.1 / Stored Procedures

Now there's a portable way to achieve it using:StoredProcedureQuery spq = em.createStoredProcedureQuery("PERSON_SP");

If we have any parameters in this stored procedure we need to register them, for example:spq.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT);spq.setParameter(1, "FRANK");spq.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN);spq.setParameter(2, 100);

You can define it as well using the @NamedStoredProcedureQuery:@Entity@NamedStoredProcedureQuery(name="PERSON_StoredProcedure", procedureName="PERSON_SP")public class Product {…}

and in your JPA client:StoredProcedreQuery spq = EntityManager.createNamedStoredProcedureQuery("PERSON_StoredProcedure");spq.registerStoredProcedureParameter(1, String.class, ParameterMode.INOUT);spq.setParameter(1, "FRANK");spq.registerStoredProcedureParameter(2, Integer.class, ParameterMode.IN);spq.setParameter(2, 100);

query.execute();String response = query.getOutputParameterValue(1);

Hamed Hatami @ 2014

JPA 2.1 / Unsynchronized Persistence Context

@Statefulpublic class ShoppingCart {

@PersistenceContext(type=EXTENDED,synchronization=UNSYNCHRONIZED)Private EntityManager em;

Private Customer customer;Private Order order;

public void startToShop(Integer custId) {customer = em.find(Customer.class,custId);order = new Order(); }

public void addToCart(Book book) {Item item = new Item(book);order.addItem(item); }

public void confirmOrder() {em.joinTransaction();customer.addOrder(order);}}

Hamed Hatami @ 2014

JPA 2.1

JOIN using the ON conditionSELECT e FROM Employee e LEFT JOIN e.address ON a.city = :city

Support for downcast in JPQLSELECT b.name FROM User e JOIN TREAT(e.projects AS LargeProject) b

Support for Functions in JPQLSELECT FUNCTION('YEAR', e.startDate) AS year, COUNT(e) FROM Employee e GROUP BY year

Criteria Bulk updates and deletes:

CDI listeners in Entity classes

CriteriaUpdate<Employee> q = cb.createCriteriaUpdate(Employee.class);Root<Employee> c = q.from(Employee.class);q.set(c.get(Employee.wage), 2000).where(c.it(c.get(Employee.wage), 2000));

@Entity@EntityListeners(Alarm.class)public class Customer {

@Id private Integer id;private String name;…}

public class Alarm {@PostPersistpublic void alert(Customer c) {…}}

Hamed Hatami @ 2014

JPA 2.1

Dynamically defined named queries

@PersistenceContext Private EntityManager em;

private EntityManagerFactory emf = em.getEntityManagerFactory();

emf.addNamedQuery("supplierStatus", em.createQuery("SELECT e.name FROM Employee e WHERE e.status = :status"));

Hamed Hatami @ 2014

JTA 1.2

* Declarative transactions outside EJB

* Transaction scope - @TransactionScoped

Hamed Hatami @ 2014

JTA 1.2 / Transactional Annotation

@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 UserService {...}

Hamed Hatami @ 2014

JSR 344: JavaServer Faces 2.2

• HTML5 Support (Form API)

• @FlowScoped

• @ViewScoped for CDI

• Stateless views

• Resource library contracts

• File upload component

• View actions

• Security

• Fixes and enhancements

Hamed Hatami @ 2014

JSF 2.2 / Pass-Through HTML 5 Components

<html>...<input type=“color” jsf:value=“#{colorBean.color2}” />...</html>

<h:inputText> <f:passThroughAttribute name="placeholder" value="Enter text"/> </h:inputText>

Hamed Hatami @ 2014

JSF 2.2 / Faces Flow

@Named@FlowScoped(id="flow-a")public class FlowABean implements Serializable {

public String getName() { return "FlowABean"; } public String getReturnValue() { return "/return1"; }

@Produces public Flow getFlow(FlowBuilder builder) { builder.startNode("router1"); builder.flowReturn("success").fromOutcome("/complete"); builder.flowReturn("errorOccurred").fromOutcome("error"); builder.switchNode("router1") .navigationCase().condition("#{facesFlowScope.customerId == null}") .fromOutcome("create-customer") .defaultOutcome("view-customer"); builder.viewNode("create-customer"); builder.viewNode("maintain-customer-record"); builder.methodCall("upgrade-customer") .method("#{maintainCustomerBean.upgradeCustomer}").defaultOutcome("view-customer"); builder.initializer("#{maintainCustomerBean.initializeFlow}"); builder.finalizer("#{maintainCustomerBean.cleanUpFlow}"); return builder.getFlow(); }}

Hamed Hatami @ 2014

JSF 2.2 / File Upload Component

<h:inputFile id="file“ value="#{fileUploadBean.uploadedFile}"> <f:validator validatorId="FileValidator" /></h:inputFile>

@Named @RequestScopedpublic class FileUploadBean { private Part uploadedFile; // getter/setter public String getFileText() { String text = ""; if (null != uploadedFile) { try { InputStream is = uploadedFile.getInputStream(); text = new Scanner( is ).useDelimiter("\\A").next(); } catch (IOException ex) {} } return text; }}

Hamed Hatami @ 2014

JSR 352: Batch Applications for the Java Platform 1.0

• Batch processing is execution of series of "jobs" that is suitable for non-interactive, bulk-oriented and long-running tasks.

• no standard Java programming model existed for batch applications.

• API for robust batch processing targeted to Java EE, Java SE

Hamed Hatami @ 2014

Batch Applications for the Java Platform / Step Example

<step id=”sendStatements”><chunk reader=”accountReader” processor=”accountProcessor” writer=”emailWriter” item-count=”10” /></step>

@Named(“accountReader")...implements ItemReader... {public Account readItem() {// read account using JPA

@Named(“accountProcessor")...implements ItemProcessor... {Public Statement processItems(Account account) {// read Account, return Statement

@Named(“emailWriter")...implements ItemWriter... {public void writeItems(List<Statements> statements) {// use JavaMail to send email

Hamed Hatami @ 2014

JSR 349: Bean Validation 1.1

• Method constraints

• Bean Validation artifacts injectable

• Fixes, clarifications and enhancements

Hamed Hatami @ 2014

Bean Validation 1.1 / Method Level Constraints

public void placeOrder(

@NotNull String productName,@NotNull @Max(“10”) Integer quantity,

@Customer String customer) {...}

@Futurepublic Date getAppointment() {...}

Hamed Hatami @ 2014

JSR 236: Concurrency Utilities for Java EE 1.0

• Provides simple, safe API for concurrency in Java EE

• Builds on Java SE concurrency - java.util.concurrent.ExecutorService

• Relatively low-level API

• Important enabler for Java EE ecosystem

• Managing your own threads within a Java EE container is not recommended

• Using java.util.concurrent API in a Java EE application component such as EJB or Servlet are problematic since the container and server have no knowledge of these resource

Hamed Hatami @ 2014

Concurrency Utilities for Java EE

Managed Task Executorpublic class TestServlet extends HTTPServlet {

@Resource(name=“concurrent/MyExecutorService”)private ManagedExecutorService executor;

Future future = executor.submit(new MyTask());

class MyTask implements Runnable { public void run() { ... // Task logic } }}

Hamed Hatami @ 2014

JSR 340: Servlet 3.1

• NIO.2 async I/O (Non-blocking I/O)

• Leverage Java EE concurrency

• Security improvements

• Web Sockets support

• Ease-of-Development

Hamed Hatami @ 2014

Servlet 3.1

@WebServlet(urlPatterns="/test", asyncSupported=true)public class TestServlet extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

AsyncContext ac = req.startAsync(); ac.addListener(new AsyncListener() {

public void onComplete(AsyncEvent event) throws IOException { event.getSuppliedResponse().getOutputStream().print("Complete"); } public void onError(AsyncEvent event) { System.out.println(event.getThrowable()); } public void onStartAsync(AsyncEvent event) { } public void onTimeout(AsyncEvent event) { System.out.println("my asyncListener.onTimeout"); }

});

...

Hamed Hatami @ 2014

JSR 345: Enterprise JavaBeans 3.2

The scope of EJB 3.2 is intended to be relatively constrained in focusingon these goals:

• Incremental factorization (Interceptors).

• Further use of annotations to simplify the EJB programming model.

• Proposed Optional: BMP/CMP.

• Proposed Optional: Web Services invocation using RPC.

Hamed Hatami @ 2014

Others

• CDI 1.1:

• Global enablement.• @AroundConstruct.• @Vetoed...

• EL 3.0:

• Lambda expressions.• Collections,• Operators,• Standalone API...

Hamed Hatami @ 2014

Support IDEs and Servers

IDEs

• Netbeans 7.4 – free

• IntelliJ IDEA 12.x~13 – commercial and community edition

• Eclipse Juno 4.0 - free

Servers

• GlassFish 4.0 (RI)

• Wildfly 8.0 (CR1)

• Weblogic 12.1.2c Partially (WS,JSON-P).

• Apache Tomcat Version 8.0.0-RC5.

Hamed Hatami @ 2014

Resources

• Java EE Tutorials • http://docs.oracle.com/javaee/7/tutorial/doc/home.htm • http://www.programming-simplified.com/index.html

• Digging Deeper • http://docs.oracle.com/javaee/7/firstcup/doc/home.htm • https://glassfish.java.net/hol/ • https://java.net/projects/cargotracker/

• Java EE 7 Transparent Expert Groups • http://javaee-spec.java.net• Java EE 7 Reference Implementación • http://glassfish.org• The Aquarium • http://blogs.oracle.com/theaquarium• Speakers • http://www.infoq.com/presentations/Java-EE-7-8

Hamed Hatami @ 2014

Thanks for listening and attending