Example usage for javax.jms TopicSession createSubscriber

List of usage examples for javax.jms TopicSession createSubscriber

Introduction

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

Prototype


TopicSubscriber createSubscriber(Topic topic) throws JMSException;

Source Link

Document

Creates a nondurable subscriber to the specified topic.

Usage

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 {//w w  w .  java2  s .  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.messaging.broker.subscribe.TopicSubscriber.java

private void createSubscriber(TopicSession topicSession) throws JMSException {
    Topic topic = connector.getTopic();//from  w ww  .j  a va2s .com
    if (topic == null) {
        // if topic doesn't exist, create it.
        topic = topicSession.createTopic(topicName);
    }
    topicSubscriber = topicSession.createSubscriber(topic);
    topicSubscriber.setMessageListener(messageListener);
}

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

@Override
public void subscribe() {
    try {//  w w  w .  j ava  2 s  .co m
        TopicSession topicSession = newSession();
        Topic topic = lookupTopic(topicName);
        if (topic == null) {
            // if topic doesn't exist, create it.
            topic = topicSession.createTopic(topicName);
        }
        javax.jms.TopicSubscriber topicSubscriber = topicSession.createSubscriber(topic);
        topicSubscriber.setMessageListener(new javax.jms.MessageListener() {
            @Override
            public void onMessage(Message message) {
                try {
                    String topicName = null, messageText = null;

                    if (message instanceof ActiveMQTextMessage) {
                        ActiveMQTextMessage textMessage = (ActiveMQTextMessage) message;
                        topicName = textMessage.getDestination().getPhysicalName();
                        messageText = textMessage.getText();
                    } else if (message instanceof ActiveMQBytesMessage) {
                        ActiveMQBytesMessage bytesMessage = (ActiveMQBytesMessage) message;
                        topicName = bytesMessage.getDestination().getPhysicalName();
                        messageText = new String(bytesMessage.getContent().data);
                    } else {
                        throw new RuntimeException(
                                String.format("Could not receive message, " + "unknown JMS message type: %s",
                                        message.getClass().getName()));
                    }
                    org.apache.stratos.messaging.domain.Message message_ = new org.apache.stratos.messaging.domain.Message(
                            topicName, messageText);
                    messageListener.messageReceived(message_);
                } catch (Exception e) {
                    String error = "An error occurred when receiving message";
                    log.error(error, e);
                }
            }
        });
    } catch (Exception e) {
        String message = "Could not subscribe to topic: " + topicName;
        log.error(message, e);
        throw new MessagingException(message, e);
    }
}

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;/*  w ww . ja va2  s.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.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;//from w ww.  j  a v 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.openmrs.event.EventEngine.java

/**
 * @see Event#subscribe(Destination, EventListener)
 *//*from ww  w  .ja v  a  2s  .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:com.zotoh.maedr.device.JmsIO.java

private void inizTopic(Context ctx, Object obj) throws Exception {

    TopicConnectionFactory f = (TopicConnectionFactory) obj;
    final JmsIO me = this;
    TopicConnection conn;/*from ww  w . ja v a2 s  .  com*/
    Topic t = (Topic) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createTopicConnection(_jmsUser, _jmsPwd);
    } else {
        conn = f.createTopicConnection();
    }

    _conn = conn;

    TopicSession s = conn.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE);
    TopicSubscriber b;

    if (_durable) {
        b = s.createDurableSubscriber(t, GUID.generate());
    } else {
        b = s.createSubscriber(t);
    }

    b.setMessageListener(new MessageListener() {
        public void onMessage(Message msg) {
            me.onMessage(msg);
        }
    });
}