KEMBAR78
Web Technologies in Java EE 7 | PDF
Web Technologies
in Java EE
JSF 2.2, JAX-RS 2.0, JSON-P, WebSocket
Agenda
•
•
•
•
•

Client-Side vs Server-Side Web
JAX-RS 2.0 RESTful Services
JSON-P Java API for JSON Processing
Java API for WebSocket
JSF 2.2 Java Server Faces
$ whoami
• Lukáš Fryč
– Software Engineer, JBoss, Red Hat
• RichFaces & Arquillian Core Developer

– Interests
•
•
•
•

Living and advocating Java EE (6 yrs)
HTML5, Web Components, AngularJS
Running, Hiking
Spending time with my family
Client-Side
vs

Server-Side
Web Architecture
Client- vs. Server-Side Web
• Server-Side Web (Thin Client)
– Well-established approach
– 90's, 00's

• Client-Side Web (Thick Client)
– Modern approach
– Fully leverages enhancements in web standards
and protocols
– 10's
Server-Side
Client-Side
Client-Side Web Approach
• Off-loading server
– Scalability, Stateless

• Client-Side Frameworks
– AngularJS, Ember, Backbone, Errai, Polymer, ..........

• Standards improvements
– HTML5 + Protocols

• REST interfaces
– Data-oriented, presentation independent
Java API for RESTful
Services
JAX-RS 2.0
JAX-RS Origins
• RESTful Principles
– Assign everything an ID
– Link things together
– Use common methods (GET, POST, ...)
– Stateless communication
JAX-RS 1.0 Goals
• POJO-Based API
• HTTP Centric
• Format Independence
– plain/text
– XML
– HTML
– JSON
JAX-RS API
• Resources
– @Path

• HTTP methods
– @GET / @POST / @PUT / @DELETE / ...

• Parameters
– @PathParam / @QueryParam / ...

• Media-Type
– @Consumes / @Produces
Demo
JAX-RS Endpoint
http://javaee-samples.github.io/
HTTP Method Purpose
Method

Meaning

@GET

Read, possibly cached

@POST

Use to modify or update a
resource or create new one
(without known ID)

@PUT

Create a resource or
overwrite existing ( with
known ID)

@DELETE

Remove

@HEAD

GET with no response

@OPTIONS

Supported methods
Parameter Injection
Annotation

Example

@PathParam(“id”)

@Path(“/consumer/{id}”)

@QueryParam(“query”)

GET /consumer/search?
query=???

@CookieParam(“userna
me”)

Cookie: ...

@HeaderParam(“Authori
zation”)

Header: Authorization: ...

@FormParam(“inputNa
me”)

@Consumes("multipart/form-data")

@MatrixParam

GET /consumer/search;query=???
New in JAX-RS 2.0
• New Features
– Client API
– Filters and Interceptors
– Asynchronous API
– Hypermedia

• Improvements
– Content-Type Negotiation
– Validation Alignments
Client API
• HTTP client libraries too low-level
• Need for standardization
Demo
JAX-RS – Client API
Filters and Interceptors
• Customize JAX-RS
– via well-defined extension points

• Use cases:
– Logging
– Compression
– Security

• Shared between server & client
Filters
• Non-wrapping extension points
– Pre: RequestFilter
– Post: ResponseFilter

• Part of a filter chain
• Do not call the next filter directly
• Each filter decides to proceed or break
chain
– FilterAction.NEXT, FilterAction.STOP
Interceptors
• Wrapping extensions points
– ReadFrom: ReaderInterceptor
– WriteTo: WriterInterceptor

• Part of an interceptor chain
• Call the next handler directly
• Each handler decides to proceed or
break chain
– By calling ctx.proceed();
Asynchronous
• Let “borrowed” threads run free!
– Suspend and resume connections
• Suspend while waiting for an event
(@Suspended AsyncResponse)
• Resume when event arrives

• Leverages Servlet 3.x async support
– HttpServletRequest.upgrade(ProtocolHandler)

• Client API support
– Future<T>, InvocationCallback<T>
Demo
JAX-RS – Asynchronous
Validation
• Constraint annotations
– Fields and properties
– Parameters
• Including request entity

– Methods
• Response entities

– Resource classes

• Custom constraints
Demo
JAX-RS – Bean Validation
Hypermedia
• Link types
– Structural links
• <customer>http://.../customers/1234</customer>

– Transitional links
• Links: <http://.../cancel>; rel=cancel
Java API for JSON
Processing
JSON-P
Motivation: JSON
• JavaScript Object Notation
– The format of the Web
• Comes from JavaScript object syntax
• Human-Readable

– Language independent
• Standard parsers in many languages

– Key-value Pair Format
{ “firstName”: “John”, “lastName”: “Smith” }
Motivation: Java API for JSON
• Lot of vendor-dependent APIs
– Need for standardization

• Standard API for JSON processing
– parse, generate, transform

• Binding? Querying?
JSON-P APIs
• Streaming API
• Similar to XML DOM

• Object Model API
• Similar to StAX
JSON-P APIs
• Streaming API
– JsonParser, JsonGenerator

• Object Model API
– JsonObject, JsonArray
– JsonBuilder
– JsonReader, JsonWriter
Object Model - JsonReader
• Reads JsonObject and JsonArray
– I/O Reader, InputStream

• Uses pluggable JsonParser
// Reads a JSON Object
try (JsonWriter reader = Json.createReader(io)) {
JsonObject obj = reader.readObject();
}
Object Model - JsonWriter
• Writes JsonObject and JsonArray
to output source
– I/O Writer, OutputStream

• Uses pluggable JsonGenerator
• Allows pretty-printing and other features
// Writes a JSON Object
JsonObject obj;
try (JsonWriter writer = Json.createWriter(io)) {
Writer.writeObject(obj);
}
Object Model – Json*Builder
• Chained API
– For bulding JsonObject and JsonArray
• Can consume JsonObject and JsonArray

– Type-safe (no mixing arrays/objects)

• Json.createObjectBuilder()
• Json.createArrayBuilder()
Demo
JSON Object Model API
Streaming - JsonParser
• Parses JSON in a streaming way from
input sources
– Similar to StAX’s XMLStreamReader
– a pull parser

• Json.createParser()
Streaming - JsonGenerator
• Generates JSON in a streaming way to
output sources
– Similar to StAX’s XMLStreamWriter

• Json.createGenerator()
Demo
JSON Streaming API
Java API for WebSocket
Motivation
• HTTP is half-duplex
• HTTP is inefficient
• HTTP hacked to achieve Push
– HTTP Polling
– HTTP Long-Polling (Comet)
– Server Sent Events
HTTP Upgrade - Request
GET /socket/updates HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: www.sample.org
HTTP Upgrade - Response
HTTP/1.1 101 WebSocket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
WebSocket
• Full duplex & efficient communication
• A component of HTML5
– JavaScript API under W3C
– Protocol under IETF

• Wide support for browsers
– http://caniuse.com/#feat=websockets
WebSocket: Limitations
• Use of existing infrastructure
– Proxies doesn't have to handle connection
upgrade

• Fallback mechanisms
– Atmosphere
WebSocket: Trade-offs
• WebSocket
– Low efforts to maintain TCP connection
– Limited by number of available sockets on
one machine
– Highly interactive applications
• I.e. don't use if you don't expect high amount of
transfered messages

• HTTP
– Resource-consuming protocol
– Fairly interactive applications
WebSocket: Use Cases
• Realtime, truly low latency
– Chat applications
– Live sports ticker
– Realtime updating social streams
– Multiplayer online games

• Requires architecture shift to
– Non-blocking IO
– Event queues
Java API for WebSocket
• Programmatic
• Annotation-based
– our focus
WebSocket Annotations
• @ServerEndpoint
– @OnOpen
– @OnMessage
– @OnClose
Demo
WebSocket - Whiteboard
Method Parameters
• Session
• Implicitly supported types
– String, byte[]
– JsonArray, JsonObject

• More types supported by Encoders
Integration to Java EE 7
• Relation to Servlet 3.1
– HttpServletRequest.upgrade(ProtocolHandler)

• Dependency Injection
– CDI beans
– EJB beans

• Security
– ws://... vs. wss://...

– web.xml: <security-constraint>
JavaServer Faces
JSF 2.2
JSF Origins
• MVC Framework
– Component-oriented
– Server-Side
– Extensible

• Component Libraries
Component Libraries
• Rich components
– RichFaces
– PrimeFaces
– ICEFaces

• Functionality
– PrettyFaces
– OmniFaces
JSF 1.0 Goals
• What it adds over other frameworks?
– Maintainability
– Tooling Support
– I18N
JSF 1.0 Goals
• What it adds over other frameworks?
– Maintainability
– Tooling Support
– I18N
JSF 1.0
•
•
•
•
•
•
•

Components
Renderers
Managed beans (CDI)
Converters / Validators
Navigation
Request lifecycle
Error handling
JSF 2.0
•
•
•
•
•
•
•

Facelets (as default VDL)
Composite Components
AJAX
Resource Libraries
Behaviors
GET support - <f:viewParam>
Project Stage
JSF 2.2
• Big Tickets
– Performance, Markup, Multi-tenancy

• Small Features
– <f:viewAction>
– CSRF protection
– ClientWindow
– Favours CDI

• Many smaller improvements
JSF 2.2
• Stateless Views
• (Performance)

• HTML5 Friendly Markup
• (Modern Markups)

• Flows, Resource Library Contracts
• (Multi-Tenancy)
Stateless JSF
• What is state?
– UI Components, Model, Persistence
– Developer's concern

• Implementation
– <f:view transient=”true”>
HTML5 Friendly Markup
JSF Components
<html>
<my:colorPicker value=“#{colorBean.color2}” />
<my:calendar value=“#{calendarBean.date1}” />
</html>
HTML5 Markup
<html>
<input type=“color” j:value=“#{colorBean.color2}” />
<input type=“date” j:value=“#{calendarBean.date1}” />
</html>
Multitenant Capability
• JSF app as a collection of modules
– Faces Flows
• Modularize behavior
• Builds on navigation

– Resource Library Contracts
• Modularize appearance
• Builds on Facelets

• Well defined contract for each
Demo
JSF – Declarative Flows,
Resource Contracts
JSF Component Libraries
RichFaces
RichFaces 4.3
• Rich & interactive components
• Client-Side Validation
• Push
RichFaces 5.0
• Sneak peek
– Visual Improvements
• 3rd-party widget libraries
• Skinnability
– LESS
– Bootstrap 3

– New Components
• Charts
Summary
• JSF
– Fully-featured web framework

• JAX-RS
– RESTful services

• WebSocket
– Efficient bi-directional communication

• JSON-P
– Standardization of JSON processing
Links
• http://javaee-samples.github.io/

Web Technologies in Java EE 7

  • 1.
    Web Technologies in JavaEE JSF 2.2, JAX-RS 2.0, JSON-P, WebSocket
  • 2.
    Agenda • • • • • Client-Side vs Server-SideWeb JAX-RS 2.0 RESTful Services JSON-P Java API for JSON Processing Java API for WebSocket JSF 2.2 Java Server Faces
  • 3.
    $ whoami • LukášFryč – Software Engineer, JBoss, Red Hat • RichFaces & Arquillian Core Developer – Interests • • • • Living and advocating Java EE (6 yrs) HTML5, Web Components, AngularJS Running, Hiking Spending time with my family
  • 4.
  • 5.
    Client- vs. Server-SideWeb • Server-Side Web (Thin Client) – Well-established approach – 90's, 00's • Client-Side Web (Thick Client) – Modern approach – Fully leverages enhancements in web standards and protocols – 10's
  • 6.
  • 7.
  • 8.
    Client-Side Web Approach •Off-loading server – Scalability, Stateless • Client-Side Frameworks – AngularJS, Ember, Backbone, Errai, Polymer, .......... • Standards improvements – HTML5 + Protocols • REST interfaces – Data-oriented, presentation independent
  • 9.
    Java API forRESTful Services JAX-RS 2.0
  • 10.
    JAX-RS Origins • RESTfulPrinciples – Assign everything an ID – Link things together – Use common methods (GET, POST, ...) – Stateless communication
  • 11.
    JAX-RS 1.0 Goals •POJO-Based API • HTTP Centric • Format Independence – plain/text – XML – HTML – JSON
  • 12.
    JAX-RS API • Resources –@Path • HTTP methods – @GET / @POST / @PUT / @DELETE / ... • Parameters – @PathParam / @QueryParam / ... • Media-Type – @Consumes / @Produces
  • 13.
  • 14.
    HTTP Method Purpose Method Meaning @GET Read,possibly cached @POST Use to modify or update a resource or create new one (without known ID) @PUT Create a resource or overwrite existing ( with known ID) @DELETE Remove @HEAD GET with no response @OPTIONS Supported methods
  • 15.
    Parameter Injection Annotation Example @PathParam(“id”) @Path(“/consumer/{id}”) @QueryParam(“query”) GET /consumer/search? query=??? @CookieParam(“userna me”) Cookie:... @HeaderParam(“Authori zation”) Header: Authorization: ... @FormParam(“inputNa me”) @Consumes("multipart/form-data") @MatrixParam GET /consumer/search;query=???
  • 16.
    New in JAX-RS2.0 • New Features – Client API – Filters and Interceptors – Asynchronous API – Hypermedia • Improvements – Content-Type Negotiation – Validation Alignments
  • 17.
    Client API • HTTPclient libraries too low-level • Need for standardization
  • 18.
  • 19.
    Filters and Interceptors •Customize JAX-RS – via well-defined extension points • Use cases: – Logging – Compression – Security • Shared between server & client
  • 20.
    Filters • Non-wrapping extensionpoints – Pre: RequestFilter – Post: ResponseFilter • Part of a filter chain • Do not call the next filter directly • Each filter decides to proceed or break chain – FilterAction.NEXT, FilterAction.STOP
  • 21.
    Interceptors • Wrapping extensionspoints – ReadFrom: ReaderInterceptor – WriteTo: WriterInterceptor • Part of an interceptor chain • Call the next handler directly • Each handler decides to proceed or break chain – By calling ctx.proceed();
  • 22.
    Asynchronous • Let “borrowed”threads run free! – Suspend and resume connections • Suspend while waiting for an event (@Suspended AsyncResponse) • Resume when event arrives • Leverages Servlet 3.x async support – HttpServletRequest.upgrade(ProtocolHandler) • Client API support – Future<T>, InvocationCallback<T>
  • 23.
  • 24.
    Validation • Constraint annotations –Fields and properties – Parameters • Including request entity – Methods • Response entities – Resource classes • Custom constraints
  • 25.
  • 26.
    Hypermedia • Link types –Structural links • <customer>http://.../customers/1234</customer> – Transitional links • Links: <http://.../cancel>; rel=cancel
  • 27.
    Java API forJSON Processing JSON-P
  • 28.
    Motivation: JSON • JavaScriptObject Notation – The format of the Web • Comes from JavaScript object syntax • Human-Readable – Language independent • Standard parsers in many languages – Key-value Pair Format { “firstName”: “John”, “lastName”: “Smith” }
  • 29.
    Motivation: Java APIfor JSON • Lot of vendor-dependent APIs – Need for standardization • Standard API for JSON processing – parse, generate, transform • Binding? Querying?
  • 30.
    JSON-P APIs • StreamingAPI • Similar to XML DOM • Object Model API • Similar to StAX
  • 31.
    JSON-P APIs • StreamingAPI – JsonParser, JsonGenerator • Object Model API – JsonObject, JsonArray – JsonBuilder – JsonReader, JsonWriter
  • 32.
    Object Model -JsonReader • Reads JsonObject and JsonArray – I/O Reader, InputStream • Uses pluggable JsonParser // Reads a JSON Object try (JsonWriter reader = Json.createReader(io)) { JsonObject obj = reader.readObject(); }
  • 33.
    Object Model -JsonWriter • Writes JsonObject and JsonArray to output source – I/O Writer, OutputStream • Uses pluggable JsonGenerator • Allows pretty-printing and other features // Writes a JSON Object JsonObject obj; try (JsonWriter writer = Json.createWriter(io)) { Writer.writeObject(obj); }
  • 34.
    Object Model –Json*Builder • Chained API – For bulding JsonObject and JsonArray • Can consume JsonObject and JsonArray – Type-safe (no mixing arrays/objects) • Json.createObjectBuilder() • Json.createArrayBuilder()
  • 35.
  • 36.
    Streaming - JsonParser •Parses JSON in a streaming way from input sources – Similar to StAX’s XMLStreamReader – a pull parser • Json.createParser()
  • 37.
    Streaming - JsonGenerator •Generates JSON in a streaming way to output sources – Similar to StAX’s XMLStreamWriter • Json.createGenerator()
  • 38.
  • 39.
    Java API forWebSocket
  • 40.
    Motivation • HTTP ishalf-duplex • HTTP is inefficient • HTTP hacked to achieve Push – HTTP Polling – HTTP Long-Polling (Comet) – Server Sent Events
  • 41.
    HTTP Upgrade -Request GET /socket/updates HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: www.sample.org
  • 42.
    HTTP Upgrade -Response HTTP/1.1 101 WebSocket Protocol Handshake Upgrade: WebSocket Connection: Upgrade
  • 43.
    WebSocket • Full duplex& efficient communication • A component of HTML5 – JavaScript API under W3C – Protocol under IETF • Wide support for browsers – http://caniuse.com/#feat=websockets
  • 44.
    WebSocket: Limitations • Useof existing infrastructure – Proxies doesn't have to handle connection upgrade • Fallback mechanisms – Atmosphere
  • 45.
    WebSocket: Trade-offs • WebSocket –Low efforts to maintain TCP connection – Limited by number of available sockets on one machine – Highly interactive applications • I.e. don't use if you don't expect high amount of transfered messages • HTTP – Resource-consuming protocol – Fairly interactive applications
  • 46.
    WebSocket: Use Cases •Realtime, truly low latency – Chat applications – Live sports ticker – Realtime updating social streams – Multiplayer online games • Requires architecture shift to – Non-blocking IO – Event queues
  • 47.
    Java API forWebSocket • Programmatic • Annotation-based – our focus
  • 48.
    WebSocket Annotations • @ServerEndpoint –@OnOpen – @OnMessage – @OnClose
  • 49.
  • 50.
    Method Parameters • Session •Implicitly supported types – String, byte[] – JsonArray, JsonObject • More types supported by Encoders
  • 51.
    Integration to JavaEE 7 • Relation to Servlet 3.1 – HttpServletRequest.upgrade(ProtocolHandler) • Dependency Injection – CDI beans – EJB beans • Security – ws://... vs. wss://... – web.xml: <security-constraint>
  • 52.
  • 53.
    JSF Origins • MVCFramework – Component-oriented – Server-Side – Extensible • Component Libraries
  • 54.
    Component Libraries • Richcomponents – RichFaces – PrimeFaces – ICEFaces • Functionality – PrettyFaces – OmniFaces
  • 61.
    JSF 1.0 Goals •What it adds over other frameworks? – Maintainability – Tooling Support – I18N
  • 62.
    JSF 1.0 Goals •What it adds over other frameworks? – Maintainability – Tooling Support – I18N
  • 63.
    JSF 1.0 • • • • • • • Components Renderers Managed beans(CDI) Converters / Validators Navigation Request lifecycle Error handling
  • 64.
    JSF 2.0 • • • • • • • Facelets (asdefault VDL) Composite Components AJAX Resource Libraries Behaviors GET support - <f:viewParam> Project Stage
  • 65.
    JSF 2.2 • BigTickets – Performance, Markup, Multi-tenancy • Small Features – <f:viewAction> – CSRF protection – ClientWindow – Favours CDI • Many smaller improvements
  • 66.
    JSF 2.2 • StatelessViews • (Performance) • HTML5 Friendly Markup • (Modern Markups) • Flows, Resource Library Contracts • (Multi-Tenancy)
  • 67.
    Stateless JSF • Whatis state? – UI Components, Model, Persistence – Developer's concern • Implementation – <f:view transient=”true”>
  • 68.
    HTML5 Friendly Markup JSFComponents <html> <my:colorPicker value=“#{colorBean.color2}” /> <my:calendar value=“#{calendarBean.date1}” /> </html> HTML5 Markup <html> <input type=“color” j:value=“#{colorBean.color2}” /> <input type=“date” j:value=“#{calendarBean.date1}” /> </html>
  • 69.
    Multitenant Capability • JSFapp as a collection of modules – Faces Flows • Modularize behavior • Builds on navigation – Resource Library Contracts • Modularize appearance • Builds on Facelets • Well defined contract for each
  • 70.
    Demo JSF – DeclarativeFlows, Resource Contracts
  • 71.
  • 72.
    RichFaces 4.3 • Rich& interactive components • Client-Side Validation • Push
  • 76.
    RichFaces 5.0 • Sneakpeek – Visual Improvements • 3rd-party widget libraries • Skinnability – LESS – Bootstrap 3 – New Components • Charts
  • 77.
    Summary • JSF – Fully-featuredweb framework • JAX-RS – RESTful services • WebSocket – Efficient bi-directional communication • JSON-P – Standardization of JSON processing
  • 78.