Example usage for javax.jms MessageConsumer receive

List of usage examples for javax.jms MessageConsumer receive

Introduction

In this page you can find the example usage for javax.jms MessageConsumer receive.

Prototype


Message receive(long timeout) throws JMSException;

Source Link

Document

Receives the next message that arrives within the specified timeout interval.

Usage

From source file:com.linagora.obm.sync.TestQueueManager.java

@Test
public void testConsumeLater() throws Exception {
    String testText = "test text";

    writeMessageOnTopic(testText, TOPIC, queueManager);

    Connection connection = createManagedConnection();
    connection.start();//from w w w  .j  a  va  2 s.co  m
    Session consumerSession = createManagedSession(connection);
    MessageConsumer consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC);
    TextMessage messageReceived = (TextMessage) consumer.receive(TIMEOUT);
    Assert.assertNull(messageReceived);
}

From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java

public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener,
        JdbcTransactionalStorage errorStorage) {
    String result = null;/*from  www.j a  va 2 s .  com*/

    PoolingConnectionFactory jmsConnectionFactory = null;
    PoolingDataSource jdbcDataSource = null;
    BitronixTransactionManager btm = null;
    javax.jms.Connection jmsConnection = null;

    try {
        jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener);
        if (jmsConnectionFactory != null) {
            jdbcDataSource = getPoolingDataSource(errorStorage);
            if (jdbcDataSource != null) {
                String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null);
                String logDir = AppConstants.getInstance().getString("log.dir", null);
                TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm");
                TransactionManagerServices.getConfiguration()
                        .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog");
                TransactionManagerServices.getConfiguration()
                        .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog");
                btm = TransactionManagerServices.getTransactionManager();

                jmsConnection = jmsConnectionFactory.createConnection();

                Session jmsSession = null;
                MessageConsumer jmsConsumer = null;

                java.sql.Connection jdbcConnection = null;

                btm.begin();
                log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]");

                try {
                    jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                    String queueName = esbJmsListener.getPhysicalDestinationShortName();
                    Queue queue = jmsSession.createQueue(queueName);
                    jmsConsumer = jmsSession.createConsumer(queue);

                    jmsConnection.start();

                    long timeout = 30000;
                    log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout
                            + "] msec");
                    Message rawMessage = jmsConsumer.receive(timeout);

                    if (rawMessage == null) {
                        log.debug("no message found on queue [" + queueName + "]");
                    } else {
                        String id = rawMessage.getJMSMessageID();
                        log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]");
                        Serializable sobj = null;
                        if (rawMessage != null) {
                            if (rawMessage instanceof Serializable) {
                                sobj = (Serializable) rawMessage;
                            } else {
                                try {
                                    sobj = new MessageWrapper(rawMessage, esbJmsListener);
                                } catch (ListenerException e) {
                                    log.error("could not wrap non serializable message for messageId [" + id
                                            + "]", e);
                                    if (rawMessage instanceof TextMessage) {
                                        TextMessage textMessage = (TextMessage) rawMessage;
                                        sobj = textMessage.getText();
                                    } else {
                                        sobj = rawMessage.toString();
                                    }
                                }
                            }
                        }

                        jdbcConnection = jdbcDataSource.getConnection();

                        result = errorStorage.storeMessage(jdbcConnection, id, id,
                                new Date(System.currentTimeMillis()), "moved message", null, sobj);
                    }

                    log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                    btm.commit();
                } catch (Exception e) {
                    if (btm.getCurrentTransaction() != null) {
                        log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                        btm.rollback();
                    }
                    log.error("exception on receiving message and moving to errorStorage", e);
                } finally {
                    if (jdbcConnection != null) {
                        jdbcConnection.close();
                    }
                    if (jmsConnection != null) {
                        jmsConnection.stop();
                    }
                    if (jmsConsumer != null) {
                        jmsConsumer.close();
                    }
                    if (jmsSession != null) {
                        jmsSession.close();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("exception on receiving message and moving to errorStorage", e);
    } finally {
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            } catch (JMSException e) {
                log.warn("exception on closing connection", e);
            }
        }
        if (jmsConnectionFactory != null) {
            jmsConnectionFactory.close();
        }
        if (jdbcDataSource != null) {
            jdbcDataSource.close();
        }
        if (btm != null) {
            btm.shutdown();
        }
    }
    return result;
}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

private void receiveMessagesWithoutCommit(final MessageConsumer consumer, int numberOfMessages)
        throws Exception {
    for (int i = 0; i < numberOfMessages; i++) {
        final Message m = consumer.receive(1000l);
        assertNotNull("Message " + i + " is not received", m);
    }/*w w  w  .j  ava  2s  . co  m*/
}

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

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*from   www .  j  a  v a2 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:nl.nn.adapterframework.jms.JmsMessageBrowser.java

public Object getMessage(String messageId) throws ListenerException {
    Session session = null;//from w  ww.j a  va 2s. c om
    Object msg = null;
    MessageConsumer mc = null;
    try {
        session = createSession();
        mc = getMessageConsumer(session, getDestination(), getCombinedSelector(messageId));
        msg = mc.receive(getTimeOut());
        return msg;
    } catch (Exception e) {
        throw new ListenerException(e);
    } finally {
        try {
            if (mc != null) {
                mc.close();
            }
        } catch (JMSException e1) {
            throw new ListenerException("exception closing message consumer", e1);
        }
        closeSession(session);
    }
}

From source file:org.openbaton.common.vnfm_sdk.amqp.VnfmSpringHelper.java

/**
 * This method should be used for receiving text message from EMS
 *
 * resp = { 'output': out, // the output of the command 'err': err, // the error outputs of the
 * commands 'status': status // the exit status of the command }
 *
 * @param queueName//from ww w .j  av a 2s. c  om
 * @return
 * @throws JMSException
 */
public String receiveTextFromQueue(String queueName)
        throws JMSException, ExecutionException, InterruptedException, VnfmSdkException {
    String res;

    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
    connection.start();
    String scriptMaxTime = properties.getProperty("script-max-time");
    if (scriptMaxTime != null) {
        TextMessage textMessage = (TextMessage) consumer.receive(Long.parseLong(scriptMaxTime));
        if (textMessage != null)
            res = textMessage.getText();
        else
            throw new VnfmSdkException("No message got from queue " + queueName + " after " + scriptMaxTime);
    } else
        res = ((TextMessage) consumer.receive()).getText();
    log.debug("Received Text from " + queueName + ": " + res);
    consumer.close();
    session.close();
    connection.close();
    return res;
}

From source file:org.apache.activemq.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void consumerAndRollback(int iteration) throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(QUEUE_NAME);
    MessageConsumer consumer = session.createConsumer(queue);

    long msgCount = getProxyToQueue(queue.getQueueName()).getQueueSize();

    for (int i = 0; i < msgCount; ++i) {
        Message message = consumer.receive(50000);
        assertNotNull(message);/*from w  w  w . j  av  a 2s  . co  m*/
        if (iteration > 0) {
            assertTrue(message.getJMSRedelivered());
        }
    }

    connection.close();
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSPollingConsumer.java

private Message receiveMessage(MessageConsumer messageConsumer) throws JMSException {
    Message msg = null;//from  w  w w.  j a va 2 s.  c  om
    if (iReceiveTimeout == null) {
        msg = messageConsumer.receive(1);
    } else if (iReceiveTimeout > 0) {
        msg = messageConsumer.receive(iReceiveTimeout);
    } else {
        msg = messageConsumer.receive();
    }
    return msg;
}

From source file:com.linagora.obm.sync.TestQueueManager.java

@Test
public void testSimple() throws Exception {
    String testText = "test text";

    Connection connection = createManagedConnection();
    connection.start();/* w w w  .  jav a2  s . c o m*/
    Session consumerSession = createManagedSession(connection);
    MessageConsumer consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC);

    writeMessageOnTopic(testText, TOPIC, queueManager);

    TextMessage messageReceived = (TextMessage) consumer.receive(TIMEOUT);
    Assert.assertEquals(testText, messageReceived.getText());
}

From source file:com.linagora.obm.sync.TestQueueManager.java

@Test
public void testClosedSession() throws Exception {
    String testText = "test text";

    Connection connection = createManagedConnection();
    connection.start();/*from   www  .j  a  v a2s  .c  o  m*/
    Session consumerSession = queueManager.createSession(connection);
    MessageConsumer consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC);

    writeMessageOnTopic(testText, TOPIC, queueManager);

    TextMessage messageReceived1 = (TextMessage) consumer.receive(TIMEOUT);
    consumerSession.close();

    writeMessageOnTopic(testText, TOPIC, queueManager);
    consumerSession = createManagedSession(connection);
    consumer = queueManager.createConsumerOnTopic(consumerSession, TOPIC);

    TextMessage messageReceived2 = (TextMessage) consumer.receive(TIMEOUT);
    Assert.assertEquals(testText, messageReceived1.getText());
    Assert.assertNull(messageReceived2);
}