Wednesday, 25 July 2012

A simple JMSClient to test JMS queue/topic in Weblogic

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Hashtable;

public class TestJMS {
    private static InitialContext context = null;
    private static QueueConnectionFactory connectionFactory = null;
    private static QueueConnection connection = null;
    private static QueueSession session = null;
    private static Queue queue = null;
    private static QueueSender queueSender = null;
    private static TextMessage message = null;
    //Using the Default Connection Factories
    //ref --> http://docs.oracle.com/cd/E15051_01/wls/docs103/jms/fund.html
    private static final String CONNECTION_FACTORY_JNDI_NAME = "weblogic.jms.ConnectionFactory";
    private static final String QUEUE_JNDI_NAME = "Police.Eno.CourtServiceQueue";

    public TestJMS() {
        super();
    }

    public static void sendMessage(String messageText) {
        try {
            try {
                Hashtable properties = new Hashtable();
                properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
                properties.put(Context.PROVIDER_URL, "t3://localhost:7001");

                context = new InitialContext(properties);
                connectionFactory = (QueueConnectionFactory) context.lookup(CONNECTION_FACTORY_JNDI_NAME);
                connection = connectionFactory.createQueueConnection();
                session = connection.createQueueSession(false, 0);

                queue = (Queue) context.lookup(QUEUE_JNDI_NAME);
                queueSender = session.createSender(queue);
                message = session.createTextMessage();
                message.setText(messageText);
                queueSender.send(message);
            } finally {
                message = null;
                queueSender.close();
                queueSender = null;
                queue = null;
                session.close();
                session = null;
                connection.close();
                connection = null;
                connectionFactory = null;
                context = null;
            }
        } catch (NamingException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        } catch (JMSException e) {
            e.printStackTrace(System.err);
            System.exit(0);
        }
    }

    public static void main(String args[]) {
        sendMessage("test message here!!!");
    }
}

No comments:

Post a Comment