Friday Jun 15, 2012

Server-Sent Events using GlassFish (TOTD #180)

Bhakti blogged about Server-Sent Events on GlassFish and I've been planning to try it out for past some days. Finally, I took some time out today to learn about it and build a simplistic example showcasing the touch points.

Server-Sent Events is developed as part of HTML5 specification and provides push notifications from a server to a browser client in the form of DOM events. It is defined as a cross-browser JavaScript API called EventSource. The client creates an EventSource by requesting a particular URL and registers an onmessage event listener to receive the event notifications. This can be done as shown

var url = 'http://' + document.location.host + '/glassfish-sse/simple';
eventSource = new EventSource(url);

eventSource.onmessage = function (event) {
var theParagraph = document.createElement('p');
theParagraph.innerHTML = event.data.toString();
document.body.appendChild(theParagraph);
}

This code subscribes to a URL, receives the data in the event listener, adds it to a HTML paragraph element, and displays it in the document. This is where you'll parse JSON and other processing to display if some other data format is received from the URL.

The URL to which the EventSource is subscribed to is updated on the server side and there are multipe ways to do that. GlassFish 4.0 provide support for Server-Sent Events and it can be achieved registering a handler as shown below:

@ServerSentEvent("/simple")
public class MySimpleHandler extends ServerSentEventHandler {

public void sendMessage(String data) {
try {
connection.sendMessage(data);
} catch (IOException ex) {
. . .
}
}
}

And then events can be sent to this handler using a singleton session bean as shown:

@Startup
@Stateless
public class SimpleEvent {

@Inject @ServerSentEventContext("/simple")
ServerSentEventHandlerContext<MySimpleHandler> simpleHandlers;

@Schedule(hour="*", minute="*", second="*/10")
public void sendDate() {
for(MySimpleHandler handler : simpleHandlers.getHandlers()) {
handler.sendMessage(new Date().toString());
}
}
}

This stateless session bean injects ServerSentEventHandlers listening on "/simple" path. Note, there may be multiple handlers listening on this path. The sendDate method triggers every 10 seconds and send the current timestamp to all the handlers. The client side browser simply displays the string.

The HTTP request headers look like:

Accept: text/event-stream
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Cookie: JSESSIONID=97ff28773ea6a085e11131acf47b
Host: localhost:8080
Referer: http://localhost:8080/glassfish-sse/faces/index2.xhtml
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5

And the response headers as:

Content-Type: text/event-stream
Date: Thu, 14 Jun 2012 21:16:10 GMT
Server: GlassFish Server Open Source Edition 4.0
Transfer-Encoding: chunked
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 4.0 Java/Apple Inc./1.6)

Notice, the MIME type of the messages from server to the client is text/event-stream and that is defined by the specification.

The code in Bhakti's blog can be further simplified by using the recently-introduced Twitter API for Java as shown below:

@Schedule(hour="*", minute="*", second="*/10")
public void sendTweets() {
for(MyTwitterHandler handler : twitterHandler.getHandlers()) {
String result = twitter.search("glassfish", String.class);
handler.sendMessage(result);
}
}

The complete source explained in this blog can be downloaded here and tried on GlassFish 4.0 build 34. The latest promoted build can be downloaded from here and the complete source code for the API and implementation is here.

I tried this sample on Chrome Version 19.0.1084.54 on Mac OS X 10.7.3.

Thursday Jun 03, 2010

Jazoon 2010 Day 3 - Java EE 6 on Cloud, HTML 5 with JSF 2 and another run on Üetliberg

The Day 3 of Jazoon (Day 1 & 2) started with a great presentation on Gaia satellite and Data Processing by William O'Mullane. Gaia is a European Space Agency space mission that will be launched in Summer of 2012 to compile a catalog of approximately 1 billion stars. Most of their software is Java-based and have been fairly happy with the decision taken 10 years ago. They are very happy with the performance of Java and in certain cases its even 10x faster than C.

I gave a talk on "Running Java EE 6 applications in the Cloud". The talk explained flexibility, light-weight, extensibility, and ease-of-use of Java EE 6. It demonstrated a simple sample development and rapid deployment feature using NetBeans IDE. And then quickly jumped into how this application can be deployed on Amazon EC2, RightScale, Elastra, and Joyent infrastructure. I learned about the Simple Cloud API (Storage only) and Apache libcloud from Doug Tidwell's talk yesterday and so will try them as well.

I gave a tee-shirt from the Bay Area JUG Roundup to Rainer Grau - moderator of the conference and he was kind enough to change it for rest of the day. See his picture below.

The slides from my talk are available below:

More detailed steps to deploy your Java EE 6 application on each cloud management / provider mentioned above will be available in a later blog. Instant feedback via twitter is always much appreciated as shown in the case below:

The Spring 3.0 Themes and Trends talk was quite a dejavu because it was mostly a rehash of what is available in the Java EE 6 today. And I could not understand why would anybody use Spring (instead of Java EE) to use the goodness of the JSF and JPA technologies ?

Roger's talk on "Exploring HTML 5 with JSF 2" was very interesting and had a packed room, small but packed. He showed lots of HTML 5 samples and how Java Server Faces 2 can be used to include new tags like audio / video in a JSF composite component, Web Sockets and even Web Workers with JSF 2. His slides are available at:

Roger & I will work on publishing detailed steps on these demos in the coming days.

Spring Roo was a good one but it seems like that its basically trying to bring Ruby-on-Rails concepts like Dynamic Functions and Scaffold with some usual tooling tricks and heavy code generation to the Java programming language. One more framework, one more convention, one more programming style ... not sure if it fills any gap!

Dan & Aslak presented on Real Java EE Testing with Arquillian and this was mostly a demo-driven talk showing how different Java EE technologies can be easily tested using ShrinkWrap and Arquillian. And the cool thing is that they support deployment to GlassFish Embedded as well.

Here are some pictures from earlier today:

And the day concluded with yet another great run up Üetliberg, just a simple out & back but 1404 ft elevation gain in 4.59 miles. The elevation map is shown below:

More details about the run are given below:

Here are some pictures captured during the run:


It is just beautiful - definitely worth going at least once!

Last but not the least, Roger & I had a great dinner at au gratin - a great restaurant + adjoining bar on the first floor on Bahnhofplatz. They've got great food variety at a great location, reasonably priced (as per the Swiss standards ;-), and an American Football aficionado server by the name David. If you meet him, say our hello to him :-)

And here is the complete photo album:

This was my first Jazoon conference in the beautiful country of Switzerland and I thoroughly enjoyed it. I had some useful conversations and made some good contacts. I'd love to come back here again next year as well!

Next step Über Conf ...

Technorati: conf jazoon zurich javaee glassfish cloud amazon rightscale elastra joyent html5 jsf2 spring

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today