Archive

Archive for June, 2010

Atmosphere 0.6 released: Transparent WebSocket and Comet support, JQuery support, more adoption

Atmosphere 0.6 has finally arrived! This release is the biggest ever release we have made so far and includes many bugs fixes and tons of new features:

WebSocket support

The Websocket specification is now supported. You can now write portable Websocket applications and deploy them into a Web Server that support the protocol. If the Web Server isn’t yet supporting the specification, Atmosphere will emulate Websocket by using Comet instead (long polling or http-streaming technique). So you are guarantee that your application will works independent of the transport used: Websocket or Comet.

JQuery Plug In supporting WebSocket and Comet

Starting with 0.6, Atmosphere ships with a JQuery Plug In which can be used for building powerful Client side application. The Plug In support Websocket and Comet and able to transparently decide which one to use based on what the server and the client support.

New Framework supported

Atmosphere has been successfully tested with the following framework: Spring, Struts, Wicket, JSF, Akka, GWT, Grails, JRuby on Rails, etc.

New Programmatic API

Atmosphere 0.6 supports new API which complement our existing set of annotations:

@GET
public SuspendResponse<String> subscribe() {
     return new SuspendResponse.SuspendResponseBuilder<String>()
                       .broadcaster(topic)
                       .outputComments(true)
                       .addListener(new EventsLogger())
                       .build();
}

Improved Server Sides Events Support

The Broadcaster API and Factory has been improved and the result can be seen here.

Server Sides Events Caching Support

When using Websocket or Comet, a connection can always be closed by an unexpected network failure, a time out, a proxy, etc. If some Server Side events happens during that downtime, there is a risk your application may have missed those events. Our new API called BroadcasterCache can be configured to avoid that situation by caching Server Sides Events based on some custom headers, timestamps, sessions, etc. That way your application is guarantee of never loosing any Server Sides Events for any reasons. As you as you reconnect, Server Sides Events can be retrieved. We currently ship with two built-in BroadcasterCache: Header and Session, but any application is free to write its own.

Atmosphere Spade Server Deployer

Our small all-in-one Web Server can now fully deploy war file

java -jar atmosphere-spade-server.jar any_web_app.war

This tiny Web Server can easily be used to write unit test as demonstrated here.

New Web Server Supported

We now support Tomcat 7, GlassFish 3.1 WebSocket and Resin 4.0.

Improved Unit Test coverage

We have now more than 150 units covering Atmosphere functionality. Web Server which support an embed interface are now automatically tested: Jetty, Tomcat and Grizzly.

Bug Fixes and Improvements

Our growing popularity has a price! Between 0.5 and 0.6 we fixed almost 50 issues and improved a lot of API.

What’s next?

We started discussing 0.7 features: More Web Server supported like Netty, Stomp protocol supported, More JQuery integration, etc. Jump in the discussion if you are interested.

For any questions or to download Atmosphere Client and Server Framework, go to our main site and use our Nabble forum (no subscription needed), or follow the team or myself and tweet your questions there! You can also checkout the code on Github.

Categories: Atmosphere, Comet, JQuery, Websocket

Async Http Client 1.0.0 released

A few month ago, we, at Ning, open sourced our Async Http Client  library:

Today we are announcing the 1.0.0 GA availability. This release includes many improvements, bug fixes and features based on our community’s feedback. You can browse the complete (and long) change logs:

http://github.com/ning/async-http-client/commits/master/

In short:

  • Default Async Provider powered by Netty 3.2.1.Final (just released!)
  • Support both http and https
  • Support the majority of  HTTP method like OPTIONS, GET, PUT, POST, DELETE, etc.
  • Works well with JRuby, Python, Groovy, etc.
  • Works well with asynchronous WebServer and Framework like Jetty Continuation, Atmosphere, etc.
  • Many useful utilities to optimally manipulate the request/response.
  • More than 100 unit tests you can look at to get started.
  • And many many more.

You can now use the following dependency

<dependency>
<groupId>com.ning</groupId>
<artifactId>async-http-client</artifactId>
<version>1.0.0</version>
</dependency>

or clone our repository from:

http://github.com/AsyncHttpClient/async-http-client

Our next release roadmap can be browsed from here:

http://groups.google.com/group/asynchttpclient/web/road-map-to-1-0-0-…

Finally, if you are interested to contribute or have any questions, join our group here:

http://groups.google.com/group/asynchttpclient

Thanks to all the contributors from Ning and outside Ning!

Categories: Atmosphere, Ning

Trick of the Friday #1: Delivering Server Side Events to your Websocket/Comet Application.

When writing asynchronous web application (Comet and/or Websocket based), most of the time you need to generate server sides events from external components or non web-based technology.

As an example, you may have EJBs, JMS queue/topic that may need to deliver server sides events to your set of asynchronous connections. With Atmosphere, it is quite easy to generate server sides events using Broadcaster. A Broadcaster role is to push back server sides events to the Browser. Within the scope of a Web application, all you need to do is:

// Retrieve the default Broadcaster

Broadcaster broadcaster = atmosphereResource.getBroadcaster();

// Or create your own

Broadcaster broadcaster = new Broadcaster(“myBroadcaster”);

// Or let Atmosphere injects it for you like:

@Post

public void broadcast(@PathParam(“myBroadcaster”) Broadscaster broadcaster);

This return the Broadcaster associated with the current asynchronous connection (Websocket or Comet). A Broadcaster can be shared amongst all your connections (chat like application) or to a subset based on some topic (pub sub, etc). The Broadcaster concept is really close to an events queue Browser can subscribe to and received asynchronous events.

But what about non web components (EJB, JMS, Akka/Scala Actor, etc.) or web component with different scope (another web application, another Servlet, etc.)? They can also generate server sides events by using Atmosphere’s BroadcasterFactory

Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, “id_of_the_broadcaster”);

// Or

Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(JerseyBroadcaster.class, “id_of_the_broadcaster”);

broadcaster.broadcast(‘Hello from an EJB”);

By default, the value of “id_of_the_broadcaster” is based on the  Atmosphere’s <url-pattern> value (ex:/*). You can always set that value by calling:

broadcaster.setID(“ForAkkaActorWho”);

What about if you don’t know the name of your Broadcaster? You can also retrieve all available Broadcasters by doing:

// An unmodifiable collection

Collection<Broadcaster> broadcasters = BroadcasterFactory.getDefault().lookupAll();

In conclusion, being able to generate server sides events from external components is a mandatory features required when writing asynchronous application. Before picking a framework for writing an asynchronous application, always make sure such features is available to avoid having to write it yourself (and maintain it).

For any questions or to download Atmosphere Client and Server Framework, go to our main site and use our Nabble forum (no subscription needed), or follow the team or myself and tweet your questions there! You can also checkout the code on Github. Or download our latest presentation to get an overview of what the framework is.

Categories: Atmosphere, Comet, Websocket

Using Atmosphere’s JQuery Plug In to build applications supporting both Websocket and Comet

Until all Browsers and WebServers properly supports the Websocket protocol, it will be difficult to write portable asynchronous applications. Not anymore, using the new JQuery Atmosphere Plugin which is able to auto-detect which transport (Websocket or Comet) to use based on what the Browser and Web Server support.

Since the Websocket protocol is relatively new, not all web servers and browser supports it which means writing a websocket application always lock your users with a limited set of browsers and web server. For example, as of today, only Jetty 8, Resin 4 and GlassFish 3.1 supports Websocket on the server side,  and  Chrome 4 and Safari 5 on client side. Eventually they may all support the protocol, but it will take a couple of years before it happens. Not to say that Internet Explorer will probably implement a subset of it, or a broken version just to continue what they started with IE 6. On the server side, as I discussed here, it will takes years before the Java Community Process (JCP) comes with a specification for all java side Web server. The good new is we already have a solution for the server side named Atmosphere, which allow the creation of portable Async/Real Time application supporting both Websocket and Comet at the same time.

Does portable library exists on the client side, e.g being able to write application that can use Websocket when available, and fallback/downgrade to use Comet technique (http streaming or long polling)? As far as I can tell, there is no such open source library available today supporting both Websocket and Comet (feel free to point me to them). Not anymore, with the new Atmosphere JQuery Plugin.

Introducing the Atmosphere JQuery Plug In

The  Atmosphere JQuery Plug In easily allow you to write asynchronous and real time applications without the need to wait for Websocket adoption. The Atmosphere JQuery Plug In can be used with any Webserver that support Websocket and/or Comet. The Atmosphere Framework is not mandatory on the Server side, but you will miss something if you don’t use it as I will demonstrate in this blog. That means you can use it with node.js or any existing Comet framework like Grizzly Comet, Jetty Continuation and Servlet 3,0 Async.

Using it with a server side application build on top of Atmosphere allow the plug in to detect what the Web Server support and optimally select Websocket or any  Comet technique.  As an example, you can set the default transport to Websocket, deploy in Jetty 8 and use Chrome to run your application. In that case, the Websocket protocol will be used. Now if you try with Firefox, the Plug In will  downgrade to Comet without any changes required on both client and server side. You can also deploy your application in Tomcat 7, which doesn’t support Websocket and still the application will works without any change. The great news is as soon as Tomcat starts supporting Websocket, your application will still works without requiring any code changes, and will upgrade automatically and use the Websocket protocol.

Writing a PubSub application that supports both Websocket and Comet.

To demonstrate how the Atmosphere JQuery Plug In works, let’s write a simple PubSub application that can support WebSocket and Comet (long-polling and http streaming). If you can’t wait, you can browse the entire code here. On the client side, let’s create a very simple HTML page which allow us to:

  1. Select the topic we want to subscribe to.
  2. Select the transport to use: Auto-Detect, Websocket, Long-Polling or Http Streaming. Auto-Detect means the Atmosphere JQuery Plug In will try to pick the best one for us.
  3. Publish message to the topic we have subscribed to.

The goal here is to write a simple PubSub that you can deploy anywhere, use with any browsers without having to care about the transport used. Something like:

First, the user needs to enter a topic. Next is to pick the transport to use to communicate to the Web Server. By default, let’s use Websocket and fallback to http-streaming in case the browser or the server isn’t supporting Websocket.

$.atmosphere.subscribe(

document.location.toString() + ‘pubsub/’ + getElementByIdValue(‘topic’),

callback : null

$.atmosphere.request = {transport: getElementByIdValue(‘transport’)});

The subscribe function takes three parameters:

  1. The location of the server application, including the topic value. More details about the server side in the next section.
  2. A function callback which will get invoked when the server is receiving topic’s messages.
  3. A Request object that can be used to configure the Plug In.

The Request object is where you can configure the Plug In. The object default value are:

connected: false,
timeout: 60000,
method: ‘GET’,
headers: {},
contentType : “text/html;charset=ISO-8859-1”,
cache: true,
async: true,
ifModified: false,
callback: null,
dataType: ‘ ‘,
url : url,
data : ‘ ‘,
suspend : true,
maxRequest : 60,
logLevel :  ‘info’,
requestCount : 0,
fallbackTransport : ‘long-polling’,
transport : ‘websocket’

This is where you can configure the HTTP request similar to JQuery.ajax() function, with extra configuration like transport, fallbackTransport and callback. With the above configuration, the Plug In will first try to use Websocket and if  the client of server (or both) isn’t supporting Websocket, will use the fallbackTransport as the second choice.  Next is to define a callback which will be invoked when the server sent us update about our subscribed topic:

function callback(response)
{

var data = response.responseBody

if (data.length > 0) {

$(‘ul’).prepend($(‘<li></li>’).text(” Message Received: ” + data + ” using transport: ” + response.transport));

}

}

The important piece here is the response object, which is defined as:

status: 200,
responseBody : ‘ ‘,
headers : [],
state : “messageReceived”,
transport : “websocket”,
push : [],
error: null

The responseBody contains what the server has just sent us. You can also retrieve some headers depending on which transport is used, if there is an error, etc. The push function is a key piece here as it allow you to publish message to the Web Server message. The Plug In will either re-use the current transport to push messages to the Web Server, or open a new one if the current transport doesn’t support it. All of this done magically by the Plug In. For our sample, the push function is defined as:

response.push(document.location.toString() + ‘pubsub/’ + getElementByIdValue(‘topic’),

null,

$.atmosphere.request = {data: ‘message=’ + getElementByIdValue(‘phrase’) })

This function will be invoked every time you click on the “Push Message” button.

Make it fun

As a try, you can deploy the application on Jetty 8, use Chrome and Firefox to see how it works (download here). You can switch transport on the fly be selecting the transport using the drop down menu. If you use Chrome, all transport will works where Firefox fake Websocket (using the default fallbackTransport value). Do the same on Tomcat and now Chrome will still works event if you set the transport to Websocket.

Humm…what about the server side?

Without going into the details of how to write an Atmosphere application (download the white paper or search this blog), the server side for this sample JUST consists of:

@Path(“/pubsub/{topic}”)

@Produces(“text/html;charset=ISO-8859-1”)

public class JQueryPubSub {

private @PathParam(“topic”) Broadcaster topic;

@GET
public SuspendResponse<String> subscribe() {

return new SuspendResponse.SuspendResponseBuilder<String>()

.broadcaster(topic)

.outputComments(true)

.addListener(new EventsLogger())

.build();

}

@POST
@Broadcast
public Broadcastable publish(@FormParam(“message”) String message) {

return new Broadcastable(message, “”, topic);

}

}

The mapping is simple:

  • Invoking $.atmosphere.subscribe will invoke the subscribe() method on the server side. This method will tells Atmosphere to suspend the connection and create a topic (Broadcaster). The Broadcast is like a queue. As soon as you offer a message to it the message will be sent to all the subscriber of that queue. In our case it means all browser connected to that topic.
  • Invoking response.push will invoke the publish() method on the server side. The value will be broadcasted to all subscribed connections, independently of the transport used.

Simple, is it 🙂 Did you noted that there is no mention of Comet or Websocket on the server side? With the Atmosphere Framework, you write an application without having to care about it.

For any questions or to download Atmosphere JQuery Plug In, go to our main site and use our Google Group forum (no subscription needed), or follow the team or myself and tweet your questions there! You can also checkout the code on Github. Or download our latest presentation to get an overview of what the framework is.

Categories: Atmosphere, Comet, JQuery, Websocket