MessageSender.java
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:1k
源码类别:

Java编程

开发平台:

Java

  1. package day21ex.messagesender;
  2. import java.io.*;
  3. import java.util.*;
  4. import javax.transaction.*;
  5. import javax.naming.*;
  6. import javax.jms.*;
  7. import javax.ejb.*;
  8. public class MessageSender{
  9.    public final static String JMS_FACTORY =
  10.                     "java:comp/env/jms/TopicConnectionFactory";
  11.    public final static String TOPIC =
  12.                     "java:comp/env/jms/OrderVerifierTopic";
  13.    public void sendAMessage(Context jndiCtx, String msg)  {
  14.       TopicConnection tConnect = null;
  15.       try {
  16.          TopicConnectionFactory tFactory = 
  17.             (TopicConnectionFactory) jndiCtx.lookup(JMS_FACTORY);
  18.          Topic t = (Topic)jndiCtx.lookup(TOPIC);
  19.          tConnect = 
  20.             tFactory.createTopicConnection();
  21.          TopicSession session = tConnect.createTopicSession(false,
  22.                                QueueSession.AUTO_ACKNOWLEDGE);
  23.          TopicPublisher publisher = session.createPublisher(t);
  24.          TextMessage jmsMsg = session.createTextMessage();
  25.          jmsMsg.setText(msg);
  26.          publisher.publish(jmsMsg);
  27.          print("Message sent to the topic:" + msg);
  28.       }catch  (Exception e) {
  29.          e.printStackTrace();
  30.          throw new EJBException("MessageSender:sendAMessage: Error!",e);
  31.       } finally {
  32.          try {
  33.             if( tConnect != null ) {
  34.                tConnect.close();
  35.             }
  36.          } catch(Exception e) {}
  37.       }
  38.    }
  39.    void print(String s) {
  40.       System.out.println("MessageSender:"+ s);
  41.    }
  42. }