Example usage for javax.jms MessageConsumer close

List of usage examples for javax.jms MessageConsumer close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the message consumer.

Usage

From source file:ConsumerTool.java

protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer,
        long timeout) throws JMSException, IOException {
    System.out.println(/*from w w w . ja  v  a2s  .c  om*/
            "[" + this.getName() + "] We will consume messages while they continue to be delivered within: "
                    + timeout + " ms, and then we will shutdown");

    Message message;
    while ((message = consumer.receive(timeout)) != null) {
        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:dk.netarkivet.common.distribute.JMSConnection.java

/**
 * Remove a messagelistener from a channel (a queue or a topic).
 *
 * @param ml          A specific MessageListener
 * @param channelName a channelname/*from  www. jav a2s.c o  m*/
 */
private void removeListener(MessageListener ml, String channelName) {
    String errMsg = "JMS-error - could not remove Listener from " + "queue/topic: " + channelName;
    int tries = 0;
    Exception lastException = null;
    boolean operationSuccessful = false;

    log.info("Removing listener from channel '" + channelName + "'");
    while (!operationSuccessful && tries < JMS_MAXTRIES) {
        try {
            tries++;
            connectionLock.readLock().lock();
            try {
                MessageConsumer messageConsumer = getConsumer(channelName, ml);
                messageConsumer.close();
                consumers.remove(getConsumerKey(channelName, ml));
                listeners.remove(getConsumerKey(channelName, ml));
            } finally {
                connectionLock.readLock().unlock();
            }
            operationSuccessful = true;
        } catch (JMSException e) {
            lastException = e;
            log.debug("Remove  listener failed (try " + tries + ")", e);
            onException(e);
            log.debug("Will and sleep a while before trying to remove" + " listener again");
            TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
        } catch (Exception e) {
            lastException = e;
            log.debug("Remove  listener failed (try " + tries + ")", e);
            reconnect();
            log.debug("Will and sleep a while before trying to remove" + " listener again");
            TimeUtils.exponentialBackoffSleep(tries, Calendar.MINUTE);
        }
    }
    if (!operationSuccessful) {
        log.warn(errMsg, lastException);
        throw new IOFailure(errMsg, lastException);
    }
}

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 w  w  w .  j  a  v  a  2s . c  o  m*/
 * @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:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf,
        String name) throws NamingException, JMSException, InterruptedException {
    AtomicInteger totalReceived = new AtomicInteger(0);
    System.out.printf("Subscription %s: \n", name);

    Destination subscription = (Destination) context.lookup(name);
    // Create Connection
    Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
    connection.start();//  www  . j  a v a 2s . co m
    // Create Session, no transaction, client ack
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // Create consumer
    MessageConsumer consumer = session.createConsumer(subscription);
    // Set callback listener. Gets called for each received message.
    consumer.setMessageListener(message -> {
        try {
            System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter
                    message.getJMSMessageID());
            message.acknowledge();
        } catch (Exception e) {
            System.out.printf("%s", e.toString());
        }
    });

    // wait on the main thread until all sent messages have been received
    while (totalReceived.get() < totalSend) {
        Thread.sleep(1000);
    }
    consumer.close();
    session.close();
    connection.stop();
    connection.close();
}

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++;/*  w w  w  . j  av a 2s . c  o m*/
            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:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Comsume messages and close the connection. */
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer,
        long timeout) throws JMSException, IOException {
    LOG.info("[" + this.getName() + "] consume messages while continue to be delivered within: " + timeout
            + " ms, and then we will shutdown");
    Message message;//from   www  .java 2s  .c  om
    while ((message = consumer.receive(timeout)) != null) {
        onMessage(message);
    }
    LOG.info("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
}

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

/** Comsumer messages and close the connection.
 * @throws IOException,JMSException/*  w  w w  . ja v a  2  s .c om*/
 */
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer)
        throws JMSException, IOException {
    LOG.info("[" + 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++;
            onMessage(message);
        }
    }
    LOG.info("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
    if (pauseBeforeShutdown) {
        LOG.info("[" + this.getName() + "] Press return to shut down");
        // System.in.read();
    }
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*from ww w . j a v  a2  s.  c  o m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // wait on the main thread until all sent messages have been received
        while (totalReceived.get() < totalSend) {
            Thread.sleep(1000);
        }
        consumer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception/*  ww  w. j  a v  a2s  .c o m*/
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {//from   w ww  . ja  va  2 s .  com
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

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