Java EE 7 from an HTML5 Perspective, JavaLand 2015

2,484 views

Published on

This 45 minute session begins by explaining what we mean by the admittedly vague term "HTML5 web application". We use the Cargo Tracker sample Java EE 7 application as the vehicle for this explanation. Diving into the code, we examine the parts of the Java EE 7 family of technologies, and the HTML5 techniques used in the application.

Published in: Software

Java EE 7 from an HTML5 Perspective, JavaLand 2015

  1. 1. JAVA EE 7 FROM AN HTML5 PERSPECTIVE Ed Burns @edburns and Oliver Szymanski @source_knights
  2. 2. 2 Safe Harbor Statement 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. Copyright 2015 Ed Burns and Oliver Szymanski
  3. 3. Speaker Qualifications – Ed Burns Copyright 2015 Ed Burns and Oliver Szymanski 3 ¨  Involved with JSF since 2002 ¨  JSF Spec lead since 2003 ¤  Most fun part of the job: cleanly integrating other people’s great ideas into JSF (and hopefully improving on the in the process) ¤  Not an expert in applying JSF in practice ¨  Servlet Spec lead since 2014
  4. 4. Speaker Qualifications – Ed Burns Copyright 2015 Ed Burns and Oliver Szymanski 4 ¨  Author of four books for McGraw-Hill
  5. 5. Speaker Qualifications – Oliver Szymanski Copyright 2015 Ed Burns and Oliver Szymanski 5 ¨  Independent Java Enterprise Consultant ¨  Specialty in the Financial Sector ¨  JUG Founder Erlangen/Nuremberg Germany
  6. 6. Speaker Qualifications – Oliver Szymanski Copyright 2015 Ed Burns and Oliver Szymanski 6 ¨  Contributing author for ¤  Heise Developer Channel ¤  S&S Entwickler ¤  Java aktuell ¤  Java Magazin
  7. 7. Meet the Family Copyright 2015 Ed Burns and Oliver Szymanski 7
  8. 8. Meet the Family ¨  Java API for JSON Processing ¨  Java API for WebSocket ¨  Batch Application ¨  Concurrency Utilities ¨  Caching ¨  Java Persistence Architecture ¨  … ¨  Java API for REST ¨  JavaServer Faces ¨  Servlets ¨  Expression Language ¨  Java Messaging Service ¨  Contexts and Dependency Injection ¨  Java Transaction Architecture 8 Copyright 2015 Ed Burns and Oliver Szymanski
  9. 9. Meet the HTML5-Friendly Family ¨  Java API for JSON Processing ¨  Java API for WebSocket ¨  Batch Application ¨  Concurrency Utilities ¨  Caching ¨  Java Persistence Architecture ¨  … ¨  Java API for REST ¨  JavaServer Faces ¨  Servlets ¨  Expression Language ¨  Java Messaging Service ¨  Contexts and Dependency Injection ¨  Java Transaction Architecture 9 Copyright 2015 Ed Burns and Oliver Szymanski
  10. 10. HTML5Why all the fuss? More cute logos at http://www.w3.org/html/logo/
  11. 11. HTML5Why all the fuss? PAST AND PRESENT SERVER
  12. 12. Classification ¨  Why? ¤  Multiple Computers ¤  Interconnections Between Them ¤  Shared State Among Them ¨  Today's production Web apps are extremely complex distributed applications. A Web App is a Distributed App
  13. 13. Yeah, So What? ¨  Why does this classification matter? ¤  Because History Matters ¨  To understand the current state of web applications, we must go back to the history of distributed applications, and of the Internet itself.
  14. 14. HTML5 ¨  Remember all the fuss about Ajax in 2006? ¤  Asynchronous ¤  JavaScript ¤  And ¤  XMLHttpRequest What’s in a name?
  15. 15. HTML5 ¨  Remember all the fuss about Ajax in 2006? ¤  Asynchronous ¤  JavaScript ¤  And ¤  XMLHttpRequest ¨  Ajax is a programming technique, not a single technology What’s in a name?
  16. 16. HTML4 ¨  What do people mean when they say HTML4? ¤  IE6 ¤  Not very high performance JavaScript ¤  Lots of browser tricks ¤  Use of native plugins is common ¨  HTML4 is seen as a single technology What’s in a name?
  17. 17. HTML5 ¨  What do people mean when they say HTML5? ¤  “Modern” browsers ¤  A gigantic collection of related technologies n  Markup n  Offline storage n  EventSource n  DOM n  JavaScript n  CSS3 What’s in a name? n  Canvas n  Input controls n  Web components n  Application Cache n  WebSocket n  JSON n  Geolocation n  XMLHttpRequest Level 2
  18. 18. HTML5 ¨  The rise of Chrome and the end of polyfill ¨  Standards have finally won ¤  How good is your standards body? n  W3C, ECMA, IETF ¤  HTML5: Microsoft, Google, Apple, what about Mozilla? ¨  Aside: ¤  Is HTML5 a bloated specification? ¤  Is JavaEE a bloated specification? ¤  What is bloat? A indicator of how old something is. ¤  http://mir.aculo.us/2010/10/19/standards-bloat-and- html5/ Is it really a big deal?
  19. 19. HTML5 ¨  The death of the browser plugin: April 2010 http://www.apple.com/hotnews/thoughts-on-flash/ ¨  Where does the tension remain? ¤  Take advantage of the power in the client ¤  Minimize the complexity of distributing and maintaining the software Is it really a big deal?
  20. 20. HTML5 ¨  HTML5 is a marketing term that describes a way of building the UI for a distributed system. ¤  UI processing task resides entirely in the browser Putting it in context
  21. 21. What Makes a Distributed App ¨  Finding the best allocation of processing tasks to processing nodes ¤  User Interface ¤  Domain Logic ¤  Application Logic ¤  Data Persistence ¤  Communication ¤  Reliability, Security
  22. 22. What Makes a Distributed App ¨  Finding the best allocation of processing tasks to processing nodes ¤  User Interface ¤  Domain Logic ¤  Application Logic ¤  Data Persistence ¤  Communication ¤  Reliability, Security
  23. 23. UI Considerations ¨  The UI is the hardest part to get right ¨  The technology for building the UI is changing very rapidly, and will continue to change for the forseeable future ¨  The technology for the other aspects of application development is less volatile, more mature. ¨  The major software stack and device vendors are competing on the basis of their UI technology, as the gateway to the rest of their stack
  24. 24. HTML5 Friendly Markup ¨  This is a JSF page The best part of Wicket comes to JSF <!DOCTYPE html>! <html xmlns="http://www.w3.org/1999/xhtml"! xmlns:myNS="http://xmlns.jcp.org/jsf”>! <form myNS:id="form">! <input name="textField" type="text" myNS:value="#{bean.text1}" />! <input type="submit" myNS:id="submitButton" value="submit" /> ! <p>submitted text: #{bean.text1}.</p>! </form>! </html>! !
  25. 25. HTML5 Friendly Markup ¨  JSF Views are written in a View Declaration Language (VDL). ¨  The standard Facelet VDL is an XML application with two kinds of elements ¤  HTML Markup ¤  JSF Components ¨  HTML Markup is passed through straight to the browser ¨  JSF Components take some action on the server, during the lifecycle` Let’s get back to basics
  26. 26. HTML5 Friendly Markup ¨  Before JSF 2.2 ¤  JSF tags hide complexity of underlying HTML+script+css +images ¤  JSF “Renderer”: n  encode: markup to browser n  decode: name=value from browser <html>… <my:colorPicker value=“#{colorBean.color2}” /> <my:calendar value=“#{calendarBean.date1}” /> </html> ¨  Context: Missing feature in browser? Write a JSF component. Let the elegance of HTML shine through
  27. 27. HTML5 Friendly Markup ¨  With JSF 2.2 ¤  Pure HTML+script+css+images in the JSF page ¤  JSF Renderer handles decode from browser n  Leverage the strength of the JSF lifecycle n  Leverage the expressiveness of HTML5 <html>… <input type=“color” jsf:value=“#{colorBean.color2}”/> <input type=“date” jsf:value=“#{calendarBean.date1}” /> </html> ¨  Context: New feature in browser? Use “pass through elements” Let the elegance of HTML shine through
  28. 28. JSR 341 Expression Language 3.0 ¨  First introduced in JSTL 1.0 in 2004 ¨  Moved to JSP 2.0 in 2006 ¨  Unified with JSF 1.2 in JSP 2.1 in 2006 ¨  JSR 341: first independent specification in 2013 ¨  Used in JSF, JSP and CDI ¨  Key differentiator between JavaServer and non- JavaServer stacks Overview
  29. 29. JSR 341 Expression Language 3.0 ¨  Lambda expressions ¨  Support for stand-alone environments ¨  New operators ¨  Static field and method reference ¨  Custom type converter ¨  Collection construction ¨  Collection operations New Feature Summary
  30. 30. JSR 341 Expression Language 3.0 ¨  Same syntax as JavaSE 8, but available in EE 7 ¨  Behaves like an anonymous function ¨  Body consist of an EL expression ¨  Full access to EL environment in the body Lambda expression x -> x+1! (x,y) -> x+y! () -> 64!
  31. 31. JSR 341 Expression Language 3.0 ¨  The lambda is evaluated and discarded Lambda expression: immediate evaluation (x -> x+1)(10)! !à 11! ((x,y)->x+y)(3,4) !à 7! (()->64)() ! !à 64!
  32. 32. JSR 341 Expression Language 3.0 ¨  JSF Facelet page <h:dataTable rendered=!“#{user.loggedIn}”
 value="#{library.books.stream().
 filter(b->b.category == 'Comedy').
 map(b->b.title).toList()}" var="book">! <h:column>#{book.title}</h:column>! </h:dataTable>! Collection operations: examples
  33. 33. What Makes a Distributed App ¨  Finding the best allocation of processing tasks to processing nodes ¤  User Interface ¤  Domain Logic ¤  Application Logic ¤  Data Persistence ¤  Communication ¤  Reliability, Security
  34. 34. Java API for JSON Processing 1.0 ¨  API to parse and generate JSON ¨  Streaming API ¤  Low-level, efficient way to parse/generate JSON ¤  Provides pluggability for parsers/generators ¨  Object Model ¤  Simple, easy-to-use high-level API ¤  Implemented on top of Streaming API ¨  Binding JSON to Java objects forthcoming Overview – JSR 353
  35. 35. Java API for JSON Processing 1.0 ¨  Parses JSON in a streaming way from input sources ¤  Similar to StaX’s XMLStreamReader, a pull parser ¨  Created using ¤  Json.createParser(…)! ¤  Json.createParserFactory().createParser( …)! ¨  Parser state events ¤  START_ARRAY, END_ARRAY, START_OBJECT, END_OBJECT, … Streaming API
  36. 36. Java API for JSON Processing 1.0 ¨  JsonObject/JsonArray – JSON object and array structures ¤  JsonString and JsonNumber for string and number values ¨  JsonBuilder – Builds JsonObject and JsonArray ¨  JsonReader – Reads JsonObject and JsonArray from input source ¨  JsonWriter – Writes JsonObject and JsonArray to output source Object Model API
  37. 37. Java API for RESTful Web Services 2.0 ¨  Client API ¨  Message Filters & Entity Interceptors ¨  Asynchronous Processing – Server & Client ¨  Hypermedia Support ¨  Common Configuration Overview – JSR 339
  38. 38. 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);! }! });! }! }!
  39. 39. 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() {
         . . .
     }
 }!
  40. 40. Java Message Service 2.0 ¨  Less verbose ¨  Reduce boilerplate code ¨  Resource injection ¨  Connection, Session, and other objects are AutoCloseable ¨  Requires Resource Adapter for Java EE containers ¨  Simplified API in both Java SE and EE Overview – JSR 343
  41. 41. Java Message Service 2.0 ¨  Make JMS objects implement AutoCloseable! ¤  Connection ! ¤  Session ! ¤  MessageProducer ! ¤  MessageConsumer ! ¤  QueueBrowser! ¨  Requires Java SE 7 Auto close resources
  42. 42. @Resource(lookup = "jms/connFactory")
 ConnectionFactory cf; ! @Resource(lookup="jms/inboundQueue")! Destination dest;! ! public void sendMessage (String payload) throws JMSException {! try ( Connection conn = connectionFactory.createConnection(); ! Session session = conn.createSession();! MessageProducer producer = session.createProducer(dest);! ){ ! Message mess = sess.createTextMessage(payload); ! producer.send(mess); ! } catch(JMSException e){ ! // exception handling ! }
 }! Create closeable resources in a try- with-resources block close() is called automatically at end of block Java Message Service 2.0 Auto close resources
  43. 43. @Resource(lookup = "java:global/jms/demoConnectionFactory")! ConnectionFactory connectionFactory; ! ! @Resource(lookup = "java:global/jms/demoQueue")! Queue demoQueue;! ! public void sendMessage (String payload) {! try (JMSContext context = connectionFactory.createContext();){! context.createProducer().send(demoQueue, payload);! } catch (JMSRuntimeException ex) {! // exception handling! }! }! close() is called automatically at end of block JMSContext combines Connection and Session Payload can be sent directly No checked exceptions thrown Java Message Service 2.0 Introducing JMSContext
  44. 44. @Inject
 JMSContext context;! ! @Resource(lookup = "java:global/jms/demoQueue”)
 Queue demoQueue;! ! public void sendMessage(String payload) {! context.createProducer().send(demoQueue, payload);! }! Default resource definition Or @JmsConnectionFactory! 13 lines è1 line! Java Message Service 2.0 Default Data Source Definition
  45. 45. What Makes a Distributed App ¨  Finding the best allocation of processing tasks to processing nodes ¤  User Interface ¤  Domain Logic ¤  Application Logic ¤  Data Persistence ¤  Communication ¤  Reliability, Security
  46. 46. WebSockets ¨  Several moving parts, each with its own standard! ¤  Client: W3C JavaScript API http://dev.w3.org/html5/ websockets/ ¤  Transport: IETF RFC 6455 http://www.ietf.org/rfc/ rfc6455.txt ¤  Server: JSR-356: http://jcp.org/en/jsr/detail?id=356 ¨  Even with all these parts, it’s still very understandable ¤  Client: 17 page downs ¤  Transport: 86 page downs (about a third of which you can skip) What’s In a name?
  47. 47. WebSockets
  48. 48. WebSocket ¨  It really is a Socket for the Web ¤  It just works over proxies ¨  Lets you do TCP easily in a web app ¤  Establish the connection ¤  Send messages both ways ¤  Send messages independent of timing ¤  Close the connection ¨  Two basic types: text and binary Big Picture
  49. 49. WebSocketEstablish the connection
  50. 50. WebSocketTCP over HTTP, use the Upgrade: header
  51. 51. WebSocketTCP over HTTP, use the Upgrade: header
  52. 52. WebSocketTCP over HTTP, use the Upgrade: header
  53. 53. WebSocketBrowser Support – caniuse.com
  54. 54. JavaScript/Browser Client ¨  Minimal Lifecycle ¤  new WebSocket(url)! ¤  pass in some functions n  onopen! n  onmessage! ¤  call send()! ¤  call close() ! ¨  Can connect to arbitrary servers, other than the page origin ¨  Server may enforce use of Origin header JavaScript WebSocket Object
  55. 55. JavaScript/Browser ClientJavaScript WebSocket Object ¨  [Clamp] if value is out of range, truncate it to closest in- range value for that primitive type.
  56. 56. Java Server ¨  Minimal Lifecycle ¤  Handshake ¤  Messaging ¤  Close ¨  All methods that deal with communication to the other endpoint are passed a javax.websocket.Session. ¨  Has nothing to do with javax.servlet.http.HttpSession. ¨  HttpSession can be obtained from Java Endpoint
  57. 57. Java Server ¨  Passing Parameters ¨  example URI “/bookings/JohnSmith”: guestID is “JohnSmith” ¨  Strings and primitives supported Java Endpoint
  58. 58. Java Server Two Styles ¨  Annotated ¤  The most commonly used ¤  Very easy to get started ¤  Throw it in the WAR and you’re done ¨  Programmatic ¤  If you don’t want to bake config into your .class files ¤  Must use Java inheritance Java Endpoint
  59. 59. Java Server ¨  Must bootstrap via ServletContextListener! ¤  Look up the javax.websocket.server.ServerContaine r attribute ¤  It will be an instance of javax.websocket.server.ServerContaine r! ¤  Call addEndpoint(), two variants n  takes a class that is the annotated endpoint class n  takes a ServerEndpointConfig instance Programmatic Endpoint
  60. 60. Java ServerAnnotated Endpoint
  61. 61. Java ServerAnnotated Endpoint
  62. 62. Java Server ¨  The ServerEndpointConfig instance ¤  getEndpointClass() returns n  annotated endpoint n  class that extends javax.websocket.Endpoint! ¤  getPath() returns the path, may contain url- template content Programmatic Endpoint
  63. 63. WebSocket ¨  Send or receive text or binary messages ¤  As complete messages ¤  As sequence of partial messages ¤  Using traditional blocking I/O ¨  Send or receive WebSocket messages as pure Java Objects (kinda like Serialization) ¤  Using encode/decode mechanism ¤  Encoder/decoder for all primitive types built in ¨  Send and receive messages synchronously or asynchronously Flexible Message Processing
  64. 64. 66 Safe Harbor Statement The preceding was intended to outline our general product direction. It was intended for information purposes only, and may not be incorporated into any contract. It was 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. Copyright 2015 Ed Burns and Oliver Szymanski
  65. 65. Thank you67 Copyright 2015 Ed Burns and Oliver Szymanski

×