building java html5
TRANSCRIPT
-
8/10/2019 Building Java Html5
1/64
Java API for WebSocketsOTN Developer Days - India
David Delabassee - @delabasseeSoftware Evangelist - Oracle
-
8/10/2019 Building Java Html5
2/64
2 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Java EE 7 The Latest in Enterprise Java
-
8/10/2019 Building Java Html5
3/64
3 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Agenda
Introduction to WebSockets
What are they for ?
Delving into the APIs
-
8/10/2019 Building Java Html5
4/64
4 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Interactive Web Sites
Flavors of Server Push
Polling
Long polling
Comet/AJAX
Complex, inefficient, wasteful
-
8/10/2019 Building Java Html5
5/645Copyright 2013, Oracle and/or its affiliates. All rights reserved.
WebSockets to the rescue
TCP based, bi-directional, full-duplex messaging
IETF defined protocol: RFC 6455
Part of HTML5
W3C defined JavaScript API
-
8/10/2019 Building Java Html5
6/646 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
But can I use WebSockets?
http://caniuse.com/websockets
-
8/10/2019 Building Java Html5
7/647 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Click to edit Master text styles
Browsers and WebSockets
http://caniuse.com/websockets
-
8/10/2019 Building Java Html5
8/64
-
8/10/2019 Building Java Html5
9/64
9 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Whats the basic idea ?
Establish a WebSocket connection
Send messages backwards and forwards
End the connection
-
8/10/2019 Building Java Html5
10/64
10 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Establish a connection
Ap
Browser,
Rich Client,Application Server,
!
Handshake Response
Handshake Request
-
8/10/2019 Building Java Html5
11/64
Connected !
11 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Establishing a connection
Handshake Response
Handshake Request
-
8/10/2019 Building Java Html5
12/64
12 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Http Request
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==Sec-WebSocket-Protocol: megachat, chat
Sec-WebSocket-Extensions : compress, mux
Sec-WebSocket-Version: 13
Origin: http://example.com
Handshake Request
-
8/10/2019 Building Java Html5
13/64
13 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Handshake Response
Http Response
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaG
Sec-WebSocket-Protocol: chatSec-WebSocket-Extensions: compress, mux
-
8/10/2019 Building Java Html5
14/64
14 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Fundamentals
-
8/10/2019 Building Java Html5
15/64
15 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Endpoints
Browser
JavaEndpoint
JavaJavaFX
JavaEndpoint
JavaScriptEndpoint
-
8/10/2019 Building Java Html5
16/64
Connected !
16 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Lifecycle
open open
message
message
message
error
close
Disconnected !
close
-
8/10/2019 Building Java Html5
17/64
17 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
WebSockets Endpoints
Create Java classes that are WebSocket endpoints
The endpoint implements all the WebSocket functionalit
Endpoints can be
Annotated - POJO + Annotations
Programmatic - Java classes that extend WebSocket API
-
8/10/2019 Building Java Html5
18/64
18 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello World Server
@ServerEndpoint("/echo")public class EchoServer {
@OnMessage
public String echo(String incomingMessage) {
return Hello " + incomingMessage;
}
}
-
8/10/2019 Building Java Html5
19/64
19 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello World Server
public class EchoServerextends Endpoint{
@Override
public void onOpen(Session session, EndpointConfig endpointCon
final Session mySession = session;
mySession.addMessageHandler(newMessageHandler.Whole()
@Override
public void onMessage(String text) {
try {mySession.getBasicRemote().sendText("I got " + text
} catch (IOException ioe) {
System.out.println(Oops " + ioe.getMessage());
}}});
}
}
-
8/10/2019 Building Java Html5
20/64
20 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello World Client
@ClientEndpoint
public class HelloClient {
@OnOpen
public void init(Session session) {
try {
session.getBasicRemote().sendText("Hello you!");
} catch (IOException ioe) {
// oops
}
}
}
-
8/10/2019 Building Java Html5
21/64
21 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello World Client
public class MyClient extends Endpoint{
@Override
public void onOpen(final Session session, EndpointConfi
session.addMessageHandler(new MessageHandler.Whole
@Override
public void onMessage(String text) {
System.out.println("Received: " + text);
}
});
try {
session.getBasicRemote().sendText(Duke);} catch (IOException ex) {
// Ooops
}
}
}
-
8/10/2019 Building Java Html5
22/64
22 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello World Client
public class MyClient extends Endpoint{
@Overridepublic void onOpen(final Session session, EndpointConfi
try {
session.getBasicRemote().sendText(Hello again!
} catch (IOException ex) {
// Ooops
}
}
-
8/10/2019 Building Java Html5
23/64
23 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Hello Client - Bootstrap
WebSocketContainer container =
ContainerProvider.getWebSocketCont
String uri = "ws://myServer:8080/websocket";
container.connectToServer(MyClient.class, null, URI.creat
-
8/10/2019 Building Java Html5
24/64
24 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Intercepting WebSocket events
Annotated
Endpoints
Programmatic Endpointjavax.websocket.Endpointmetho
Open event @OnOpenpublic void onOpen(Session ses
EndpointCon
Message event @OnMessageCreate and register an instance of a
javax.websocket.MessageHa
Error event @OnErrorpublic void onError(Session se
Throwable
Close event @OnClosepublic void onClose(Session se
CloseReaso
-
8/10/2019 Building Java Html5
25/64
25 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Messaging
M
-
8/10/2019 Building Java Html5
26/64
26 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Message
Payload
Text
Binary
Ping-Pong
Sync / Asynch
Whole message / Sequence of partial messages
No delivery guarantee!
S di
-
8/10/2019 Building Java Html5
27/64
27 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Use theRemoteEndpointinterface, obtained from the SessiomySession.getBasicRemote().sendText(Hello);
Return a value from your @OnMessagemethod (convenience)
@OnMessage
public String echo(String incomingMessage) {
return(Hello);
}
Sending messages
S di
-
8/10/2019 Building Java Html5
28/64
28 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Click to edit Master text stylesMeans of sending RemoteEndpoint method to
as whole string sendText(String message)
as binary data sendBinary(ByteBuffer message)
in string fragments sendText(String part, boolean las
in binary data fragments sendBinary(ByteBuffer part, boole
as a blocking stream of text Writer getSendWriter())
as a blocking stream of binary data OutputStream getSendStream()
as a custom object of type T sendObject(T customObject)
Sending messages
R i i
-
8/10/2019 Building Java Html5
29/64
29 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Receiving messages
Annotation - Annotated a suitable method with@OnMessage
@OnMessage
public void gettingAText(String message)
@OnMessage
public void gettingPartialText(String message, boolean i
Programmatic - Implement aMessageHandler, add it to theSe
MyTextMessageHandler implements MessageHandler.Whole
-
8/10/2019 Building Java Html5
30/64
30 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Receive a message - @OnMessage
Text
public void handleText(String message)
public void handleReader(Reader r)public void handleTextPieces(String message, boole
Binarypublic void handleBinary(ByteBuffer bb)
public void handleStream(InputStream is)
public void handleBinaryPieces(ByteBuffer bb, bool
Any object public void handleObject(CustomObject co)
Recei e a message Programmaticall
-
8/10/2019 Building Java Html5
31/64
31 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Receive a message - Programmatically
Text
MessageHandler.Whole
MessageHandler.PartialMessageHandler.Whole
BinaryMessageHandler.Whole
MessageHandler.Partial
MessageHandler.Whole
Any object MessageHandler.Whole
session.addMessageHandler();
Sending Java Object
-
8/10/2019 Building Java Html5
32/64
32 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Sending Java Object
Java primitive
Text
x.toString()
Java Object
Custom javax.websocket.Encoderimplementation
Text or binary
Encoders and Decoders
-
8/10/2019 Building Java Html5
33/64
33 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Encoder
Object to Binary: Encoder.Binary,Encoder.Bina
Object to Text: Encoder.Text,Encoder.TextStre
Decoder
Text to Object: Decoder.Text,Decoder.TextStre
Binary to Object: Decoder.Binary,Decoder.Bina
Lifecycle
init()and destroy() methods
willDecode ()
Encoders and Decoders
Custom Payload Text
-
8/10/2019 Building Java Html5
34/64
34 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Custom Payload - Text
public class MyMessage implements Decoder.Text,Encoder.Text {
privateJsonObjectjsonObject;
public booleanwillDecode(String string) {
return true; // Only if can process the payload }
public MyMessagedecode(String s) {
jsonObject = new JsonReader(new StringReader(s)).readObje
return this;
}
public Stringencode(MyMessage myMessage) {
return myMessage.jsonObject.toString();
}
}
Custom Payload Binary
-
8/10/2019 Building Java Html5
35/64
35 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Custom Payload - Binary
public class MyMessage implements Decoder.Binary,Encoder.Binary {
public booleanwillDecode(byte[]bytes) {...
return true; // Only if can process the payload
}
public MyMessage decode(byte[] bytes) {
...
return this;
}
public byte[] encode(MyMessage myMessage) {
...}
}
Encoders and Decoders Configurations
-
8/10/2019 Building Java Html5
36/64
36 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Encoders and Decoders - Configurations
@ServerEndpoint(
decoders = { Foo.class, Bar.class },
encoders = { Baz.class, Forz.class })
List myEncoders = new List();
myEncoders.add(Foo.class);
myEncoders.add(Bar.class);ServerEndpointConfig myConfig =
ServerEndpointConfig.Builder.create(MyEp.class, "/
.encoders(myEncoders)
.build();
-
8/10/2019 Building Java Html5
37/64
37 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Configuration and Sessions
Instance diagram of EndpointConfigs and Se
-
8/10/2019 Building Java Html5
38/64
38 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Instance diagram of EndpointConfigs and Se
LogicalEndpoint
Client A
EndpoiSessionA
Client B
SessionB Endpoi
Serv
User state and endpoint state
-
8/10/2019 Building Java Html5
39/64
39 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
User state and endpoint state
Session
Representation of the WebSocket connection with a peer
One instance per peer
Has property bag for per peer endpoint application state
ServerEndpointConfig
Holds all the configuration information for a logical endpoint
One instance per logical endpoint
Has property bag for per logical endpoint application state
Can extend EndpointConfigto add behavior
Storing Chat application state
-
8/10/2019 Building Java Html5
40/64
40 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Storing Chat application state
LogicalEndpoint
John
Endpoint JSession J
Sally
Session S Endpoint S
Sally
John Serv
-
8/10/2019 Building Java Html5
41/64
41 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Advanced Messaging
Synchronous and Asynchronous sending
-
8/10/2019 Building Java Html5
42/64
42 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Synchronous and Asynchronous sending
Ping and pong
RemoteEndpoint.sendPing(ByteBuffer bb)
RemoteEndpoint.sendPong(ByteBuffer bb)
Synchronous send
Most commonly used mode
RemoteEndpoint.Basic, send methods block until transmcomplete
Asynchronous send modesUse the RemoteEndpoint.Asyncinterface, send methods
immediately, before transmission completes
send by Future: send methods return a Futureobject
send by completion: send methods take a callback listener
To batch or not to batch messages
-
8/10/2019 Building Java Html5
43/64
43
client
Copyright 2013, Oracle and/or its affiliates. All rights reserved.
To batch or not to batch messages
Server
client
endpoint
batch
m
m
m
mm m
mm
m batch
Batching
-
8/10/2019 Building Java Html5
44/64
44 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Batching
Not supported by all implementationsGood for high frequency messaging applications
Application has to permit it for the implementation to use it
RemoteEndpoint.getBatchingAllowed()
RemoteEndpoint.setBatchingAllowed(boolean al
If you use batching, you may need to flush the buffers
RemoteEndpoint.flushBatch()
-
8/10/2019 Building Java Html5
45/64
45 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
WebSocket Path Mapping
WebSocket Path Anatomy
-
8/10/2019 Building Java Html5
46/64
46 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
y
Web Container
Client
WAR
Endpoint
URL Endpoint
endpoint path:
WAR context root: mywebServer hostname: www.myapps.c
ws://www.myapps.com/mywebapp/f
Path Types - exact URI
-
8/10/2019 Building Java Html5
47/64
47 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
yp
Server endpoints can be mapped to exact URI
Example /fooor/airlines/seating/updater
/foo !=/Foo
Implementations use an exact match policy
Cant have 2 endpoints mapped to the same URI in the sam
Path Types - URI Template
-
8/10/2019 Building Java Html5
48/64
48 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
yp p
URI-Template
Level 1, i.e. simple string extension
Example /travel/{mode}
/travel/{mode}/{class}
Match if incoming URI is a valid expansion of the URI temp
/travel/boat , /travel/plane !
/travel , /travel/steam/train "
Cant have two equivalent URI-templates in an application
/travel/{mode} + /travel/{vip}
"
Expanded parameters can be retrieved by name inside the
URI Template and Path Parameter
-
8/10/2019 Building Java Html5
49/64
49 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
p
@ServerEnpoint("/travel/{mode}")
public class Trip {
@OnOpen
public void Booking ( @PathParam("mode") String travel
switch (travelMode) {
case#
"plane"#
:. . .
URI Template and Path Parameter
-
8/10/2019 Building Java Html5
50/64
50 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
p
@ServerEnpoint("/travel/{mode}/{class}")
public class Trip {
@OnOpen
public void Booking (Session session, EndpointConfig c
Map pathParam = session.getPathPara
String travelMode = pathParam.get("mode");String travelClass = pathParam.get("class");
. . .
}
URI Template, Path Parameter and Query
-
8/10/2019 Building Java Html5
51/64
51 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
y
ws://masterTrip.com/travel/plane?destination=rome
@OnOpen
public void makeOffer(Session session, EndpointConfig
String targetLocation =
session.getRequestParameterMap().get("destinat
. . .
-
8/10/2019 Building Java Html5
52/64
52Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Misc.
Security
-
8/10/2019 Building Java Html5
53/64
53Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Based on the Servlet model
WebSocket Endpoints are considered resources via their ur
Require users be authenticated to access a WebSocket end
Limit access to a WebSocket endpoint
to certain users, via role mapping
to an encrypted protocol (wss://)API to give at runtime a view on the security model
Endpoint Configuration
-
8/10/2019 Building Java Html5
54/64
54Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Control the instantiation and initialization of EndpointAccess the initial HTTP request
Eg. Perform custom checks
Modify the handshake response
Choose a subprotocol from those requested by the client
ServerEndpointConfig.Builder
.create(MyEndpoint.class, /myUri
-
8/10/2019 Building Java Html5
55/64
55Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Wrap up
WebSocket
-
8/10/2019 Building Java Html5
56/64
56
Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Concepts
Session, Endpoints, Lifecycle
Java API for WebSocket
Annotation & Programmatic based
Part of Java EE 7
Annotations
-
8/10/2019 Building Java Html5
57/64
57
Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Annotation Level Purpose
@ServerEndpoint
class Turns a POJO into a WebSocket En
@ClientEndpoint
class Turns a POJO into a WebSocket Cli
@OnMessage
method Intercepts WebSocket Message eve
@OnOpen
method Intercepts WebSocket Open events
@OnError
method Intercepts errors during a conversat
@OnClose
method Intercepts WebSocket Close events
@PathParam
methodparam
Flags a matched path segment of a
WebSocket
-
8/10/2019 Building Java Html5
58/64
58
Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Advanced
Security
Synch/Asynchronous
Protocols
Batching
Endpoint Config!
Considerations
Firewall
Tools
-
8/10/2019 Building Java Html5
59/64
59
Copyright 2013, Oracle and/or its affiliates. All rights reserved.
customer_access
Account Info
/account.jsp
/account/info
/banner/secure
customer
premium_customer
CONFIDENTIAL
-
8/10/2019 Building Java Html5
60/64
60 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
...
login access
Account Info
/index.jsp
CONFIDENTIAL
BASICfile
customer
premium_customer
...
Make sure
is only avai
Use (encry
auth.
User
use th
Resources
-
8/10/2019 Building Java Html5
61/64
61 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
Java EE 7 Tutorial
Java WebSocket Programming (Oracle Press)
https://blogs.oracle.com/theaquarium/
Get started now!
-
8/10/2019 Building Java Html5
62/64
62 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
NetBeans bundles GlassFish
Incremental compilation; auto-deployComplete Java EE 7 support
All Java EE 7 project types
HTML5 features available in Java EE projects
Maven Support
Advanced Wizards
Entity to REST generation, DB to JSF 2.2 ...
Embedded WebKit browser
Network Monitor
-
8/10/2019 Building Java Html5
63/64
63 Copyright 2013, Oracle and/or its affiliates. All rights reserved.
The preceding is intended to outline our general product directiointended for information purposes only, and may not be incorp
into any contract. It is not a commitment to deliver any materialor functionality, and should not be relied upon in making purc
decisions. The development, release, and timing of any featufunctionality described for Oracles products remains at th
discretion of Oracle.
-
8/10/2019 Building Java Html5
64/64
64 Copyright 2012, Oracle and/or its affiliates. All rights reserved.
Graphic Section Divider
Copyright 2014, Oracle and/or its affiliates. All rights reserved.Copyright 2013, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 1241
Graphic Section Divider