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:jenkins.plugins.logstash.persistence.ActiveMqDao.java

@Override
public void push(String data) throws IOException {
    TopicConnection connection = null;
    Session session = null;//from   w w  w  .  ja v  a2s.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:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void subscribe(final String topicName, final MessageListener listener) {
    String topicName2 = null;/*from  w  w w  . j a  v  a2s .  c  o 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:org.openmrs.event.EventEngine.java

/**
 * @see Event#subscribe(Destination, EventListener)
 *//* w w  w. j  a v  a  2 s . c  o m*/
public void subscribe(Destination destination, final EventListener listenerToRegister) {

    initializeIfNeeded();

    TopicConnection conn;
    Topic topic = (Topic) destination;

    try {
        conn = (TopicConnection) jmsTemplate.getConnectionFactory().createConnection();
        TopicSession session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = session.createSubscriber(topic);
        subscriber.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                listenerToRegister.onMessage(message);
            }
        });

        //Check if this is a duplicate and remove it
        String key = topic.getTopicName() + DELIMITER + listenerToRegister.getClass().getName();
        if (subscribers.containsKey(key)) {
            unsubscribe(destination, listenerToRegister);
        }

        subscribers.put(key, subscriber);
        conn.start();

    } catch (JMSException e) {
        // TODO Auto-generated catch block. Do something smarter here.
        e.printStackTrace();
    }

    //      List<EventListener> currentListeners = listeners.get(key);
    //
    //      if (currentListeners == null) {
    //         currentListeners = new ArrayList<EventListener>();
    //         currentListeners.add(listenerToRegister);
    //         listeners.put(key, currentListeners);
    //         if (log.isInfoEnabled())
    //            log.info("subscribed: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //      } else {
    //         // prevent duplicates because of weird spring loading
    //         String listernToRegisterName = listenerToRegister.getClass()
    //               .getName();
    //         Iterator<EventListener> iterator = currentListeners.iterator();
    //         while (iterator.hasNext()) {
    //            EventListener lstnr = iterator.next();
    //            if (lstnr.getClass().getName().equals(listernToRegisterName))
    //               iterator.remove();
    //         }
    //
    //         if (log.isInfoEnabled())
    //            log.info("subscribing: " + listenerToRegister + " to key: "
    //                  + key);
    //
    //         currentListeners.add(listenerToRegister);
    //      }

}

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

private String doJmsURL(boolean pooled, String endpoint) {
    try {/*w  w  w. j a v a  2  s.  c o  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.activemq.usecases.DurableSubscriptionHangTestCase.java

private void registerDurableSubscription() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();
    connection.setClientID(clientID);/*w w  w.  j a v a 2 s  .co  m*/
    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   w  w  w .  j ava 2 s .  co m
    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   ww w.  j av  a 2  s. c o  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;//from  ww w.  jav a 2s.  co  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.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void registerListener(String eventTypeName, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;/*w ww. j av  a  2  s .c  o m*/
    }

    log.info("Registering handler for event " + eventTypeName);
    if (!isValidHandler(handler)) {
        return;
    }

    Topic topic = topicMap.get(eventTypeName);
    if (topic == null) {
        log.error("Caller attempted to register interest to events of unknown type " + eventTypeName);
        throw new RuntimeException("Unknown event type specified in registration request.");
    }

    if (isListenerRegistered(handler, eventTypeName)) {
        log.warn("Caller attempted to register interest for the same event again.");
        return;
    }
    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    try {
        TopicConnection connection = (TopicConnection) connectionFactory.createConnection();
        if (connection.getClientID() == null) {
            connection.setClientID(handler.getClientId());
        }
        log.debug("Connection is of type " + connection);
        TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = topicSession.createSubscriber(topic);
        MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber, handler);
        saveListenerRegistration(listener, eventTypeName);
        subscriber.setMessageListener(listener);
        connection.start();
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }
}

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

/**
 * Initialize and return topic connection
 *
 * @param userName username// w  ww  .j a  va  2 s. c  om
 * @return topic connection
 * @throws EventBrokerException
 */
public TopicConnection getTopicConnection(String userName) throws EventBrokerException {
    InitialContext initialContext = null;
    try {

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