Java JMS Message copy

Description

Java JMS Message copy


import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

public class Main implements MessageListener {
   Session sn;/*w ww .  ja v a 2  s  .c om*/
   MessageProducer mp;

   public Main(String args[]) {
      try {
         Context ctx = new InitialContext();
         ConnectionFactory cf = (ConnectionFactory) ctx.lookup(args[0]);
         Connection con = cf.createConnection();
         sn = con.createSession(true, Session.AUTO_ACKNOWLEDGE);
         Destination from = sn.createQueue(args[0]);
         MessageConsumer mc = sn.createConsumer(from);
         Destination to = sn.createQueue(args[1]);
         mp = sn.createProducer(to);
         con.start();
         mc.setMessageListener(this);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main(String[] args) {
      new Main(args);
   }

   public void onMessage(Message msg) {
      try {
         mp.send(msg);
         sn.commit();
      } catch (Exception e) {
         try {
            sn.rollback();
         } catch (Exception e1) {
            e1.printStackTrace();
         }
      }

   }
}



PreviousNext

Related