Example usage for javax.jms TopicSession close

List of usage examples for javax.jms TopicSession close

Introduction

In this page you can find the example usage for javax.jms TopicSession close.

Prototype


void close() throws JMSException;

Source Link

Document

Closes the session.

Usage

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void subscribe(final String topicName, final MessageListener listener) {
    String topicName2 = null;// w  w w.j  ava2 s . com
    checkArgument(isNotBlank(topicName2 = trimToEmpty(topicName)), "Uninitialized or invalid topic");
    checkNotNull(listener);
    TopicConnection conn = null;
    TopicSession session = null;
    MessageConsumer consumer = null;
    try {
        conn = broker().getConsumersConnFactory().createTopicConnection();
        conn.start();
        session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(topicName2);
        consumer = session.createConsumer(topic);
        consumer.setMessageListener(listener);
        register(TopicSubscriber.builder().topicName(topicName2).connection(conn).session(session)
                .consumer(consumer).build());
        LOGGER.info("Subscribed to topic: " + topicName2);
    } catch (JMSException e) {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException ignore) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (JMSException ignore) {
            }
        }
        LOGGER.error("Failed to subscribe to topic: " + topicName2, e);
    }
}

From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void sendMessage(final String topicName, final String message) {
    checkArgument(isNotBlank(topicName), "Uninitialized or invalid topic");
    checkArgument(isNotBlank(message), "Uninitialized or invalid message");
    TopicConnection conn = null;// w  ww. j  a va2 s.c o  m
    TopicSession session = null;
    MessageProducer producer = null;
    try {
        conn = (TopicConnection) broker().getProducersConnFactory().createConnection();
        /* conn = broker().getConnFactory().createTopicConnection();
        conn.start(); */
        session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE);
        final Topic topic = session.createTopic(topicName);
        producer = session.createProducer(topic);
        producer.setDeliveryMode(NON_PERSISTENT);
        final TextMessage textMessage = session.createTextMessage(message);
        producer.send(textMessage);
    } catch (JMSException e) {
        LOGGER.error("Failed to send message to topic: " + topicName, e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException ignore) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException ignore) {
            }
        }
        /* if (conn != null) {
           try {
              conn.close();
           } catch (JMSException ignore) { }
        } */
    }
}

From source file:org.apache.stratos.adc.topology.mgt.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerIp = System.getProperty(TopologyConstants.MB_SERVER_IP) == null
            ? TopologyConstants.DEFAULT_MB_SERVER_IP
            : System.getProperty(TopologyConstants.MB_SERVER_IP);

    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://" + mbServerIp
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {/*from  w w w  . j  av a 2s .  co m*/
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}

From source file:org.apache.stratos.lb.endpoint.subscriber.TopologySubscriber.java

public static void subscribe(String topicName) {
    Properties initialContextProperties = new Properties();
    TopicSubscriber topicSubscriber = null;
    TopicSession topicSession = null;
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

    initialContextProperties.put("java.naming.factory.initial",
            "org.wso2.andes.jndi.PropertiesFileInitialContextFactory");

    String mbServerUrl = null;/*from ww w  .  ja v a 2s. co  m*/
    if (ConfigHolder.getInstance().getLbConfig() != null) {
        mbServerUrl = ConfigHolder.getInstance().getLbConfig().getLoadBalancerConfig().getMbServerUrl();
    }
    String connectionString = "amqp://admin:admin@clientID/carbon?brokerlist='tcp://"
            + (mbServerUrl == null ? TopologyConstants.DEFAULT_MB_SERVER_URL : mbServerUrl)
            + "'&reconnect='true'";
    initialContextProperties.put("connectionfactory.qpidConnectionfactory", connectionString);

    try {
        initialContext = new InitialContext(initialContextProperties);
        TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory) initialContext
                .lookup("qpidConnectionfactory");
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
        topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createSubscriber(topic);

        topicSubscriber.setMessageListener(new TopologyListener());

    } catch (Exception e) {
        log.error(e.getMessage(), e);

        try {
            if (topicSubscriber != null) {
                topicSubscriber.close();
            }

            if (topicSession != null) {
                topicSession.close();
            }

            if (topicConnection != null) {
                topicConnection.close();
            }
        } catch (JMSException e1) {
            // ignore
        }

    } finally {
        // start the health checker
        Thread healthChecker = new Thread(new TopicHealthChecker(topicName, topicSubscriber));
        healthChecker.start();
    }
}

From source file:org.apache.stratos.messaging.broker.connect.amqp.AmqpTopicPublisher.java

/**
 * Publish message to message broker./*  w  w w  .j a  v a 2s. co m*/
 *
 * @param message Message to be published
 * @param retry   Retry if message broker is not available
 */
@Override
public void publish(String message, boolean retry) {
    boolean published = false;
    while (!published) {
        TopicSession topicSession = null;
        javax.jms.TopicPublisher topicPublisher = null;
        try {
            while (connectionStatus == ConnectionStatus.ReConnecting) {
                // Connection has been broken, wait until reconnected
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ignore) {
                }
            }

            if (connectionStatus == ConnectionStatus.ReConnected) {
                // Publisher has reconnected, wait another 2 seconds to make sure all subscribers
                // have been reconnected to receive the message
                Thread.sleep(2000);
                connectionStatus = ConnectionStatus.Connected;
            }

            topicSession = newSession();
            Topic topic = lookupTopic(topicName);
            if (topic == null) {
                // if the topic doesn't exist, create it.
                topic = topicSession.createTopic(topicName);
            }
            topicPublisher = topicSession.createPublisher(topic);
            TextMessage textMessage = topicSession.createTextMessage(message);
            topicPublisher.publish(textMessage);
            published = true;
        } catch (Exception e) {
            String errorMessage = "Could not publish to topic: [topic-name] %s";
            log.error(errorMessage, e);
            if (!retry) {
                // Retry is disabled, throw exception
                throw new MessagingException(errorMessage, e);
            }
            // Try to reconnect
            reconnect();
        } finally {

            try {
                if (topicSession != null) {
                    topicSession.close();
                }
                if (topicPublisher != null) {
                    topicPublisher.close();
                }

            } catch (JMSException e) {
                message = "Error cleaning up pubisher";
                log.error(message, e);
                throw new MessagingException(message, 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 v a 2 s .  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.nuxeo.ecm.core.jms.CoreEventPublisher.java

public void publish(Object content, Topic topic, MessageFactory factory, String eventId) throws JMSException {
    TopicConnection connection = null;//from  w  w w  .  j av a 2s  . c o m
    TopicSession session = null;
    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.andes.event.core.internal.delivery.jms.JMSDeliveryManager.java

/**
 * {@inheritDoc}/*from  w w w .j av a2 s .  c  om*/
 */
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.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 {//  ww  w  .  j av a  2s .  com
        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.s4.integration.TenantStratosSubscriptionMessagePublisher.java

/**
 * Publish message to MB/ActiveMQ Queue//from   w ww  . j av  a2  s  .co  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);
            }
        }
    }

}