Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java EE 7 Overview Hamed Hatami January 2014 from Iran JUG.

Similar presentations


Presentation on theme: "Java EE 7 Overview Hamed Hatami January 2014 from Iran JUG."— Presentation transcript:

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

2 Hamed Hatami @ 2014 Agenda  Overview  A Taste of API Changes  Looking Ahead

3 Hamed Hatami @ 2014 Java EE 7 Launch Last Month June 2013

4 Hamed Hatami @ 2014 Java EE 7 - Major Themes in Context 2014 - Future2013 - Future 1998-2004 Enterprise Java Platform Robustness Web Services J2EE 20 specs Java EE 7 2005-2012 Ease of Development Lightweight Developer Productivity & HTML5 32 specs EE 5, EE 6 28 specs

5 Hamed Hatami @ 2014 Java EE 7 – Past, Present, Future

6 Hamed Hatami @ 2014 Java EE 7 – Themes

7 Hamed Hatami @ 2014 Java EE 7 - JSRs Connector 1.6 Managed Beans 1.0 EJB 3.2 Servlet 3.1 Portable Extension s Portable Extension s JSF 2.2 JAX-RS 2.0 JMS 2.0 JPA 2.1 EL 3.0 JTA 1.2 JSP 2.2 Interceptors 1.1 CDI 1.1 Common Annotations 1.1 Concurrency Utilities (JSR 236) Concurrency Utilities (JSR 236) Batch Applications (JSR 352) Java API for JSON (JSR 353) Java API for WebSocket (JSR 356) Java API for WebSocket (JSR 356) Updated Major Release New

8 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 of transaction management, security, and persistence. but are not supported by standalone servlet containers. Web Profile is provided with pre-installed, pre-integrated, fully tested Web infrastructure features. The Java EE 7 Web Profile adds support for HTML5 with WebSockets, JSON, JAX-RS 2.0, and more.

9 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

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

11 Hamed Hatami @ 2014 JMS 2 - Simplified API @Inject private JMSContext context; @Resource(mappedName = "jms/inboundQueue") private Queue inboundQueue; public void sendMessage (String payload) { context.createProducer().send(inboundQueue, payload); }

12 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")

13 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) {... }... }

14 Hamed Hatami @ 2014 Why WebSocket? HTTP is half duplex HTTP is verbose Hacks for Server Push Polling Long Polling Comet/Ajax Complex, Wasteful, Inefficient

15 Hamed Hatami @ 2014 HTTP Communication

16 Hamed Hatami @ 2014 Polling

17 Hamed Hatami @ 2014 Long Polling

18 Hamed Hatami @ 2014 HTTP Streaming (Comet)

19 Hamed Hatami @ 2014 WebSocket to rescue TCP based, bi-directional, full-duplex messaging Capable of sending both UTF-8 string and binary frames in any direction at the same time Operating from a single socket across the web As part of HTML5, the application of the client interface will become native to all modern browsers To establish a Web Socket connection, the browser or client simply makes a request to the server for an upgrade from HTTP to a Web Socket

20 Hamed Hatami @ 2014 Java API for WebSocket @ServerEndpoint(”/chat”) public class ChatServer { Set peers =... @OnOpen public void onOpen(Session peer) { peers.add(peer); } @OnClose public void onClose(Session peer) { peers.remove(peer); }...

21 Hamed Hatami @ 2014 Java API for WebSocket @OnMessage public void message(String message, Session client) throws IOException { for (Session session : peers) { if (!session.equals(client)) { session.getRemote().sendObject(message); }

22 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.

23 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.

24 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" } ]

25 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

26 Hamed Hatami @ 2014 JAX-RS 2 // Get instance of Client Client client = ClientBuilder.newClient(); // Get customer name for the shipped products String name = client.target(“../orders/{orderId}/customer”).pathParam(”orderId", ”10”).queryParam(”shipped", ”true”).request().get(String.class);

27 Hamed Hatami @ 2014 JAX-RS 2 / Logging Filter public class RequestLoggingFilter implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) { log(requestContext); // Non-wrapping => returns without invoking next filter }... }

28 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

29 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”

30 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);

31 Hamed Hatami @ 2014 JPA 2.1 / Unsynchronized Persistence Context @Stateful public 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); }

32 Hamed Hatami @ 2014 JPA 2.1 JOIN using the ON condition SELECT e FROM Employee e LEFT JOIN e.address ON a.city = :city Support for downcast in JPQL SELECT b.name FROM User e JOIN TREAT(e.projects AS LargeProject) b Support for Functions in JPQL SELECT 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 q = cb.createCriteriaUpdate(Employee.class); Root 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 { @PostPersist public void alert(Customer c) { … }

33 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") );

34 Hamed Hatami @ 2014 JTA 1.2 * Declarative transactions outside EJB * Transaction scope - @TransactionScoped

35 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 {...}

36 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

37 Hamed Hatami @ 2014 JSF 2.2 / Pass-Through HTML 5 Components......

38 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(); }

39 Hamed Hatami @ 2014 JSF 2.2 / File Upload Component @Named @RequestScoped public 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; }

40 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

41 Hamed Hatami @ 2014 Batch Applications for the Java Platform / Step Example <chunk reader=”accountReader” processor=”accountProcessor” writer=”emailWriter” item-count=”10” /> @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) { // use JavaMail to send email

42 Hamed Hatami @ 2014 JSR 349: Bean Validation 1.1 Method constraints Bean Validation artifacts injectable Fixes, clarifications and enhancements

43 Hamed Hatami @ 2014 Bean Validation 1.1 / Method Level Constraints public void placeOrder( @NotNull String productName, @NotNull @Max(“10”) Integer quantity, @Customer String customer) {... } @Future public Date getAppointment() {... }

44 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

45 Hamed Hatami @ 2014 Concurrency Utilities for Java EE Managed Task Executor public 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 }

46 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

47 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"); } });...

48 Hamed Hatami @ 2014 JSR 345: Enterprise JavaBeans 3.2 The scope of EJB 3.2 is intended to be relatively constrained in focusing on 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.

49 Hamed Hatami @ 2014 Others CDI 1.1: Global enablement. @AroundConstruct. @Vetoed... EL 3.0: Lambda expressions. Collections, Operators, Standalone API...

50 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.

51 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

52 Hamed Hatami @ 2014 Thanks for listening and attending


Download ppt "Java EE 7 Overview Hamed Hatami January 2014 from Iran JUG."

Similar presentations


Ads by Google