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.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testTransactedSessionWithUnackMessages() throws Exception {
    _connection = getConnection();/*from  ww w  . j av a2s  .c  o  m*/
    _connection.start();

    boolean transactional = true;
    int numberOfMessages = 2;
    final Session session = _connection.createSession(transactional, Session.SESSION_TRANSACTED);
    final Destination destination = session.createQueue(getTestQueueName());
    final MessageConsumer consumer = session.createConsumer(destination);

    sendMessage(session, destination, numberOfMessages);
    receiveMessagesWithoutCommit(consumer, numberOfMessages);

    final ManagedConnection mBean = getConnectionMBean();
    final CompositeDataSupport row = getTheOneChannelRow(mBean);
    boolean flowBlocked = false;
    assertChannelRowData(row, numberOfMessages, transactional, flowBlocked);

    // check that commit advances the lastIoTime
    final Date initialLastIOTime = mBean.getLastIoTime();
    session.commit();
    assertTrue("commit should have caused last IO time to advance",
            mBean.getLastIoTime().after(initialLastIOTime));

    // check that channels() now returns one session with no unacknowledged messages
    final CompositeDataSupport rowAfterCommit = getTheOneChannelRow(mBean);
    final Number unackCountAfterCommit = (Number) rowAfterCommit.get(ManagedConnection.UNACKED_COUNT);
    assertEquals("Unexpected number of unacknowledged messages", 0, unackCountAfterCommit);
}

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

/**
 * Tests if the consumer receives the messages that were sent before the
 * connection was started.//from   www  .  j a  va 2  s .  c  o 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.logicblaze.lingo.jmx.remote.jms.activemq.ActiveMQServerListenerInfo.java

ActiveMQServerListenerInfo(String id, Map holder, Destination replyTo, Session session) throws JMSException {
    this.id = id;
    this.holder = holder;
    this.replyTo = replyTo;
    this.session = session;
    this.producer = session.createProducer(replyTo);
    Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic((ActiveMQDestination) replyTo);
    advisoryConsumer = session.createConsumer(advisoryTopic);
    advisoryConsumer.setMessageListener(this); //
}

From source file:org.logicblaze.lingo.jmx.remote.jms.ServerListenerInfo.java

ServerListenerInfo(String id, Map holder, Destination replyTo, Session session) throws JMSException {
    this.id = id;
    this.holder = holder;
    this.replyTo = replyTo;
    this.session = session;
    this.producer = session.createProducer(replyTo);
    Topic advisoryTopic = AdvisorySupport.getConsumerAdvisoryTopic((ActiveMQDestination) replyTo);
    advisoryConsumer = session.createConsumer(advisoryTopic);
    advisoryConsumer.setMessageListener(this);
}

From source file:org.apache.activemq.network.MQTTNetworkOfBrokersFailoverTest.java

private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);

    URI brokerUri = broker.getVmConnectorURI();

    final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString());
    final Connection connection = cf.createConnection();
    connection.start();/*from  www  .ja  va  2  s .  c  om*/
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination dest = session
            .createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar");
    MessageConsumer consumer = session.createConsumer(dest);
    consumer.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            latch.countDown();
            // shutdown this connection
            Dispatch.getGlobalQueue().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        session.close();
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    });

    return latch;
}

From source file:ubic.gemma.job.grid.util.JMSBrokerMonitorImpl.java

private MapMessage sendTaskSubmissionQueueDiagnosticMessage() throws JMSException {
    MapMessage reply = jmsTemplate.execute(new SessionCallback<MapMessage>() {
        @Override/* w ww .  j  a v  a2  s .c  o m*/
        public MapMessage doInJms(Session session) throws JMSException {
            Queue replyTo = session.createTemporaryQueue();
            Message message = session.createMessage();
            message.setJMSReplyTo(replyTo);
            Queue queryQueue = session.createQueue("ActiveMQ.Statistics.Destination.tasks.submit");
            MessageProducer producer = session.createProducer(queryQueue);
            MessageConsumer consumer = session.createConsumer(replyTo);
            producer.send(message);
            return (MapMessage) consumer.receive(5000);
        }
    }, true);
    return reply;
}

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;
    MessageConsumer consumer = null;//  w  ww.  java  2  s  . com
    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:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;/*from  w  w  w  . j  a v  a2s.c  o  m*/
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

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

/**
 * WARNING - starts infinite loop - you have to kill 
 * @param uri/*from   ww  w .j a  v  a  2s . co  m*/
 * @param submitQName
 * @param statusTName
 * @param statusQName
 * @throws Exception
 */
private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName)
        throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(submitQName);

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    System.out.println("Starting consumer for submissions to queue " + submitQName);
    while (isActive()) { // You have to kill it or call stop() to stop it!

        try {

            // Consumes messages from the queue.
            Message m = consumer.receive(1000);
            if (m != null) {

                // TODO FIXME Check if we have the max number of processes
                // exceeded and wait until we dont...

                TextMessage t = (TextMessage) m;
                ObjectMapper mapper = new ObjectMapper();

                final StatusBean bean = mapper.readValue(t.getText(), getBeanClass());

                if (bean != null) { // We add this to the status list so that it can be rendered in the UI

                    if (!isHandled(bean))
                        continue; // Consume it and move on

                    // Now we put the bean in the status queue and we 
                    // start the process
                    RemoteSubmission factory = new RemoteSubmission(uri);
                    factory.setLifeTime(t.getJMSExpiration());
                    factory.setPriority(t.getJMSPriority());
                    factory.setTimestamp(t.getJMSTimestamp());
                    factory.setQueueName(statusQName); // Move the message over to a status queue.

                    factory.submit(bean, false);

                    final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean);
                    if (process != null) {
                        if (process.isBlocking()) {
                            System.out.println("About to run job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                        processCount++;
                        process.start();
                        if (process.isBlocking()) {
                            System.out.println(
                                    "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")");
                        } else {
                            System.out.println("Started job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                    }

                }
            }

        } catch (Throwable ne) {
            // Really basic error reporting, they have to pipe to file.
            ne.printStackTrace();
            setActive(false);
        }
    }

}

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/* ww w . ja  v a  2s  .co  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());
}