Create simple Java application to post JSON message to CometD Bayeux Channel using Apache HttpClient and Maven style NetBeans project

The objective discussed in this article is to post messages to a CometD Bayeux Channel with a standalone Java Class – without dependencies on CometD. For example to control from Java the Slideshow introduced in the synchronized Slideshow demo application created using CometD (see previous articles Push based synchronized Slideshow demo application implemented using CometD and jQuery running on Tomcat and Publishing to CometD Bayeux Channel from inside the Oracle Database – PL/SQL based push to CometD Web Client ).

This article describes the creation of a simple Java Class leveraging Apache HttpClient to post HTTP requests (JSON messages) to a CometD Bayeux Channel. The main point is to show working code with the lest dependencies, not an optimal program (it is far from optimal). The article demonstrates how NetBeans and Maven conspire here to make the task as simple as possible. The Maven support in NetBeans allows me to simply create a new Maven style project of (arche)type Java Application.

I can then add the dependency entry for Apache HttpClient to the pom.xml. When I next Build the NetBeans project With Dependencies, the required JAR-files are downloaded to my local Maven Repository (see this article for getting going with Maven:NetBeans 7.1 – JavaFX 2.0 support, refactoring enhancements and great Maven 3 integration and Preparing your environment for modern open source Java libraries and frameworks using Git and Maven, throwing in Tomcat as a bonus ).

Using the example code from the article mentioned below in the Resources, it is a breeze to make a POST request with JSON payload. After figuring out the JSON messages required by CometD – one for handshaking and one for publishing the slide selection message – as is described in Publishing to CometD Bayeux Channel from inside the Oracle Database – PL/SQL based push to CometD Web Client ), it is just a short step to control the slideshow from Java with two simple JSON messages.

Image

Steps

1. Create NetBeans project of type Maven – Java Application

Image

Then select Maven, Java Application and press Next:

Image

Set the properties for the project and click on Finish:

Image

2. Add dependency for Apache HttpClient

The Maven pom.xml file is created based on the these properties. The dependency on Apache HttpClient can be added in the dependencies element:

Image

3. Create Java Class that can make Http Post request with JSON content

The class JavaCometPublisher is created. It contains method postToURL() that is the bare minimum piece of code required to make a HTTP Post request and pass some JSON content:

package nl.amis.comet.client.javapublisher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class JavaCometPublisher {

    private static String postToURL(String url, String message, DefaultHttpClient httpClient) throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(message);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : "
                    + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(
                new InputStreamReader((response.getEntity().getContent())));

        String output;
        StringBuffer totalOutput = new StringBuffer();
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            totalOutput.append(output);
        }
        return totalOutput.toString();
    }
}

4. Use Http Post to handshake with CometD and publish to Bayeux Channel

With this postJsonToUrl() method at our disposal, it becomes easy to connect to CometD and publish to the /slide/show channel. This is done in method setSlide():

    public static void setSlide(int slideNumber) throws IOException {
        String url = "http://localhost:8085/slideshow/cometd";
        String message = "[{\"version\":\"1.0\",\"minimumVersion\":\"0.9\",\"channel\":\"/meta/handshake\",\"supportedConnectionTypes\":[\"long-polling\",\"callback-polling\"],\"advice\":{\"timeout\":60000,\"interval\":0},\"id\":\"1\"}]";
        DefaultHttpClient httpClient = new DefaultHttpClient();
        String response = postToURL(url, message, httpClient);
        String clientId = response.substring(155, response.indexOf("\"", 155));
        String slideSelectionMessage = "[{\"channel\":\"/slide/show\",\"data\":{\"uniqueId\":1326523938212,\"slideNumber\":" + slideNumber + "},\"id\":\"40\",\"clientId\":\"" + clientId + "\"}]";
        response = postToURL(url, slideSelectionMessage, httpClient);
        httpClient.getConnectionManager().shutdown();
    }

6. Create the main method that runs the slideshow:

    public static void main(String[] args) throws InterruptedException {
        JavaCometPublisher p = new JavaCometPublisher();
        try {
            Thread.sleep(5000);
            p.setSlide(2);
            Thread.sleep(2000);
            p.setSlide(4);
            Thread.sleep(2000);
            p.setSlide(3);
            Thread.sleep(2000);
            p.setSlide(5);
            Thread.sleep(2000);
            p.setSlide(1);
            Thread.sleep(2000);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

7. Run the Java Class and take control of that slideshow

Resources

Download NetBeans project described in this article: JavaPublisherToCometDChannel.zip.

Article describing the creation of an HTTP POST client using Apache HttpClient: http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-apache-httpclient/