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:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();// w  w  w  . j av a  2  s .c  o  m

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

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

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

From source file:org.apache.activemq.JmsConnectionStartStopTest.java

/**
 * Tests if the consumer receives the messages that were sent before the
 * connection was started./*  w  w w .  ja va  2 s. co  m*/
 *
 * @throws JMSException
 */
public void testStoppedConsumerHoldsMessagesTillStarted() throws JMSException {
    Session startedSession = startedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session stoppedSession = stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    // Setup the consumers.
    Topic topic = startedSession.createTopic("test");
    MessageConsumer startedConsumer = startedSession.createConsumer(topic);
    MessageConsumer stoppedConsumer = stoppedSession.createConsumer(topic);

    // Send the message.
    MessageProducer producer = startedSession.createProducer(topic);
    TextMessage message = startedSession.createTextMessage("Hello");
    producer.send(message);

    // Test the assertions.
    Message m = startedConsumer.receive(1000);
    assertNotNull(m);

    m = stoppedConsumer.receive(1000);
    assertNull(m);

    stoppedConnection.start();
    m = stoppedConsumer.receive(5000);
    assertNotNull(m);

    startedSession.close();
    stoppedSession.close();
}

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  va 2s.  com
 */
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:nl.nn.adapterframework.jms.PullingJmsListener.java

/** 
 * @see nl.nn.adapterframework.core.IPostboxListener#retrieveRawMessage(java.lang.String, java.util.Map)
 *///from   w w  w .  j a  va 2 s  .  c  om
public Object retrieveRawMessage(String messageSelector, Map threadContext) throws ListenerException {
    Session session = null;
    try {
        session = getSession(threadContext);
        MessageConsumer mc = null;
        try {
            mc = getMessageConsumer(session, getDestination(), messageSelector);
            Object result = (getTimeOut() < 0) ? mc.receiveNoWait() : mc.receive(getTimeOut());
            return result;
        } finally {
            if (mc != null) {
                try {
                    mc.close();
                } catch (JMSException e) {
                    log.warn(getLogPrefix() + "exception closing messageConsumer", e);
                }
            }
        }
    } catch (Exception e) {
        throw new ListenerException(getLogPrefix() + "exception preparing to retrieve message", e);
    } finally {
        releaseSession(session);
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public Message consumeMessage(String consumerName, long receiveInterval) {
    Message consumedMessage = null;//from  www  . j  av a2  s.  c om
    MessageConsumer consumer = _testConsumers.get(consumerName);
    try {
        consumedMessage = consumer.receive(receiveInterval);
    } catch (JMSException e) {
        throw new DistributedTestException("Unable to consume message with consumer: " + consumerName, e);
    }
    return consumedMessage;
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.jms.HermesJmsRequestTransport.java

protected Response makeResponse(SubmitContext submitContext, Request request, long timeStarted,
        Message messageSend, MessageConsumer messageConsumer) throws JMSException {
    long timeout = getTimeout(submitContext, request);
    Message messageReceive = messageConsumer.receive(timeout);
    if (messageReceive != null) {
        JMSResponse response = resolveMessage(request, timeStarted, messageSend, messageReceive);
        submitContext.setProperty(IS_JMS_MESSAGE_RECEIVED, true);
        submitContext.setProperty(JMS_RESPONSE, response);
        return response;
    } else {//from   www. j  a v  a2  s  .  c o m
        return new JMSResponse("", null, null, request, timeStarted);
    }
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Comsume messages. */
protected void consumeMessages(Connection connection, Session session, MessageConsumer consumer, long timeout)
        throws JMSException, IOException {
    Message message;//from   w w w .  j  a  v a2 s .c  o  m
    while (!this.receiver.getNoMoreMessagesFlag()) {
        while ((message = consumer.receive(timeout)) != null) {
            onMessageOptimistic(message);
        }
    }
    consumer.close();
    session.close();
    connection.close();
}

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

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

    Connection connection = createManagedConnection();
    connection.start();/*from  ww  w.j a v a  2 s. co  m*/
    Session consumerSession1 = createManagedSession(connection);
    MessageConsumer consumer1 = queueManager.createConsumerOnTopic(consumerSession1, TOPIC);

    Session consumerSession2 = createManagedSession(connection);
    MessageConsumer consumer2 = queueManager.createConsumerOnTopic(consumerSession2, TOPIC);

    writeMessageOnTopic(testText, TOPIC, queueManager);

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

From source file:ConsumerTool.java

protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer)
        throws JMSException, IOException {
    System.out.println("[" + this.getName() + "] We are about to wait until we consume: " + maxiumMessages
            + " message(s) then we will shutdown");

    for (int i = 0; i < maxiumMessages && isRunning();) {
        Message message = consumer.receive(1000);
        if (message != null) {
            i++;//from w  w  w.j a  va 2s  .c  om
            onMessage(message);
        }
    }
    System.out.println("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
    if (pauseBeforeShutdown) {
        System.out.println("[" + this.getName() + "] Press return to shut down");
        System.in.read();
    }
}

From source file:org.openengsb.ports.jms.JMSPortTest.java

private String sendWithTempQueue(final String msg) {
    String resultString = jmsTemplate.execute(new SessionCallback<String>() {
        @Override//from   w w w .  j  a v  a2s .c  o  m
        public String doInJms(Session session) throws JMSException {
            Queue queue = session.createQueue("receive");
            MessageProducer producer = session.createProducer(queue);
            TemporaryQueue tempQueue = session.createTemporaryQueue();
            MessageConsumer consumer = session.createConsumer(tempQueue);
            TextMessage message = session.createTextMessage(msg);
            message.setJMSReplyTo(tempQueue);
            producer.send(message);
            TextMessage response = (TextMessage) consumer.receive(10000);
            assertThat(
                    "server should set the value of the correltion ID to the value of the received message id",
                    response.getJMSCorrelationID(), is(message.getJMSMessageID()));
            JmsUtils.closeMessageProducer(producer);
            JmsUtils.closeMessageConsumer(consumer);
            return response != null ? response.getText() : null;
        }
    }, true);
    return resultString;
}