Comet: Reverse Ajax for streaming data from the server

Daniel Rubio has written an article called “Comet: Reverse Ajax for streaming data from the server,” describing ‘Comet,’ a technology to push events from the server side to a browser client. Comet manages to avoid the issues related to having a browser poll a server to check for new events.

Ajax, or Asynchronous JavaScript and XML, has become a household name in the area of Web applications, this mechanism by which a browser accesses a RESTful Web service and updates its GUI without a screen refresh, has spread from its pioneering roots in on-line maps and calendars to pretty much a standard feature in most new Web applications. However, it was not until recently that a new term was coined to complement this approach, one which is now often dubbed reverse-Ajax, its name: Comet.

The first thing you need to realize is that the data service on the server side needs to be designed to hold state on behalf of browsers clients, a process that can either be very difficult or very easy, depending on the platform and language you are using. Once again, this takes us to the stateless nature of Web applications and the way a browser needs to identify itself constantly either via cookies or session IDs, or what some characterize as the Hollywood principle – “don’t call us we’ll call you” – referring that only a browser is equipped to make calls and never vice-versa.


This last issue takes us down the road of building an asynchronous server application, or if you prefer a fancier name, an HTTP-based event routing bus, or in other words, a latent application on the serverside able to keep track of clients wishing to receive updates, a design very much in line with the messaging systems used in enterprise systems that are based on publish/subscribe channels.


However, since this last mechanism represents a departure from the “bread and butter” approach used in most Web platforms, it is a big reason why most Comet applications today rely on either custom adapted application-servers or embeddable versions that can tackle these issues. In the particular case of Java, Jetty and Grizzly are two servers that currently have out-of-the box support for Comet-type designs, with varying support in other languages like Python and other popular Java servers like Tomcat, for what is technically known as “continuation support,” a paradigm by which applications are shielded from the stateless nature of the Web. Continuation support also is a touted feature of higher-level language Web frameworks written in Smalltalk and Lisp that have this capability.


Turning our attention to the client side of things, a browser can take various routes to stay in contact with these type of server applications. Among these approaches are long-polling, dynamic script tags and inclusively a workaround using IFrames, none are standard approaches by any means, which is yet another reason why many client side Comet designs rely on the use of frameworks to abstract away incompatibilities between browser implementations – similar to Ajax – with one such framework being Dojo, which in itself now serves as both an Ajax/Comet framework.

Of course, the term Comet itself is something to wonder about. AJAX’ meaning is fairly well-known, as “Asynchronous Javascript and XML,” but what about Comet?

As far as the actual term is concerned, Comet emerged as a pun to Ajax’s meaning outside IT circles as a household cleaner. But quirky name or not, Comet is serving the purpose of an umbrella name for delivering data onto browsers as it becomes available on the serverside, a technique that will surely be of the same impact and go hand in hand with what we know today as Ajax.

Advertisements

Ant – an introduction

Ant is a Java based build tool developed as part of the Apache Jakarta project. You can get it from the Ant home site: ant.apache.org. At first the usefulness of Ant may not be readily apparent, but after using it for awhile on even small projects you may be surprised at how much you come to rely on it. For example, the ability to build files into specific directories, generate JavaDoc and package classes into JAR files for deployment all in one keystroke is extremely powerful. Here is a non-exhaustive list of what Ant can do:

  • Extract source from a version control system
  • Create directories
  • Delete directories
  • Compile code
  • Generate JavaDoc
  • Jar files
  • Copy files
  • Generate e-mail
  • FTP files
  • Execute SQL statements
  • Run unit tests

After downloading and unzipping the download contents, copy the Ant directory to the root of your C:\ drive, so the path is “C:\Ant”. You can install it anywhere you want, but this is most convenient. We also have to set up some environment variables so that the system can find Ant when we need it. You need to add System Variable called ANT_HOME, set this to the directory where you put Ant, in this case “C: \Ant”. Make sure there is also a System Variable called JAVA_HOME that point to your Java SDK directory.

We’re almost done. Now all you have to do is add the above variables to your path. Look for the “PATH” environment variable under System Variables and click “Edit”. Add this to the end of the path:

;%JAVA_HOME%\bin;%ANT_HOME%\bin

Notice that entries in the path on Windows are delimited by “;”. Now restart your machine to make sure the environment variables stick. We’re almost ready to test our installation. Open up a command window and type: ant. If the above steps went well, then you should see your first Ant error message:

D:\>ant

Buildfile: build.xml does not exist!
Build failed

This means that the installation worked. If you got anything other than this, then more than likely one of the above installation steps weren’t performed.

Ant requires a couple of things to run: Java source files (obviously), and a build file. First we’re going to create a really simple Java program for Ant to build.

public class AntTest{
public AntTest(){
System.out.println(“Isn’t Ant cool?”);
}

public static void main(String[] args){
new AntTest();
}
}

Don’t try to compile it yet, we’re gonna let Ant do that. The next thing we need is the build file.

<project name=”AntExamplel” default=”dist” basedir=”.”>
<!– set global properties for this build –>
<property name=”src” value=”.”/>
<property name=”build” value=”build”/>
<property name=”dist” value=”dist”/>

<target name=”init”>
<!– Create the time stamp –>
<tstamp/>

<!– Create the build directory structure used by compile –>
<mkdir dir=”${build}”/>
</target>

<target name=”compile” depends=”init”>
<!– Compile the java code from ${src} into ${build} –>
<javac srcdir=”${src}” destdir=”${build}”/>
</target>

<target name=”dist” depends=”compile”>
<!– Create the ${dist}/lib directory –>
<mkdir dir=”${dist}/lib”/>

<!– Put everything in ${build} into the AntTutorial-${DSTAMP}.jar file –>
<jar jarfile=”${dist}/lib/AntExample-${DSTAMP}.jar” basedir=”${build}”/>
</target>

<target name=”clean”>
<!– Delete the ${build} and ${dist} directory trees –>
<delete dir=”${build}”/>

<delete dir=”${dist}”/>
</target>
</project>

Make sure that you saved the build.xml file in the same directory as the Java source file. We’re not going to get into what the build file is actually doing yet, so just trust me…

Now, in your command window, cd to the directory where the Java source and the build file are saved (a lot of tutorials leave this step out, strangely enough) and type “ant“. Hopefully you will see the BUILD SUCCESSFUL message at the bottom. Now check out the directory. You’ll notice that there are two new directories: “build“, and “dist“. These directories were built by Ant. The “build” directory will include the compiled Java class file(s) and the “dist” directory will contain a .jar file with our project name and a timestamp.

Reference: http://ant.apache.org/manual/index.html

Tags: , ,

Binding XML to Java

Manipulating XML data easily and efficiently in Java remains an important problem. Numerous approaches to XML binding exist in the industry, including DOM, JAXB, XML Beans, Castor, and SDO and so on. In the article “Binding XML to Java” the authors explore how the Eclipse Modeling Framework, EMF, solves the XML binding problem in a number of interesting ways, and compare that to the alternatives.


“…The model that is used to represent models in EMF is called Ecore, and since Ecore is itself a model, it is called a Meta model, i.e., the model of a model. EMF supports this core meta model API, Ecore, analogous to XML Schema, as well as a core instance data model API, EObject, analogous to DOM Node. Ecore is to abstract syntax what XML Schema is to concrete syntax, i.e., a unifying meta model. But rather start with vague abstractions, it seems best to start from something well known and concrete on which to draw comparisons… “


Read More

Developing Ajax-based Java applications

Developing Ajax-based Java applications

ABSTRACT:

This Tech Talk provides an overview of the ICEfaces framework, which is designed to add AJAX to JSF based on a technology called Direct-to-DOM Rendering. This approach allows a web application to be rendered entirely on the server side. The browser essentially acts as a remote control to a server-side rendering of the DOM – making the AJAX capabilities transparent to the developer. Developers can work in a pure JSF programming model, have no exposure to JavaScript development or any of the low-level intricacies of AJAX and still get the full rich web capability.

Sign and verify XML documents using Apache WSS4J and WebSphere DataPower SOA Appliances

With the increasing adoption of Web services and Service-Oriented Architectures (SOAs), ensuring the authenticity, integrity, and nonrepudiability of XML messages has become an essential component of secure and robust messaging infrastructures. Using a sample scenario, this article walks you through how to use Apache WSS4J and IBM® WebSphere® DataPower® SOA Appliances together to enable the signing and verification of XML documents.

Reference

Serializing Java Objects with XStream – A Short tutorial

 

This is a very quick introduction to XStream. Skim read it to get an idea of how simple it is to convert objects to XML and back again. I am sure you’ll have questions afterwards.XStream

Create Classes to be serialized:

Here are a couple of simple classes. XStream can convert instances of these to XML and back again.

public class Person{

private String firstName;
private String lastName;
private PhoneNumber phone;
private PhoneNumber fax;

public Person(String firstName, String lastName){

setFirstName(firstName);

setLastName(lastName);

}

public String getFirstName(){ return firstName; }

public void setFirstName(String firstName){ this.firstName = firstName; }

public String getLastName(){ return lastName; }

public void setLastName(String lastName){ this.lastName = lastName; }

public PhoneNumber getPhone(){ return phone; }

public void setPhone(PhoneNumber phone){ this.phone = phone; }

public PhoneNumber getFax(){ return fax; }

public void setFax(PhoneNumber fax){ this.fax = fax; }

}

 

public class PhoneNumber{

private int code; private String number;

public PhoneNumber(int code, String number){

this.code = code; this.number = number;

}

}

 

Note: Notice that the fields are private. XStream doesn’t care about the visibility of the fields. No getters or setters are needed. Also, XStream does not limit you to having a default constructor.

Initializing XStream:

To use XStream, simply instantiate the XStream class.

XStream xstream = new XStream();

You require xstream-[version].jar and xpp3-[version].jar in the classpath. XPP3 is a very fast XML pull-parser implementation. If you do not want to include this dependency, you can use the standard JAXP DOM parser instead.

XStream xstream = new XStream(new DomDriver());

Now, to make the XML outputted by the XStream more concise, you can create aliases for your custom class names to XML element names. This is only type of mapping required to use XStream and also this is optional.

xstream.alias(“person”, Person.class);

xstream.alias(“phone-number”, PhoneNumber.class);

Note: This step is optional. Without it XStream would work fine, but the XML element names would contain the fully qualified name of each class (including package) which would bulk up the XML a bit.

 

Serializing an object to XML:

Lets write a test class, in which we create a Person class and populate its fields:

Person sam = new Person(”Syed”, “Aslam”);

sam.setPhone(new PhoneNumber(95, “253265″));

sam.setFax(new PhoneNumber(95, “423140″));

Now, to convert it to XML, all you have to do is make a call to XStream:

XStream xstream = new XStream();String xml = xstream.toXML(sam);

And that’s it. The test class would look like this:

 

import com.thoughtworks.xstream.*;

public class XStreamTest{

public static void main(String[] args){

XStream xstream = new XStream();

Person sam = new Person(”Syed”, “Aslam”);

sam.setPhone(new PhoneNumber(95, “253265″));

sam.setFax(new PhoneNumber(95, “423140″));

String xml = xstream.toXML(sam);

System.out.println(xml);

}

}

 

The resulting XML would look like this:

<person>
  <firstname>Syed</firstname>
  <lastname>Aslam</lastname>
  <phone>
    <code>95</code>
    <number>253265</number>
  </phone>
  <fax>
    <code>95</code>
    <number>423140</number>
  </fax>
</person>

It’s that simple. Look how clean the XML is.

Deserializing an object back from XML

To reconstruct an object, purely from XML:

Person newPerson = (Person) xstream.fromXML(xml);