Example usage for javax.jms Session createConsumer

List of usage examples for javax.jms Session createConsumer

Introduction

In this page you can find the example usage for javax.jms Session createConsumer.

Prototype


MessageConsumer createConsumer(Destination destination) throws JMSException;

Source Link

Document

Creates a MessageConsumer for the specified destination.

Usage

From source file:org.wso2.carbon.sample.consumer.JMSQueueMessageConsumer.java

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/* w w  w.  ja  v  a 2  s. c  o m*/
        queueConnection = queueConnectionFactory.createQueueConnection();

        queueConnection.start();
    } catch (JMSException e) {
        log.info("Can not create queue connection." + e);
        return;
    }
    Session session = null;
    try {

        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);

        int count = 0;
        long totalLatency = 0;
        long lastTimestamp = System.currentTimeMillis();

        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                //                    if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                long currentTime = System.currentTimeMillis();
                long sentTimestamp = (Long) mapMessage.getObject("time");

                totalLatency = totalLatency + (currentTime - sentTimestamp);

                int logCount = 1000;

                if ((count % logCount == 0) && (count > warmUpCount)) {
                    double rate = (logCount * 1000.0d / (System.currentTimeMillis() - lastTimestamp));
                    log.info("Consumer: " + consumerId + " (" + logCount + " received) rate: " + rate
                            + " Latency:" + (totalLatency / (logCount * 1.0d)));
                    //                            log.info("total latency:" + totalLatency);
                    log.info("Total rate: " + (int) (consumers * rate));
                    totalLatency = 0;
                    lastTimestamp = System.currentTimeMillis();
                }
                count++;
            }
        }
        log.info("Finished listening for messages.");

    } catch (JMSException e) {
        log.info("Can not subscribe." + e);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.error(e);
            }
        }
        try {
            queueConnection.stop();
            queueConnection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.fusesource.forge.jmstest.tests.simple.SimpleConsumer.java

protected void run() {
    Connection con = null;/*www .j ava 2 s  .c o m*/
    Session session = null;
    final CountDownLatch latch = new CountDownLatch(Integer.MAX_VALUE);
    try {
        con = getConnection();
        session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination dest = getDestinationProvider().getDestination(session, "queue:TEST");
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                String grp = null;
                long nr = 0L;
                try {
                    grp = msg.getStringProperty("JMSXGroupID");
                    nr = msg.getLongProperty("MsgNr");
                } catch (JMSException jme) {
                }
                log().info("Received Message Group=(" + grp + ") MsgNr=" + nr);
                latch.countDown();
            }
        });
        con.start();
        latch.await();
        con.close();
    } catch (Exception e) {
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.apache.falcon.oozie.workflow.FalconPostProcessingTest.java

private void consumer(String brokerUrl, String topic, boolean checkUserMessage) throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*  w  w w.  j a va 2  s .  c  om*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(topic);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    // Verify user message
    if (checkUserMessage) {
        verifyMesssage(consumer);
    }

    // Verify falcon message
    verifyMesssage(consumer);

    connection.close();
}

From source file:org.trellisldp.app.triplestore.TrellisApplicationTest.java

@BeforeEach
public void aquireConnection() throws Exception {
    final ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
    connection = connectionFactory.createConnection();
    connection.start();//from w  w w .  j  a v  a2s .  c o  m
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue("trellis");
    consumer = session.createConsumer(destination);
    consumer.setMessageListener(this);
}

From source file:Supplier.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;//from w w  w .  j  av  a 2 s  .c om
    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue(QUEUE);
        MessageConsumer consumer = session.createConsumer(orderQueue);

        connection.start();

        while (true) {
            Message message = consumer.receive();
            MessageProducer producer = session.createProducer(message.getJMSReplyTo());
            MapMessage orderMessage;
            if (message instanceof MapMessage) {
                orderMessage = (MapMessage) message;
            } else {
                // End of Stream
                producer.send(session.createMessage());
                session.commit();
                producer.close();
                break;
            }

            int quantity = orderMessage.getInt("Quantity");
            System.out.println(
                    ITEM + " Supplier: Vendor ordered " + quantity + " " + orderMessage.getString("Item"));

            MapMessage outMessage = session.createMapMessage();
            outMessage.setInt("VendorOrderNumber", orderMessage.getInt("VendorOrderNumber"));
            outMessage.setString("Item", ITEM);

            quantity = Math.min(orderMessage.getInt("Quantity"),
                    new Random().nextInt(orderMessage.getInt("Quantity") * 10));
            outMessage.setInt("Quantity", quantity);

            producer.send(outMessage);
            System.out.println(ITEM + " Supplier: Sent " + quantity + " " + ITEM + "(s)");
            session.commit();
            System.out.println(ITEM + " Supplier: committed transaction");
            producer.close();
        }
        connection.close();
    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.logicblaze.lingo.jms.JmsRemotingTest.java

protected void subscribeToQueue(JmsServiceExporter exporter, String queueName) throws JMSException {
    Session serverSession = createSession();
    Queue queue = serverSession.createQueue(queueName);
    MessageConsumer consumer = serverSession.createConsumer(queue);
    consumer.setMessageListener(exporter);
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {/*  www  . j  a  v a 2 s  .co m*/
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

/**
 * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still
 * be in the queue even when it was browsed.
 *
 * Re-enable once https://issues.apache.org/jira/browse/APLO-226 is fixed.
 *
 * @throws Exception/*from   ww  w .  j a v a  2s . c  o m*/
 */
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();

    Message[] outbound = new Message[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }

    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    //Thread.sleep(200);

    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], (Message) enumeration.nextElement());

    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], (Message) enumeration.nextElement());

    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();

    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();

}

From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    this.terminateConnection = connectionFactory.createConnection();
    terminateConnection.start();/*w w  w .  jav  a  2 s  . co  m*/

    Session session = terminateConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic topic = session.createTopic(Constants.TERMINATE_CONSUMER_TOPIC);
    final MessageConsumer consumer = session.createConsumer(topic);

    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        terminateConnection.close();
                        return;
                    }

                    if (consumerId.equals(bean.getConsumerId())) {
                        if (bean.getStatus() == ConsumerStatus.REQUEST_TERMINATE) {
                            System.out.println(getName() + " has been requested to terminate and will exit.");
                            cbean.setStatus(ConsumerStatus.REQUEST_TERMINATE);
                            Thread.currentThread().sleep(2500);
                            System.exit(0);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    consumer.setMessageListener(listener);

}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizFac(Context ctx, Object obj) throws Exception {

    ConnectionFactory f = (ConnectionFactory) obj;
    final JmsIO me = this;
    Connection conn;/*w  w w .j a v a  2  s. c  o m*/
    Object c = ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createConnection();
    }

    _conn = conn;

    if (c instanceof Destination) {
        //TODO ? ack always ?
        Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageConsumer u = s.createConsumer((Destination) c);
        u.setMessageListener(new MessageListener() {
            public void onMessage(Message msg) {
                me.onMessage(msg);
            }
        });
    } else {
        throw new Exception("JmsIO: Object not of Destination type");
    }
}