Prezi

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in the manual

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

JavaOne 2013 - Build.now(); True Real-Time Applications with JavaEE 7 (A Hack Session)

Introduction to HTML5, JavaEE 7 Websocket protocol APIs, and JSON-P API
by Mohamed Taman on 15 November 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of JavaOne 2013 - Build.now(); True Real-Time Applications with JavaEE 7 (A Hack Session)

Build.now();
True Real-Time Applications with Java EE 7 ( A Hack Session)
{ }
connect
close
connected
payload
messages
payload
closed
By: Mohamed Taman,
Systems Architects & EC, JCP member
Who am I?
Working as
Systems Architect & Design supervisor
for Egyptian ministry of finance company “
e
-finance
”.

JCP & EC
Member, responsible for JSRs revision, evaluation, RI testing and evangelist the new technologies specifications & JCP process standardization.

Beside that I am one of the board member of “
Oracle Egypt Architect Club
”.

A frequent Speaker

(
JavaOne, Devoxx, Oracle Days,Tunis JUG Day, jMaghreb, JEEConf & JDC... etc
),

Consultant, Trainer, Blogger, & articles writer, books author and tech. reviewer.

Regularly posts on my blog , and also on
DZone
&
JCG
community.
Java is the my best choices since 2001,
when I code it
,
I feel like

Coding the Architecture
”.
Thanks for
Attending & Listening.

Hack
Session
Agenda
version 4.0
JSON API JSR 353
Websocket API
JSR 356
Java EE 7 – Candidate JSRs
Updated
Major
Release
New
Adopt-a-JSR Program
Adopt-a-JSR is an initiative by JUG leaders to encourage JUG members to get involved in a JSR and to evangelize that JSR to their JUG and the wider Java community, in order to increase grass roots participation.
Java EE 8 is scheduled to release in 2015 and would love help from your JUG to adopt a JSR.
Why Web Sockets?!
Historically, creating web applications that need bidirectional communication between a client and a server (e.g., instant messaging and gaming applications) has required an abuse of HTTP to poll the server for updates while sending upstream notifications as distinct HTTP calls [RFC6202].
Need Interactive Web Sites
HTTP is half-duplex
HTTP is verbose
Hacks for Server Push
Polling
Long Polling
Comet/Ajax
SSE
Complex, Inefficient, Wasteful
WebSocket is the solution
Why
Then How it works??
Simple enough
TCP
based, bi-directional, full-duplex messaging
.
A Dramatic reduction in unnecessary network latency and traffic.
Most wide adopted HTML5 API by majority of browsers.
Supports HTTP proxies, filtering, authentication and intermediaries
.
Specs:
Originally proposed as part of
HTML5.
IETF
-defined Protocol: RFC 6455
Handshake
Data Transfer
W3C
defined JavaScript API
.
Handshake Request
Handshake Response
GET
/chat HTTP/1.1
Host:
server.example.com
Upgrade:
websocket
Connection:
Upgrade
Sec-WebSocket-Key:
dGhlIHNhbXBsZSBub25jZQ==
Origin:
http://example.com
Sec-WebSocket-Protocol:
chat, superchat
Sec-WebSocket-Version:
13
HTTP/1.1 101
Switching Protocols
Upgrade:
websocket
Connection:
Upgrade
Sec-WebSocket-Accept:
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=Sec-
WebSocket-Protocol:
chat
open
message
message
message
open
How it reduces network latency and traffic??
lets look at simple stock ticker example
Request Header
Response
So where is the problem?
Lets see the following use cases when deploying this simple application to large number of users.

Note:
request/response header characters count = 871 byte without the data, and data = 21 byte.
We will compute the network overhead for customers polling for data every 1 second for just HTTP request and response:
Use case A:
1000 client, Network traffic is (871 x 1000) =
871,000 byte = 6,968,000 bit per second (
6.6 Mbps
)
Use case B:
10,000 client, Network traffic is (871 x 10,000) =
8,710,000 byte = 69,680,000 bit per second (
66 Mbps
)
Use case C:
100,000 client, Network traffic is (871 x 100,000) =
87,100,000 byte = 696,800,000 bit per second (
665 Mbps
)
By using websocket
The websocket frame is 2 bytes overhead, lets see how it will affect the network traffic in our use cases for message received every 1 second:
Use case A:
1000 client, Network traffic is (2 x 1000) =
2000 byte = 16,000 bit per second (
0.015 Mbps
)
Use case C:
100,000 client, Network traffic is (2 x 100,000) =
200,000 byte = 1,600,000 bit per second (
1.526 Mbps
)
Use case B:
10,000 client, Network traffic is (2 x 10000) =
20,000 byte = 160,000 bit per second (
0.153 Mbps
)
JEE7, Whats new??
Lets explore HTML5 websocket API
www.w3.org/TR/websockets/
http://caniuse.com/#feat=websockets
How it works On the browser side
You need to create an instance of
the WebSocket browser class
This class exposes a bunch of interesting events for which you want to have proper handlers
var wsUri = " ws://echo.websocket.org/";
websocket = new
WebSocket
(wsUri);
websocket.
onopen
= function(evt) { onOpen(evt) };
websocket.
onmessage
= function(evt) { onMessage(evt) };
websocket.
onclose
= function(evt) { onClose(evt) };
websocket.
onerror
= function(evt) { onError(evt) };
onopen

event is fired when the connection is established.
onmessage

event fires whenever the client receives a message from the server.
onclose

is triggered when the connection has been closed.
onerror

is fired whenever an error occurs.
To send a message to the server, all you need to do is place a call to the method send, as shown here:

var

message

= "Hello test @" +

new
Date().toString();
websocket.
send
(
message
);
They are working
Asynchronously.
JAX-RPC, CMP/ BMP,
and JSR 88
Pruned candidates
1
7
8
3
6
4
5
2
1- JEE7, what is new?
2- Why websocket?
3- Explore HTML5 websocket API
5- Data Exchange types
4- Websocket API (356) support
6- JSON API (353) support
Final Project "RTRCT"
7- Unit test websocket API
Real Time Runners Champion
HTML5 Support
Higher productivity
Less coding, more CDI
Richer Functionality & APIs Support
More Defaults, no more configurations
Offers a standards-based platform
WebSocket support (JSR356)
JSON support (JSR353)
HTML5 Forms introduced in JSF 2.2
JSR 356: Java API for
WebSocket 1.0
Data Exchange types
JSR 353: Java API for
JSON Processing 1.0
Websockets
JSON
As part of the Adopt-A-JSR program, I am trying to gather interests in these APIs, and provide these feedback to the Expert Group.
Disconnected
Connected
message
error
message
message
This protocol for a variety of web applications:

games, stock tickers, multiuser applications with simultaneous
editing, user interfaces exposing server-side services in real time,
etc.
We can use
three
one
three
two
two
one
What does it offer
JSR 356 defines how to write a client/server standards-based WebSocket application.
It defines not just the service endpoint but also ways it can be written with either an annotation-driven
(@ServerEndpoint)
or an interface-driven
(Endpoint)
model.
A separate client-side API introduced as well,
Client
(@ClientEndpoint)
Websocket Support
Who implement it?
Java-WebSocket
Grizzly
Apache Tomcat 7
GlassFish 4.0
Autobahn
WeberKnecht
Jetty
JBoss
Caucho Resin
jWebSocket
WebSocket Gateway
WebSocket SDK
Webbit
Atmosphere
websockets4j
GNU WebSocket4J
Netty
TorqueBox
SwaggerSocket
jWamp
JSR 356 Specification
Provide support in the Java EE platform for
Creating WebSocket Java components to handle bi-directional WebSocket conversations.

Initiating and intercepting WebSocket events.

Creation and consumption of WebSocket text and binary messages.

The ability to define WebSocket protocols and content models for an application.

Configuration and management of WebSocket sessions, like timeouts, retries, cookies, connection pooling.

Specification of how WebSocket application will work within the Java EE security model.
lets explore the JSR APIs
import javax.websocket.*;

@ServerEndpoint
("/taman/hello")
public class
NotHelloEndpoint
{

@OnMessage


public
String greeting(String name)
{

return


welcome peer
“ + name;
}
}
Not hello world
WebSocket Annotations
@ServerEndpoint
@ClientEndpoint
@OnMessage
@PathParam
@OnOpen
@OnClose
@OnError
Level:
class ,
Turns a POJO into a WebSocket Endpoint
Level:
method ,
Intercepts close events
Level:
method , Intercepts message events
Level:
class ,
Turns a POJO to act as a client Endpoint
Level:
method ,
Intercepts error during conversation
Level:
method ,
Intercepts Open events during clients connection
Level:
method parameters ,
Flags a matched path segment of a URI-template
Level 1 only URI Template Matching
SPI for extensions and data frames
Defining a custom payloads
For compression, multiplexing for example
More.....
By implementing Encoder/Decoder interface
@serverEndpoint(value="/hello",
encoders=
{JSONMessage.class},
decoders=
{JSONMessage.class})
@ServerEndpoint(“/orders/
{order-id}
”)
public class MyEndpoint {
@OnMessage
public void processOrder(
@PathParam(“order-id”)
String orderId)
{ . . . }
}
public class
JSONMessage implements
Decoder.Text
<JSONMessage>,
Encoder.Text
<JSONMessage>
{
private
JsonObject jsonObj;

public
JSONMessage decode(String s)
{ jsonObj =
new
JsonReader(
new
StringReader(s)).readObject();
return
this;}


public boolean
willDecode(String string) {
return
true;
// Only if can process the payload
}


public
String encode(JSONMessage message) {
return
message.jsonObject.toString(); }
}
Websocket java Client
@ClientEndpoint
public class
Client {
@OnMessage

public void
message(String message, Session session) {
// process message from server
}
}

WebSocketContainer c = ContainerProvider.getWebSocketContainer();
c.connectToServer(Client.class, “hello”);
Packaging
Client side
Classes + resources packaged as a JAR

Web Container
Only WAR packaging
Classes + resources packaged in
WEB-INF/classes or WEB-INF/lib
How to trace WebSocket messages ?
JSON (JavaScript Object Notation) 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.

These properties make JSON an ideal data-interchange language.
http://www.json.org/
org.json.
org.json.me.
Jackson JSON Processor.
Json-lib.
JSON Tools.
Stringtree.
SOJO.
Jettison.
json-taglib.
XStream.
Flexjson.
JON tools.
Argo.
jsonij.
fastjson.
mjson.
jjson.
json-simple.
json-io.
JsonMarshaller.
google-gson.
Json-smart.
FOSS Nova JSON.
A lot of implementation there....
There are many more for different languages
@
http://www.json.org/
Why we need a Java API while there are many implementations?
Many popular web services use JSON format for invoking and returning the data. Currently Java applications use different implementation libraries to produce/consume JSON from the web services especially REST web services.
http://jcp.org/en/jsr/proposalDetails?id=353
Hence, there is a need to standardize a Java API for JSON so that applications that use JSON need not bundle the implementation libraries but use the API.
Streaming API
DOM API JsonReader
Streaming
API
JSON support
Object
Model API
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
JsonParser
– 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, ...
JsonGenerator
– Generates JSON in a streaming way to output sources
• Similar to StaX’s XMLStreamWriter
– Created using
• Json.createGenerator(…)!
• Json.createGeneratorFactory().createGenerator(…)!
– Optionally, configured with features
• E.g. for stylish printing

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
• Reads JsonObject and JsonArray from input source
– i/o Reader, InputStream (+ encoding)
• Optionally, configured with features
• Uses pluggable JsonParser!

// Reads a JSON object
try(JsonReader reader = new JsonReader(io)) {!
JsonObject obj = reader.readObject();!
}!
Some code......
JSON object
{
"fName": "Mohamed", "lName": "Taman", "age": 1,
"address" : {
"streetAddress": "18 street #1",
"state": "Maadi",
"City": "Cairo",
"postalCode": "11344"
},
"phoneNumber": [
{ "type": "home", "number": "20223720543" },
{ "type": "cell", "number": "201005318017" }
]
}
User JsonObject
JsonBuilderFactory factory = Json.createBuilderFactory(config);
JsonObject value = factory.createObjectBuilder()
.add("firstName", "Mohamed").add("lName", "Taman").add("age", 1)
.add("address", factory.createObjectBuilder()
.add("streetAddress", "18 street #1").add("state", "Maadi").add("City", "Cairo")
.add("postalCode", "11344"))
.add("phoneNumber", factory.createArrayBuilder()
.add(factory.createObjectBuilder()
.add("type", "home").add("number", "20223720543"))
.add(factory.createObjectBuilder()
.add("type", "cell").add("number", "201005318017")))
.build();
JsonBuilderFactory factory = Json.createBuilderFactory(config);
JsonArray value = factory.createArrayBuilder()
.add(factory.createObjectBuilder()
.add("type", "home")
.add("number", "20223720543"))
.add(factory.createObjectBuilder()
.add("type", "cell")
.add("number", "201005318017"))
.build();
The following code creates JSON array
To produce the following array
[
{ "type": "home", "number": "20223720543" },
{ "type": "cell", "number": "201005318017" }
]
Binding JSON to Java objects like JAXB

is forthcoming improvement
What is missing....
Final release Lunched: Q2 2013
"
RTRC
" Project

Real Time Runners Champion
*
Follow me for more hacks on Java SE & Java EE 7,8
Tyrus provides us with an easy way to connect to websocket endpoint (
ClientManager
).
We will use it for unit testing
So lets dirt our hands.
This project uses HTML5 websocket API alongside Geolocation API, & server websocket endpoint, to provide runners real time tracing to the other runners distances.
close
{' '}
https://glassfish.java.net/
2013
I have won The 11 Annual JCP award 2013 as
Outstanding adopt-A-JSR Participant
Postponed to JEE8
Weblogic 12c
sveiki
Здраво
Hallo
Hello
Ahoj
Alo
привет
Hej
Hallå
Olá
Merhaba
Bonjour
Ciao
Hola
2.0
Won an
Executive Committee
seat as MoroccoJUG representative
http://about.me/mohamedtaman
http://www.linkedin.com/in/mohamedtaman
@_tamanm
http://tamanmohamed.blogspot.com/
mohamed.taman@gmail.com
https://github.com/Adopt-a-JSR/JEE7-Hack-Sessions.git
See the full transcript