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:org.openanzo.combus.bayeux.BridgeConnectionManager.java

/**
 * Handle a single Bayeux client disconnecting from the server. This closes the client's state like its JSM temporary topic and consumer and removes the
 * client's subscriptions to any graph update topics.
 * //ww w  . jav  a 2 s  . c o m
 * @param clientId
 */
protected void disconnectClient(String clientId) {
    if (log.isDebugEnabled()) {
        log.debug(LogUtils.COMBUS_MARKER, "Disconnecting:{} ", clientId);
    }

    // Avoid a deadlock by not doing JMS operations while holding mapLock.
    // We instead gather up the references we need and close them after releasing mapLock.
    List<MessageConsumer> consumersToClose = Collections.emptyList();
    TemporaryTopic topicToClose = null;
    MessageConsumer tempTopicConsumerToClose = null;
    String username = null;
    String errorMsg = "Error while disconnecting:" + clientId;

    mapLock.lock();
    try {
        ClientState state = clientIdToClientState.get(clientId);
        if (state != null) {
            username = state.principal.getName();
            errorMsg += username + "/" + clientId;

            topicToClose = state.topic;
            tempTopicConsumerToClose = state.consumer;

            try {
                tempDestinationToClientState.remove(state.topic.getTopicName());
            } catch (JMSException e) {
                log.warn(LogUtils.COMBUS_MARKER, errorMsg, e);
            }

            if (state.topicSubscriptions.size() > 0) {
                consumersToClose = new ArrayList<MessageConsumer>(state.topicSubscriptions.size());
                for (String topic : state.topicSubscriptions) {
                    MessageConsumer consumer = unsubscribeTopic(topic, state.clientId);
                    consumersToClose.add(consumer);
                }
            }
            state.topicSubscriptions.clear();

            clientIdToClientState.remove(clientId);
        }
    } finally {
        mapLock.unlock();
    }

    // Now actually destroy the JMS state since we're no longer holding mapLock.
    for (MessageConsumer consumer : consumersToClose) {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (NullPointerException npe) {
                //Catch exception due to defect within activemq's ActiveMQMessageConsumer.dispose() method
            } catch (JMSException e) {
                log.warn(LogUtils.COMBUS_MARKER, errorMsg, e);
            }
        }
    }
    cleanupTemporaryTopic(topicToClose, tempTopicConsumerToClose, username, clientId);
}

From source file:org.openanzo.combus.bayeux.BridgeConnectionManager.java

/**
 * Closes the given consumer with some exception handling to handle an ActiveMQ bug. WARNING: This method make JMS calls so don't call this method while
 * holding mapLock due to possible deadlock.
 * /*from   w  w  w  . jav  a  2s . com*/
 * @param consumer
 */
private void closeMessageConsumer(MessageConsumer consumer) {
    if (consumer != null) {
        try {
            consumer.close();
        } catch (NullPointerException npe) {

        } catch (JMSException jmsex) {
            log.warn(LogUtils.COMBUS_MARKER, "Error unsubscribing from graph updates.", jmsex);
        }
    }
}

From source file:org.openanzo.combus.CombusConnection.java

/**
 * Unregister topic//from   w w  w.j av a 2s  .c o m
 * 
 * @param topic
 *            topic to unregister
 * @throws AnzoException
 */
public void unregisterTopicListener(String topic) throws AnzoException {
    if (connected) {
        synchronized (topicConsumer) {
            MessageConsumer consumer = topicConsumer.remove(topic);
            if (consumer != null) {
                try {
                    try {
                        consumer.close();
                    } catch (NullPointerException npe) {
                        //Catch exception due to defect within activemq's ActiveMQMessageConsumer.dispose() method
                        if (log.isTraceEnabled()) {
                            log.trace(LogUtils.COMBUS_MARKER, "NPE due to activemq dispose issue", npe);
                        }
                    }
                } catch (JMSException jmsex) {
                    log.debug(LogUtils.COMBUS_MARKER, Messages.formatString(
                            ExceptionConstants.COMBUS.ERROR_PROCESSING_MESSGE, "unregister topic"), jmsex);
                    throw new AnzoException(ExceptionConstants.COMBUS.NOT_AUTHORIZED_FOR_TOPIC, jmsex, userName,
                            topic);
                }
            }
        }
    }
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

/**
 * Private function to get a message or none if there is an error.
 *
 * @param destinationId//from  w w  w  . jav a  2s  .  co m
 *          The destination queue or topic to pull the message from.
 * @param type
 *          The type of the destination either queue or topic.
 * @return A message or none if there was a problem getting the message.
 */
private Option<Message> waitForMessage(String destinationId, DestinationType type) {
    MessageConsumer consumer = null;
    try {

        // Create the destination (Topic or Queue)
        Destination destination;
        if (type.equals(DestinationType.Queue)) {
            destination = getSession().createQueue(destinationId);
        } else {
            destination = getSession().createTopic(destinationId);
        }

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

        // Wait for a message
        Message message = consumer.receive();
        return Option.option(message);
    } catch (JMSException e) {
        if (e instanceof javax.jms.IllegalStateException || e.getCause() instanceof InterruptedException
                || e.getCause() instanceof InterruptedIOException) {
            // Swallowing the shutdown exception
            logger.trace("Shutting down message receiver {}", ExceptionUtils.getStackTrace(e));
        } else {
            logger.error("Unable to receive messages {}", ExceptionUtils.getStackTrace(e));
        }
        return Option.<Message>none();
    } finally {
        try {
            if (consumer != null) {
                consumer.close();
            }
        } catch (JMSException e) {
            logger.error("Unable to close connections after receipt of message {}",
                    ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.sample.jms.SampleQueueReceiver.java

public void receiveMessages(MessageConsumer consumer) throws NamingException, JMSException {

    PropertyConfigurator.configure("log4j.properties");

    //Receive all the message
    while (consumer.receive() != null) {
        messageCount++;/*from w w w .  j  a va2s .  c o  m*/

    }

    consumer.close();
    queueSession.close();
    queueConnection.stop();
    queueConnection.close();
}

From source file:org.springframework.jms.support.JmsUtils.java

/**
 * Close the given JMS MessageConsumer and ignore any thrown exception.
 * This is useful for typical {@code finally} blocks in manual JMS code.
 * @param consumer the JMS MessageConsumer to close (may be {@code null})
 *///  w  w  w . j a  v a  2  s .  c  o m
public static void closeMessageConsumer(@Nullable MessageConsumer consumer) {
    if (consumer != null) {
        // Clear interruptions to ensure that the consumer closes successfully...
        // (working around misbehaving JMS providers such as ActiveMQ)
        boolean wasInterrupted = Thread.interrupted();
        try {
            consumer.close();
        } catch (JMSException ex) {
            logger.trace("Could not close JMS MessageConsumer", ex);
        } catch (Throwable ex) {
            // We don't trust the JMS provider: It might throw RuntimeException or Error.
            logger.trace("Unexpected exception on closing JMS MessageConsumer", ex);
        } finally {
            if (wasInterrupted) {
                // Reset the interrupted flag as it was before.
                Thread.currentThread().interrupt();
            }
        }
    }
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public Message receive(Channel channel, long timeout) throws Exception {
    Message ret = null;/* w  w w .  ja v a 2  s .c  om*/
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        javax.jms.MessageConsumer consumer = m_session.createConsumer(queue);

        javax.jms.Message m = consumer.receive(timeout);

        consumer.close();

        if (m instanceof javax.jms.ObjectMessage) {
            ret = (Message) ((javax.jms.ObjectMessage) m).getObject();
        }
    } else if (m_closed == false) {
        throw new Exception("Unable to find queue for channel");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Receive (timeout " + timeout + ") on channel " + channel + " = " + ret);
    }

    return (ret);
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public Message receiveNoWait(Channel channel) throws Exception {
    Message ret = null;//from w  ww  . j av  a  2 s .c o  m
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        javax.jms.MessageConsumer consumer = m_session.createConsumer(queue);

        javax.jms.Message m = consumer.receive(5);

        if (m instanceof javax.jms.ObjectMessage) {
            ret = (Message) ((javax.jms.ObjectMessage) m).getObject();
        }

        consumer.close();

    } else {
        throw new Exception("Unable to find queue for channel");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Receive (no wait) on channel " + channel + " = " + ret);
    }

    return (ret);
}

From source file:org.wso2.carbon.bpmn.extensions.jms.JMSMessageSender.java

/**
 * Creating a temporary  Queue Consumer; The purpose of this is to make
 * a binding for this destination in the message broker. If there is no
 * bindings created in the server before sending messages, messages will not
 * be stored in the server. So we create a consumer and close it, if there
 * are no bindings already created in the server
 *
 * *///from   ww  w. j  a  v a  2  s.  c  om
public void createTempQueueConsumer() throws JMSException {
    MessageConsumer consumer = ((QueueSession) session).createConsumer((Destination) destination);
    consumer.close();
}

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  w  w .  jav  a  2s  .  c  om
 * @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();
        }
    }
}