Monday, May 26, 2008

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

public class MyListener implements MessageListener{
// Define the connection for the provider private static String ProviderUrl = "t3://localhost:7001";
// Defines the JNDI context factory. public static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
// Defines the JMS connection factory for the queue. public static String JMS_FACTORY="jms/MyConnectionFactory";
// Defines the queue. public static String QUEUE="jms/MyQueue";
private QueueConnectionFactory queueConnectionFactory;
private QueueConnection queueConnection;
private QueueSession queueSession;
private QueueReceiver queueReceiver;
private Queue queue; private boolean quit = false;
/** * On Message() gets triggered on receipt of a message */

public void onMessage(Message msg) {
try {
String msgText;
if (msg instanceof TextMessage) {
msgText = ((TextMessage)msg).getText();
} else {
msgText = msg.toString();
}
System.out.println("Message Received... "+ msgText );
if (msgText.equalsIgnoreCase("quit")) {
synchronized(this) {
quit = true; // Notify main thread to quit this.notifyAll();
}
}
} catch (JMSException jmse) { jmse.printStackTrace(); } }
/** * Initializes the context for setting up JMS... * */
public void init(Context ctx, String queueName) throws NamingException, JMSException {
System.out.println( "Looking up connection factory:" + JMS_FACTORY );
queueConnectionFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
queueConnection = queueConnectionFactory.createQueueConnection();
queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
System.out.println( "Listening to Queue..." + queueName ); queue = (Queue) ctx.lookup(queueName);
queueReceiver = queueSession.createReceiver(queue);
queueReceiver.setMessageListener(this);
queueConnection.start();
}
/** * Closes JMS objects gracefully * */
public void close()throws JMSException {
queueReceiver.close();
queueSession.close();
queueConnection.close();
}
/** * public static void main() (Entry point). * */
public static void main(String[] args) throws Exception {
InitialContext ic = getInitialContext(ProviderUrl);
MyListener myListener = new MyListener();
myListener.init(ic, QUEUE);
System.out.println("JMS MyListener Module ready to listen for messages. Module will exit on getting a \"quit\" message....");
// Wait until a "quit" message has been received.

synchronized(myListener) {
while (! myListener.quit) {
try {
myListener.wait();
} catch (InterruptedException ie) {}
}
}
myListener.close(); }
/* * gets the initial context object * */
private static InitialContext getInitialContext(String url) throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
return new InitialContext(env);
}
}

No comments: