Example usage for javax.jms Connection setClientID

List of usage examples for javax.jms Connection setClientID

Introduction

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

Prototype

void setClientID(String clientID) throws JMSException;

Source Link

Document

Sets the client identifier for this connection.

Usage

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 ww  .  j a  v  a2  s. com*/
    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:RequesterTool.java

public void run() {

    Connection connection = null;
    try {/*  www. j  av  a 2s.c o  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:com.mirth.connect.connectors.jms.JmsConnector.java

protected Connection createConnection() throws NamingException, JMSException, InitialisationException {
    Connection connection = null;

    if (connectionFactory == null) {
        connectionFactory = createConnectionFactory();
    }//  ww  w.j  a va  2 s  . c  o m

    if (connectionFactory != null && connectionFactory instanceof XAConnectionFactory) {
        if (MuleManager.getInstance().getTransactionManager() != null) {
            connectionFactory = new ConnectionFactoryWrapper(connectionFactory,
                    MuleManager.getInstance().getTransactionManager());
        }
    }

    if (username != null) {
        connection = jmsSupport.createConnection(connectionFactory, replacer.replaceValues(username),
                replacer.replaceValues(password));
    } else {
        connection = jmsSupport.createConnection(connectionFactory);
    }

    if (clientId != null) {
        connection.setClientID(replacer.replaceValues(getClientId()));
    }

    if (recoverJmsConnections && connection != null) {
        connection.setExceptionListener(new ExceptionListener() {
            public void onException(JMSException jmsException) {
                logger.debug("About to recycle myself due to remote JMS connection shutdown.");
                final JmsConnector jmsConnector = JmsConnector.this;
                try {
                    jmsConnector.doStop();
                    jmsConnector.initialised.set(false);
                } catch (UMOException e) {
                    logger.warn(e.getMessage(), e);
                }

                try {
                    jmsConnector.doConnect();
                    jmsConnector.doInitialise();
                    jmsConnector.doStart();
                } catch (FatalConnectException fcex) {
                    logger.fatal("Failed to reconnect to JMS server. I'm giving up.");
                } catch (UMOException umoex) {
                    throw new UnhandledException("Failed to recover a connector.", umoex);
                }
            }
        });
    }

    return connection;
}

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. java2s.  c om*/
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;
}

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

/**
 * Build a new connection with the given clientId
 *
 * @param clientId   the clientId//from  w w w  . j a  v a 2  s  .co  m
        
 * @return
  */
private Connection buildConnection(String clientId) {
    try {
        Connection result;
        if (StringUtil.isEmpty(userName)) {
            result = this.connectionFactory.createConnection();
        } else {
            result = this.connectionFactory.createConnection(this.userName, this.password);
        }
        result.setClientID(clientId);

        return result;
    } catch (JMSException e) {
        throw new TechnicalException("Could not establish JMS connection", e);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from w  w  w.ja va2  s .c om
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 0, 0);

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicMessageSizeShared() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*from  ww w . j ava  2 s  .  c  o m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");
    MessageConsumer consumer2 = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 0, 0);
    consumer2.close();

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from w  w w  .  java  2s  . c om
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicPersistentAndNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    AtomicLong publishedNonPersistentMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from   ww  w  . ja va2 s.  c o  m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize);
    publishTestTopicMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200,
            publishedMessageSize.get() + publishedNonPersistentMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testMessageSizeOneDurable() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();
    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*from w w  w .j  a v a  2  s .  c  o m*/

    publishTestMessagesDurable(connection, new String[] { "sub1" }, 200, publishedMessageSize,
            DeliveryMode.PERSISTENT, false);

    // verify the count and size - durable is offline so all 200 should be
    // pending since none are in prefetch
    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume all messages
    consumeDurableTestMessages(connection, "sub1", 200, publishedMessageSize);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);
    verifyPendingDurableStats(defaultTopicName, 0, 0);

    connection.close();
}