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:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void subscribe(final String topicName, final MessageListener listener) {
    String topicName2 = null;//w w  w  . ja v  a2  s. c  o  m
    checkArgument(isNotBlank(topicName2 = trimToEmpty(topicName)), "Uninitialized or invalid topic");
    checkNotNull(listener);
    TopicConnection conn = null;
    TopicSession session = null;
    MessageConsumer consumer = null;
    try {
        conn = broker().getConsumersConnFactory().createTopicConnection();
        conn.start();
        session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(topicName2);
        consumer = session.createConsumer(topic);
        consumer.setMessageListener(listener);
        register(TopicSubscriber.builder().topicName(topicName2).connection(conn).session(session)
                .consumer(consumer).build());
        LOGGER.info("Subscribed to topic: " + topicName2);
    } catch (JMSException e) {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException ignore) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (JMSException ignore) {
            }
        }
        LOGGER.error("Failed to subscribe to topic: " + topicName2, e);
    }
}

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;//w w w .  j  a  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 .j  a v  a 2 s . co 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:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Try to use ActiveMQ StatisticsPlugin to get size and if that fails
 * fallback to {@link JMSMailQueue#getSize()}
 *//*w w w. ja  va2 s. co  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:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) {
    String ip = null;//from w  w  w. j  av a2 s  . co  m
    try {
        ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.severe("Unable to get localhost IP address.");
    }

    String ltopic = getTopic();
    if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null
            && provider.getBroker() != null) {
        log.info("Waiting for message with selector: " + selector);
        Connection connection = null;
        MessageConsumer consumer = null;
        try {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.setClientID(ip + "_" + UUID.randomUUID().toString());
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic destination = session.createTopic(ltopic);

            consumer = session.createConsumer(destination, selector);

            Message message = consumer.receive(timeout * 60 * 1000);
            if (message != null) {
                String value = getMessageBody(message);
                if (build != null) {
                    if (StringUtils.isNotEmpty(variable)) {
                        EnvVars vars = new EnvVars();
                        vars.put(variable, value);
                        build.addAction(new CIEnvironmentContributingAction(vars));

                    }
                }
                log.info("Received message with selector: " + selector + "\n" + formatMessage(message));
                return value;
            }
            log.info("Timed out waiting for message!");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (Exception e) {
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        }
    } else {
        log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker.");
    }
    return null;
}

From source file:com.legstar.mq.client.AbstractCicsMQ.java

/**
 * A response is serialized as a header message part followed by data
 * message parts. This method creates a response message for the request.
 * <p/>// www . j  av a 2s  .c  o m
 * The reply is correlated to the request by means of the JMS message ID
 * that was generated when we sent the request. That ID was attached to the
 * request object.
 * 
 * @param request the request being serviced
 * @throws RequestException if receive fails
 */
public void recvResponse(final LegStarRequest request) throws RequestException {

    MessageConsumer consumer = null;
    try {
        String selector = "JMSCorrelationID='" + new String(request.getAttachment()) + "'";
        if (_log.isDebugEnabled()) {
            _log.debug("Receiving response for Request:" + request.getID() + " on Connection:" + _connectionID
                    + ". Selector: " + selector);
        }

        consumer = getJmsQueueSession().createConsumer(getJmsReplyQueue(), selector);
        Message jmsMessage = consumer.receive(getCicsMQEndpoint().getReceiveTimeout());
        if (!(jmsMessage instanceof BytesMessage)) {
            throw new RequestException("Message received does not contain bytes");
        }
        BytesMessage message = (BytesMessage) jmsMessage;
        message.reset();

        /* Check that data length makes sense */
        long dataLength = message.getBodyLength();
        if (dataLength > Integer.MAX_VALUE) {
            throw new RequestException("Size of BytesMessage exceeds Integer.MAX_VALUE");
        }

        request.setResponseMessage(createReplyMessage(message, (int) dataLength));

        _lastUsedTime = System.currentTimeMillis();
        if (_log.isDebugEnabled()) {
            _log.debug("Received response for Request:" + request.getID() + " on Connection:" + _connectionID
                    + ". Selector: " + selector);
        }
    } catch (JMSException e) {
        throw new RequestException(e);
    } catch (HostReceiveException e) {
        throw new RequestException(e);
    } finally {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException e) {
                _log.error(e);
            }
        }
    }

}

From source file:net.timewalker.ffmq4.common.session.AbstractSession.java

/**
 * Close remaining consumers/*  w ww. j a  va2  s.  c  om*/
 */
private void closeRemainingConsumers() {
    List<AbstractMessageConsumer> consumersToClose = new ArrayList<>(consumersMap.size());
    synchronized (consumersMap) {
        consumersToClose.addAll(consumersMap.values());
    }
    for (int n = 0; n < consumersToClose.size(); n++) {
        MessageConsumer consumer = consumersToClose.get(n);
        log.debug("Auto-closing unclosed consumer : " + consumer);
        try {
            consumer.close();
        } catch (Exception e) {
            log.error("Could not close consumer " + consumer, e);
        }
    }
}

From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java

public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener,
        JdbcTransactionalStorage errorStorage) {
    String result = null;/*w  w  w.  ja va2s .  com*/

    PoolingConnectionFactory jmsConnectionFactory = null;
    PoolingDataSource jdbcDataSource = null;
    BitronixTransactionManager btm = null;
    javax.jms.Connection jmsConnection = null;

    try {
        jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener);
        if (jmsConnectionFactory != null) {
            jdbcDataSource = getPoolingDataSource(errorStorage);
            if (jdbcDataSource != null) {
                String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null);
                String logDir = AppConstants.getInstance().getString("log.dir", null);
                TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm");
                TransactionManagerServices.getConfiguration()
                        .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog");
                TransactionManagerServices.getConfiguration()
                        .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog");
                btm = TransactionManagerServices.getTransactionManager();

                jmsConnection = jmsConnectionFactory.createConnection();

                Session jmsSession = null;
                MessageConsumer jmsConsumer = null;

                java.sql.Connection jdbcConnection = null;

                btm.begin();
                log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]");

                try {
                    jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                    String queueName = esbJmsListener.getPhysicalDestinationShortName();
                    Queue queue = jmsSession.createQueue(queueName);
                    jmsConsumer = jmsSession.createConsumer(queue);

                    jmsConnection.start();

                    long timeout = 30000;
                    log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout
                            + "] msec");
                    Message rawMessage = jmsConsumer.receive(timeout);

                    if (rawMessage == null) {
                        log.debug("no message found on queue [" + queueName + "]");
                    } else {
                        String id = rawMessage.getJMSMessageID();
                        log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]");
                        Serializable sobj = null;
                        if (rawMessage != null) {
                            if (rawMessage instanceof Serializable) {
                                sobj = (Serializable) rawMessage;
                            } else {
                                try {
                                    sobj = new MessageWrapper(rawMessage, esbJmsListener);
                                } catch (ListenerException e) {
                                    log.error("could not wrap non serializable message for messageId [" + id
                                            + "]", e);
                                    if (rawMessage instanceof TextMessage) {
                                        TextMessage textMessage = (TextMessage) rawMessage;
                                        sobj = textMessage.getText();
                                    } else {
                                        sobj = rawMessage.toString();
                                    }
                                }
                            }
                        }

                        jdbcConnection = jdbcDataSource.getConnection();

                        result = errorStorage.storeMessage(jdbcConnection, id, id,
                                new Date(System.currentTimeMillis()), "moved message", null, sobj);
                    }

                    log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                    btm.commit();
                } catch (Exception e) {
                    if (btm.getCurrentTransaction() != null) {
                        log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                        btm.rollback();
                    }
                    log.error("exception on receiving message and moving to errorStorage", e);
                } finally {
                    if (jdbcConnection != null) {
                        jdbcConnection.close();
                    }
                    if (jmsConnection != null) {
                        jmsConnection.stop();
                    }
                    if (jmsConsumer != null) {
                        jmsConsumer.close();
                    }
                    if (jmsSession != null) {
                        jmsSession.close();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("exception on receiving message and moving to errorStorage", e);
    } finally {
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            } catch (JMSException e) {
                log.warn("exception on closing connection", e);
            }
        }
        if (jmsConnectionFactory != null) {
            jmsConnectionFactory.close();
        }
        if (jdbcDataSource != null) {
            jdbcDataSource.close();
        }
        if (btm != null) {
            btm.shutdown();
        }
    }
    return result;
}

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

public Object getMessage(String messageId) throws ListenerException {
    Session session = null;//from w w w  .  j  a  v a 2s  .  c o  m
    Object msg = null;
    MessageConsumer mc = null;
    try {
        session = createSession();
        mc = getMessageConsumer(session, getDestination(), getCombinedSelector(messageId));
        msg = mc.receive(getTimeOut());
        return msg;
    } catch (Exception e) {
        throw new ListenerException(e);
    } finally {
        try {
            if (mc != null) {
                mc.close();
            }
        } catch (JMSException e1) {
            throw new ListenerException("exception closing message consumer", e1);
        }
        closeSession(session);
    }
}

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

public void deleteMessage(String messageId) throws ListenerException {
    Session session = null;//w w  w .j av a 2 s.  co m
    MessageConsumer mc = null;
    try {
        session = createSession();
        log.debug("retrieving message [" + messageId + "] in order to delete it");
        mc = getMessageConsumer(session, getDestination(), getCombinedSelector(messageId));
        mc.receive(getTimeOut());
    } catch (Exception e) {
        throw new ListenerException(e);
    } finally {
        try {
            if (mc != null) {
                mc.close();
            }
        } catch (JMSException e1) {
            throw new ListenerException("exception closing message consumer", e1);
        }
        closeSession(session);
    }
}