1 22 package org.jboss.test.cts.jms; 23 24 import javax.jms.JMSException ; 25 import javax.jms.QueueConnection ; 26 import javax.jms.QueueConnectionFactory ; 27 import javax.jms.QueueSender ; 28 import javax.jms.QueueSession ; 29 import javax.jms.Session ; 30 import javax.jms.TextMessage ; 31 import javax.jms.Queue ; 32 import javax.naming.Context ; 33 import javax.naming.InitialContext ; 34 import javax.naming.NamingException ; 35 36 public class MsgSender 37 { 38 org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(getClass()); 39 40 public final static String JMS_FACTORY="ConnectionFactory"; 41 public final static String QUEUE="queue/testQueue"; 42 43 private QueueConnectionFactory qconFactory; 44 private QueueConnection qcon; 45 private QueueSession qsession; 46 private QueueSender qsender; 47 private TextMessage msg; 48 private Queue queue; 49 50 public MsgSender ( ) 51 { 52 } 53 54 58 public void init(Context ctx, String queueName) 59 throws NamingException , JMSException 60 { 61 qconFactory = (QueueConnectionFactory ) ctx.lookup(JMS_FACTORY); 62 qcon = qconFactory.createQueueConnection(); 63 qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); 64 try 65 { 66 queue = (Queue ) ctx.lookup(queueName); 67 } 68 catch (NamingException ne) 69 { 70 queue = qsession.createQueue(queueName); 71 ctx.bind(queueName, queue); 72 } 73 qcon.start(); 74 } 75 76 79 public void close() 80 throws JMSException 81 { 82 if( qcon != null ) { 83 qsender.close(); 84 qsession.close(); 85 qcon.close(); 86 qcon = null; 87 } 88 } 89 90 public void sendMsg( String message ) 91 { 92 try 93 { 94 init( new InitialContext (), QUEUE); 95 log.debug("Sending a message.." ); 96 qsender = qsession.createSender(queue); 97 msg = qsession.createTextMessage(); 98 msg.setText(message); 99 qsender.send(msg); 100 close(); 101 } 102 catch(Exception ex) 103 { 104 ex.printStackTrace( ); 105 } 106 } 107 108 private static InitialContext getInitialContext(String url) 109 throws NamingException 110 { 111 return new InitialContext (); 116 } 117 118 } 119 120 121 122 123 124 125 | Popular Tags |