Friday, March 13, 2015

JMS Listener:



This makes Message handling is loosely coupled with either subscriber /Receiver

MessageListener is an interface which is available in the JMS package. which facilitates the Listner
for a message and send an event to either a Subscriber / Receiver.

This interface contain on method .

public void onMessage(Message msg);

Provide an implimentation to this in your own class

import javax.jms.*;

public class JMSListener implements MessageListener
{

    public void onMessage(Message msg)
    {
        try{
           
            TextMessage tm  = (TextMessage) msg;
            System.out.println(tm.getText());

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


configure this JMSListener in the subscriber,

    tSubscriber.setMessageListener(new JMSListener());

Transaction Management in JMS



          By Default JMS auto Transactyions are auto committed.  Session is actually taken care the Transaction Mgmt in JMS.

To enable Transaction mgmt ,Set "true" to the first parameter While creating a session from connection.

Set  "false" to the first parameter While creating a session from connection and try following statement.

    QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    qsession.rollback();

It will cause the following exception,

com.ibm.msg.client.jms.DetailedIllegalStateException: JMSCC0014: It is not valid to call the 'rollback' method on a nontransacted session. The application called a method that must not be called on a nontransacted session. Change the application program to remove this behavior.

Set "true" to the first parameter While creating a session from connection and try following statement.

    QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
   
    <send a message 1>
    <send a message 2>
    <send a message 3>

    qsession.rollback();

Browse the above message in the MQ Explorer and find out the result.

Following Program explain the Transaction mgmt in JMS

import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
import java.io.*;
public class JMSTransactionDemo
{
    public static void main(String args[])
    {
      
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter 10 Messages ......");

            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
            Context ctx = new InitialContext(ht);
          
            QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("MY_QCF");
          
            Queue qu = (Queue) ctx.lookup("MY_Q");

            QueueConnection qcon = qcf.createQueueConnection();

            //QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            QueueSession qsession = qcon.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);

            QueueSender qSender =  qsession.createSender(qu);
          
            for(int i=0;i<=10;i++){    

                TextMessage msg =  qsession.createTextMessage();
              
                String line = br.readLine();

                msg.setText(line );
              
          
                qSender.send(msg);

                if(i==5)
                    qsession.rollback();

                if(i==10)
                    qsession.commit();
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Thursday, March 12, 2015

About JMS

A specification that describes a common way for Java programs to create,send, receive and read distributed enterprise messages.
                              JMS is a part of the Java Platform, Enterprise Edition, and is defined by a specification developed under the Java Community Process as JSR 914.  It is a messaging standard that allows application components based on the Java Enterprise Edition (Java EE) to create, send, receive, and read messages.  It allows the communication between different components of a distributed application to be loosely coupled, reliable, and asynchronous.

Messages are

    Asynchronous:
    -------------
        a client does not have to request them in order to receive them.
    Reliable:
    ----------
        can ensure message is delivered safely once and only once.

Messaging Domains
-----------------
   Point-to-Point



    Publish/Subscribe





JMS Administration With IBM WebSphere MQ
-----------------------------------------------
0. Create a Queue Manager in Websphere MQ as QM1
   Create a Local queue under a QM1 as LQ1

1.check the PROVIDER_URL in the C:\Program Files\IBM\WebSphere MQ\java\bin

2. Create a folder for PROVIDER_URL like (C:/JNDI-Directory)

3. execute the JMSAdmin.bat in C:\Program Files\IBM\WebSphere MQ\java\bin

4. define the queue connection Factory
     define qcf(MY_QCF) qmgr(QM1)
  which will create a file in the C:/JNDI-Directory as  .bindings

5.create destination object
    define q(MY_Q) queue(LQ1) qmgr(QM1)

  which will update this details in the .bindings file in C:/JNDI-Directory

6. configure JNDI in Websphere MQ   
    . click on JMS Administrated Object
    . right click and choose add initial context
    . select File System Option
    . and browse the JNDI-Directory by clicking the Browse button
    . Click Next -> Finish

JMS Client
-----------




1.  Initialize the InitialContext with the following values
    .provide the value PROVIDER_URL
    .provide the value INITIAL_CONTEXT_FACTORY

    Hashtable ht = new Hashtable();
    ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
    ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
    Context ctx = new InitialContext(ht);

2. Retrieve the configured QueueConnectionFactory from InitialContext by passing "MY_QCF"
    QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("MY_QCF");

3. Retrieve the configured Queue from InitialContext by passing "MY_Q"
    Queue qu = (Queue) ctx.lookup("MY_Q");

4. Create the QueueConnection from QueueConnectionFactory
    QueueConnection qcon = qcf.createQueueConnection();

5. Create the QueueSession from QueueConnection
    QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

7. Create the QueueSender  from QueueSession
    QueueSender qSender =  qsession.createSender(qu);

8. Create the Text Message from QueueSession
    TextMessage msg =  qsession.createTextMessage();

9. send a text throw Text Message
   
    msg.setText(args[0]);

    qSender.send(msg);



Example Sender Program

import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
public class JMSSender
{
    public static void main(String args[])
    {
       
        try
        {
            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
            Context ctx = new InitialContext(ht);
           
            QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("MY_QCF");
           
            Queue qu = (Queue) ctx.lookup("MY_Q");

            QueueConnection qcon = qcf.createQueueConnection();

            QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
           
            QueueSender qSender =  qsession.createSender(qu);

            TextMessage msg =  qsession.createTextMessage();

            msg.setText(args[0]);
           
            qSender.send(msg);

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


Example Receiver Program


import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
public class JMSReceiver
{
    public static void main(String args[])
    {
       
        try
        {
            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");

            Context ctx = new InitialContext(ht);
           
            QueueConnectionFactory qcf = (QueueConnectionFactory)ctx.lookup("MY_QCF");
           
            Queue qu = (Queue) ctx.lookup("MY_Q");

            QueueConnection qcon = qcf.createQueueConnection();
           
            qcon.start();

            QueueSession qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
           
            QueueReceiver qReceiver = qsession.createReceiver(qu);
           
            TextMessage tmsg= (TextMessage) qReceiver.receive(30000);
           
            System.out.println(tmsg.getText());
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}


Example Publisher Program

import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
public class JMSPublisher
{
    public static void main(String args[])
    {
       
        try
        {
            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
           
            Context ctx = new InitialContext(ht);
           
            TopicConnectionFactory tcf = (TopicConnectionFactory)ctx.lookup("MY_TCF");

            Topic topic= (Topic ) ctx.lookup("MY_T");

            TopicConnection tcon = tcf.createTopicConnection();
           
            TopicSession tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
           
            TopicPublisher tp = tsession.createPublisher(topic);

            TextMessage msg =  tsession.createTextMessage();

            msg.setText(args[0]);
           
            tp.publish(msg);
           
            tsession.close();

            tcon.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

Example Subscriber Program

import javax.jms.*;
import java.util.Hashtable;
import javax.naming.*;
public class JMSSubscriber
{
    public static void main(String args[])
    {
       
        try
        {
            Hashtable ht = new Hashtable();
            ht.put(Context.PROVIDER_URL,"file:/C:/JNDI-Directory");
            ht.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
            Context ctx = new InitialContext(ht);
           
            TopicConnectionFactory tcf = (TopicConnectionFactory)ctx.lookup("MY_TCF");
           
            Topic topic = (Topic) ctx.lookup("MY_T");

            TopicConnection tcon = tcf.createTopicConnection();
           
            tcon.start();

            TopicSession tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
           
            TopicSubscriber tSubscriber= tsession.createSubscriber(topic);
           
            TextMessage tmsg= (TextMessage) tSubscriber.receive(3000000);
           
            System.out.println(tmsg);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}