/** * A WebSphere MQ application which uses MQQueueConnectionFactory to send msg to a Queue. * This MQQueueConnectionFactory is looked up in JNDI Context. * Before you look up, you should create a JNDI Context using 'WebSphere MQ JMS administration tool'. * This method to create is provided at other file. */ package com.ibm.mq.test; import java.util.Hashtable; import javax.jms.DeliveryMode; import javax.jms.JMSException; import javax.jms.Queue; import javax.jms.QueueConnection; import javax.jms.QueueSender; import javax.jms.QueueSession; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import com.ibm.mq.jms.MQQueueConnectionFactory; public class MQSendByCF_JNDI { public static void main(String[] args) { MQSendByCF_JNDI sender = new MQSendByCF_JNDI(); try { sender.initMQObjects(); sender.sendMsg(); } catch(Exception e) { e.printStackTrace(); } finally { sender.closeMQObjects(); } } MQQueueConnectionFactory mqcf; QueueConnection conn; QueueSession session; TextMessage textMsg; Queue queue; QueueSender sender; public void initMQObjects() throws Exception { String strMsg = "Where are you?"; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory"); env.put(Context.PROVIDER_URL, "file:/D:/JNDI"); try { Context ctx = new InitialContext(env); mqcf = (MQQueueConnectionFactory) ctx.lookup("QCF_TEST"); /*This Queue [Q_TEST] is not a real queue on QebSphere MQ, but it is binded to a real queue on WebSphere MQ.*/ queue = (Queue) ctx.lookup("Q_TEST"); } catch (NamingException e) { System.out.println("Find MQ Objects from Context Failed."); throw e; } conn = mqcf.createQueueConnection(); session = conn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); textMsg = session.createTextMessage(strMsg); sender = session.createSender(queue); } /** * Name: sendMsg * Date: 2010-10-1 * paramter: * Return_type: void * User: Leng Fuping * Description: Send Msg */ public void sendMsg() throws Exception { try { conn.start(); } catch (JMSException e) { System.out.println("Send Msg Failed."); throw e; } sender.send(textMsg,DeliveryMode.NON_PERSISTENT,0,0); System.out.println("Send Msg succeed."); } /** * Name: closeMQObjects * Date: 2010-10-1 * paramter: * Return_type: void * User: Leng Fuping * Description: Close MQ Objects */ public void closeMQObjects() { try { if(conn != null) { conn.stop(); } if(sender != null) { sender.close(); } if(session != null) { session.close(); } if(conn != null) { conn.close(); } if(mqcf != null) { mqcf.clear(); } System.out.println("Close MQ objects succeed."); } catch (JMSException e) { System.out.println("Close MQ objects failed: " + e.getMessage()); } } }