Top Banner
1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley
29

1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

Dec 25, 2015

Download

Documents

Tyrone Morton
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

1

WebSocket & JSON Java APIs Hackday

By Somay Nakhal @SomayNakhal

David Illsley @davidillsley

Page 2: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

2

Hackday ?

Adapt A JSR programme Explore new APIs JSR 353 JSON Processing API JSR 356 WebSockets API Provide feedback

Page 3: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

3

WebSocket and Java

Page 4: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

4

Interactive web application HTTP is half-duplex Polling Long Polling Comet/Ajax Complex, Inefficient, Wasteful

Page 5: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

5

Enter WebSocket Protocol

TCP based, bi-directional, full-duplex messaging Part of HTML5 IETF-defined Protocol: RFC 6455 W3C defined JavaScript API Uses HTTP upgrade handshake Supports HTTP proxies, filtering, authentication and intermediaries

Page 6: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

6

How does it work?

Establish connection (Single TCP connection) Send messages in both direction (Bi-directional) Send messages independent of each other (Full Duplex) End connection

Page 7: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

7

Browser Support

caniuse.com

Page 8: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

8

WebSocket API (JavaScript)

var websocket = new WebSocket("ws://www.host.com/path"); websocket.onopen = function(evt) { onOpen(evt) }; websocket.onclose = function(evt) { onClose(evt) }; websocket.onmessage = function(evt) { onMessage(evt) }; websocket.onerror = function(evt) { onError(evt) }; }

function onMessage(evt) { alert( evt.data); }function onError(evt) { alert( evt.data); }

websocket.send("client to server");

Page 9: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

9

JSR 356 Java API for WebSocket

Page 10: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

10

Client and Server WebSocket protocol APIs in Java Integration with Java EE Web container Reference Implementation: – http://java.net/projects/tyrus – Bundled in latest Glassfish 4 builds

JSR 356 Java API for WebSocket

Page 11: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

11

Terminology

Endpoint: Client or server Connection: Network connection between two endpoints Peer: Other endpoint of the connection Session: represents a sequence of websocket interactions

between and end point and a peer

Page 12: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

12

Annotations

@WebSocketEndpoint– Class level annotation for websocket server endpoint

@WebSocketClient – Class level annotation for websocket client endpoint

@WebSocketOpen – Method level annotation signifies a method to be called whenever a new

client connects to this endpoint

@WebSocketClose– Method level annotation signifies a method to be called whenever a new

client is about to disconnects from this endpoint

@WebSocketMessage– Method level annotation signifies a method to be called whenever an

incoming message is received

Page 13: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

13

Some Code!

@WebSocketEndpoint("/hello-world")public class HelloWorld {

@WebSocketMessagepublic String sayHello(String name) {

return "Hello " + name;}

}

Page 14: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

14

More Code!

@WebSocketEndpoint("/hello-world")public class HelloWorld {

private Set<Session> peers = Collections.synchronizedSet(…)

@WebSocketOpenpublic void onOpen (Session peer) {

peers.add(peer);}

private void sendMessageToPeer(String message, Session peer) { peer.getRemote().sendString(s);

}

}

Page 15: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

15

JSON and Java

Page 16: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

16

In the beginning...

There was XML

... and the DOM... and SAX...

Then, after much gnashing of teeth, there was JSON

{ "message" : "Hello World!" }

More at json.org and wikipedia

Page 17: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

17

tumbleweed...

Page 18: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

18

Not Quite

"The Software shall be used for Good, not Evil."

From: http://www.json.org/license.html

Page 19: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

19

And many more...

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

(list from json.org)

Page 20: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

20

Fast-forward to December 2011

JSR 353: JavaTM API for JSON Processing

"JSON(JavaScript Object Notation) is a lightweight data-interchange format. 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. 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. Applications will be smaller in size and portable."

http://jcp.org/en/jsr/detail?id=353

Page 21: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

21

Goals/Non Goals

"The goal of this specification is to develop such APIs to:

* Produce and consume JSON text in a streaming fashion(similar to StAX API for XML)

* Build a Java object model for JSON text using API classes(similar to DOM API for XML)

Non-goals of this specification include:

* Binding of JSON text to Java objects and vice versa."

"This JSR is targeted for Java SE 6 or higher and Java EE 7 or higher platforms."

http://jcp.org/en/jsr/detail?id=353

Page 22: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

22

Fast-forward to February 2013

Pretty much done

Just finished the formal public review phase

Looking for final feedback from JUGs

... and to get the word out about what's coming

Page 23: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

23

Some code...

JsonGenerator generator = Json.createGenerator(System.out)

// or generator = Json.createGenerator(servletResponse.getWriter())

generator .writeStartObject() .write("firstName", "John") .write("lastName", "Smith") .write("age", 25) .writeStartObject("address") .write("streetAddress", "21 2nd Street") .write("city", "New York") .write("state", "NY") .write("postalCode", "10021") .writeEnd() .writeStartArray("phoneNumber") .writeStartObject() .write("type", "home") .write("number", "212 555-1234") .writeEnd() .writeStartObject() .write("type", "fax") .write("number", "646 555-4567") .writeEnd() .writeEnd() .writeEnd(); generator.close();

Page 24: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

24

Produces

{ "firstName": "John", "lastName": "Smith", "age": 25, "address" : { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ {"type": "home", "number": "212 555-1234"}, {"type": "fax", "number": "646 555-4567"} ] }

(JavaDoc - JsonGenerator) http://bit.ly/11CwMde

Page 25: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

25

Or to build an object model...

JsonObject value = Json.createObjectBuilder() .add("firstName", "John") .add("lastName", "Smith") .add("age", 25) .add("address", Json.createObjectBuilder() .add("streetAddress", "21 2nd Street") .add("city", "New York") .add("state", "NY") .add("postalCode", "10021")) .add("phoneNumber", 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();

// or from a stream..

JsonObject value2 = Json.createReader(inputStream).readObject();

(JavaDoc - JsonObject) bit.ly/11CwMde

Page 26: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

26

And to read things from it...

int age = value2.getIntValue("age", 18);

JsonObject address = value2.getValue("address", JsonObject.class);

String city = "London";

if(address != null){

city = address.getStringValue("city", "London");

}

JsonArray phoneNumbers = value2.getValue("phoneNumber", JsonArray.class);

if(phoneNumbers != null){

for(JsonValue val: value2){

if(val instanceof JsonObject){

JsonObject jo = (JsonObject)val;

System.out.println(jo.getStringValue("number","Number Missing");

}

}

}

Page 27: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

27

And a low-level event API

Event event = parser.next(); // START_OBJECT event = parser.next(); // KEY_NAME event = parser.next(); // VALUE_STRING parser.getString(); // "John"

(JavaDoc - JsonParser) bit.ly/VzGWEr

Page 28: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

28

JSON Hacks/Workshop

Latest version of the library not in Glassfish yet, so a small standalone maven project

https://github.com/davidillsley/json-workshop

Includes tests for some uncompleted code operating on stored JSON.. see the README for more.

Page 29: 1 WebSocket & JSON Java APIs Hackday By Somay Nakhal @SomayNakhal David Illsley @davidillsley.

29