Example usage for javax.jms TopicConnectionFactory createTopicConnection

List of usage examples for javax.jms TopicConnectionFactory createTopicConnection

Introduction

In this page you can find the example usage for javax.jms TopicConnectionFactory createTopicConnection.

Prototype


TopicConnection createTopicConnection(String userName, String password) throws JMSException;

Source Link

Document

Creates a topic connection with the specified user identity.

Usage

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/*  w w  w  .  jav a2 s  .  c  om*/
 *
 * @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: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  a va  2s  .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:TopicRequestor.java

/** Create JMS client for publishing and subscribing to messages. */
private void start(String broker, String username, String password) {
    // Create a connection.
    try {//from  www.  j  ava  2  s  . c  o  m
        javax.jms.TopicConnectionFactory factory;
        factory = new ActiveMQConnectionFactory(username, password, broker);
        connect = factory.createTopicConnection(username, password);
        session = connect.createTopicSession(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 Topic for all requests.  TopicRequestor will be created
    // as needed.
    javax.jms.Topic topic = null;
    try {
        topic = session.createTopic(APP_TOPIC);
        // Now that all 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("\nRequestor application:\n" + "============================\n"
                + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME
                + ".\n" + "The application uses a TopicRequestor to on the " + APP_TOPIC + " topic."
                + "The Replier application gets the message, and transforms it."
                + "The Requestor application displays the result.\n\n"
                + "Type some mixed case text, and then press Enter to make a request.\n");
        while (true) {
            String s = stdin.readLine();

            if (s == null)
                exit();
            else if (s.length() > 0) {
                javax.jms.TextMessage msg = session.createTextMessage();
                msg.setText(username + ": " + s);
                // Instead of publishing, we will use a TopicRequestor.
                javax.jms.TopicRequestor requestor = new javax.jms.TopicRequestor(session, topic);
                javax.jms.Message response = requestor.request(msg);
                // The message should be a TextMessage.  Just report it.
                javax.jms.TextMessage textMessage = (javax.jms.TextMessage) response;
                System.out.println("[Reply] " + textMessage.getText());
            }
        }
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
    } catch (javax.jms.JMSException jmse) {
        jmse.printStackTrace();
    }
}

From source file:com.zotoh.maedr.device.JmsIO.java

private void inizTopic(Context ctx, Object obj) throws Exception {

    TopicConnectionFactory f = (TopicConnectionFactory) obj;
    final JmsIO me = this;
    TopicConnection conn;/*from  ww  w  . j  av  a 2  s . co m*/
    Topic t = (Topic) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createTopicConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createTopicConnection();
    }

    _conn = conn;

    TopicSession s = conn.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
    TopicSubscriber b;

    if (_durable) {
        b = s.createDurableSubscriber(t, GUID.generate());
    } else {
        b = s.createSubscriber(t);
    }

    b.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}

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

public Connection createConnection(String userName, String password) {
    Connection connection = null;
    try {/* w  w w . j  a v  a2s  . c  om*/
        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.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {/*from   w  w  w  .  j  a va2s .co m*/

        boolean ok = false;
        String server = endpoint.split("#")[0];
        server = server.replace("jms:", "jnp://");
        String name = endpoint.split("#")[1];
        String msg = "";
        String[] info = DBSettingsLoader.GetCredentials(pooled, endpoint);
        String username = null;
        String password = null;
        if (info != null) {
            username = info[0];
            password = info[1];
        } else {
            info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
            if (info != null) {
                username = info[0];
                password = info[1];
            }
        }

        if (name.startsWith("topic")) {
            try {
                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                //properties1.put(Context.PROVIDER_URL, "jnp://127.0.0.1:1099");
                properties1.put(Context.PROVIDER_URL, server);

                InitialContext iniCtx = new InitialContext(properties1);

                TopicConnectionFactory tcf = (TopicConnectionFactory) iniCtx.lookup("TopicConnectionFactory");
                TopicConnection createTopicConnection = null;
                if (info != null) {
                    createTopicConnection = tcf.createTopicConnection(username, Utility.DE(password)); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                } else {
                    createTopicConnection = tcf.createTopicConnection(); //Topic topic = (Topic) iniCtx.lookup("/topic/quickstart_jmstopic_topic");
                }
                createTopicConnection.start();
                createTopicConnection.stop();
                createTopicConnection.close();
                //Topic topic = (Topic) iniCtx.lookup("//" + name);
                ok = true;

                //topic = null;
                iniCtx.close();

            } catch (Exception ex) {
                System.out.println(ex);
                msg = ex.getLocalizedMessage();
                //return ex.getLocalizedMessage();
            }
        } else if (name.startsWith("queue")) {
            try {

                Properties properties1 = new Properties();
                properties1.put(Context.INITIAL_CONTEXT_FACTORY,
                        "org.jnp.interfaces.NamingContextFactory");
                properties1.put(Context.URL_PKG_PREFIXES,
                        "org.jboss.naming:org.jnp.interfaces");
                properties1.put(Context.PROVIDER_URL, server);
                InitialContext iniCtx = new InitialContext(properties1);
                QueueConnection conn;
                QueueSession session;
                Queue que;

                Object tmp = iniCtx.lookup("ConnectionFactory");
                QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
                if (info != null) {
                    conn = qcf.createQueueConnection(username, Utility.DE(password));
                } else {
                    conn = qcf.createQueueConnection();
                }

                que = (Queue) iniCtx.lookup(name);
                session = conn.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);
                conn.start();

                //System.out.println("Connection Started");
                ok = true;

                conn.stop();
                session.close();
                iniCtx.close();

            } catch (Exception ex) {
                log.log(Level.WARN, "Could not bind to jms queue", ex);
                msg = ex.getLocalizedMessage();
            }
            if (ok) {
                return "OK";
            }
            return "Unable to bind to JMS queue: " + msg;
        } else {
            return "Unsupported Protocol";
        }
    } catch (Exception ex) {
        log.log(Level.WARN, "service " + endpoint + " is offline or an error occured", ex);
        return "Offline " + ex.getLocalizedMessage();
    }
    return "undeterminable";
}

From source file:org.apache.axis2.transport.jms.JMSOutTransportInfo.java

/**
 * Create a one time MessageProducer for this JMS OutTransport information.
 * For simplicity and best compatibility, this method uses only JMS 1.0.2b API.
 * Please be cautious when making any changes
 *
 * @return a JMSSender based on one-time use resources
 * @throws JMSException on errors, to be handled and logged by the caller 
 *///from w  ww.  ja  v  a2 s . c  o m
public JMSMessageSender createJMSSender() throws JMSException {

    // digest the targetAddress and locate CF from the EPR
    loadConnectionFactoryFromProperies();

    // create a one time connection and session to be used
    String user = properties != null ? properties.get(JMSConstants.PARAM_JMS_USERNAME) : null;
    String pass = properties != null ? properties.get(JMSConstants.PARAM_JMS_PASSWORD) : null;

    QueueConnectionFactory qConFac = null;
    TopicConnectionFactory tConFac = null;

    int destType = -1;
    // TODO: there is something missing here for destination type generic
    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType)) {
        destType = JMSConstants.QUEUE;
        qConFac = (QueueConnectionFactory) connectionFactory;

    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType)) {
        destType = JMSConstants.TOPIC;
        tConFac = (TopicConnectionFactory) connectionFactory;
    } else {
        //treat jmsdestination type=queue(default is queue)
        destType = JMSConstants.QUEUE;
        qConFac = (QueueConnectionFactory) connectionFactory;
    }

    Connection connection = null;
    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 (connection == null) {
        connection = jmsConnectionFactory != null ? jmsConnectionFactory.getConnection() : null;
    }

    Session session = null;
    MessageProducer producer = null;

    if (connection != null) {
        if (destType == JMSConstants.QUEUE) {
            session = ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = ((QueueSession) session).createSender((Queue) destination);
        } else {
            session = ((TopicConnection) connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
            producer = ((TopicSession) session).createPublisher((Topic) destination);
        }
    }

    return new JMSMessageSender(connection, session, producer, destination,
            jmsConnectionFactory == null ? JMSConstants.CACHE_NONE : jmsConnectionFactory.getCacheLevel(),
            false, destType == -1 ? null : destType == JMSConstants.QUEUE ? Boolean.TRUE : Boolean.FALSE);

}

From source file:org.apache.synapse.transport.jms.JMSConnectionFactory.java

/**
 * Begin [or restart] listening for messages on the list of destinations associated
 * with this connection factory. (Called during Axis2 initialization of
 * the Transport receivers, or after a disconnection has been detected)
 *
 * When called from the JMS transport sender, this call simply acquires the actual
 * JMS connection factory from the JNDI, creates a new connection and starts it.
 *
 * @throws JMSException on exceptions//from  w  w  w .j  a v  a2s .com
 * @throws NamingException on exceptions
 */
public synchronized void connectAndListen() throws JMSException, NamingException {

    // if this is a reconnection/re-initialization effort after the detection of a
    // disconnection, close all sessions and the CF connection and re-initialize
    if (connection != null) {
        log.info("Re-initializing the JMS connection factory : " + name);

        Iterator sessionIter = jmsSessions.values().iterator();
        while (sessionIter.hasNext()) {
            try {
                ((Session) sessionIter.next()).close();
            } catch (JMSException ignore) {
            }
        }
        try {
            connection.stop();
        } catch (JMSException ignore) {
        }

    } else {
        if (log.isDebugEnabled()) {
            log.debug("Initializing the JMS connection factory : " + name);
        }
    }

    // get the CF reference freshly [again] from JNDI
    context = new InitialContext(jndiProperties);
    conFactory = (ConnectionFactory) context.lookup(connFactoryJNDIName);
    log.info("Connected to the JMS connection factory : " + connFactoryJNDIName);

    try {
        ConnectionFactory conFac = null;
        QueueConnectionFactory qConFac = null;
        TopicConnectionFactory tConFac = null;
        if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(getConnectionFactoryType())) {
            qConFac = (QueueConnectionFactory) conFactory;
        } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(getConnectionFactoryType())) {
            tConFac = (TopicConnectionFactory) conFactory;
        } else {
            handleException("Unable to determine type of Connection Factory - i.e. Queue/Topic", null);
        }

        String user = (String) jndiProperties.get(Context.SECURITY_PRINCIPAL);
        String pass = (String) jndiProperties.get(Context.SECURITY_CREDENTIALS);

        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();
            }
        }

        connection.setExceptionListener(this);

    } catch (JMSException e) {
        handleException("Error connecting to Connection Factory : " + connFactoryJNDIName, e);
    }

    Iterator destJNDINameIter = serviceJNDINameMapping.keySet().iterator();
    while (destJNDINameIter.hasNext()) {
        String destJNDIName = (String) destJNDINameIter.next();
        String destinationType = (String) destinationTypeMapping.get(destJNDIName);
        startListeningOnDestination(destJNDIName, destinationType);
    }

    connection.start(); // indicate readyness to start receiving messages
    log.info("Connection factory : " + name + " initialized...");
}

From source file:org.apache.synapse.transport.jms.JMSSender.java

/**
 * Performs the actual sending of the JMS message
 *//*from   ww w. j  ava  2  s  . com*/
public void sendMessage(MessageContext msgCtx, String targetAddress, OutTransportInfo outTransportInfo)
        throws AxisFault {

    JMSConnectionFactory jmsConnectionFactory = null;
    Connection connection = null; // holds a one time connection if used
    JMSOutTransportInfo jmsOut = null;
    Session session = null;
    Destination destination = null;
    Destination replyDestination = null;

    try {
        if (targetAddress != null) {

            jmsOut = new JMSOutTransportInfo(targetAddress);
            // do we have a definition for a connection factory to use for this address?
            jmsConnectionFactory = getJMSConnectionFactory(jmsOut);

            if (jmsConnectionFactory != null) {
                // create new or get existing session to send to the destination from the CF
                session = jmsConnectionFactory.getSessionForDestination(JMSUtils.getDestination(targetAddress));

            } else {
                // digest the targetAddress and locate CF from the EPR
                jmsOut.loadConnectionFactoryFromProperies();
                try {
                    // create a one time connection and session to be used
                    Hashtable jndiProps = jmsOut.getProperties();
                    String user = (String) jndiProps.get(Context.SECURITY_PRINCIPAL);
                    String pass = (String) jndiProps.get(Context.SECURITY_CREDENTIALS);

                    QueueConnectionFactory qConFac = null;
                    TopicConnectionFactory tConFac = null;
                    ConnectionFactory conFac = null;

                    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        qConFac = (QueueConnectionFactory) jmsOut.getConnectionFactory();
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        tConFac = (TopicConnectionFactory) jmsOut.getConnectionFactory();
                    } else {
                        handleException(
                                "Unable to determine type of JMS " + "Connection Factory - i.e Queue/Topic");
                    }

                    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 (JMSConstants.DESTINATION_TYPE_QUEUE.equals(jmsOut.getDestinationType())) {
                        session = ((QueueConnection) connection).createQueueSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(jmsOut.getDestinationType())) {
                        session = ((TopicConnection) connection).createTopicSession(false,
                                Session.AUTO_ACKNOWLEDGE);
                    }

                } catch (JMSException e) {
                    handleException("Error creating a connection/session for : " + targetAddress);
                }
            }
            destination = jmsOut.getDestination();

        } else if (outTransportInfo != null && outTransportInfo instanceof JMSOutTransportInfo) {

            jmsOut = (JMSOutTransportInfo) outTransportInfo;
            jmsConnectionFactory = jmsOut.getJmsConnectionFactory();

            session = jmsConnectionFactory.getSessionForDestination(jmsOut.getDestination().toString());
            destination = jmsOut.getDestination();
        }

        String replyDestName = (String) msgCtx.getProperty(JMSConstants.JMS_REPLY_TO);
        if (replyDestName != null) {
            if (jmsConnectionFactory != null) {
                replyDestination = jmsConnectionFactory.getDestination(replyDestName);
            } else {
                replyDestination = jmsOut.getReplyDestination(replyDestName);
            }
        }

        // now we are going to use the JMS session, but if this was a session from a
        // defined JMS connection factory, we need to synchronize as sessions are not
        // thread safe
        synchronized (session) {

            // convert the axis message context into a JMS Message that we can send over JMS
            Message message = null;
            String correlationId = null;
            try {
                message = createJMSMessage(msgCtx, session);
            } catch (JMSException e) {
                handleException("Error creating a JMS message from the axis message context", e);
            }

            String destinationType = jmsOut.getDestinationType();

            // if the destination does not exist, see if we can create it
            destination = JMSUtils.createDestinationIfRequired(destination, destinationType, targetAddress,
                    session);

            // should we wait for a synchronous response on this same thread?
            boolean waitForResponse = waitForSynchronousResponse(msgCtx);

            // if this is a synchronous out-in, prepare to listen on the response destination
            if (waitForResponse) {
                replyDestination = JMSUtils.setReplyDestination(replyDestination, session, message);
            }

            // send the outgoing message over JMS to the destination selected
            JMSUtils.sendMessageToJMSDestination(session, destination, message);

            // if we are expecting a synchronous response back for the message sent out
            if (waitForResponse) {
                try {
                    connection.start();
                } catch (JMSException ignore) {
                }
                try {
                    correlationId = message.getJMSMessageID();
                } catch (JMSException ignore) {
                }
                waitForResponseAndProcess(session, replyDestination, msgCtx, correlationId);
            }
        }

    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException ignore) {
            }
        }
    }
}