Example usage for javax.jms TopicConnection close

List of usage examples for javax.jms TopicConnection close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the connection.

Usage

From source file:org.miloss.fgsms.bueller.Bueller.java

private String doJmsURL(boolean pooled, String endpoint) {
    try {/*from  w  w w. j  av a  2s  .c  om*/

        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:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void subscribe(final String topicName, final MessageListener listener) {
    String topicName2 = null;//ww  w.  j a v  a2  s . co m
    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:jenkins.plugins.logstash.persistence.ActiveMqDao.java

@Override
public void push(String data) throws IOException {
    TopicConnection connection = null;
    Session session = null;/*from w  w w.  j a  v  a  2s  .c om*/
    try {
        // Create a Connection
        connection = connectionFactory.createTopicConnection();

        connection.start();

        // Create a Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination Queue
        Destination destination = session.createTopic(key);

        // Create the MessageProducer from the Session to the Queue
        MessageProducer producer = session.createProducer(destination);

        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // Create the message
        TextMessage message = session.createTextMessage(data);
        message.setJMSType("application/json");
        // Tell the producer to send the message
        producer.send(message);

        //logger.log( Level.FINER, String.format("JMS message sent with ID [%s]", message.getJMSMessageID()));

    } catch (JMSException e) {
        logger.log(Level.SEVERE, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        throw new IOException(e);
    } finally {
        // Clean up
        try {
            if (null != session)
                session.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
        try {
            if (null != connection)
                connection.close();
        } catch (JMSException e) {
            logger.log(Level.WARNING, null != e.getMessage() ? e.getMessage() : e.getClass().getName());
        }
    }
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private void produceExpiredAndOneNonExpiredMessages() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();
    TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(topicName);
    MessageProducer producer = session.createProducer(topic);
    producer.setTimeToLive(TimeUnit.SECONDS.toMillis(1));
    for (int i = 0; i < 40000; i++) {
        sendRandomMessage(session, producer);
    }//  ww  w  . jav a  2s  .  c om
    producer.setTimeToLive(TimeUnit.DAYS.toMillis(1));
    sendRandomMessage(session, producer);
    connection.close();
    LOG.info("produceExpiredAndOneNonExpiredMessages done");
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private void registerDurableSubscription() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.setClientID(clientID);//from  w  ww . j  av a  2 s .  c om
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    TopicSubscriber durableSubscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    connection.start();
    durableSubscriber.close();
    connection.close();
    LOG.info("Durable Sub Registered");
}

From source file:org.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();

    connection.setClientID(clientID);//from  ww  w  .j av  a2  s . c om
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    connection.start();
    TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    LOG.info("About to receive messages");
    Message message = subscriber.receive(120000);
    subscriber.close();
    connection.close();
    LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done");

    return message;
}

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;/*from w  ww  .j  ava2 s  .co  m*/
    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 {
        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;//w  ww  . j a v a2  s.  c  o  m
    TopicConnection topicConnection = null;
    InitialContext initialContext = null;

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

    String mbServerUrl = null;
    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.nuxeo.ecm.core.event.jms.JmsEventForwarder.java

protected void produceJMSMessage(SerializableEventBundle message) throws JMSBusNotActiveException {
    InitialContext ctx;/*from  ww  w .  j  a  va 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;
    TopicSession session = null;//from w w  w  .  j a v  a  2s  .c o  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();
        }
    }
}