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.openmrs.event.EventEngine.java

/**
 * @see Event#subscribe(Destination, EventListener)
 *//*from w w w  .jav  a2  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: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;
    Topic t = (Topic) ctx.lookup(_dest);

    if (!isEmpty(_jmsUser)) {
        conn = f.createTopicConnection(_jmsUser, _jmsPwd);
    } else {/*  ww w. ja  va 2s . c o  m*/
        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);
        }
    });
}

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  w w .  j ava2  s .  co 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:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java

public void subscribe(final String topicName, final MessageListener listener) {
    String topicName2 = null;/*  www  . j ava  2 s.  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: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;
    TopicSession session = null;//from  w w  w . ja va 2s .  c  o  m
    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.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(String filePath, String topicName, String queueName, String format, String broker,
        String providerURL) {//from w ww.ja va 2  s  .c  om
    if (format == null || "map".equals(format)) {
        format = "csv";
    }
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messagesList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messagesList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.source.client.JMSClient.java

public void sendJMSEvents(List<String> messageList, String topicName, String queueName, String format,
        String broker, String providerURL) {
    if (format == null || "map".equals(format)) {
        format = "csv";
    }//from   w  ww .  j ava 2s . c om
    if ("".equalsIgnoreCase(broker)) {
        broker = "activemq";
    }
    Session session = null;
    Properties properties = new Properties();
    if (!"activemq".equalsIgnoreCase(broker) && !"mb".equalsIgnoreCase(broker)
            && !"qpid".equalsIgnoreCase(broker)) {
        log.error("Please enter a valid JMS message broker. (ex: activemq, mb, qpid");
        return;
    }
    try {
        if (topicName != null && !"".equalsIgnoreCase(topicName)) {
            TopicConnection topicConnection;
            TopicConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (TopicConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                topicConnection = connFactory.createTopicConnection();
                topicConnection.start();
                session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Topic topic = session.createTopic(topicName);
                    MessageProducer producer = session.createProducer(topic);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + topicName + "' topic");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                        log.info("All Order Messages sent");
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        topicConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else if (queueName != null && !queueName.equalsIgnoreCase("")) {
            QueueConnection queueConnection;
            QueueConnectionFactory connFactory = null;
            if ("activemq".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
                // to provide custom provider urls
                if (providerURL != null) {
                    properties.put(Context.PROVIDER_URL, providerURL);
                }
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
            } else if ("mb".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("mb.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            } else if ("qpid".equalsIgnoreCase(broker)) {
                properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("qpid.properties"));
                Context context = new InitialContext(properties);
                connFactory = (QueueConnectionFactory) context.lookup("qpidConnectionFactory");
            }
            if (connFactory != null) {
                queueConnection = connFactory.createQueueConnection();
                queueConnection.start();
                session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                if (session != null) {
                    Queue queue = session.createQueue(queueName);
                    MessageProducer producer = session.createProducer(queue);
                    //List<String> messagesList = JMSClientUtil.readFile(filePath);
                    try {
                        if ("csv".equalsIgnoreCase(format)) {
                            log.info("Sending Map messages on '" + queueName + "' queue");
                            JMSClientUtil.publishMapMessage(producer, session, messageList);

                        } else {
                            log.info("Sending  " + format + " messages on '" + queueName + "' queue");
                            JMSClientUtil.publishTextMessage(producer, session, messageList);
                        }
                    } catch (JMSException e) {
                        log.error("Cannot subscribe." + e.getMessage(), e);
                    } catch (IOException e) {
                        log.error("Error when reading the data file." + e.getMessage(), e);
                    } finally {
                        producer.close();
                        session.close();
                        queueConnection.stop();
                    }
                }
            } else {
                log.error("Error when creating connection factory. Please check necessary jar files");
            }
        } else {
            log.error("Enter queue name or topic name to be published!");
        }
    } catch (Exception e) {
        log.error("Error when publishing" + e.getMessage(), e);
    }
}