Example usage for javax.jms MessageConsumer receiveNoWait

List of usage examples for javax.jms MessageConsumer receiveNoWait

Introduction

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

Prototype


Message receiveNoWait() throws JMSException;

Source Link

Document

Receives the next message if one is immediately available.

Usage

From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java

@Test
public void testMessageConsumer() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=true");
    ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory);
    Connection connection = null;
    Session session = null;// w ww  . jav a2  s. c o m
    MessageConsumer consumer = null;
    try {
        connection = connectionFactory.createConnection();
        assertEquals(1, connectionFactory.getActiveConnectionCount());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertEquals(1, connectionFactory.getActiveSessionCount());
        Destination myQueue = session.createQueue("test-queue");
        consumer = session.createConsumer(myQueue);

        assertEquals(1, connectionFactory.getActiveMessageConsumerCount());

        consumer.receiveNoWait();

        assertEquals(0, connectionFactory.getActiveMessageProducerCount());
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
        assertEquals(0, connectionFactory.getActiveMessageConsumerCount());
        JmsUtils.closeSession(session);
        assertEquals(0, connectionFactory.getActiveSessionCount());
        JmsUtils.closeConnection(connection);
        assertEquals(0, connectionFactory.getActiveConnectionCount());
    }
}

From source file:com.ccc.ccm.client.JMSTemplateAutowired.java

/**
* Actually receive a message from the given consumer.
* @param consumer the JMS MessageConsumer to receive with
* @param timeout the receive timeout//from  ww w . ja  va2  s.  c  o  m
* @return the JMS Message received, or <code>null</code> if none
* @throws JMSException if thrown by JMS API methods
*/
private Message doReceive(MessageConsumer consumer, long timeout) throws JMSException {
    if (timeout == RECEIVE_TIMEOUT_NO_WAIT) {
        return consumer.receiveNoWait();
    } else if (timeout > 0) {
        return consumer.receive(timeout);
    } else {
        return consumer.receive();
    }
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcherTests.java

private void runTest(JmsDispatcherProperties connectorProperties, final int numMessagesToSend,
        final int numMessagesExpected) throws Exception {
    DonkeyDao dao = new PassthruDaoFactory().getDao();
    long messageIdSequence = 1;
    Destination destination;/*  ww w  . ja v a 2  s.c om*/

    if (connectorProperties.isUseJndi()) {
        destination = (Destination) initialContext.lookup(connectorProperties.getDestinationName());
    } else {
        if (connectorProperties.isTopic()) {
            destination = session.createTopic(connectorProperties.getDestinationName());
        } else {
            destination = session.createQueue(connectorProperties.getDestinationName());
        }
    }

    MessageConsumer consumer = session.createConsumer(destination);

    DestinationConnector connector = new TestJmsDispatcher(TEST_CHANNEL_ID, 1, connectorProperties);
    connector.onDeploy();
    connector.start();

    for (int i = 0; i < numMessagesToSend; i++) {
        ConnectorMessage message = new ConnectorMessage();
        message.setMessageId(messageIdSequence++);
        message.setChannelId(TEST_CHANNEL_ID);
        message.setChainId(1);
        message.setServerId(TEST_SERVER_ID);

        MessageContent rawContent = new MessageContent(message.getChannelId(), message.getMessageId(),
                message.getMetaDataId(), ContentType.RAW, TEST_HL7_MESSAGE, "HL7", false);
        MessageContent encodedContent = SerializationUtils.clone(rawContent);
        encodedContent.setContentType(ContentType.ENCODED);

        message.setRaw(rawContent);
        message.setEncoded(encodedContent);
        message.setStatus(Status.TRANSFORMED);

        connector.process(dao, message, Status.RECEIVED);
    }

    connector.stop();
    connector.onUndeploy();
    dao.close();

    Message message = null;
    int numMessagesReceived = 0;

    while (null != (message = consumer.receiveNoWait())) {
        assertTrue((message instanceof TextMessage));
        assertEquals(TEST_HL7_MESSAGE, ((TextMessage) message).getText());
        numMessagesReceived++;
    }

    assertEquals(numMessagesExpected, numMessagesReceived);
    consumer.close();
}

From source file:com.mirth.connect.connectors.jms.test.JmsDispatcherTests.java

private void runTest(JmsDispatcherProperties connectorProperties, final int numMessagesToSend,
        final int numMessagesExpected) throws Exception {
    DonkeyDao dao = new PassthruDaoFactory().getDao();
    long messageIdSequence = 1;
    Destination destination;/*from   w w w  .  ja  va 2 s  . c  o  m*/

    if (connectorProperties.isUseJndi()) {
        destination = (Destination) initialContext.lookup(connectorProperties.getDestinationName());
    } else {
        if (connectorProperties.isTopic()) {
            destination = session.createTopic(connectorProperties.getDestinationName());
        } else {
            destination = session.createQueue(connectorProperties.getDestinationName());
        }
    }

    MessageConsumer consumer = session.createConsumer(destination);

    DestinationConnector connector = new TestJmsDispatcher(TEST_CHANNEL_ID, TEST_SERVER_ID, 1,
            connectorProperties);
    connector.onDeploy();
    connector.start();

    for (int i = 0; i < numMessagesToSend; i++) {
        ConnectorMessage message = new ConnectorMessage();
        message.setMessageId(messageIdSequence++);
        message.setChannelId(TEST_CHANNEL_ID);
        message.setChainId(1);
        message.setServerId(TEST_SERVER_ID);

        MessageContent rawContent = new MessageContent(message.getChannelId(), message.getMessageId(),
                message.getMetaDataId(), ContentType.RAW, TEST_HL7_MESSAGE, "HL7", false);
        MessageContent encodedContent = SerializationUtils.clone(rawContent);
        encodedContent.setContentType(ContentType.ENCODED);

        message.setRaw(rawContent);
        message.setEncoded(encodedContent);
        message.setStatus(Status.TRANSFORMED);

        connector.process(dao, message, Status.RECEIVED);
    }

    connector.stop();
    connector.onUndeploy();
    dao.close();

    Message message = null;
    int numMessagesReceived = 0;

    while (null != (message = consumer.receiveNoWait())) {
        assertTrue((message instanceof TextMessage));
        assertEquals(TEST_HL7_MESSAGE, ((TextMessage) message).getText());
        numMessagesReceived++;
    }

    assertEquals(numMessagesExpected, numMessagesReceived);
    consumer.close();
}

From source file:nl.nn.adapterframework.jms.PullingJmsListener.java

/** 
 * @see nl.nn.adapterframework.core.IPostboxListener#retrieveRawMessage(java.lang.String, java.util.Map)
 *//*  w w w .  ja va 2s. co m*/
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.activemq.apollo.JmsQueueBrowserTest.java

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();//from   w  ww.  j  a  v a 2  s  .  com

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();

    List<Message> messages = new ArrayList<Message>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }

    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }

    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > 200);

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from
 * other tests may still exist from other tests' runs.
 * <p/>/*from  ww  w .j a  v a  2  s  . c o m*/
 * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones.
 * @param destination destination name without any protocol specifics
 */
protected void purge(final String destination) throws JMSException {
    Connection c = null;
    Session s = null;
    try {
        logger.debug("purging queue : " + destination);
        c = getConnection(false, false);
        assertNotNull(c);
        c.start();

        s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination d = s.createQueue(destination);
        MessageConsumer consumer = s.createConsumer(d);

        while (consumer.receiveNoWait() != null) {
            logger.debug("Destination " + destination + " isn't empty, draining it");
        }
    } catch (Exception e) {
        logger.error("unable to purge : " + destination);
    } finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic//from   w w w . j  a va 2 s  .  c om
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}

From source file:org.wso2.andes.systest.TestingBaseCase.java

/**
 * Perform the Main test of a topic Consumer with the given AckMode.
 *
 * Test creates a new connection and sets up the connection to prevent
 * failover//w w w. j a  v a 2s. c o m
 *
 * A new consumer is connected and started so that it will prefetch msgs.
 *
 * An asynchrounous publisher is started to fill the broker with messages.
 *
 * We then wait to be notified of the disconnection via the ExceptionListener
 *
 * 0-10 does not have the same notification paths but sync() apparently should
 * give us the exception, currently it doesn't, so the test is excluded from 0-10
 *
 * We should ensure that this test has the same path for all protocol versions.
 *
 * Clients should not have to modify their code based on the protocol in use.
 *
 * @param ackMode @see javax.jms.Session
 *
 * @throws Exception
 */
protected void topicConsumer(int ackMode, boolean durable) throws Exception {
    Connection connection = getConnection();

    connection.setExceptionListener(this);

    Session session = connection.createSession(ackMode == Session.SESSION_TRANSACTED, ackMode);

    _destination = session.createTopic(getName());

    MessageConsumer consumer;

    if (durable) {
        consumer = session.createDurableSubscriber(_destination, getTestQueueName());
    } else {
        consumer = session.createConsumer(_destination);
    }

    connection.start();

    // Start the consumer pre-fetching
    // Don't care about response as we will fill the broker up with messages
    // after this point and ensure that the client is disconnected at the
    // right point.
    consumer.receiveNoWait();
    startPublisher(_destination);

    boolean disconnected = _disconnectionLatch.await(DISCONNECTION_WAIT, TimeUnit.SECONDS);

    assertTrue("Client was not disconnected", disconnected);
    assertTrue("Client was not disconnected.", _connectionException != null);

    Exception linked = _connectionException.getLinkedException();

    _publisher.join(JOIN_WAIT);

    assertFalse("Publisher still running", _publisher.isAlive());

    //Validate publishing occurred ok
    if (_publisherError != null) {
        throw _publisherError;
    }

    // NOTE these exceptions will need to be modeled so that they are not
    // 0-8 specific. e.g. JMSSessionClosedException

    assertNotNull("No error received onException listener.", _connectionException);

    assertNotNull("No linked exception set on:" + _connectionException.getMessage(), linked);

    assertTrue("Incorrect linked exception received.", linked instanceof AMQException);

    AMQException amqException = (AMQException) linked;

    assertEquals("Channel was not closed with correct code.", AMQConstant.RESOURCE_ERROR,
            amqException.getErrorCode());
}