Example usage for javax.jms TopicConnection start

List of usage examples for javax.jms TopicConnection start

Introduction

In this page you can find the example usage for javax.jms TopicConnection start.

Prototype


void start() throws JMSException;

Source Link

Document

Starts (or restarts) a connection's delivery of incoming messages.

Usage

From source file:org.wso2.carbon.appfactory.eventing.jms.TopicPublisher.java

public void publishMessage(Event event) throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, QPID_ICF);
    properties.put(CF_NAME_PREFIX + CF_NAME, Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    try {//w w w  . j a va  2  s.  c  o  m
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(CF_NAME);
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to initialize InitialContext.", e);
    }

    TopicConnection topicConnection = null;
    TopicSession topicSession = null;
    try {
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        // Send message
        String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
        Topic topic = topicSession.createTopic(event.getTarget());

        //Until MB supports 'Dynamic Topics' we have to create a subscription, therefore forcing Message broker to
        // create the topic.
        String defaultSubscriptionId = tenantDomain + "/" + DEFAULT_SUBSCRIPTION + UUID.randomUUID();
        topicSubscriber = topicSession.createDurableSubscriber(topic, defaultSubscriptionId);
        // We are unsubscribing from the Topic as soon as
        topicSession.unsubscribe(defaultSubscriptionId);

        // create the message to send
        MapMessage mapMessage = topicSession.createMapMessage();
        mapMessage.setString(MESSAGE_TITLE, event.getMessageTitle());
        mapMessage.setString(MESSAGE_BODY, event.getMessageBody());
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicConnection.start();
        topicPublisher.publish(mapMessage);
        if (log.isDebugEnabled()) {
            log.debug("Message with Id:" + mapMessage.getJMSMessageID() + ", with title:"
                    + event.getMessageTitle() + " was successfully published.");
        }

    } catch (JMSException e) {
        log.error("Failed to publish message due to " + e.getMessage(), e);
        throw new AppFactoryEventException("Failed to publish message due to " + e.getMessage(), e);
    } finally {
        if (topicSubscriber != null) {
            try {
                topicSubscriber.close();
            } catch (JMSException e) {
                log.error("Failed to close default topic subscriber", e);
            }
        }
        if (topicSession != null) {
            try {
                topicSession.close();
            } catch (JMSException e) {
                log.error("Failed to close topic session", e);
            }
        }
        if (topicConnection != null) {
            try {
                topicConnection.close();
            } catch (JMSException e) {
                log.error("Failed to close topic connection", e);
            }
        }
    }
}

From source file:org.wso2.carbon.appfactory.resource.mgt.listeners.TenantCreationDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException// w ww.ja v  a2s .  c o m
 */
public void subscribe() throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, "true");
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnectionFactory connFactory;
    TopicConnection topicConnection;
    TopicSession topicSession;
    TopicSubscriber topicSubscriber;
    InitialContext ctx;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(
                new TenantCreationMessageListener(topicConnection, topicSession, topicSubscriber));
        topicConnection.start();
        if (log.isDebugEnabled()) {
            log.debug("Durable Subscriber created for topic " + topicName + " with subscription id : "
                    + subscriptionId);
        }
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    } catch (JMSException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    }
}

From source file:org.wso2.carbon.appfactory.s4.integration.TenantStratosSubscriptionMessagePublisher.java

/**
 * Publish message to MB/ActiveMQ Queue//  ww w. jav a  2  s.c o m
 * @param runtimeJson runtimebeans as a json
 * @param tenantInfoJson tenantInfoBean as a json
 * @param restServiceProperties propertyMap
 * @param stage current stage
 * @throws AppFactoryEventException
 */
public void publishMessage(String runtimeJson, String tenantInfoJson, Map<String, String> restServiceProperties,
        String stage) throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnection topicConnection = null;
    TopicSession topicSession = null;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic = topicSession.createTopic(topicName);
        MapMessage mapMessage = topicSession.createMapMessage();
        mapMessage.setString(AppFactoryConstants.STAGE, stage);
        mapMessage.setString(AppFactoryConstants.RUNTIMES_INFO, runtimeJson);
        mapMessage.setString(AppFactoryConstants.TENANT_INFO, tenantInfoJson);
        javax.jms.TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.publish(mapMessage);

        //TODO remove this log
        log.info("Message with Id:" + mapMessage.getJMSMessageID() + " was successfully published to the"
                + " topic " + topicName);

        if (log.isDebugEnabled()) {
            log.debug("Message with Id:" + mapMessage.getJMSMessageID() + " was successfully published to the"
                    + " topic " + topicName);
        }
    } catch (NamingException e) {
        String msg = "Failed to initialize InitialContext";
        throw new AppFactoryEventException(msg, e);
    } catch (JMSException e) {
        String msg = "Failed to publish message due to " + e.getMessage();
        throw new AppFactoryEventException(msg, e);
    } finally {
        if (topicSession != null) {
            try {
                topicSession.close();
            } catch (JMSException e) {
                log.error("Failed to close topic session", e);
            }
        }
        if (topicConnection != null) {
            try {
                topicConnection.close();
            } catch (JMSException e) {
                log.error("Failed to close topic connection", e);
            }
        }
    }

}

From source file:org.wso2.carbon.appfactory.stratos.listeners.StratosSubscriptionDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException/*from ww w  .j a v  a  2  s .  c o m*/
 */
public void subscribe() throws AppFactoryEventException {
    Properties properties = new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, AppFactoryConstants.ANDES_ICF);
    properties.put(AppFactoryConstants.CF_NAME_PREFIX + AppFactoryConstants.CF_NAME,
            Util.getTCPConnectionURL());
    properties.put(CarbonConstants.REQUEST_BASE_CONTEXT, true);
    properties.put(AppFactoryConstants.TOPIC, topicName);
    TopicConnectionFactory connFactory;
    TopicConnection topicConnection;
    TopicSession topicSession;
    TopicSubscriber topicSubscriber;
    InitialContext ctx;
    try {
        ctx = new InitialContext(properties);
        connFactory = (TopicConnectionFactory) ctx.lookup(AppFactoryConstants.CF_NAME);
        topicConnection = connFactory.createTopicConnection();
        topicSession = topicConnection.createTopicSession(false, TopicSession.CLIENT_ACKNOWLEDGE);
        Topic topic;
        try {
            topic = (Topic) ctx.lookup(topicName);
        } catch (NamingException e) {
            topic = topicSession.createTopic(topicName);
        }
        topicSubscriber = topicSession.createDurableSubscriber(topic, subscriptionId);
        topicSubscriber.setMessageListener(
                new StratosSubscriptionMessageListener(topicConnection, topicSession, topicSubscriber));
        topicConnection.start();
        if (log.isDebugEnabled()) {
            log.debug("Durable Subscriber created for topic " + topicName + " with subscription id : "
                    + subscriptionId);
        }
    } catch (NamingException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    } catch (JMSException e) {
        throw new AppFactoryEventException("Failed to subscribe to topic : " + topicName
                + " with subscription id" + " : " + subscriptionId, e);
    }
}

From source file:org.wso2.carbon.event.core.internal.delivery.jms.JMSDeliveryManager.java

public TopicConnection getTopicConnection(String userName) throws EventBrokerException {
    InitialContext initialContext = null;
    try {/*from w ww  .  j  ava  2 s  .  c  o  m*/

        initialContext = new InitialContext(getInitialContextProperties(userName,
                EventBrokerHolder.getInstance().getQpidServerDetails().getAccessKey()));
        TopicConnectionFactory topicConnectionFactory = getTopicConnectionFactory(initialContext);

        TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        return topicConnection;
    } catch (NamingException e) {
        throw new EventBrokerException("Can not create the initial context", e);
    } catch (JMSException e) {
        throw new EventBrokerException("Can not create topic connection", e);
    } catch (Exception e) {
        throw new EventBrokerException("Can not create topic connection", e);
    } finally {
        if (initialContext != null) {
            try {
                initialContext.close();
            } catch (NamingException e) {
                log.error("Can not close the inital context factory ", e);
            }
        }
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSConsumerClient.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//from   w  w  w . j a  v a2s. c  om
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {

        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                messageCount++;
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    preservedEventList.add(map);
                    log.info("Received Map Message : \n" + map + "\n");
                } else if (message instanceof TextMessage) {
                    String textMessage = ((TextMessage) message).getText();
                    preservedEventList.add(textMessage);
                    log.info("Received Text Message : \n" + textMessage + "\n");
                } else {
                    preservedEventList.add(message.toString());
                    log.info("Received message : \n" + message.toString() + "\n");
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * This method will publish the data in the test data file to the given topic via ActiveMQ message broker
 *
 * @param topicName             the topic which the messages should be published under
 * @param format                format of the test data file (csv or text)
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 *///from w w w  . j a  v  a2  s  . co  m
public static void publish(String topicName, String format, String testCaseFolderName, String dataFileName) {

    if (format == null || "map".equals(format)) {
        format = "csv";
    }

    try {
        Properties properties = new Properties();

        String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
        properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
        Context context = new InitialContext(properties);
        TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
        TopicConnection topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        Session session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic(topicName);
        MessageProducer producer = session.createProducer(topic);

        List<String> messagesList = readFile(filePath);
        try {

            if (format.equalsIgnoreCase("csv")) {
                log.info("Sending Map messages on '" + topicName + "' topic");
                publishMapMessages(producer, session, messagesList);

            } else {
                log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                publishTextMessage(producer, session, messagesList);
            }
        } catch (JMSException e) {
            log.error("Can not subscribe." + e.getMessage(), e);
        } finally {
            producer.close();
            session.close();
            topicConnection.stop();
            topicConnection.close();
        }
    } catch (Exception e) {
        log.error("Error when publishing messages" + e.getMessage(), e);
    }

    log.info("All Order Messages sent");
}

From source file:org.wso2.carbon.sample.consumer.TopicConsumer.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//from   w  ww.j  a v  a 2 s. co  m
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message : " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message : " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message : " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.sample.jmsclient.JMSClient.java

public static void publishMessages(String topicName, String broker) {
    try {/*from  w  w w  .j  ava2 s  . c o m*/

        //            filePath = JMSClientUtil.getEventFilePath(sampleNumber, format, topicName, filePath);

        TopicConnection topicConnection = null;
        Session session = null;

        Properties properties = new Properties();
        if (broker.equalsIgnoreCase("activemq")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("mb")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else if (broker.equalsIgnoreCase("qpid")) {
            properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
            Context context = new InitialContext(properties);
            TopicConnectionFactory connFactory = (TopicConnectionFactory) context
                    .lookup("qpidConnectionFactory");
            topicConnection = connFactory.createTopicConnection();
            topicConnection.start();
            session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        } else {
            log.info("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        }

        if (session != null) {
            Topic topic = session.createTopic(topicName);
            MessageProducer producer = session.createProducer(topic);

            try {

                List<Map<String, Object>> messageList = new ArrayList<Map<String, Object>>();

                Random random = new Random();
                for (int j = 0; j < sessionsPerThread; j++) {
                    for (int i = 0; i < msgsPerSession; i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();

                        map.put("id", random.nextInt() + "");
                        map.put("value", random.nextInt());
                        map.put("content", "sample content");
                        map.put("client", "jmsQueueClient");
                        // setting the timestamp later
                        messageList.add(map);
                    }

                    publishMapMessage(producer, session, messageList);

                }
            } catch (JMSException e) {
                log.error("Can not subscribe." + e.getMessage(), e);
            } catch (IOException e) {
                log.error("Error when reading the data file." + e.getMessage(), e);
            } finally {
                producer.close();
                session.close();
                topicConnection.stop();
            }
        }
    } catch (Exception e) {
        log.error("Error when publishing message" + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.sink.util.TopicConsumer.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//from  w  ww .  j ava 2s .c om
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                resultContainer.eventReceived(message);
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message : " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message : " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message : " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}