Sample JMS Client Application

A sample JMS client application is provided for your reference.  You can compile and run it after creating iMQ administered objects as described in this tutorial.
 

In the following, we will explain the code segments in further detail so that you will have a better understanding of them.

In order to use JNDI to locate iMQ administered objects, you need to first set the environment which tells JNDI which initial context to use and where to find the provider.  You should make sure that you use the same JNDI attributes that you specified when creating the object store.  Refer to the Adding an Object Store section for details on these attributes.

    Hashtable         env;

    env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.fscontext.RefFSContextFactory");
    env.put(Context.PROVIDER_URL, "file:///d:/mytemp");

Using the environment that you have just specified, create the initial context.

    try {
        ctx = new InitialContext(env);
    } catch (NamingException ne)  {
        System.err.println("Failed to create InitialContext: " + ne);
        ne.printStackTrace();
        System.exit(-1);
    }

Now that you have the initial context, you can lookup iMQ administered objects that you have created and stored in the object store earlier.  Remember that the lookup name for the Queue Connection Factory was myQCF and was myQueue for Queue.

    String MYQCFNAME     = "myQCF";
    String MYQUEUENAME   = "myQueue";

    try {
        qcf = (javax.jms.QueueConnectionFactory) ctx.lookup(MYQCFNAME);
        queueConnection = qcf.createQueueConnection();
        queueSession = queueConnection.createQueueSession(false,
                       Session.AUTO_ACKNOWLEDGE);

        queue = (javax.jms.Queue)ctx.lookup(MYQUEUENAME);

    } catch (JMSException e)  {
        System.err.println("JMS Exception: " + e);
        e.printStackTrace();
        System.exit(-1);
    } catch (NamingException ne)  {
        System.err.println("Failed to lookup admin object: " + ne);
        ne.printStackTrace();
        System.exit(-1);
    }

Now that you have instances of a Queue Connection Factory and Queue, you can use them to create a queue connection, queue session, sender, and receiver, and start sending and receiving messages.
 

<<Back>>     >> Next>>     <<Return to TOC>>