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.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();//from  w ww .  j ava2s .c o m

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

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);

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

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

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

    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();

}

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

private void startAsyncConsumerOn(Destination queue, Connection asyncConnection,
        final CountDownLatch requiredNumberOfMessagesRead, final AtomicInteger totalConsumed) throws Exception {
    Session session = asyncConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    consumer.setMessageListener(new MessageListener() {

        @Override/*  w  w  w.j av  a2 s.  c  o m*/
        public void onMessage(Message arg0) {
            totalConsumed.incrementAndGet();
            requiredNumberOfMessagesRead.countDown();
        }
    });
}

From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Try to use ActiveMQ StatisticsPlugin to get size and if that fails
 * fallback to {@link JMSMailQueue#getSize()}
 *//*from w  w  w.  ja v a 2s.c  o  m*/
@Override
public long getSize() throws MailQueueException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    TemporaryQueue replyTo = null;
    long size = -1;

    try {
        connection = connectionFactory.createConnection();
        connection.start();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        replyTo = session.createTemporaryQueue();
        consumer = session.createConsumer(replyTo);

        Queue myQueue = session.createQueue(queuename);
        producer = session.createProducer(null);

        String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName();
        Queue query = session.createQueue(queueName);

        Message msg = session.createMessage();
        msg.setJMSReplyTo(replyTo);
        producer.send(query, msg);
        MapMessage reply = (MapMessage) consumer.receive(2000);
        if (reply != null && reply.itemExists("size")) {
            try {
                size = reply.getLong("size");
                return size;
            } catch (NumberFormatException e) {
                // if we hit this we can't calculate the size so just catch
                // it
            }
        }

    } catch (Exception e) {
        throw new MailQueueException("Unable to remove mails", e);

    } finally {

        if (consumer != null) {

            try {
                consumer.close();
            } catch (JMSException e1) {
                e1.printStackTrace();
                // ignore on rollback
            }
        }

        if (producer != null) {

            try {
                producer.close();
            } catch (JMSException e1) {
                // ignore on rollback
            }
        }

        if (replyTo != null) {
            try {

                // we need to delete the temporary queue to be sure we will
                // free up memory if thats not done and a pool is used
                // its possible that we will register a new mbean in jmx for
                // every TemporaryQueue which will never get unregistered
                replyTo.delete();
            } catch (JMSException e) {
            }
        }
        try {
            if (session != null)
                session.close();
        } catch (JMSException e1) {
            // ignore here
        }

        try {
            if (connection != null)
                connection.close();
        } catch (JMSException e1) {
            // ignore here
        }
    }

    // if we came to this point we should just fallback to super method
    return super.getSize();
}

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();//w w w .j  a v  a 2 s .  c o m

    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.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java

@Activate
@Modified/* www.ja v a 2  s.co  m*/
protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = PropertiesUtil.toInteger(props.get(MAX_RETRIES), -1);
    if (_maxRetries > -1) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = PropertiesUtil.toInteger(props.get(RETRY_INTERVAL), -1);
    if (_retryInterval > -1) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = PropertiesUtil.toInteger(props.get(SMTP_PORT), -1);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = PropertiesUtil.toString(props.get(SMTP_SERVER), "");
    if (!StringUtils.isBlank(_smtpServer)) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _replyAsAddress = PropertiesUtil.toString(props.get(REPLY_AS_ADDRESS), "");
    if (!StringUtils.isBlank(_replyAsAddress)) {
        if (diff(replyAsAddress, _replyAsAddress)) {
            replyAsAddress = _replyAsAddress;
        }
    } else {
        LOGGER.error("No reply-as email address set");
    }

    String _replyAsName = PropertiesUtil.toString(props.get(REPLY_AS_NAME), "");
    if (!StringUtils.isBlank(_replyAsName)) {
        if (diff(replyAsName, _replyAsName)) {
            replyAsName = _replyAsName;
        }
    } else {
        LOGGER.error("No reply-as email name set");
    }

    useTls = PropertiesUtil.toBoolean(props.get(SMTP_USE_TLS), false);
    useSsl = PropertiesUtil.toBoolean(props.get(SMTP_USE_SSL), false);
    authUser = PropertiesUtil.toString(props.get(SMTP_AUTH_USER), "");
    authPass = PropertiesUtil.toString(props.get(SMTP_AUTH_PASS), "");

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to retrieve message from specified message queue
 *
 * @param queueName Name of the queue//from  w ww .jav a 2 s .  c  o  m
 * @param timeout Timeout value (in milliseconds)
 * @return Retrieved message from the queue
 * @throws JMSException if error occurred
 */
public Message consumeMessageFromQueue(String queueName, long timeout) throws JMSException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

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

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageConsumer from the Session to the Topic or Queue
        consumer = session.createConsumer(destination);

        // Wait for a message
        return consumer.receive(timeout);

    } finally {
        if (consumer != null) {
            consumer.close();
        }
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;
    Destination orderQueue;//from   w w  w. j a va2  s  .c o  m
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

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

}

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();//from  ww 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.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/*from  ww w .  java2  s.  co m*/
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyDeliveringStats(defaultQueueName, 0, 0);

    MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
    Message msg = consumer.receive();
    verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
    msg.acknowledge();

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyDeliveringStats(defaultQueueName, 0, 0);

    connection.close();
}

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

public Message receive(Scenario scenario) throws Exception {
    assertNotNull("scenario is null!", scenario);
    Connection connection = null;
    try {// www .  j a va  2 s  . c  o  m
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createOutputDestination(session, scenario);
            MessageConsumer consumer = null;
            try {
                consumer = session.createConsumer(destination);
                return scenario.receive(session, consumer);
            } finally {
                if (consumer != null) {
                    consumer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}