SlideShare a Scribd company logo
Java EE 7 Websocket Chat

Creating a Chat Application using Java EE 7,
Websockets and GlassFish 4

2014 Micha Kops / www.hascode.com
Table of Contents
●

What we're going to build (I)

●

What we're going to build (II)

●

Prerequisites

●

Creating a new web app

●

Adding the Maven Embedded GlassFish Plugin

●

Websocket Endpoint

●

Chat Message Data Transfer Object

●

Converting Chat Messages

●

Encoder Implementation

●

The Client Side

●

Client DOM Scripts (I)

●

Client DOM Scripts (II)

●

Client DOM Scripts (III)

●

Client HTML (I)

●

Client HTML (II)

●

Build, deploy, run …

●

Tutorial, Sources and Links

2014 Micha Kops / www.hascode.com
What we're going to build (I)

2014 Micha Kops / www.hascode.com
What we're going to build (II)
●

●

●

●

A chat application client using Bootstrap and
jQuery
A user may register with a nickname for a
chatroom from a list of given rooms
Messages in a chat room are pushed to each
subscribed client using web sockets
A user may log out from the chat room

2014 Micha Kops / www.hascode.com
Prerequisites
●

Java 7 JDK

●

Maven 3

●

An IDE of your choice

●

A websockets-capable web
browser

2014 Micha Kops / www.hascode.com
Creating a new web app
●

Using the javaee7-webapp Maven
Archetype

<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
</dependencies>

2014 Micha Kops / www.hascode.com
Adding the Maven
Embedded GlassFish Plugin
<plugin>
<groupId>org.glassfish.embedded</groupId>
<artifactId>maven-embedded-glassfish-plugin</artifactId>
<version>4.0</version>
<configuration>
<goalPrefix>embedded-glassfish</goalPrefix>
<app>${basedir}/target/${project.artifactId}-${project.version}.war</app>
<autoDelete>true</autoDelete>
<port>8080</port>
<name>${project.artifactId}</name>
<contextRoot>hascode</contextRoot>
</configuration>
<executions>
<execution>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>

2014 Micha Kops / www.hascode.com
Websocket Endpoint
@ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class)
public class ChatEndpoint {
private final Logger log = Logger.getLogger(getClass().getName());
@OnOpen
public void open(final Session session, @PathParam("room") final String room) {
log.info("session openend and bound to room: " + room);
session.getUserProperties().put("room", room);
}
@OnMessage
public void onMessage(final Session session, final ChatMessage chatMessage) {
String room = (String) session.getUserProperties().get("room");
try {
for (Session s : session.getOpenSessions()) {
if (s.isOpen()
&& room.equals(s.getUserProperties().get("room"))) {
s.getBasicRemote().sendObject(chatMessage);
}
}
} catch (IOException | EncodeException e) {
log.log(Level.WARNING, "onMessage failed", e);
}
}
}

2014 Micha Kops / www.hascode.com
Chat Message Data Transfer
Object
package com.hascode.tutorial;
import java.util.Date;
public class ChatMessage {
private String message;
private String sender;
private Date received;
// getter, setter, toString omitted..
}

2014 Micha Kops / www.hascode.com
Converting Chat Messages
public class ChatMessageDecoder implements Decoder.Text<ChatMessage> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public ChatMessage decode(final String textMessage) throws DecodeException {
ChatMessage chatMessage = new ChatMessage();
JsonObject obj = Json.createReader(new StringReader(textMessage))
.readObject();
chatMessage.setMessage(obj.getString("message"));
chatMessage.setSender(obj.getString("sender"));
chatMessage.setReceived(new Date());
return chatMessage;
}
@Override
public boolean willDecode(final String s) {
return true;
}
}

2014 Micha Kops / www.hascode.com
Encoder Implementation
public class ChatMessageEncoder implements Encoder.Text<ChatMessage> {
@Override
public void init(final EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public String encode(final ChatMessage chatMessage) throws EncodeException {
return Json.createObjectBuilder()
.add("message", chatMessage.getMessage())
.add("sender", chatMessage.getSender())
.add("received", chatMessage.getReceived().toString()).build()
.toString();
}
}

2014 Micha Kops / www.hascode.com
The Client Side
●

●

●

●

●

●

●

We're using JavaScript to create the following stuff:
A websocket URL follows this schema:
ws://IP:PORT/CONTEXT_PATH/ENDPOINT_URL e.g
ws://0.0.0.0:8080/hascode/chat/java
A new websocket connection is created using the native WebSocket object e.g.
var wsocket = new WebSocket(‘ws://0.0.0.0:8080/hascode/chat/java’);
Registering a callback function to receive incoming messages from the server
goes like this: wsocket.onmessage = yourCallbackFunction;
Sending a message to the server is done by wsocket.send() .. pass a string,
binary data .. whatever you like ..
Closing a connection is simply done by wsocket.close()
There is a lot of useful information that I did not add to this tutorial from
keepalive-pings to the handshake protocol and other features .. one good
starting point for detailed information about websockets might be IETF RFC
6455

2014 Micha Kops / www.hascode.com
Client DOM Scripts (I)
var wsocket;
var serviceLocation = "ws://0.0.0.0:8080/hascode/chat/";
var $nickName;
var $message;
var $chatWindow;
var room = '';
function onMessageReceived(evt) {
//var msg = eval('(' + evt.data + ')');
var msg = JSON.parse(evt.data); // native API
var $messageLine = $('<tr><td class="received">' + msg.received
+ '</td><td class="user label label-info">' + msg.sender
+ '</td><td class="message badge">' + msg.message
+ '</td></tr>');
$chatWindow.append($messageLine);
}
function sendMessage() {
var msg = '{"message":"' + $message.val() + '", "sender":"'
+ $nickName.val() + '", "received":""}';
wsocket.send(msg);
$message.val('').focus();
}

2014 Micha Kops / www.hascode.com
Client DOM Scripts (II)
function connectToChatserver() {
room = $('#chatroom option:selected').val();
wsocket = new WebSocket(serviceLocation + room);
wsocket.onmessage = onMessageReceived;
}
function leaveRoom() {
wsocket.close();
$chatWindow.empty();
$('.chat-wrapper').hide();
$('.chat-signin').show();
$nickName.focus();
}

2014 Micha Kops / www.hascode.com
Client DOM Scripts (III)
$(document).ready(function() {
$nickName = $('#nickname');
$message = $('#message');
$chatWindow = $('#response');
$('.chat-wrapper').hide();
$nickName.focus();
$('#enterRoom').click(function(evt) {
evt.preventDefault();
connectToChatserver();
$('.chat-wrapper h2').text('Chat # '+$nickName.val() + "@" + room);
$('.chat-signin').hide();
$('.chat-wrapper').show();
$message.focus();
});
$('#do-chat').submit(function(evt) {
evt.preventDefault();
sendMessage()
});
$('#leave-room').click(function(){
leaveRoom();
});
});

2014 Micha Kops / www.hascode.com
Client HTML (I)
<div class="container chat-signin">
<form class="form-signin">
<h2 class="form-signin-heading">Chat sign in</h2>
<label for="nickname">Nickname</label> <input type="text"
class="input-block-level" placeholder="Nickname" id="nickname">
<div class="btn-group">
<label for="chatroom">Chatroom</label> <select size="1"
id="chatroom">
<option>arduino</option>
<option>java</option>
<option>groovy</option>
<option>scala</option>
</select>
</div>
<button class="btn btn-large btn-primary" type="submit"
id="enterRoom">Sign in</button>
</form>
</div>

2014 Micha Kops / www.hascode.com
Client HTML (II)
<div class="container chat-wrapper">
<form id="do-chat">
<h2 class="alert alert-success"></h2>
<table id="response" class="table table-bordered"></table>
<fieldset>
<legend>Enter your message..</legend>
<div class="controls">
<input type="text" class="input-block-level" placeholder="Your message..."
id="message" style="height:60px"/>
<input type="submit" class="btn btn-large btn-block btn-primary"
value="Send message" />
<button class="btn btn-large btn-block" type="button" id="leave-room">Leave
room</button>
</div>
</fieldset>
</form>
</div>

2014 Micha Kops / www.hascode.com
Build, deploy, run …
●

Simply run: mvn package
embedded-glassfish:run

2014 Micha Kops / www.hascode.com
Tutorial, Sources and Links
●

Please feel free to take a look
at the full tutorial on my blog:
http://www.hascode.com/2013/08/

2014 Micha Kops / www.hascode.com

More Related Content

What's hot

Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsArun Gupta
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionMazenetsolution
 
Android webservices
Android webservicesAndroid webservices
Android webservicesKrazy Koder
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Languagegiurca
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)Ghadeer AlHasan
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Oscar Renalias
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 

What's hot (19)

Servlets intro
Servlets introServlets intro
Servlets intro
 
Getting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent EventsGetting Started with WebSockets and Server-Sent Events
Getting Started with WebSockets and Server-Sent Events
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Servlet life cycle
Servlet life cycleServlet life cycle
Servlet life cycle
 
Android webservices
Android webservicesAndroid webservices
Android webservices
 
Url programming
Url programmingUrl programming
Url programming
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlet
Servlet Servlet
Servlet
 
#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)#3 (Multi Threads With TCP)
#3 (Multi Threads With TCP)
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
AJAX
AJAXAJAX
AJAX
 
Servlets
ServletsServlets
Servlets
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 

Similar to Creating a Java EE 7 Websocket Chat Application

softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsdaviddemello
 
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Bart Uelen
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
WebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptWebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptMichele Di Salvatore
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi clientichsanbarokah
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008Association Paris-Web
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication developmentGanesh Gembali
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slideshelenmga
 
Mobile Device APIs
Mobile Device APIsMobile Device APIs
Mobile Device APIsJames Pearce
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsDoris Chen
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump StartHaim Michael
 

Similar to Creating a Java EE 7 Websocket Chat Application (20)

softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Get Real: Adventures in realtime web apps
Get Real: Adventures in realtime web appsGet Real: Adventures in realtime web apps
Get Real: Adventures in realtime web apps
 
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
Tadhack madrid June 2014: Joris Swinnen and WebRTC Nederland "Invite my colle...
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
WebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascriptWebRTC + Socket.io: building a skype-like video chat with native javascript
WebRTC + Socket.io: building a skype-like video chat with native javascript
 
Laporan multi client
Laporan multi clientLaporan multi client
Laporan multi client
 
5.node js
5.node js5.node js
5.node js
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
IE 8 et les standards du Web - Chris Wilson - Paris Web 2008
 
Mobile webapplication development
Mobile webapplication developmentMobile webapplication development
Mobile webapplication development
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Mobile Device APIs
Mobile Device APIsMobile Device APIs
Mobile Device APIs
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
What Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 AppsWhat Web Developers Need to Know to Develop Windows 8 Apps
What Web Developers Need to Know to Develop Windows 8 Apps
 
CGI.ppt
CGI.pptCGI.ppt
CGI.ppt
 
WebSockets Jump Start
WebSockets Jump StartWebSockets Jump Start
WebSockets Jump Start
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 

Recently uploaded

10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsUXDXConf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
Server-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at PricelineServer-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at PricelineUXDXConf
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKUXDXConf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty SecureFemke de Vroome
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Boni Yeamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101vincent683379
 

Recently uploaded (20)

10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Server-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at PricelineServer-Driven User Interface (SDUI) at Priceline
Server-Driven User Interface (SDUI) at Priceline
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.Enterprise Security Monitoring, And Log Management.
Enterprise Security Monitoring, And Log Management.
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 

Creating a Java EE 7 Websocket Chat Application

  • 1. Java EE 7 Websocket Chat Creating a Chat Application using Java EE 7, Websockets and GlassFish 4 2014 Micha Kops / www.hascode.com
  • 2. Table of Contents ● What we're going to build (I) ● What we're going to build (II) ● Prerequisites ● Creating a new web app ● Adding the Maven Embedded GlassFish Plugin ● Websocket Endpoint ● Chat Message Data Transfer Object ● Converting Chat Messages ● Encoder Implementation ● The Client Side ● Client DOM Scripts (I) ● Client DOM Scripts (II) ● Client DOM Scripts (III) ● Client HTML (I) ● Client HTML (II) ● Build, deploy, run … ● Tutorial, Sources and Links 2014 Micha Kops / www.hascode.com
  • 3. What we're going to build (I) 2014 Micha Kops / www.hascode.com
  • 4. What we're going to build (II) ● ● ● ● A chat application client using Bootstrap and jQuery A user may register with a nickname for a chatroom from a list of given rooms Messages in a chat room are pushed to each subscribed client using web sockets A user may log out from the chat room 2014 Micha Kops / www.hascode.com
  • 5. Prerequisites ● Java 7 JDK ● Maven 3 ● An IDE of your choice ● A websockets-capable web browser 2014 Micha Kops / www.hascode.com
  • 6. Creating a new web app ● Using the javaee7-webapp Maven Archetype <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency> </dependencies> 2014 Micha Kops / www.hascode.com
  • 7. Adding the Maven Embedded GlassFish Plugin <plugin> <groupId>org.glassfish.embedded</groupId> <artifactId>maven-embedded-glassfish-plugin</artifactId> <version>4.0</version> <configuration> <goalPrefix>embedded-glassfish</goalPrefix> <app>${basedir}/target/${project.artifactId}-${project.version}.war</app> <autoDelete>true</autoDelete> <port>8080</port> <name>${project.artifactId}</name> <contextRoot>hascode</contextRoot> </configuration> <executions> <execution> <goals> <goal>deploy</goal> </goals> </execution> </executions> </plugin> 2014 Micha Kops / www.hascode.com
  • 8. Websocket Endpoint @ServerEndpoint(value = "/chat/{room}", encoders = ChatMessageEncoder.class, decoders = ChatMessageDecoder.class) public class ChatEndpoint { private final Logger log = Logger.getLogger(getClass().getName()); @OnOpen public void open(final Session session, @PathParam("room") final String room) { log.info("session openend and bound to room: " + room); session.getUserProperties().put("room", room); } @OnMessage public void onMessage(final Session session, final ChatMessage chatMessage) { String room = (String) session.getUserProperties().get("room"); try { for (Session s : session.getOpenSessions()) { if (s.isOpen() && room.equals(s.getUserProperties().get("room"))) { s.getBasicRemote().sendObject(chatMessage); } } } catch (IOException | EncodeException e) { log.log(Level.WARNING, "onMessage failed", e); } } } 2014 Micha Kops / www.hascode.com
  • 9. Chat Message Data Transfer Object package com.hascode.tutorial; import java.util.Date; public class ChatMessage { private String message; private String sender; private Date received; // getter, setter, toString omitted.. } 2014 Micha Kops / www.hascode.com
  • 10. Converting Chat Messages public class ChatMessageDecoder implements Decoder.Text<ChatMessage> { @Override public void init(final EndpointConfig config) { } @Override public void destroy() { } @Override public ChatMessage decode(final String textMessage) throws DecodeException { ChatMessage chatMessage = new ChatMessage(); JsonObject obj = Json.createReader(new StringReader(textMessage)) .readObject(); chatMessage.setMessage(obj.getString("message")); chatMessage.setSender(obj.getString("sender")); chatMessage.setReceived(new Date()); return chatMessage; } @Override public boolean willDecode(final String s) { return true; } } 2014 Micha Kops / www.hascode.com
  • 11. Encoder Implementation public class ChatMessageEncoder implements Encoder.Text<ChatMessage> { @Override public void init(final EndpointConfig config) { } @Override public void destroy() { } @Override public String encode(final ChatMessage chatMessage) throws EncodeException { return Json.createObjectBuilder() .add("message", chatMessage.getMessage()) .add("sender", chatMessage.getSender()) .add("received", chatMessage.getReceived().toString()).build() .toString(); } } 2014 Micha Kops / www.hascode.com
  • 12. The Client Side ● ● ● ● ● ● ● We're using JavaScript to create the following stuff: A websocket URL follows this schema: ws://IP:PORT/CONTEXT_PATH/ENDPOINT_URL e.g ws://0.0.0.0:8080/hascode/chat/java A new websocket connection is created using the native WebSocket object e.g. var wsocket = new WebSocket(‘ws://0.0.0.0:8080/hascode/chat/java’); Registering a callback function to receive incoming messages from the server goes like this: wsocket.onmessage = yourCallbackFunction; Sending a message to the server is done by wsocket.send() .. pass a string, binary data .. whatever you like .. Closing a connection is simply done by wsocket.close() There is a lot of useful information that I did not add to this tutorial from keepalive-pings to the handshake protocol and other features .. one good starting point for detailed information about websockets might be IETF RFC 6455 2014 Micha Kops / www.hascode.com
  • 13. Client DOM Scripts (I) var wsocket; var serviceLocation = "ws://0.0.0.0:8080/hascode/chat/"; var $nickName; var $message; var $chatWindow; var room = ''; function onMessageReceived(evt) { //var msg = eval('(' + evt.data + ')'); var msg = JSON.parse(evt.data); // native API var $messageLine = $('<tr><td class="received">' + msg.received + '</td><td class="user label label-info">' + msg.sender + '</td><td class="message badge">' + msg.message + '</td></tr>'); $chatWindow.append($messageLine); } function sendMessage() { var msg = '{"message":"' + $message.val() + '", "sender":"' + $nickName.val() + '", "received":""}'; wsocket.send(msg); $message.val('').focus(); } 2014 Micha Kops / www.hascode.com
  • 14. Client DOM Scripts (II) function connectToChatserver() { room = $('#chatroom option:selected').val(); wsocket = new WebSocket(serviceLocation + room); wsocket.onmessage = onMessageReceived; } function leaveRoom() { wsocket.close(); $chatWindow.empty(); $('.chat-wrapper').hide(); $('.chat-signin').show(); $nickName.focus(); } 2014 Micha Kops / www.hascode.com
  • 15. Client DOM Scripts (III) $(document).ready(function() { $nickName = $('#nickname'); $message = $('#message'); $chatWindow = $('#response'); $('.chat-wrapper').hide(); $nickName.focus(); $('#enterRoom').click(function(evt) { evt.preventDefault(); connectToChatserver(); $('.chat-wrapper h2').text('Chat # '+$nickName.val() + "@" + room); $('.chat-signin').hide(); $('.chat-wrapper').show(); $message.focus(); }); $('#do-chat').submit(function(evt) { evt.preventDefault(); sendMessage() }); $('#leave-room').click(function(){ leaveRoom(); }); }); 2014 Micha Kops / www.hascode.com
  • 16. Client HTML (I) <div class="container chat-signin"> <form class="form-signin"> <h2 class="form-signin-heading">Chat sign in</h2> <label for="nickname">Nickname</label> <input type="text" class="input-block-level" placeholder="Nickname" id="nickname"> <div class="btn-group"> <label for="chatroom">Chatroom</label> <select size="1" id="chatroom"> <option>arduino</option> <option>java</option> <option>groovy</option> <option>scala</option> </select> </div> <button class="btn btn-large btn-primary" type="submit" id="enterRoom">Sign in</button> </form> </div> 2014 Micha Kops / www.hascode.com
  • 17. Client HTML (II) <div class="container chat-wrapper"> <form id="do-chat"> <h2 class="alert alert-success"></h2> <table id="response" class="table table-bordered"></table> <fieldset> <legend>Enter your message..</legend> <div class="controls"> <input type="text" class="input-block-level" placeholder="Your message..." id="message" style="height:60px"/> <input type="submit" class="btn btn-large btn-block btn-primary" value="Send message" /> <button class="btn btn-large btn-block" type="button" id="leave-room">Leave room</button> </div> </fieldset> </form> </div> 2014 Micha Kops / www.hascode.com
  • 18. Build, deploy, run … ● Simply run: mvn package embedded-glassfish:run 2014 Micha Kops / www.hascode.com
  • 19. Tutorial, Sources and Links ● Please feel free to take a look at the full tutorial on my blog: http://www.hascode.com/2013/08/ 2014 Micha Kops / www.hascode.com