Example usage for javax.jms TopicConnection createTopicSession

List of usage examples for javax.jms TopicConnection createTopicSession

Introduction

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

Prototype


TopicSession createTopicSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a TopicSession object, specifying transacted and acknowledgeMode .

Usage

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

/**
 * {@inheritDoc}//from  w  w  w.  j a v a 2 s  .  c  o m
 */
public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

    if (isDeactivated()) {
        return;
    }

    try {
        String userName = getLoggedInUserName();
        if ((userName == null) || (userName.equals(""))) {
            // use the system user name
            userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
        }

        TopicConnection topicConnection = getTopicConnection(userName);
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String tenantDomain = EventBrokerHolder.getInstance().getTenantDomain();
        if (tenantDomain != null
                && (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {
            topicName = tenantDomain + "/" + getTopicName(topicName);
        } else {
            topicName = getTopicName(topicName);
        }

        Topic topic = topicSession.createTopic(topicName);
        //Some times we are not getting the proper topic with the required syntax, if it is not
        //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185
        if (!topic.toString().startsWith("topic://amq.topic")) {
            topic = topicSession.createTopic("BURL:" + topicName);
        }
        TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.setDeliveryMode(deliveryMode);
        TextMessage textMessage = topicSession.createTextMessage(message.getMessage());

        Map<String, String> properties = message.getProperties();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            textMessage.setStringProperty(entry.getKey(), entry.getValue());
        }

        // saving the domain to be used send with the soap header
        if (CarbonContext.getThreadLocalCarbonContext().getTenantDomain() != null) {
            textMessage.setStringProperty(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME,
                    CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        }

        topicPublisher.publish(textMessage);
        topicPublisher.close();
        topicSession.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        throw new EventBrokerException("Can not publish to topic " + topicName + " " + e.getMessage(), e);
    }
}

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

/**
 * {@inheritDoc}//  w w w .  j  a v  a 2 s.co m
 */
public void subscribe(Subscription subscription) throws EventBrokerException {

    if (isDeactivated()) {
        return;
    }

    // in a multi tenant environment deployment synchronize may creates subscriptions before
    // the event observer get activated.
    if (this.subscriptionIDSessionDetailsMap.containsKey(subscription.getId())) {
        log.warn(
                "There is an subscription already exists for the subscription with id " + subscription.getId());
        return;
    }
    JMSMessageListener jmsMessageListener = new JMSMessageListener(this.notificationManager, subscription);
    try {
        TopicConnection topicConnection = getTopicConnection(subscription.getOwner());
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "";
        if (subscription.getTenantDomain() != null && (!subscription.getTenantDomain()
                .equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {

            if (!subscription.getTopicName().startsWith("/")) {
                topicName = getTopicName(subscription.getTenantDomain() + "/" + subscription.getTopicName());
            } else {
                topicName = getTopicName(subscription.getTenantDomain() + subscription.getTopicName());
            }
        } else {
            topicName = getTopicName(subscription.getTopicName());
        }
        Topic topic = topicSession.createTopic(topicName);
        //Some times we are not getting the proper topic with the required syntax, if it is not
        //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185
        if (!topic.toString().startsWith("topic://amq.topic")) {
            topic = topicSession.createTopic("BURL:" + topicName);
        }
        TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, subscription.getId());
        topicSubscriber.setMessageListener(jmsMessageListener);

        this.subscriptionIDSessionDetailsMap.put(subscription.getId(),
                new JMSSubscriptionDetails(topicSubscriber, topicSession, topicConnection));
    } catch (JMSException e) {
        throw new EventBrokerException(
                "Can not subscribe to topic " + subscription.getTopicName() + " " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.core.jms.CoreEventPublisher.java

public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException {
    TopicConnection connection = null;
    TopicSession session = null;//from   w  w w  .j  av  a  2  s  .  co m
    TopicPublisher publisher = null;
    try {
        // get a connection from topic connection pool
        connection = getTopicConnection();

        // create a not transacted session
        session = connection.createTopicSession(transacted, TopicSession.AUTO_ACKNOWLEDGE);

        // create the publisher
        publisher = session.createPublisher(topic);
        publisher.setDeliveryMode(isDeliveryPersistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
        publisher.setDisableMessageID(isDisableMessageID);
        publisher.setDisableMessageTimestamp(isDisableMessageTimestamp);
        // create the message using the given factory
        Message msg = factory.createMessage(session, content);
        if (eventId != null) {
            msg.setStringProperty("NuxeoEventId", eventId);
        }
        // publish the message
        publisher.publish(topic, msg);
    } finally {
        if (publisher != null) {
            publisher.close();
        }
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

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

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {// w ww .j av  a 2  s . c  o 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.appfactory.resource.mgt.listeners.TenantCreationDurableSubscriber.java

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException/*from   w  w  w  .j  ava2s  . c  om*/
 */
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.extension.siddhi.io.jms.sink.util.TopicConsumer.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {/*from  ww  w.  j a v  a2  s  .c o 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) {
                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);
    }
}

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

/**
 * Subscribe as a durable subscriber to the topic.
 *
 * @throws AppFactoryEventException//from   ww w .  ja va2 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.nuxeo.ecm.core.event.jms.JmsEventForwarder.java

protected void produceJMSMessage(SerializableEventBundle message) throws JMSBusNotActiveException {
    InitialContext ctx;//from   w ww.  j a  va2s .  c o  m
    Topic nuxeoTopic;
    try {
        ctx = new InitialContext();
        nuxeoTopic = (Topic) ctx.lookup(NUXEO_JMS_TOPIC);
    } catch (NamingException e) {
        jmsBusIsActive = false;
        throw new JMSBusNotActiveException(e);
    }

    TopicConnection nuxeoTopicConnection = null;
    TopicSession nuxeoTopicSession = null;
    TopicPublisher nuxeoMessagePublisher = null;
    try {
        TopicConnectionFactory factory = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
        nuxeoTopicConnection = factory.createTopicConnection();
        nuxeoTopicSession = nuxeoTopicConnection.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);

        ObjectMessage jmsMessage = nuxeoTopicSession.createObjectMessage(message);

        // add Headers for JMS message
        jmsMessage.setStringProperty("BundleEvent", message.getEventBundleName());

        nuxeoMessagePublisher = nuxeoTopicSession.createPublisher(nuxeoTopic);

        nuxeoMessagePublisher.send(jmsMessage);
        log.debug("Event bundle " + message.getEventBundleName() + " forwarded to JMS topic");

    } catch (Exception e) {
        log.error("Error during JMS forwarding", e);
    } finally {
        if (nuxeoTopicSession != null) {
            try {
                if (nuxeoMessagePublisher != null) {
                    nuxeoMessagePublisher.close();
                }
                nuxeoTopicConnection.close();
                nuxeoTopicSession.close();
            } catch (JMSException e) {
                log.error("Error during JMS cleanup", e);
            }
        }
    }
}

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

/**
 * Publish message to MB/ActiveMQ Queue//from w  w w  .j  ava  2  s. com
 * @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.integration.test.client.JMSConsumerClient.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//  w ww .j ava  2s .c  o 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) {
                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);
    }
}