Example usage for javax.jms Connection close

List of usage examples for javax.jms Connection close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the connection.

Usage

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public Connection createConnection() {
    if (connectionFactory == null) {
        logger.error("Connection cannot be establish to the broker. Please check the broker libs provided.");
        return null;
    }/* w  ww.  j a  va  2s  .c o  m*/
    Connection connection = null;
    try {
        if ("1.1".equals(jmsSpec)) {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                connection = ((QueueConnectionFactory) (this.connectionFactory)).createQueueConnection();
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                connection = ((TopicConnectionFactory) (this.connectionFactory)).createTopicConnection();
            }
            if (isDurable) {
                connection.setClientID(clientId);
            }
            return connection;
        } else {
            QueueConnectionFactory qConFac = null;
            TopicConnectionFactory tConFac = null;
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                qConFac = (QueueConnectionFactory) this.connectionFactory;
            } else {
                tConFac = (TopicConnectionFactory) this.connectionFactory;
            }
            if (qConFac != null) {
                connection = qConFac.createQueueConnection();
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection();
            }
            if (isDurable && !isSharedSubscription) {
                connection.setClientID(clientId);
            }
            return connection;
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while creating connection through factory '" + this.connectionFactoryString
                + "' " + e.getMessage(), e);
        // Need to close the connection in the case if durable subscriptions
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
    }

    return null;
}

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 a  v  a 2  s  .c  o 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:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public Connection createConnection(String userName, String password) {
    Connection connection = null;
    try {/*from   w w w.  ja  v  a 2s  . co  m*/
        if (JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)) {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                connection = ((QueueConnectionFactory) (this.connectionFactory)).createQueueConnection(userName,
                        password);
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                connection = ((TopicConnectionFactory) (this.connectionFactory)).createTopicConnection(userName,
                        password);
            }
            if (isDurable) {
                connection.setClientID(clientId);
            }
            return connection;
        } else {
            QueueConnectionFactory qConFac = null;
            TopicConnectionFactory tConFac = null;
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                qConFac = (QueueConnectionFactory) this.connectionFactory;
            } else {
                tConFac = (TopicConnectionFactory) this.connectionFactory;
            }
            if (qConFac != null) {
                connection = qConFac.createQueueConnection(userName, password);
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection(userName, password);
            }
            if (isDurable && !isSharedSubscription) {
                connection.setClientID(clientId);
            }
            return connection;
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while creating connection through factory '" + this.connectionFactoryString
                + "' " + e.getMessage());
        // Need to close the connection in the case if durable subscriptions
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception ex) {
            }
        }
    }

    return null;
}

From source file:org.apache.servicemix.jms.jca.JcaConsumerProcessor.java

public void process(MessageExchange exchange) throws Exception {
    Context context = (Context) pendingMessages.remove(exchange.getExchangeId());
    Message message = (Message) context.getProperty(Message.class.getName());
    Message response = null;/*from ww  w.  j  a va 2s. com*/
    Connection connection = null;
    try {
        if (exchange.getStatus() == ExchangeStatus.DONE) {
            return;
        } else if (exchange.getStatus() == ExchangeStatus.ERROR) {
            if (endpoint.isRollbackOnError()) {
                TransactionManager tm = (TransactionManager) endpoint.getServiceUnit().getComponent()
                        .getComponentContext().getTransactionManager();
                tm.setRollbackOnly();
                return;
            } else if (exchange instanceof InOnly) {
                LOG.info("Exchange in error: " + exchange, exchange.getError());
                return;
            } else {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
                Exception error = exchange.getError();
                if (error == null) {
                    error = new Exception("Exchange in error");
                }
                response = session.createObjectMessage(error);
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        } else {
            connection = connectionFactory.createConnection();
            Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
            response = fromNMSResponse(exchange, context, session);
            if (response != null) {
                MessageProducer producer = session.createProducer(message.getJMSReplyTo());
                if (endpoint.isUseMsgIdInResponse()) {
                    response.setJMSCorrelationID(message.getJMSMessageID());
                } else {
                    response.setJMSCorrelationID(message.getJMSCorrelationID());
                }
                producer.send(response);
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
        if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
            exchange.setStatus(ExchangeStatus.DONE);
            channel.send(exchange);
        }
    }
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Gets an MQ message off a specified queue and returns it as an
 * <code>Object</code> to the requestor for further processing.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param responseQueue - The request queue name to put the message on
 * @param timeout - How long to wait for a connection or response
 * @param messageId - The JMS correlation ID of the message the response is associated with
 * @return <code>Object</code> - The serializable data returned by the MQ request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *///from   w w  w  .j av  a  2  s .  co  m
public static final synchronized Object getMqMessage(final String connName, final List<String> authData,
        final String responseQueue, final long timeout, final String messageId) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "getMqMessage(final String connName, final List<String> authData, final String responseQueue, final long timeout, final String messageId) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", responseQueue);
        DEBUGGER.debug("Value: {}", timeout);
        DEBUGGER.debug("Value: {}", messageId);
    }

    Connection conn = null;
    Session session = null;
    Object response = null;
    Context envContext = null;
    MessageConsumer consumer = null;
    ConnectionFactory connFactory = null;

    try {
        try {
            InitialContext initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

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

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        if (envContext != null) {
            try {
                consumer = session.createConsumer((Destination) envContext.lookup(responseQueue),
                        "JMSCorrelationID='" + messageId + "'");
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createQueue(responseQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            consumer = session.createConsumer(destination, "JMSCorrelationID='" + messageId + "'");
        }

        if (DEBUG) {
            DEBUGGER.debug("MessageConsumer: {}", consumer);
        }

        ObjectMessage message = (ObjectMessage) consumer.receive(timeout);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        if (message == null) {
            throw new UtilityException("Failed to retrieve message within the timeout specified.");
        }

        response = message.getObject();
        message.acknowledge();

        if (DEBUG) {
            DEBUGGER.debug("Object: {}", response);
        }
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return response;
}

From source file:com.cws.esolutions.core.utils.MQUtils.java

/**
 * Puts an MQ message on a specified queue and returns the associated
 * correlation ID for retrieval upon request.
 *
 * @param connName - The connection name to utilize
 * @param authData - The authentication data to utilize, if required
 * @param requestQueue - The request queue name to put the message on
 * @param targetHost - The target host for the message
 * @param value - The data to place on the request. MUST be <code>Serialiable</code>
 * @return <code>String</code> - the JMS correlation ID associated with the message
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 *//*from www.ja  v  a2 s  .c o m*/
public static final synchronized String sendMqMessage(final String connName, final List<String> authData,
        final String requestQueue, final String targetHost, final Serializable value) throws UtilityException {
    final String methodName = MQUtils.CNAME
            + "sendMqMessage(final String connName, final List<String> authData, final String requestQueue, final String targetHost, final Serializable value) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", connName);
        DEBUGGER.debug("Value: {}", requestQueue);
        DEBUGGER.debug("Value: {}", targetHost);
        DEBUGGER.debug("Value: {}", value);
    }

    Connection conn = null;
    Session session = null;
    Context envContext = null;
    InitialContext initCtx = null;
    MessageProducer producer = null;
    ConnectionFactory connFactory = null;

    final String correlationId = RandomStringUtils.randomAlphanumeric(64);

    if (DEBUG) {
        DEBUGGER.debug("correlationId: {}", correlationId);
    }

    try {
        try {
            initCtx = new InitialContext();
            envContext = (Context) initCtx.lookup(MQUtils.INIT_CONTEXT);

            connFactory = (ConnectionFactory) envContext.lookup(connName);
        } catch (NamingException nx) {
            // we're probably not in a container
            connFactory = new ActiveMQConnectionFactory(connName);
        }

        if (DEBUG) {
            DEBUGGER.debug("ConnectionFactory: {}", connFactory);
        }

        if (connFactory == null) {
            throw new UtilityException("Unable to create connection factory for provided name");
        }

        // Create a Connection
        conn = connFactory.createConnection(authData.get(0),
                PasswordUtils.decryptText(authData.get(1), authData.get(2), authData.get(3),
                        Integer.parseInt(authData.get(4)), Integer.parseInt(authData.get(5)), authData.get(6),
                        authData.get(7), authData.get(8)));
        conn.start();

        if (DEBUG) {
            DEBUGGER.debug("Connection: {}", conn);
        }

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

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", session);
        }

        // Create a MessageProducer from the Session to the Topic or Queue
        if (envContext != null) {
            try {
                producer = session.createProducer((Destination) envContext.lookup(requestQueue));
            } catch (NamingException nx) {
                throw new UtilityException(nx.getMessage(), nx);
            }
        } else {
            Destination destination = session.createTopic(requestQueue);

            if (DEBUG) {
                DEBUGGER.debug("Destination: {}", destination);
            }

            producer = session.createProducer(destination);
        }

        if (producer == null) {
            throw new JMSException("Failed to create a producer object");
        }

        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        if (DEBUG) {
            DEBUGGER.debug("MessageProducer: {}", producer);
        }

        ObjectMessage message = session.createObjectMessage(true);
        message.setJMSCorrelationID(correlationId);
        message.setStringProperty("targetHost", targetHost);

        if (DEBUG) {
            DEBUGGER.debug("correlationId: {}", correlationId);
        }

        message.setObject(value);

        if (DEBUG) {
            DEBUGGER.debug("ObjectMessage: {}", message);
        }

        producer.send(message);
    } catch (JMSException jx) {
        throw new UtilityException(jx.getMessage(), jx);
    } finally {
        try {
            // Clean up
            if (!(session == null)) {
                session.close();
            }

            if (!(conn == null)) {
                conn.close();
                conn.stop();
            }
        } catch (JMSException jx) {
            ERROR_RECORDER.error(jx.getMessage(), jx);
        }
    }

    return correlationId;
}

From source file:RequesterTool.java

public void run() {

    Connection connection = null;
    try {//from w ww  .java  2  s  .co  m

        System.out.println("Connecting to URL: " + url);
        System.out.println("Publishing a Message with size " + messageSize + " to "
                + (topic ? "topic" : "queue") + ": " + subject);
        System.out.println("Using " + (persistent ? "persistent" : "non-persistent") + " messages");
        System.out.println("Sleeping between publish " + sleepTime + " ms");

        // Create the connection
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
        connection = connectionFactory.createConnection();
        if (persistent && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
            connection.setClientID(clientId);
        }
        connection.start();

        // Create the Session
        session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        // And the Destinations..
        if (topic) {
            destination = session.createTopic(subject);
            if (replySubject == null || replySubject.equals("")) {
                replyDest = session.createTemporaryTopic();
            } else {
                replyDest = session.createTopic(replySubject);
            }
        } else {
            destination = session.createQueue(subject);
            if (replySubject == null || replySubject.equals("")) {
                replyDest = session.createTemporaryQueue();
            } else {
                replyDest = session.createQueue(replySubject);
            }
        }
        System.out.println("Reply Destination: " + replyDest);

        // Create the producer
        producer = session.createProducer(destination);
        if (persistent) {
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } else {
            producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        }
        if (timeToLive != 0) {
            System.out.println("Messages time to live " + timeToLive + " ms");
            producer.setTimeToLive(timeToLive);
        }

        // Create the reply consumer
        consumer = session.createConsumer(replyDest);

        // Start sending reqests.
        requestLoop();

        System.out.println("Done.");

        // Use the ActiveMQConnection interface to dump the connection
        // stats.
        ActiveMQConnection c = (ActiveMQConnection) connection;
        c.getConnectionStats().dump(new IndentPrinter());

    } catch (Exception e) {
        System.out.println("Caught: " + e);
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (Throwable ignore) {
        }
    }
}

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()}
 */// ww  w  . j  ava2 s.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.usecases.DurableSubscriberWithNetworkDisconnectTest.java

public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception {
    bridgeBrokers(SPOKE, HUB);//ww  w  .  ja v a2  s .  c om

    startAllBrokers();

    // Setup connection
    URI hubURI = brokers.get(HUB).broker.getVmConnectorURI();
    URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI();
    ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI);
    ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI);
    Connection conHub = facHub.createConnection();
    Connection conSpoke = facSpoke.createConnection();
    conHub.setClientID("clientHUB");
    conSpoke.setClientID("clientSPOKE");
    conHub.start();
    conSpoke.start();
    Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE);

    ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO");
    String consumerName = "consumerName";

    // Setup consumers
    MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName);
    remoteConsumer.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            try {
                TextMessage textMsg = (TextMessage) msg;
                receivedMsgs++;
                LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });

    // allow subscription information to flow back to Spoke
    sleep(1000);

    // Setup producer
    MessageProducer localProducer = sesHub.createProducer(topic);
    localProducer.setDeliveryMode(DeliveryMode.PERSISTENT);

    // Send messages
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        sleep(50);
        if (i == 50 || i == 150) {
            if (simulateStalledNetwork) {
                socketProxy.pause();
            } else {
                socketProxy.close();
            }
            networkDownTimeStart = System.currentTimeMillis();
        } else if (networkDownTimeStart > 0) {
            // restart after NETWORK_DOWN_TIME seconds
            sleep(NETWORK_DOWN_TIME);
            networkDownTimeStart = 0;
            if (simulateStalledNetwork) {
                socketProxy.goOn();
            } else {
                socketProxy.reopen();
            }
        } else {
            // slow message production to allow bridge to recover and limit message duplication
            sleep(500);
        }
        Message test = sesHub.createTextMessage("test-" + i);
        localProducer.send(test);
    }

    LOG.info("waiting for messages to flow");
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return receivedMsgs >= MESSAGE_COUNT;
        }
    });

    assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs,
            MESSAGE_COUNT <= receivedMsgs);
    brokers.get(HUB).broker.deleteAllMessages();
    brokers.get(SPOKE).broker.deleteAllMessages();
    conHub.close();
    conSpoke.close();
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java

/**
 * Get the JmsConnection from the cache if one exists, otherwise a new one will be created. This
 * method is synchronized otherwise multiple threads may try to create the same connection
 * simultaneously. Only one thread is allowed to create a connection at a time. Subsequent
 * threads will then retrieve the connection that was already created.
 *//*from w w w  .j  a v a  2s. c o  m*/
private synchronized JmsConnection getJmsConnection(JmsDispatcherProperties jmsDispatcherProperties,
        String connectionKey, Long dispatcherId, boolean replace) throws Exception {
    // If the connection needs to be replaced, clean up the old connection and remove it from the cache.
    if (replace) {
        closeJmsConnectionQuietly(connectionKey);
    }

    JmsConnection jmsConnection = jmsConnections.get(connectionKey);

    if (jmsConnection == null) {
        if (jmsConnections.size() >= maxConnections) {
            throw new Exception("Cannot create new connection. Maximum number (" + maxConnections
                    + ") of cached connections reached.");
        }

        Context initialContext = null;
        ConnectionFactory connectionFactory = null;
        Connection connection = null;

        Map<String, String> connectionProperties = jmsDispatcherProperties.getConnectionProperties();
        if (jmsDispatcherProperties.isUseJndi()) {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

            try {
                MirthContextFactory contextFactory = contextFactoryController
                        .getContextFactory(getResourceIds());
                Thread.currentThread().setContextClassLoader(contextFactory.getApplicationClassLoader());

                Hashtable<String, Object> env = new Hashtable<String, Object>();
                env.put(Context.PROVIDER_URL, jmsDispatcherProperties.getJndiProviderUrl());
                env.put(Context.INITIAL_CONTEXT_FACTORY,
                        jmsDispatcherProperties.getJndiInitialContextFactory());
                env.put(Context.SECURITY_PRINCIPAL, jmsDispatcherProperties.getUsername());
                env.put(Context.SECURITY_CREDENTIALS, jmsDispatcherProperties.getPassword());

                initialContext = new InitialContext(env);

                String connectionFactoryName = jmsDispatcherProperties.getJndiConnectionFactoryName();
                connectionFactory = (ConnectionFactory) initialContext.lookup(connectionFactoryName);
            } finally {
                Thread.currentThread().setContextClassLoader(contextClassLoader);
            }
        } else {
            String className = jmsDispatcherProperties.getConnectionFactoryClass();

            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(getResourceIds());
            connectionFactory = (ConnectionFactory) Class
                    .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance();
        }

        BeanUtil.setProperties(connectionFactory, connectionProperties);

        try {
            logger.debug("Creating JMS connection and session");
            connection = connectionFactory.createConnection(jmsDispatcherProperties.getUsername(),
                    jmsDispatcherProperties.getPassword());
            String clientId = jmsDispatcherProperties.getClientId();

            if (!clientId.isEmpty()) {
                connection.setClientID(clientId);
            }

            logger.debug("Starting JMS connection");
            connection.start();
        } catch (JMSException e) {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close JMS connection.", e);
            }

            try {
                if (initialContext != null) {
                    initialContext.close();
                }
            } catch (Exception e1) {
                logger.debug("Failed to close initial context.", e);
            }

            throw e;
        }

        // Create the new JmsConnection and add it to the cache.
        jmsConnection = new JmsConnection(connection, initialContext);
        jmsConnections.put(connectionKey, jmsConnection);
    }

    return jmsConnection;
}