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

August 13th, 2013 by

Java EE 7 is out now and so I was curious to play around with the new specifications and APIs from in this technology stack.

That’s why I didn’t hesitate to add yet another websocket-chat tutorial to the existing ones on the internet in favor of gathering some experience with this technology and a possible integration using a GlassFish 4 server, the new Java API for JSON Processing for data serialization combined with custom websocket encoders/decoders and finally adding some Bootstrap and jQuery on the client side.


 

The final chat application.

The final chat application.

Prerequisites

We need the following stuff to build and run the following application:

Creating the new Project

You should simply use the Java EE 7 Webapp Archetype here so that your final pom.xml could look similar to this one (shortened):

<properties>
	<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
	<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
 
<dependencies>
	<dependency>
		<groupId>javax</groupId>
		<artifactId>javaee-api</artifactId>
		<version>7.0</version>
		<scope>provided</scope>
	</dependency>
</dependencies>
 
<build>
	<plugins>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>3.1</version>
			<configuration>
				<source>1.7</source>
				<target>1.7</target>
				<compilerArguments>
					<endorseddirs>${endorsed.dir}</endorseddirs>
				</compilerArguments>
			</configuration>
		</plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-war-plugin</artifactId>
			<version>2.3</version>
			<configuration>
				<failOnMissingWebXml>false</failOnMissingWebXml>
			</configuration>
		</plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-dependency-plugin</artifactId>
			<version>2.6</version>
			[..]
		</plugin>
	</plugins>
</build>

Maven Embedded GlassFish Plugin

Adding the following snippet allows us to quickly download and startup a full GlassFish 4 instance with our application deployed by running one simple Maven goal.

Big thanks @resah for pointing out at one issue that got me initially (EMBEDDED_GLASSFISH-142) but is no problem if you’re using the following plugin configuration

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

Afterwards we’re able to startup the application server by running the following command:

mvn embedded-glassfish:run

The Websocket Endpoint

This is our endpoint implementation. Some short facts here about the implementation.

  • @ServerEndpoint defines a new endpoint – the value specifies the URL path and allows PathParams as we’re used know from JAX-RS.
  • So value=”/chat/{room}” allows the client to open a websocket connection to an URL like ws://<IP>:<PORT>/<CONTEXT_PATH>/chat/room .. e.g. ws://0.0.0.0:8080/hascode/chat/java
  • The value in curly braces may be injected as a path parameter in the lifecycle callback methods in the endpoint using javax.websocket.server.PathParam
  • In addition to the URL schema, we’re specifying an encoder and a decoder class. We need this because we’re using a custom DTO object to pass our chat data between server and client
  • When a client opens the first connection to the server, he passes the chat-room he wants to enter as a path-parameter and we’re storing this value in the user properties map using session.getUserProperties()..
  • Now when a chat participant posts a new message over the tcp connection to the server, we’re iterating over all open session, and each session that is assigned to the room the session/message is bound to, receives the decoded and re-encoded message
  • If we wanted to send a simple text or binary message we could have used session.getBasicRemote().sendBinary() or session.getBasicRemote().sendText()
package com.hascode.tutorial;
 
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.websocket.EncodeException;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
 
@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);
		}
	}
}

ChatMessage Data-Transfer-Object

This is the DTO we’re using to transfer the chat data bidirectional over the TCP connection.

package com.hascode.tutorial;
 
import java.util.Date;
 
public class ChatMessage {
	private String message;
	private String sender;
	private Date received;
 
	// getter, setter, toString omitted..
}

Converting ChatMessages

These are the encoder and the decoder implementations that are referenced in the @ServerEndpoint properties and that allow us to convert incoming or outgoing data between ChatMessages and the JSON format.

Decoder Implementation

The following decoder converts incoming chat message strings to out ChatMessage POJO.

We’re using the new Java API for JSON Processing (JSR353) here to pass data from the JSON format to the ChatMessage.

The willDecode() method allows us to specify if our decoder is able to handle the incoming data .. in our case this is always true ;)

package com.hascode.tutorial;
 
import java.io.StringReader;
import java.util.Date;
 
import javax.json.Json;
import javax.json.JsonObject;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;
 
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;
	}
}

Encoder Implementation

This encoder does the opposite – converting a ChatMessage to a JSON string again using the Java API for JSON Processing and its shiny new JSON builder.

package com.hascode.tutorial;
 
import javax.json.Json;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
 
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();
	}
}

Bootstrap, Javascript .. the Client Side of Life…

Finally we’re adding the following index.html to the src/main/webapp directory (shortened, please feel free to have a look a the tutorial sources for the full code)

There are only three interesting API calls that we should remember here – the rest of the javascript adds some functions to the user interface etc …

  • 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
<!DOCTYPE html>
<html lang="en">
<head>
[..]
<script>
	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();
	}
 
	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();
	}
 
	$(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();
		});
	});
</script>
</head>
 
<body>
 
	<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>
	<!-- /container -->
 
	<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>
</body>
</html>

Build, Deploy, Run…

Now we’re ready to build and deploy our application. If you’re using the embedded-glassfish-plugin your simply need to run

mvn package embedded-glassfish:run

Alternatively upload the application to your GlassFish instance and use hascode as context path (or modify the path in the index.html according to your context path!).

Finally you should be able to load the chat application at the following URL: http://localhost:8080/hascode and it should look similar to this screenshot:

The final chat application.

The final chat application.

Screencast

This is our chat in action – I’ve used two browser instances – one Chrome, one Firefox here to simulate two chat participants …

Tutorial Sources

Please feel free to download the tutorial sources from my Bitbucket repository, fork it there or clone it using Git:

git clone https://bitbucket.org/hascode/javaee7-websocket-chat.git

Direct Download

For those of you who do not want to build the application by themselves, I’ve added the war file as a direct download here:

https://bitbucket.org/hascode/javaee7-websocket-chat/downloads/javaee7-websocket-chat-1.0.0.war

Slides

I’ve added the following presentation on my slideshare account:

Client Implementation in Java

Please feel free to have a look at my article “Creating different Websocket Chat Clients in Java” for a client implementation in Java.

Resources

Article Updates

2014-11-09: Article about websocket client implementation in Java linked.

Tags: , , , , , , , , , , ,

32 Responses to “Creating a Chat Application using Java EE 7, Websockets and GlassFish 4”

  1. arr zee Says:

    wat jars i have to add to run it full with easee

  2. micha kops Says:

    the app can be downloaded here: https://bitbucket.org/hascode/javaee7-websocket-chat/downloads or do you need information regarding libraries/dependencies?

  3. admin Says:

    cann’t download the war in china?

  4. micha kops Says:

    Possibly a temporary error in Bitbucket’s CDN .. does the problem still exist?

  5. Zavael Says:

    hi, i tried your example on jetty but its somehow not working.. it signs me in the room, but when I want to send message, its doing nothing..
    To make it work on jetty i just added plugin to pom to the project from git repo on bitbucket:

    org.eclipse.jetty
    jetty-maven-plugin
    ${jettyVersion}

    with jetty version 9.0.7.v20131107
    can you help me solve the problem? thanks.. and by the way, great article :)

  6. micha kops Says:

    Jetty is a servlet container but not a Java EE application server therefore the war file produced won’t work that way when deployed on a normal servlet container. If you’d like to experiment with websockets on a jetty server, perhaps one of the following links may help you here:

    http://www.eclipse.org/jetty/documentation/current/jetty-websocket-server-api.html
    http://java.dzone.com/articles/creating-websocket-chat

    Alternatively if you’d like to try something completly different without a classical servlet container or application server, please feel free to have a look at my blog article “Creating a Websocket Chat Application with Vert.x and Java

  7. prideloki Says:

    I did this and but stuck in the chatting room.
    when I entered a message, the message didn’t show up.
    I use a NetBean and Glassfish.

  8. vandiedakaf Says:

    If this tutorial does not work for you then change serviceLocation (in index.html):

    var serviceLocation = “ws://localhost:8080/hascode/chat/”;

  9. Ashwinikumar Says:

    Great, thanks, it worked on Glassfish. There was a slight glitch for me, in the HTML – here is what I did -

    Added in head,

    and changed javascript method to jQuery(document).ready(function()

  10. Psuryawanshi Says:

    I have downloaded source code & done successfully build n deploy only with Maven 3 not on higher version. once it got deployed started app with http://localhost:8080/hascode/ url.

    it enters into room with login but not able to send sms as does nothing on send button click. when checked it was showing error on browser console as WebSocket is already in CLOSING or CLOSED state.

    Please advice how to take it further.

  11. Jaz Says:

    Hi,

    Many thanks for an excellent post!

    I have downloaded the example WAR file and deployed it to my GlassFish 4.0 Server, unfortunately I simply cannot get it to work.

    I am using Firefox which reports it is unable to connect to connect to the server as follows:

    “Firefox can’t establish a connection to the server at ws://0.0.0.0:8080/hascode/chat/arduino”

    I see no problems in the server log which reports the WAR file has been successfully deployed.

    Would really appreciate any ideas on why it is not working or how I can explore further,

    Many thanks!

  12. Billel Says:

    Hi,
    The publication list of messages does not work in chat (Enter your message … and always empty) even though sending multiple message.

    Thank you to correct or tell us how to do it (as if this feature has been removed)
    -fr——
    La liste de publication des messages ne fonctionne pas dans le chat (Enter your message… et toujours vide) même si en envoi plusieurs message.

    Merci de corrige ou de nous dire comment le faire (comme si cette fonctionnalité a été supprimé)

  13. Kristoff Says:

    Hey Psuryawanshi
    I have the same error that You had:
    WebSocket is already in CLOSING or CLOSED state

    Any luck with that?

  14. Kristoff Says:

    Update :)

    problem was in serviceLocation param.

    var serviceLocation = “ws://127.0.0.1:8080/hascode/chat/”; <- not good

    var serviceLocation = "ws://" + document.location.host + "/ChatRoomProject/chat/"; <- ok in my case.

    After this change everything works fine.

    Hope that help :)

  15. Mangal Dev Says:

    Awesome… Cool Stuff. It is so complete. Just downloaded and ran in a single shot.

    @Kristoff : Thanks dude. I was getting the same issue and with your change its working perfectly :)

  16. Bruno S Says:

    Man, perfect job! Nice tutorial…

    I’m starting learn about websockets, can u say an good link with some explanations? To help me understand websockets and if u know an tuto that uses primfaces, JSF… with websockets..

  17. arrhe Says:

    I downloaded war and deployed in tomcat server made changes in index.jsp var serviceLocation = “ws://”+document.location.host+”/hascode/chat/”;.Even after the changes it says 404 exception.

  18. micha kops Says:

    Hi arrhe,

    you can’t run a Java EE application on a Tomcat servlet container – you need to use an application server instead.

    If you want to use websockets on a Tomcat server you can find more information here:

    http://tomcat.apache.org/tomcat-8.0-doc/web-socket-howto.html

    A snippet:

    https://gist.github.com/chitan/3063774

    If you’re interested in another solution without using the Java EE stack but using Vert.x, please feel free to have a look at the following article of mine: “Creating a Websocket Chat Application with Vert.x and Java

  19. arrhe Says:

    Hi Micha kops,
    I’m a new bee can please tell what excatly do i need to do.I tried to create a dynamic web project and replaced the files available in git but still it throwing 404 exception “localhost:8080/chaton/wsapp/WsChatServlet” chat on is my application name,wsapp is my package name.

  20. micha kops Says:

    Hi Arrhe,

    could you please share your code on some public repository please – maybe I can be a better help then :)

  21. arrhe Says:

    Hi micha kops,
    I need something which should be server independent.

  22. arrhe Says:

    i Micha kops,
    I have commited it to git repository and the url for it is https://github.com/arrhe/source.Also the application should be server independent. Thank you.

  23. Neeraj Says:

    Hi sir,

    I downloaded your war file and i added this library to my login project and i am using Apache tomcat server Oracle 10G database.. while running this http://localhost/8088/hascode i am getting “This webpage is not available” error.
    Index page is not editable.Please help how to run this file.
    Thanks in advance

  24. micha kops Says:

    Hi Neeraj,

    you can’t run a Java EE application on a simple servlet container like Tomcat – please select an appropriate application server (http://www.oracle.com/technetwork/java/javaee/overview/compatibility-jsp-136984.html) or chose an alternative implementation that does not depend on Java EE .. e.g. Tomcat’s implementation of the websocket spec.

    Cheers,

    Micha

  25. micha kops Says:

    arrhe, neeraj: I think I’ll be adding a full example using tomcat or jetty .. please be patient :)

  26. arrhe Says:

    Hi Micha kops,
    Can i get the tomcat version .

  27. FR Says:

    Hi Micha,
    Have you ever had a chance to start in the example under Tomcat? I am trying to do that port myself so if you have some pointers I would really appreciate.

  28. micha kops Says:

    Hi FR,

    I’ve just digged through the Tomcat docs and the websocket examples shipped with Tomcat since version 7 http://localhost:8080/examples/websocket/chat.xhtml sources -> http://svn.apache.org/viewvc/tomcat/tc7.0.x/trunk/webapps/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.java?view=markup.

    There’s a tutorial here that might be a help: http://www.programmingforliving.com/2013/08/websocket-tomcat-8-ServerEndpointConfig-Configurator.html .. might need to alter the endpoint creation to work with the single threaded model for an endpoint.

  29. Beginner Says:

    I would like to run the project on eclipse. I imported it but know I don´t know how to run it. It would be great if someone could give a step-by-step instructions to run the code. Sorry if it seems to naive, I am strating from scatch (as we all do …).
    THank already !

  30. micha kops Says:

    No problem :)

    But you need to install Maven to manage the dependencies (you really do not want to handle this for youself), so please consider downloading and installing Apache Maven from http://maven.apache.org or use the Maven Plugin for Eclipse.

    If you’ve downloaded Maven, simply run the following command in the project directory to create Eclipse IDE project files:
    mvn eclipse:eclipse this might take a while because there’s a huge bunch of dependencies downloaded, afterwards you may import it in Eclipse using “Import > Existing Project”

    Otherwise if your Eclipse IDE has Maven Support then you may directly import the plugin with “Import > Existing Maven Project”.

    Please feel free to keep me up to date if it is working for you or if you need assistance!

    Cheers,

    Micha

  31. rajngla Says:

    Hi Micha,

    I’m going through your example, and I have 1 question. In your program you hardcoded values of the rooms (java, arduino, groovy, scala). My question would be, is there any way of having those values stored in the java list (or any other collection) and somehow passed to the .html where it would be dynamically added? So I would like to have something like for each loop in .html and print all available rooms from that list. I’m pretty new to all this so excuse me if the question sounds dumb XD

    Btw great tutorial thank you very much for that :)

  32. micha kops Says:

    Hi Rajngla,

    you could create a data-transfer-objects similar to ChatMessage e.g. ChatRoomList and push this list to the client when new chat rooms are created or deleted.

  33. ashif Says:

    iam face same proble………..404 not found

Leave a Reply

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 111,564 bad guys.

Search
Categories