JMS Message Received - Java javax.jms

Java examples for javax.jms:Message

Description

JMS Message Received

Demo Code


import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ejb.MessageDrivenContext;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

public class Main{
    public static void msgReceived(Message msg, AtomicInteger counter,
            ConnectionFactory connectionFactory,
            MessageDrivenContext sessionContext, Topic topic, Class clazz) {
        int value = counter.incrementAndGet();
        if (value % 100 == 0) {
            System.out.println("Received " + value + " on "
                    + clazz.getSimpleName());
        }/*  ww  w  .  j a v a 2s.  co m*/

        int i = 0;
        try {
            i = msg.getIntProperty("i");
        } catch (Throwable e) {
            e.printStackTrace();
            i = 1000;
        }

        try {
            if (i < 100) {
                System.out.println(clazz.getSimpleName()
                        + " waiting 1 second on " + value);
                Thread.sleep(1000);
            } else {
                // Thread.sleep(randomLong() % 100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Connection conn = connectionFactory.createConnection();
            Session sess = conn.createSession(true,
                    Session.SESSION_TRANSACTED);
            MessageProducer prod = sess.createProducer(topic);
            TextMessage outMessage = sess.createTextMessage("hello");
            outMessage.setIntProperty("receiver", 100);
            prod.send(outMessage);
            conn.close();
        } catch (JMSException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            sessionContext.setRollbackOnly();
        }
    }
}

Related Tutorials