Java Messaging Queuing – JMS

I’ve used messaging queuing extensively in a Microsoft environment for the past 4 years or so. The benefits are amazing, .NET makes it incredibly easy to use, and with the exception of needing a Windows CD, its installation and creation of queues is easier yet!

And so to the world of Java, and attempting to get it working. Perhaps I’m just missing something, but its taken me 2 or 3 visits to try and get somewhere. I eventually made some progress yesterday, and now want to develop this example further.

This post is being written as I make progress, so the order may be a bit funny. I’m writing it as I go in order not to miss any important information, but there is a risk I might, and therefore I apologise for this in advance!

My Setup

I’m developing on a Windows XP box, using NetBeans 6.8 and GlassFish v3.0.1.

A Message Sender Example

I’ve developed this as a web application initially. Ultimately I want this to be a console application if possible (Guidance much appreciated from readers!).

PS. I started off this example with a simple TextMessage however I’ve since changed it to use an ObjectMessage. I don’t plan to go over the steps for the TextMessage unless there is a request.

1. In NetBeans, create a new web application.
2. Add a class called Person and place it in a ‘beans’ package.
3. To the person class add fields for firstName and lastName, and there approriate getters/setters. Also introduce a default constructor and (optionally) a constructor to initialise all the fields.
4. Make the Person class implement Serializable.

The person class so look as follows:


public class Person implements Serializable {
  private String firstName;
  private String lastName;

  public Person() {

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = 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;

Next create a servlet named something like SendMessage. Place this in a ‘servlets’ package.

1. To this servlet, add to annotated resources – one for the connection factory and another for the queue name. See the code below.
2. We then need to create a connection, and from the connection create  a session. Finally, from the session we need to create a message producer.
3. Initialise a person object, specifying a first and last name.
4. Then create an object message from the person object.
5. Use the message producer to send the object message.
6. Finally, close the message producer and connection objects.

The servlet should be similar to this (Note: this is not production code – for example the closing of the connection should be in a finally block…)

public class SendMessage extends HttpServlet {

  private ConnectionFactory connectionFactory;

  private Queue queue;

  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {


    try {
      Connection conn = connectionFactory.createConnection();
      Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer messageProducer = session.createProducer(queue);

      Person student = new Person("Greg", "Bowie");

      ObjectMessage msg = session.createObjectMessage(student);
      System.out.println("Message Sent for Person: " + student.getFirstName() +
           " " + student.getLastName());

    } catch (Exception e) {
      System.out.println("Exception raised: " + e.toString());

Seting Up Glassfish

Next we need to set our connection and message queue up on the GlassFish server. We also need to deploy the message sender app.

1. In NetBeans, click to the Services tab. Under servers, start the GlassFish instance.
2. Once started, right click and select View Admin Console.
3. Under Resources, select JMS Resources and then select Connection Factories. Create new connection factory, matching the name specified in the annotation in the Java Servlet. (‘QueueConnectionFactory’).
4. Again under JMS Resources, create new Queue, matching the queue name specified in the servlet (‘mqTest’).
5. Finally deploy the web application.
6. Once deployed, call the servlet in a browser.
7. Return to GlassFish and under Configuration->Java Message Service and click Physical Destinations. Find the queue (‘mqTest’) and then click the View Statistics link. About half down the list of properties there should a ‘Number of Messages’ – hopefully this is set to 1!

Message Consumer

In order to create a message consumer I created Java EE application. I then created a Message Driven Bean. The bean code simply implemented the onMessage() function, decoding the message receiving into a Person object and then outputting the name received. The steps are as follows:

1. Create an Enterprise Applcation. (Named: ‘MessageExampleEE’).
2. In the ejb, right click and create a Message Driven Bean. Placed this in the ‘beans’ package. I believe this screen also allows you to specify the queue the bean should listen to.
3. Implement the onMessage() method, see source code below for full implementation.
4. I copied the class from the web application into the beans package for the Enterprise application.

The source code for the Message Driven bean is as follows:

public class MessageBean implements MessageListener {

  public MessageBean() {

  public void onMessage(Message message) {
    System.out.println("In onMessage()!");

    try {
      if (message instanceof ObjectMessage) {
        ObjectMessage msg = (ObjectMessage) message;
        Person received = (Person)msg.getObject();
        System.out.println("Received Student: " + received.getFirstName() + " " + received.getLastName());
    } catch (Exception e) {
      System.out.println("Exception raised: " + e.toString());

Note: From the default implementation of the bean, there was an annotation that was more wordy that the one in this example. When trying to deploy to GlassFish, GlassFish threw an error about this – hence the simplified one in use. The error message was along the lines of ‘EAR application deployment: Message Driven Beans can’t be Managed Beans’.

Finally deploy this Enterprise Application to the server. Once its deployed, check the server log to check its processed the message (and also check the Message Queue statistics to find out how many current messages there are).

Further Development

As stated before, this was simply to get something working. Next developments include:

  • Stop the queue from processing messages if it encounters an error.
  • Write an application to determine how many messages are in the queue.
  • Attempting to send a message from outside of GlassFish

Any help in these future developments, or pointers where to go would be gratefully received!!!

About these ads

4 thoughts on “Java Messaging Queuing – JMS

  1. Pingback: Messaging Queue – Handling Errors « Gregor Bowie's Blog

  2. Pingback: Java Messaging System – Sending To Local Glassfish (v3) « Gregor Bowie's Blog

  3. Pingback: Java Message Queuing (Continued) « Gregor Bowie's Blog

  4. Pingback: Anonymous

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s