Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSockets: Realtime Em Um Mundo Conectado 
Bruno Borges 
Principal Product Manager 
Oracle Latin America 
Agosto, 2014
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Speaker 
•Bruno Borges 
–Principal Product Manager, Java Evangelist 
–Oracle Latin America 
–@brunoborges 
–bruno.borges@oracle.com
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Overview
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Overview 
The WebSocket API in HTML5 
•Enables use of WebSocket in HTML5/web applications 
•Open/Close connections 
•Send/Receive messages 
•Fully asynchronous 
•Event driven, listen and respond to events
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Overview 
Browser Support for WebSocket API 
•Broad base of support for WebSocket in modern browsers 
•Firefox 28+, Chrome 33+, Safari 7+, IE 10+ 
•Including mobile browsers 
http://caniuse.com/#search=websocket
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Overview 
Common Use Cases 
•Time critical data delivery 
–Stocking monitoring, trading 
–Ticket reservation, seat selection 
•Applications that require true bi-directional exchanges with low latency 
–IoT control systems, gaming, gambling 
•High levels of interactivity 
–Chat systems, online sales engagement tools, support systems for trouble shooting 
•High throughput applications
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
The WebSocket Protocol (RFC 6455) 
Protocol Overview 
•Defines handshake and data transfer 
•Introduces new URI schemes 
–ws-URI = “ws:” “//” host [:port] path [ “?” query ] 
–wss-URI = “wss:” “//” host [:port] path [ “?” query ] 
–# MUST be escaped as %23 (URI fragments are meaningless) 
•Imposes an Origin Security Model 
•Supports extensibility 
–Tunnel other protocol by supporting sub-protocols, extend protocol features by supporting extensions
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
The WebSocket Protocol 
Opening Handshake 
WebLogic Server 12.1.3 
HTTP
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
The WebSocket Protocol 
Protocol Upgrade 
WebLogic Server 12.1.3 
WebSocket
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
The WebSocket Protocol 
Keep Alive: Ping and Pong 
Ping Frame 
Pong Frame 
Ping Frame 
Pong Frame 
WebLogic Server 12.1.3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
The WebSocket Protocol 
Closing Handshake 
WebLogic Server 12.1.3 
Close Frame 
Data Frame 
Data Frame 
Data Frame 
Close Frame
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Developing WebSocket Applications using the Java Standard
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
The Java Standard for WebSocket Applications 
•Java community proposed and developed a specification and standard API for using WebSocket with the Java platform 
–Many companies and individuals represented 
–Oracle specification lead, developer of reference implementation with Project Tyrus 
•JSR-356 
–Specification finalized and approved May 2013 
–Included in Java EE 7 specification 
•Integrated into WebLogic Server 12.1.3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Core Concepts 
Endpoint 
A websocket endpoint is a Java component that represents one side of a sequence of websocket interactions between two connected peers 
Connection 
A websocket connection is the networking connection between the two endpoints which are interacting using the websocket protocol 
Peer 
A websocket peer is used to represent the another participant of the websocket interactions with the endpoint 
Session 
A websocket session is used to represent a sequence of websocket interactions between an endpoint and a single peer 
Client Endpoints and Server Endpoints 
A client endpoint is an endpoint that initiates a connection to a peer but does not accept new ones 
A server endpoint is an endpoint that accepts websocket connections from peers but does not initiate connections to peers.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
•Creating a WebSocket requires a Java class that acts as an Endpoint 
–Participate in lifecycle: establish connections with peers, handle errors, close connections 
–Send and receive messages 
•Endpoints can be created from: 
–Annotation based approach using WebSocket Annotations, @ServerEndpoint 
–Programmatic API where Java class extends WebSocket API class 
•Endpoints can be defined as: 
–Clients which connect to one server only at a time 
–Servers which many clients can connect to at any time
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Annotated ServerEndpoint Example 
import javax.websocket.OnMessage; 
import javax.websocket.server.ServerEndpoint; 
@ServerEndpoint("/echo") 
public class EchoServer { 
@OnMessage 
public String echo(String incomingMessage) { 
return String.format( 
"I got this (%s) message so I am sending it back!”, incomingMessage); 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Annotated ServerEndpoint Example 
@ServerEndpoint("/echo") 
public class EchoServer { 
@OnMessage 
public void onMessage(Session session, String message) { 
session.getOpenSessions() .forEach(s -> s.getBasicRemote().sendText(message)); 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Annotated Path Parameter Example 
@ServerEndpoint("/users/{username}") 
public class UserEndpoint { 
@OnMessage 
public String handle(String message, @PathParam("username") String user) { 
return “message “ + message + “ from user “ + user; 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Programmatic Endpoint Example 
public class ProgrammaticEchoServer extends Endpoint { 
@Override 
public void onOpen(final Session session, EndpointConfig endpointConfig) { 
mySession.addMessageHandler(new MessageHandler.Whole<String>() { 
public void onMessage(String text) { 
try { 
mySession.getBasicRemote() .sendText(“I got this (“ + text + “)” + “so I am sending it back !”); 
} catch (IOException ioe) { } 
} 
}); 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Annotated ClientEndpoint Example 
import java.io.IOException; 
import javax.websocket.*; 
@ClientEndpoint 
public class HelloClient { 
@OnOpen 
public void init(Session session) { 
try { 
session.getBasicRemote().sendText("Hello you !"); 
} catch (IOException ioe) { 
// error 
} 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Programmatic ClientEndpoint Example 
public class HelloClient extends Endpoint { 
@Override 
public void onOpen(Session session, EndpointConfig EndpointConfig) { 
try { 
session.getBasicRemote().sendText("Hello you !"); 
} catch (IOException e) { 
// error 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Responding to Lifecycle Events 
Annotation 
Programmatic API 
Open Event 
@OnOpen 
public void onOpen(Session session, EndpointConfig config) 
Message Event 
@OnMessage 
•Create instance of relevant javax.websocket.MessageHandler 
•Register with Session 
Error Event 
@OnError 
public void onError(Session session, Throwable throwable) 
Close Event 
@OnClose 
public void onClose(Session session, CloseReason reason)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Receiving Message from Peers 
•Annotate a suitable method with @OnMessage 
•Implement an appropriate MessageHandler interface 
•Add it to the Session 
@OnMessage 
Void handleText(String message) 
@OnMessage 
public void handlePartialText( String message, boolean isLast) 
SimpleHandler implements MessageHandler.Whole<String> { ... } 
session.addMessageHandler( 
new SimpleHandler());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Receiving Message from Peer with @OnMessage 
Message Type 
Annotated Method Form 
Text 
public void handleText(String message) 
public void handleReader(Reader r) 
public void handleTextPieces(String message, boolean isLast) 
Binary 
public void handleBinary(ByteBuffer bytebuf) 
public void handleStream(InputStream is) 
public void handleBinaryPieces(ByteBuffer bytebuf, boolean isLast) 
Any Object 
public void handleObject(CustomObject co)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Receiving Message Programmatically from Peers 
Message Type 
Message Handler Interface 
Text 
MessageHandler.Whole<String> 
MessageHandler.Whole<Reader> 
MessageHandler.Partial<String> 
Binary 
MessageHandler.Whole<ByteBuffer> 
MessageHandler.Partial<ByteBuffer> 
MessageHandler.Whole<InputStream> 
Any Object 
MessageHandler.Whole<CustomObject>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Sending Messages to Peers 
Return a value from the @OnMessage method 
•Access the RemoteEndpoint interface from the Session object 
•Call the relevant send method 
@OnMessage public String echoToUppercase(String msg) { return msg.toUpperCase(); } 
RemoteEndpoint remote = session.getBasicRemote(); 
remote.sendText(“This is a txt message”);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Asynchronous and Synchronous Sending Modes 
Mode 
Usage 
Interface and Method 
Synchronous 
•Most commonly use mode 
•Send methods block until transmission of message is complete 
RemoteEndpoint.Basic 
void sendText(String message) 
Asynchronous 
•Send methods return immediately before transmission 
•Future and Callback options for completion handling 
RemoteEndpoint.Async 
Future sendText(String message) 
void sendText(String message, SendHandler handler)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Example Encoder 
public class AuctionMessageEncoder implements Encoder.Text<AuctionMessage> { 
@Override 
public String encode(AuctionMessage object) throws EncodeException { 
JsonObject json = null; 
switch (object.getType()) { 
case AuctionMessage.AUCTION_TIME_RESPONSE: 
json = Json.createObjectBuilder() 
.add("type", object.getType()) 
.add("communicationId", object.getCommunicationId()) 
.add("data", (int) object.getData()).build(); 
break; 
} 
return json.toString(); 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Example Decoder 
public class AuctionMessageDecoder implements Decoder.Text<AuctionMessage> { 
@Override 
public AuctionMessage decode(String s) { 
JsonReader jsonReader = Json.createReader(new StringReader(s)); 
JsonObject json = jsonReader.readObject(); 
return new AuctionMessage(json.getString("type"), 
json.getString("communicationId"), json.getString("data")); 
} 
@Override 
public boolean willDecode(String s) { 
return s.contains(AuctionMessage.BID_REQUEST) 
|| s.contains(AuctionMessage.AUCTION_LIST_REQUEST) 
|| s.contains(AuctionMessage.LOGIN_REQUEST)); 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Configuring Encoders and Decoders 
•Annotation 
•Specify encoder and decoder values on @ServerEndpoint 
•Programmatic 
•Add encoder/decoder classes to ServerEndpointConfig object 
@ServerEndpoint( decoders = { AuctionMessageDecoder.class }, encoders = { AuctionMessageEncoder.class } 
) 
List<Encoder> encoders = new List<>(); 
encoders.add(AuctionMessageEncoder.class); 
encoders.add(AuctionMessageDecoder.class); 
ServerEndpointConfig config = ServerEndpointConfig.Builder 
.create(AuctionEndpoint.class, "/bids”) 
.encoders(encoders) 
.build();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Securing WebSocket Applications
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Security 
•Based on the Servlet model 
–WebSocket Endpoints are considered resources via their uri 
•So one can 
–Require users be authenticated to access a WebSocket endpoint 
–Limit access to a WebSocket endpoint 
•to certain users, via role mapping 
•to an encrypted protocol (wss://)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.0 
Example secured configuration in web.xml 
<security-constraint> 
<web-resource-collection> 
<web-resource-name>Secure Customer WebSocket Endpoint</web-resource-name> 
<url-pattern>/customer/feed</url-pattern> 
<http-method>GET</http-method> 
</web-resource-collection> 
<auth-constraint> 
<role-name>CUSTOMERS</role-name> 
</auth-constraint> 
<user-data-constraint> 
<transport-guarantee>CONFIDENTIAL</transport-guarantee> 
</user-data-constraint> 
</security-constraint> 
<login-config> <auth-method>BASIC</auth-method> </login-config> <security-role> <role-name>CUSTOMERS</role-name> </security-role>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Tyrus – Reference Implementation 
•Official Page 
–http://tyrus.java.net 
•User Guide (1.8) 
–https://tyrus.java.net/documentation/1.8/user-guide.html 
•Used by 
–GlassFish 4.0+ 
–WebLogic 12c (12.1.3+)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Java EE 7 WebSocket API in WebLogic 12.1.3
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebLogic Server 12.1.3 Mobile, Developer Productivity 
WLS 12.1.3 
Clients 
HTML5 clients 
ADF Mobile 
Proxies 
OTD 
Apache 
OHS 
Web Sockets (JSR 356) 
TopLink Data Services 
Server-Sent Events 
JAX-RS 2.0 
WebSocket Emulation 
WebSocket Emulation 
JAX-RS 2.0, WebSocket 1.0 JSON Programming API JPA 2.1 
Server-Sent Events 
WebSocket Emulation 
JPA-RS 
JPA 
Change Notification 
Database 
JSON Programming API 
HTTP/S, JSON/XML 
WebSocket, Server-Sent Events, Long polling 
Java EE 7 
APIs 
Additional WebLogic Value-Add 
Oracle Confidential – Internal/Restricted/Highly Restricted 
37
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Protocol Fallback 
Enabling WebSocket Use Across All Environments
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Happy HTML5 WebSockets 
●HTML5 and the Java API for WebSocket 
●Enables lots of new opportunities for developing highly interactive applications and rich user experiences 
•Lightweight, fast, easy to program 
•Standardizing across the industry 
●But ... 
●WebSockets are not universally supported across all current environments 
●Most browsers support HTML5 and WebSockets - but - not all of them 
●Firewalls or proxy servers may block the required frames and protocol
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Fallback 
•Provides a behind-the-scenes fallback mechanism to emulate the WebSocket transport behavior 
•Server side with an adapter to handle HTTP Long Polling for WebSocket messages when required 
•Client side with JavaScript library - orasocket.js 
●Developers 
●Use the Java API for WebSocket to developer your application, enable fallback via web.xml context-param 
●Use the HTML5 JavaScript WebSocket API on the client, Include OraSocket.js on client pages 
●Same codebase for native WebSocket Protocol and fallback 
●Transparent runtime behavior
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
Configure Web Applications for WebSockets Fallback Support 
•Import orasocket.js in HTML 
•Modify web.xml 
<?xml version="1.0" encoding="UTF-8"?> 
<web-app version="3.0"> 
<context-param> 
<description>Enable fallback mechanism</description> 
<param-name>com.oracle.tyrus.fallback.enabled</param-name> 
<param-value>true</param-value> 
</context-param> 
</web-app>
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
WebSocket Connections with Fallback 
Composed 
Framed 
Sent 
// JS Client ws = new WebSocket(“ws://” + uri); ws.onmessage = function (evt) { … }; ws.open = function(evt) { ... } ws.onerror = function (evt) { ... } 
Dispatcher 
<html> 
<head> 
<link rel="stylesheet" href="css/ style.css" type="text/css"/> 
<script type="text/javascript” src="js/orasocket.js"></script> 
<script type="text/javascript” src="js/app_code.js"> 
... 
</html> 
WebSocket 
HTTP Long Poll 
Other ... 
Received 
De-framed 
Read 
Dispatcher 
@ServerEndpoint(value = "/customer/{id}") 
public class SuperSocketDemo { 
@OnOpen 
public void hello(Session remote) { ... } 
@OnMessage 
public void handleMessage( String message, @PathParam(“id") String userName, Session session) { ... } 
@OnClose 
public void bye(Session remote) { ... } 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR 356 WebSockets API 1.1 
Maintenance Release
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
MessageHandler with Lambda Expression 
•MessageHandler 
–Interface with one method only: onMessage(T message) 
–Should work as Lambda expression, right? 
•Session.addMessageHandler(MessageHandler) 
–Doesn’t work with Lambda Expressions because the required Generic type in MessageHandler can’t be extracted, for mapping reasons 
•New methods added to javax.websocket.Session 
–public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler); 
–public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler); 
•GlassFish 4.1 includes the fix 
WEBSOCKET_SPEC-226
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.1 
Programmatic Endpoint Example 
public class ProgrammaticEchoServer extends Endpoint { 
public void onOpen(final Session session) { 
session.addMessageHandler(new MessageHandler.Whole<String>() { 
public void onMessage(String text) { 
session.getBasicRemote() .sendText(“Got this: “ + text); 
}}); 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. | 
JSR-356: Java API for WebSocket 1.1 
Programmatic Endpoint Example 
public class ProgrammaticEchoServer extends Endpoint { 
public void onOpen(final Session session) { 
session.addMessageHandler( String.class, msg -> session.getBasicRemote() .sendText(“Got this: “ + msg)); 
} 
}
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. |

WebSockets - Realtime em Mundo Conectado

  • 1.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSockets: Realtime Em Um Mundo Conectado Bruno Borges Principal Product Manager Oracle Latin America Agosto, 2014
  • 2.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Speaker •Bruno Borges –Principal Product Manager, Java Evangelist –Oracle Latin America –@brunoborges –bruno.borges@oracle.com
  • 3.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Overview
  • 4.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Overview The WebSocket API in HTML5 •Enables use of WebSocket in HTML5/web applications •Open/Close connections •Send/Receive messages •Fully asynchronous •Event driven, listen and respond to events
  • 5.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Overview Browser Support for WebSocket API •Broad base of support for WebSocket in modern browsers •Firefox 28+, Chrome 33+, Safari 7+, IE 10+ •Including mobile browsers http://caniuse.com/#search=websocket
  • 6.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Overview Common Use Cases •Time critical data delivery –Stocking monitoring, trading –Ticket reservation, seat selection •Applications that require true bi-directional exchanges with low latency –IoT control systems, gaming, gambling •High levels of interactivity –Chat systems, online sales engagement tools, support systems for trouble shooting •High throughput applications
  • 7.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | The WebSocket Protocol (RFC 6455) Protocol Overview •Defines handshake and data transfer •Introduces new URI schemes –ws-URI = “ws:” “//” host [:port] path [ “?” query ] –wss-URI = “wss:” “//” host [:port] path [ “?” query ] –# MUST be escaped as %23 (URI fragments are meaningless) •Imposes an Origin Security Model •Supports extensibility –Tunnel other protocol by supporting sub-protocols, extend protocol features by supporting extensions
  • 8.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | The WebSocket Protocol Opening Handshake WebLogic Server 12.1.3 HTTP
  • 9.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | The WebSocket Protocol Protocol Upgrade WebLogic Server 12.1.3 WebSocket
  • 10.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | The WebSocket Protocol Keep Alive: Ping and Pong Ping Frame Pong Frame Ping Frame Pong Frame WebLogic Server 12.1.3
  • 11.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | The WebSocket Protocol Closing Handshake WebLogic Server 12.1.3 Close Frame Data Frame Data Frame Data Frame Close Frame
  • 12.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Developing WebSocket Applications using the Java Standard
  • 13.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 The Java Standard for WebSocket Applications •Java community proposed and developed a specification and standard API for using WebSocket with the Java platform –Many companies and individuals represented –Oracle specification lead, developer of reference implementation with Project Tyrus •JSR-356 –Specification finalized and approved May 2013 –Included in Java EE 7 specification •Integrated into WebLogic Server 12.1.3
  • 14.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Core Concepts Endpoint A websocket endpoint is a Java component that represents one side of a sequence of websocket interactions between two connected peers Connection A websocket connection is the networking connection between the two endpoints which are interacting using the websocket protocol Peer A websocket peer is used to represent the another participant of the websocket interactions with the endpoint Session A websocket session is used to represent a sequence of websocket interactions between an endpoint and a single peer Client Endpoints and Server Endpoints A client endpoint is an endpoint that initiates a connection to a peer but does not accept new ones A server endpoint is an endpoint that accepts websocket connections from peers but does not initiate connections to peers.
  • 15.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 •Creating a WebSocket requires a Java class that acts as an Endpoint –Participate in lifecycle: establish connections with peers, handle errors, close connections –Send and receive messages •Endpoints can be created from: –Annotation based approach using WebSocket Annotations, @ServerEndpoint –Programmatic API where Java class extends WebSocket API class •Endpoints can be defined as: –Clients which connect to one server only at a time –Servers which many clients can connect to at any time
  • 16.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Annotated ServerEndpoint Example import javax.websocket.OnMessage; import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/echo") public class EchoServer { @OnMessage public String echo(String incomingMessage) { return String.format( "I got this (%s) message so I am sending it back!”, incomingMessage); } }
  • 17.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Annotated ServerEndpoint Example @ServerEndpoint("/echo") public class EchoServer { @OnMessage public void onMessage(Session session, String message) { session.getOpenSessions() .forEach(s -> s.getBasicRemote().sendText(message)); } }
  • 18.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Annotated Path Parameter Example @ServerEndpoint("/users/{username}") public class UserEndpoint { @OnMessage public String handle(String message, @PathParam("username") String user) { return “message “ + message + “ from user “ + user; } }
  • 19.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Programmatic Endpoint Example public class ProgrammaticEchoServer extends Endpoint { @Override public void onOpen(final Session session, EndpointConfig endpointConfig) { mySession.addMessageHandler(new MessageHandler.Whole<String>() { public void onMessage(String text) { try { mySession.getBasicRemote() .sendText(“I got this (“ + text + “)” + “so I am sending it back !”); } catch (IOException ioe) { } } }); } }
  • 20.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Annotated ClientEndpoint Example import java.io.IOException; import javax.websocket.*; @ClientEndpoint public class HelloClient { @OnOpen public void init(Session session) { try { session.getBasicRemote().sendText("Hello you !"); } catch (IOException ioe) { // error } } }
  • 21.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Programmatic ClientEndpoint Example public class HelloClient extends Endpoint { @Override public void onOpen(Session session, EndpointConfig EndpointConfig) { try { session.getBasicRemote().sendText("Hello you !"); } catch (IOException e) { // error } }
  • 22.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Responding to Lifecycle Events Annotation Programmatic API Open Event @OnOpen public void onOpen(Session session, EndpointConfig config) Message Event @OnMessage •Create instance of relevant javax.websocket.MessageHandler •Register with Session Error Event @OnError public void onError(Session session, Throwable throwable) Close Event @OnClose public void onClose(Session session, CloseReason reason)
  • 23.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Receiving Message from Peers •Annotate a suitable method with @OnMessage •Implement an appropriate MessageHandler interface •Add it to the Session @OnMessage Void handleText(String message) @OnMessage public void handlePartialText( String message, boolean isLast) SimpleHandler implements MessageHandler.Whole<String> { ... } session.addMessageHandler( new SimpleHandler());
  • 24.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Receiving Message from Peer with @OnMessage Message Type Annotated Method Form Text public void handleText(String message) public void handleReader(Reader r) public void handleTextPieces(String message, boolean isLast) Binary public void handleBinary(ByteBuffer bytebuf) public void handleStream(InputStream is) public void handleBinaryPieces(ByteBuffer bytebuf, boolean isLast) Any Object public void handleObject(CustomObject co)
  • 25.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Receiving Message Programmatically from Peers Message Type Message Handler Interface Text MessageHandler.Whole<String> MessageHandler.Whole<Reader> MessageHandler.Partial<String> Binary MessageHandler.Whole<ByteBuffer> MessageHandler.Partial<ByteBuffer> MessageHandler.Whole<InputStream> Any Object MessageHandler.Whole<CustomObject>
  • 26.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Sending Messages to Peers Return a value from the @OnMessage method •Access the RemoteEndpoint interface from the Session object •Call the relevant send method @OnMessage public String echoToUppercase(String msg) { return msg.toUpperCase(); } RemoteEndpoint remote = session.getBasicRemote(); remote.sendText(“This is a txt message”);
  • 27.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Asynchronous and Synchronous Sending Modes Mode Usage Interface and Method Synchronous •Most commonly use mode •Send methods block until transmission of message is complete RemoteEndpoint.Basic void sendText(String message) Asynchronous •Send methods return immediately before transmission •Future and Callback options for completion handling RemoteEndpoint.Async Future sendText(String message) void sendText(String message, SendHandler handler)
  • 28.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Example Encoder public class AuctionMessageEncoder implements Encoder.Text<AuctionMessage> { @Override public String encode(AuctionMessage object) throws EncodeException { JsonObject json = null; switch (object.getType()) { case AuctionMessage.AUCTION_TIME_RESPONSE: json = Json.createObjectBuilder() .add("type", object.getType()) .add("communicationId", object.getCommunicationId()) .add("data", (int) object.getData()).build(); break; } return json.toString(); }
  • 29.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Example Decoder public class AuctionMessageDecoder implements Decoder.Text<AuctionMessage> { @Override public AuctionMessage decode(String s) { JsonReader jsonReader = Json.createReader(new StringReader(s)); JsonObject json = jsonReader.readObject(); return new AuctionMessage(json.getString("type"), json.getString("communicationId"), json.getString("data")); } @Override public boolean willDecode(String s) { return s.contains(AuctionMessage.BID_REQUEST) || s.contains(AuctionMessage.AUCTION_LIST_REQUEST) || s.contains(AuctionMessage.LOGIN_REQUEST)); }
  • 30.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Configuring Encoders and Decoders •Annotation •Specify encoder and decoder values on @ServerEndpoint •Programmatic •Add encoder/decoder classes to ServerEndpointConfig object @ServerEndpoint( decoders = { AuctionMessageDecoder.class }, encoders = { AuctionMessageEncoder.class } ) List<Encoder> encoders = new List<>(); encoders.add(AuctionMessageEncoder.class); encoders.add(AuctionMessageDecoder.class); ServerEndpointConfig config = ServerEndpointConfig.Builder .create(AuctionEndpoint.class, "/bids”) .encoders(encoders) .build();
  • 31.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Securing WebSocket Applications
  • 32.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Security •Based on the Servlet model –WebSocket Endpoints are considered resources via their uri •So one can –Require users be authenticated to access a WebSocket endpoint –Limit access to a WebSocket endpoint •to certain users, via role mapping •to an encrypted protocol (wss://)
  • 33.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.0 Example secured configuration in web.xml <security-constraint> <web-resource-collection> <web-resource-name>Secure Customer WebSocket Endpoint</web-resource-name> <url-pattern>/customer/feed</url-pattern> <http-method>GET</http-method> </web-resource-collection> <auth-constraint> <role-name>CUSTOMERS</role-name> </auth-constraint> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> </login-config> <security-role> <role-name>CUSTOMERS</role-name> </security-role>
  • 34.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Tyrus – Reference Implementation •Official Page –http://tyrus.java.net •User Guide (1.8) –https://tyrus.java.net/documentation/1.8/user-guide.html •Used by –GlassFish 4.0+ –WebLogic 12c (12.1.3+)
  • 35.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Java EE 7 WebSocket API in WebLogic 12.1.3
  • 36.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebLogic Server 12.1.3 Mobile, Developer Productivity WLS 12.1.3 Clients HTML5 clients ADF Mobile Proxies OTD Apache OHS Web Sockets (JSR 356) TopLink Data Services Server-Sent Events JAX-RS 2.0 WebSocket Emulation WebSocket Emulation JAX-RS 2.0, WebSocket 1.0 JSON Programming API JPA 2.1 Server-Sent Events WebSocket Emulation JPA-RS JPA Change Notification Database JSON Programming API HTTP/S, JSON/XML WebSocket, Server-Sent Events, Long polling Java EE 7 APIs Additional WebLogic Value-Add Oracle Confidential – Internal/Restricted/Highly Restricted 37
  • 37.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Protocol Fallback Enabling WebSocket Use Across All Environments
  • 38.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Happy HTML5 WebSockets ●HTML5 and the Java API for WebSocket ●Enables lots of new opportunities for developing highly interactive applications and rich user experiences •Lightweight, fast, easy to program •Standardizing across the industry ●But ... ●WebSockets are not universally supported across all current environments ●Most browsers support HTML5 and WebSockets - but - not all of them ●Firewalls or proxy servers may block the required frames and protocol
  • 39.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Fallback •Provides a behind-the-scenes fallback mechanism to emulate the WebSocket transport behavior •Server side with an adapter to handle HTTP Long Polling for WebSocket messages when required •Client side with JavaScript library - orasocket.js ●Developers ●Use the Java API for WebSocket to developer your application, enable fallback via web.xml context-param ●Use the HTML5 JavaScript WebSocket API on the client, Include OraSocket.js on client pages ●Same codebase for native WebSocket Protocol and fallback ●Transparent runtime behavior
  • 40.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | Configure Web Applications for WebSockets Fallback Support •Import orasocket.js in HTML •Modify web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0"> <context-param> <description>Enable fallback mechanism</description> <param-name>com.oracle.tyrus.fallback.enabled</param-name> <param-value>true</param-value> </context-param> </web-app>
  • 41.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | WebSocket Connections with Fallback Composed Framed Sent // JS Client ws = new WebSocket(“ws://” + uri); ws.onmessage = function (evt) { … }; ws.open = function(evt) { ... } ws.onerror = function (evt) { ... } Dispatcher <html> <head> <link rel="stylesheet" href="css/ style.css" type="text/css"/> <script type="text/javascript” src="js/orasocket.js"></script> <script type="text/javascript” src="js/app_code.js"> ... </html> WebSocket HTTP Long Poll Other ... Received De-framed Read Dispatcher @ServerEndpoint(value = "/customer/{id}") public class SuperSocketDemo { @OnOpen public void hello(Session remote) { ... } @OnMessage public void handleMessage( String message, @PathParam(“id") String userName, Session session) { ... } @OnClose public void bye(Session remote) { ... } }
  • 42.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR 356 WebSockets API 1.1 Maintenance Release
  • 43.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | MessageHandler with Lambda Expression •MessageHandler –Interface with one method only: onMessage(T message) –Should work as Lambda expression, right? •Session.addMessageHandler(MessageHandler) –Doesn’t work with Lambda Expressions because the required Generic type in MessageHandler can’t be extracted, for mapping reasons •New methods added to javax.websocket.Session –public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler); –public <T> void addMessageHandler(Class<T> clazz, MessageHandler.Partial<T> handler); •GlassFish 4.1 includes the fix WEBSOCKET_SPEC-226
  • 44.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.1 Programmatic Endpoint Example public class ProgrammaticEchoServer extends Endpoint { public void onOpen(final Session session) { session.addMessageHandler(new MessageHandler.Whole<String>() { public void onMessage(String text) { session.getBasicRemote() .sendText(“Got this: “ + text); }}); } }
  • 45.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. | JSR-356: Java API for WebSocket 1.1 Programmatic Endpoint Example public class ProgrammaticEchoServer extends Endpoint { public void onOpen(final Session session) { session.addMessageHandler( String.class, msg -> session.getBasicRemote() .sendText(“Got this: “ + msg)); } }
  • 46.
    Copyright © 2014,Oracle and/or its affiliates. All rights reserved. |