Example usage for javax.jms Connection stop

List of usage examples for javax.jms Connection stop

Introduction

In this page you can find the example usage for javax.jms Connection stop.

Prototype


void stop() throws JMSException;

Source Link

Document

Temporarily stops a connection's delivery of incoming messages.

Usage

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  v a 2s .c om

    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:org.aludratest.service.jms.impl.JmsActionImpl.java

public void close() {
    LOGGER.info("Closing JmsServcie for clientId " + this.clientId);
    for (TopicSubscriber subscriber : this.durableConsumers.values()) {
        try {//from w  ww.  j  a va2s . co m
            subscriber.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close subscriber: ", e);
        }
    }
    for (Map.Entry<String, Connection> entry : this.dynamicConnections.entrySet()) {
        try {
            Connection dynC = entry.getValue();
            dynC.stop();
            dynC.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close dynamic connection [ " + entry.getKey() + " ] : ", e);
        }
    }
    if (session != null) {
        try {
            session.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close jms session : ", e);
        }
    }
    if (connection != null) {
        try {
            connection.stop();
            connection.close();
        } catch (JMSException e) {
            LOGGER.debug("Failed to close jms connection for client-id [ " + this.clientId + " ] : ", e);
        }
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public void unsubscribeTopic(@TechnicalArgument String subscriptionName) throws JMSException {
    if (StringUtils.isEmpty(clientId)) {
        throw new IllegalArgumentException("Client-Id must be provided to unsubscribe");
    }//from  w w w  . j  a  va  2s  . c  o  m
    LOGGER.debug("Unsubscribing from subscription " + subscriptionName);
    Connection c = getDynamicConnection(subscriptionName);
    c.stop();

    TopicSubscriber subscriber = this.durableConsumers.get(subscriptionName);
    if (subscriber != null) {
        subscriber.close();
        c.createSession(false, Session.AUTO_ACKNOWLEDGE).unsubscribe(subscriptionName);
        this.durableConsumers.remove(subscriptionName);
    }
    c.close();
    this.dynamicConnections.remove(c);

}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;//  w w w.  j  av a2  s  . c  om
    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.apache.camel.component.sjms.jms.ConnectionFactoryResource.java

@Override
public void destroyObject(Connection connection) throws Exception {
    if (connection != null) {
        connection.stop();
        connection.close();/*from   www  . j av  a  2s .  c om*/
    }

}

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

public void testMoveMessagesBetweenQueuesWithActiveConsumerOnSourceQueue() throws Exception {
    setTestClientSystemProperty(ClientProperties.MAX_PREFETCH_PROP_NAME, new Integer(1).toString());
    Connection asyncConnection = getConnection();
    asyncConnection.start();/*from   www  .j  a  v  a 2s  .  c o  m*/

    final int numberOfMessagesToSend = 50;
    sendMessage(_session, _sourceQueue, numberOfMessagesToSend);
    syncSession(_session);
    assertEquals("Unexpected queue depth after send", numberOfMessagesToSend,
            _managedSourceQueue.getMessageCount().intValue());

    List<Long> amqMessagesIds = getAMQMessageIdsOn(_managedSourceQueue, 1, numberOfMessagesToSend);

    long fromMessageId = amqMessagesIds.get(0);
    long toMessageId = amqMessagesIds.get(numberOfMessagesToSend - 1);

    CountDownLatch consumerReadToHalfwayLatch = new CountDownLatch(numberOfMessagesToSend / 2);
    AtomicInteger totalConsumed = new AtomicInteger(0);
    startAsyncConsumerOn(_sourceQueue, asyncConnection, consumerReadToHalfwayLatch, totalConsumed);

    boolean halfwayPointReached = consumerReadToHalfwayLatch.await(5000, TimeUnit.MILLISECONDS);
    assertTrue("Did not read half of messages within time allowed", halfwayPointReached);

    _managedSourceQueue.moveMessages(fromMessageId, toMessageId, _destinationQueueName);

    asyncConnection.stop();

    // The exact number of messages moved will be non deterministic, as the number of messages processed
    // by the consumer cannot be predicted.  There is also the possibility that a message can remain
    // on the source queue.  This situation will arise if a message has been acquired by the consumer, but not
    // yet delivered to the client application (i.e. MessageListener#onMessage()) when the Connection#stop() occurs.
    //
    // The number of messages moved + the number consumed + any messages remaining on source should
    // *always* be equal to the number we originally sent.

    int numberOfMessagesReadByConsumer = totalConsumed.intValue();
    int numberOfMessagesOnDestinationQueue = _managedDestinationQueue.getMessageCount().intValue();
    int numberOfMessagesRemainingOnSourceQueue = _managedSourceQueue.getMessageCount().intValue();

    LOGGER.debug("Async consumer read : " + numberOfMessagesReadByConsumer
            + " Number of messages moved to destination : " + numberOfMessagesOnDestinationQueue
            + " Number of messages remaining on source : " + numberOfMessagesRemainingOnSourceQueue);
    assertEquals("Unexpected number of messages after move", numberOfMessagesToSend,
            numberOfMessagesReadByConsumer + numberOfMessagesOnDestinationQueue
                    + numberOfMessagesRemainingOnSourceQueue);
}

From source file:org.dhatim.routing.jms.activemq.ActiveMQProvider.java

private final void close(Connection conn, Session session) {
    try {/*from w w w.  ja v  a2 s  .com*/
        if (conn != null) {
            conn.stop();
            logger.debug("Stopping JMS Connection for connected session.");
        }
    } catch (Throwable e) {
        logger.debug("Failed to stop JMS connection.", e);
        conn = null;
    }
    try {
        if (session != null) {
            session.close();
            logger.debug("Closing JMS Session.");
        }
    } catch (Throwable e) {
        logger.debug("Failed to close JMS session.", e);
    } finally {
        session = null;
    }
    try {
        if (conn != null) {
            conn.close();
            logger.debug("Closing JMS Connection for connected session.");
        }
    } catch (Throwable e) {
        logger.debug("Failed to close JMS connection.", e);
    } finally {
        conn = null;
    }
}

From source file:org.eclipse.smila.connectivity.queue.worker.internal.task.impl.Send.java

/**
 * close connection if not null, catching and logging possible exceptions.
 * // w  ww  . ja v a2 s. c  om
 * @param connection
 *          a JMS conection
 */
private void closeQuietly(final Connection connection) {
    if (connection != null) {
        try {
            connection.stop();
        } catch (final Throwable e) {
            _log.error("Unable to stop connection", e);
        }
        try {
            connection.close();
        } catch (final Throwable e) {
            _log.error("Unable to close connection", e);
        }
    }
}

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

/**
 * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from
 * other tests may still exist from other tests' runs.
 * <p/>/*  w  w  w  .j a va 2s  . com*/
 * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones.
 * @param destination destination name without any protocol specifics
 */
protected void purge(final String destination) throws JMSException {
    Connection c = null;
    Session s = null;
    try {
        logger.debug("purging queue : " + destination);
        c = getConnection(false, false);
        assertNotNull(c);
        c.start();

        s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination d = s.createQueue(destination);
        MessageConsumer consumer = s.createConsumer(d);

        while (consumer.receiveNoWait() != null) {
            logger.debug("Destination " + destination + " isn't empty, draining it");
        }
    } catch (Exception e) {
        logger.error("unable to purge : " + destination);
    } finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

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

/**
 * Clear the specified topic/*w  w  w. ja  v a2 s  .  c  om*/
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}