Showing posts with label Java Message Service. Show all posts
Showing posts with label Java Message Service. Show all posts

September 7, 2011

Java Message Service (JMS) Topic- Hello World Example with MessageListener

1) Configure the JMS Topic in the JBoss 4.2.2GA Server, in the file ${JBOSS_SERVER}/server/default/deploy/jms/jbossmq-destinations-service.xml

<mbean code="org.jboss.mq.server.jmx.Topic"
  name="jboss.mq.destination:service=Topic,name=myTopic1">
  <depends optional-attribute-
  name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>

Ensure that the name myTopic1 is unique within the XML file

2) The ConnectionFactory administered object is pre-configured with the default JNDI name 'ConnectionFactory' in JBoss

Note: Add the following jar file to the classpath / build path of the Java Project / Application:

%JBOSS_HOME%\client\jbossall-client.jar

3) Create the TopicPublisherClient.java

package info.icontraining.topic;

import javax.jms.*;
import javax.naming.*;
import java.util.*;

public class TopicPublisherClient {

   public static void main(String[] args) {

      TopicConnection conn = null;
      TopicSession session = null;
      Topic topic = null;
   
      try {
         Properties props = new Properties();
         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         InitialContext iniCtx = new InitialContext(props);

         Object cf = iniCtx.lookup("ConnectionFactory");
         TopicConnectionFactory tcf = (TopicConnectionFactory) cf;
    
         conn = tcf.createTopicConnection();

         topic = (Topic) iniCtx.lookup("topic/myTopic1");
    
         session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
         conn.start();

         TopicPublisher topicPublisher = session.createPublisher(topic);

         TextMessage message = session.createTextMessage();
         message.setText("this is a test message");
         topicPublisher.publish(message);
         System.out.println("Message published.");

         topicPublisher.close();

      } catch (NamingException e) {   
         System.out.println(e.toString());
      } catch (JMSException e) {
         System.out.println("JMS Exception");
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (JMSException e) {}
         }
      }
   }
}

4) Create the TopicSubscriberClient.java

package info.icontraining.topic;

import javax.jms.*;
import javax.naming.*;
import java.util.*;

public class TopicSubscriberClient
{
   public static void main(String[] args) {
      TopicConnection topicConnection = null;
      char answer = '\0';
  
      try 
      {
         Properties props = new Properties();

          props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
          props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
          props.put(Context.PROVIDER_URL, "localhost:1099");
          props.put("java.naming.rmi.security.manager", "yes");

          Context context = new InitialContext(props);
          TopicConnectionFactory tcf= (TopicConnectionFactory) context.lookup("ConnectionFactory");
          topicConnection = tcf.createTopicConnection();

          String topicName = "topic/myTopic1";
          Topic topic = (Topic) context.lookup(topicName);
   
          TopicSession topicSession = topicConnection.createTopicSession(false,  TopicSession.AUTO_ACKNOWLEDGE);
          topicConnection.start();

          TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
   
          topicSubscriber.setMessageListener(new MyMessageListener());

          for(;;) {}
      }
      catch (JMSException e) {
         System.out.println("JMS Exception");
      } catch (Exception e) {
         System.out.println(e.toString());
      } finally {
         if (topicConnection != null) {
            try {
               topicConnection.close();
            } catch (JMSException e) {}
         }
      }
   }

   static class MyMessageListener implements MessageListener { 

      public void onMessage(Message message) {

         TextMessage tm = (TextMessage) message;

         try {
            System.out.println("onMessage==>"+ tm.getText());
         } catch(Throwable t) {
            t.printStackTrace();
         }
      }
   }
}

5) Run multiple instances of TopicSubscriberClient in multiple heaps. Next, run TopicPublisherClient to send the message to the JMS Topic.

September 5, 2011

javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.NamingContextFactory [Root exception is java.lang.ClassNotFoundException

Topic: Java Message Service (JMS)

Application Server: JBoss 4.2.2 GA

Exception:

javax.naming.NoInitialContextException: Cannot instantiate class: org.jboss.naming.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jboss.naming.NamingContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.init(Unknown Source)
at javax.naming.InitialContext.(Unknown Source)
at info.icontraining.queue.QueueSenderClient.main(QueueSenderClient.java:27)
Caused by: java.lang.ClassNotFoundException: org.jboss.naming.NamingContextFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.naming.internal.VersionHelper12.loadClass(Unknown Source)
... 5 more

Resolution:

This exception is thrown with the JMS client code resides outside the JBoss application server. In order to resolve, add the following jar file to the build path / classpath of the application:

%JBOSS_HOME%\client\jbossall-client.jar

April 3, 2011

Java Message Service (JMS) Queue - Hello World Example

1) Configure the JMS Queue in the JBoss 4.2.2GA Server, in the file ${JBOSS_SERVER}/server/default/deploy/jms/jbossmq-destinations-service.xml

<mbean code="org.jboss.mq.server.jmx.Queue"
  name="jboss.mq.destination:service=Queue,name=myQueue1">
  <depends optional-attribute-
  name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>

The name myQueue1 should be unique within the XML file

2) The ConnectionFactory administered object is pre-configured with the default JNDI name 'ConnectionFactory' in JBoss

Note: Add the following jar file to the classpath / build path of the Java Project / Application:

%JBOSS_HOME%\client\jbossall-client.jar

3) Create the QueueSenderClient.java

package info.icontraining.queue;

import javax.jms.*;
import javax.jms.Queue;
import javax.naming.*;
import java.util.*;

public class QueueSenderClient {

   public static void main(String[] args) {
      QueueConnection conn = null;
      QueueSession session = null;
      Queue que;
   
      try {
         Hashtable props = new Hashtable();
         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         InitialContext iniCtx = new InitialContext(props);
         Object tmp = iniCtx.lookup("ConnectionFactory");
         QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
    
         conn = qcf.createQueueConnection();
         que = (Queue) iniCtx.lookup("queue/myQueue1");

         session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
   
         conn.start();

         QueueSender queueSender = session.createSender(que);
    
         TextMessage message = session.createTextMessage();
         message.setText("This is a TextMessage from QueueSenderClient");

         queueSender.send(message);
 
         queueSender.close();
 
      } catch (NamingException e) {
         e.printStackTrace();
      } catch (JMSException e) {
         e.printStackTrace();
      } finally {
         if (conn != null) {
            try {
               conn.close();
            } catch (JMSException e) {
               e.printStackTrace();
            }
         }  
      }
   }
}

4) Create the QueueReceiverClient.java

package info.icontraining.queue;

import javax.jms.*;
import javax.jms.Queue;
import javax.naming.*;
import java.util.*;

public class QueueReceiverClient {
   public static void main(String[] args) {
      QueueConnection queueConnection = null;

      try {
         Hashtable props = new Hashtable();

         props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.NamingContextFactory");
         props.put(Context.URL_PKG_PREFIXES, "jboss.naming:org.jnp.interfaces");
         props.put(Context.PROVIDER_URL, "localhost:1099");
         props.put("java.naming.rmi.security.manager", "yes");

         Context context = new InitialContext(props);

         QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");

         String queueName = "queue/myQueue1";
         Queue queue = (Queue) context.lookup(queueName);
         queueConnection = queueConnectionFactory.createQueueConnection();

         QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         QueueReceiver queueReceiver = queueSession.createReceiver(queue);

         queueConnection.start();

         Message message = queueReceiver.receiveNoWait();

         if (message != null) {
            if (message instanceof TextMessage) {
               TextMessage textMessage = (TextMessage) message;
               System.out.println("Received: " + textMessage.getText());
            }
         }
      } catch (NamingException e) {
         e.printStackTrace();
      } catch (JMSException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (queueConnection != null) {
            try {
               queueConnection.close();
            } catch (JMSException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

5) Run QueueSenderClient first to send the message to the JMS Queue. Next, run QueueReceiverClient to receive the message.