Example usage for javax.jms ConnectionFactory createConnection

List of usage examples for javax.jms ConnectionFactory createConnection

Introduction

In this page you can find the example usage for javax.jms ConnectionFactory createConnection.

Prototype


Connection createConnection(String userName, String password) throws JMSException;

Source Link

Document

Creates a connection with the specified user identity.

Usage

From source file:nl.nn.adapterframework.extensions.tibco.TibcoUtils.java

public static Connection getConnection(String provUrl, String authAlias, String userName, String password)
        throws JMSException {
    String url = StringUtils.replace(provUrl, "tibjmsnaming:", "tcp:");
    CredentialFactory cf = new CredentialFactory(authAlias, userName, password);
    ConnectionFactory factory = new com.tibco.tibjms.TibjmsConnectionFactory(url);
    return factory.createConnection(cf.getUsername(), cf.getPassword());
}

From source file:org.wso2.carbon.apimgt.jms.listener.utils.JMSUtils.java

/**
 * This is a JMS spec independent method to create a Connection. Please be cautious when
 * making any changes/*from w  w w.ja  v a  2 s . c o m*/
 *
 * @param conFac    the ConnectionFactory to use
 * @param user      optional user name
 * @param pass      optional password
 * @param jmsSpec11 should we use JMS 1.1 API ?
 * @param isQueue   is this to deal with a Queue?
 * @param isDurable whether the messaging provider is durable
 * @param clientID  durable subscriber client id
 * @return a JMS Connection as requested
 * @throws JMSException on errors, to be handled and logged by the caller
 */
public static Connection createConnection(ConnectionFactory conFac, String user, String pass, boolean jmsSpec11,
        Boolean isQueue, boolean isDurable, String clientID) throws JMSException {

    Connection connection = null;
    if (log.isDebugEnabled()) {
        log.debug("Creating a " + (isQueue ? "Queue" : "Topic") + "Connection using credentials : (" + user
                + "/" + pass + ")");
    }

    if (jmsSpec11 || isQueue == null) {
        if (user != null && pass != null) {
            connection = conFac.createConnection(user, pass);
        } else {
            connection = conFac.createConnection();
        }
        if (isDurable) {
            connection.setClientID(clientID);
        }

    } else {
        QueueConnectionFactory qConFac = null;
        TopicConnectionFactory tConFac = null;
        if (isQueue) {
            qConFac = (QueueConnectionFactory) conFac;
        } else {
            tConFac = (TopicConnectionFactory) conFac;
        }

        if (user != null && pass != null) {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection(user, pass);
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection(user, pass);
            }
        } else {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection();
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection();
            }
        }
        if (isDurable) {
            connection.setClientID(clientID);
        }
    }
    return connection;
}

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  a  va  2 s  .  c om*/
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:org.apache.axis2.transport.jms.JMSUtils.java

/**
 * This is a JMS spec independent method to create a Connection. Please be cautious when
 * making any changes//from  w  ww . j ava2s.  co m
 *
 * @param conFac the ConnectionFactory to use
 * @param user optional user name
 * @param pass optional password
 * @param jmsSpec11 should we use JMS 1.1 API ?
 * @param isQueue is this to deal with a Queue?
 * @return a JMS Connection as requested
 * @throws JMSException on errors, to be handled and logged by the caller
 */
public static Connection createConnection(ConnectionFactory conFac, String user, String pass, boolean jmsSpec11,
        Boolean isQueue) throws JMSException {

    Connection connection = null;
    if (log.isDebugEnabled()) {
        log.debug("Creating a " + (isQueue == null ? "Generic" : isQueue ? "Queue" : "Topic")
                + "Connection using credentials : (" + user + "/" + pass + ")");
    }

    if (jmsSpec11 || isQueue == null) {
        if (user != null && pass != null) {
            connection = conFac.createConnection(user, pass);
        } else {
            connection = conFac.createConnection();
        }

    } else {
        QueueConnectionFactory qConFac = null;
        TopicConnectionFactory tConFac = null;
        if (isQueue) {
            qConFac = (QueueConnectionFactory) conFac;
        } else {
            tConFac = (TopicConnectionFactory) conFac;
        }

        if (user != null && pass != null) {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection(user, pass);
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection(user, pass);
            }
        } else {
            if (qConFac != null) {
                connection = qConFac.createQueueConnection();
            } else if (tConFac != null) {
                connection = tConFac.createTopicConnection();
            }
        }
    }
    return connection;
}

From source file:Chat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password) {
    // Create a connection.
    try {//from   w w w .j  a  v  a  2 s . com
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics
    try {
        javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC);
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }

    try {
        // Read all standard input and send it as a message.
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nChat application:\n" + "=================\n" + "The application user " + username
                + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n"
                + "The application will publish messages to the " + APP_TOPIC + " topic.\n"
                + "The application also subscribes to that topic to consume any messages published there.\n\n"
                + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                + ".\n");
        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = pubSession.createTextMessage();
                msg.setText(username + ": " + s);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:org.wso2.carbon.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void createConnection(Properties config) {
    try {//  w  ww .j a  va2 s  .c  om
        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, config.getProperty("initialContextFactory"));
        props.put(Context.PROVIDER_URL, config.getProperty("providerUrl"));
        props.put(Context.SECURITY_PRINCIPAL, config.getProperty("securityPrincipal"));
        props.put(Context.SECURITY_CREDENTIALS, config.getProperty("securityCredentials"));
        props.put("topic.cacheInvalidateTopic", config.getProperty("cacheInvalidateTopic"));
        InitialContext jndi = new InitialContext(props);
        ConnectionFactory connectionFactory = (ConnectionFactory) jndi.lookup("ConnectionFactory");
        destination = (Destination) jndi.lookup("cacheInvalidateTopic");

        connection = connectionFactory.createConnection(config.getProperty("securityPrincipal"),
                config.getProperty("securityCredentials"));
        connection.start();
    } catch (NamingException | JMSException e) {
        log.error("Global cache invalidation: Error message broker initialization", e);
    }
}

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  w  ww  . j  ava  2 s.c  om*/
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:DurableChat.java

public void DurableChatter(String broker, String username, String password) {
    javax.jms.MessageProducer publisher = null;
    javax.jms.MessageConsumer subscriber = null;
    javax.jms.Topic topic = null;//  w w  w.  j ava 2 s  .  c  o  m

    //Create a connection:
    try {
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connection = factory.createConnection(username, password);

        //Durable Subscriptions are indexed by username, clientID and subscription name
        //It is a good practice to set the clientID:
        connection.setClientID(username);
        pubSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("Error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    //Create Publisher and Durable Subscriber:
    try {

        topic = pubSession.createTopic(APP_TOPIC);
        subscriber = subSession.createDurableSubscriber(topic, username);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        connection.start();
    } catch (javax.jms.JMSException jmse) {
        System.out.println("Error: connection not started.");
        jmse.printStackTrace();
        System.exit(1);
    }

    //Wait for user input
    try {
        System.out.println("\nDurableChat application:\n" + "========================\n" + "The user "
                + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n"
                + "The application will publish messages to the " + APP_TOPIC + " topic.\n"
                + "The application also creates a durable subscription to that topic to consume any messages published there.\n\n"
                + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                + ".\n");
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        while (true) {
            String s = stdin.readLine();

            if (s == null) {
                exit();
            } else if (s.length() > 0) {
                try {
                    javax.jms.TextMessage msg = pubSession.createTextMessage();
                    msg.setText(username + ": " + s);
                    //Publish the message persistantly:
                    publisher.send(msg, //message
                            javax.jms.DeliveryMode.PERSISTENT, //publish persistently
                            javax.jms.Message.DEFAULT_PRIORITY, //priority
                            MESSAGE_LIFESPAN); //Time to Live
                } catch (javax.jms.JMSException jmse) {
                    System.err.println("Error publishing message:" + jmse.getMessage());
                }
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:HierarchicalChat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password, String pubTopicname,
        String subTopicname) {//from  w w  w.  j  a  va 2 s .  c  o  m

    // Create a connection.
    try {
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics
    // Note that the publish and subscribe topics are different.
    try {
        javax.jms.Topic subscriberTopic = pubSession.createTopic(subTopicname);
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(subscriberTopic, null, false);
        subscriber.setMessageListener(this);
        javax.jms.Topic publisherTopic = pubSession.createTopic(pubTopicname);
        publisher = pubSession.createProducer(publisherTopic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
    try {
        // Read all standard input and send it as a message.
        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nHierarchicalChat application:\n" + "============================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application will publish messages to the " + DEFAULT_PUBLISHER_TOPIC + " topic."
                + ".\n" + "The application also subscribes to topics using the wildcard syntax "
                + DEFAULT_SUBSCRIBER_TOPIC + " so that it can receive all messages to "
                + DEFAULT_SUBSCRIBER_ROOT + " and its subtopics.\n\n"
                + "Type some text, and then press Enter to publish a TextMesssage from " + username + ".\n");
        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = pubSession.createTextMessage();
                msg.setText(username + ": " + s);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:SelectorChat.java

/** Create JMS client for publishing and subscribing to messages. */
private void chatter(String broker, String username, String password, String selection) {

    // Create a connection.
    try {/*from   w ww  .j ava 2 s .  c  om*/
        javax.jms.ConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createConnection(username, password);
        pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
        subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
    } catch (javax.jms.JMSException jmse) {
        System.err.println("error: Cannot connect to Broker - " + broker);
        jmse.printStackTrace();
        System.exit(1);
    }

    // Create Publisher and Subscriber to 'chat' topics

    try {
        javax.jms.Topic topic = pubSession.createTopic(APP_TOPIC);
        // NOTE: The subscriber's message selector will now be set:
        javax.jms.MessageConsumer subscriber = subSession.createConsumer(topic,
                PROPERTY_NAME + " = \'" + selection + "\'", false);
        subscriber.setMessageListener(this);
        publisher = pubSession.createProducer(topic);
        // Now that setup is complete, start the Connection
        connect.start();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
        System.exit(1);
    }

    try {
        // Read all standard input and send it as a message.

        java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
        System.out.println("\nSelectorChat application:\n" + "===========================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application will publish messages with " + PROPERTY_NAME + " set to " + selection
                + " to the " + APP_TOPIC + " topic .\n"
                + "The application also subscribes to that topic, selecting only messages where "
                + PROPERTY_NAME + " is " + selection + ".\n"
                + "Type some text, and then press Enter to publish it as a TextMesssage from " + username
                + ".\n");

        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = pubSession.createTextMessage();
                msg.setText(username + ": " + s);
                // NOTE: here we set a property on messages to be published:
                msg.setStringProperty(PROPERTY_NAME, selection);
                publisher.send(msg);
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}