Example usage for javax.jms Session createTopic

List of usage examples for javax.jms Session createTopic

Introduction

In this page you can find the example usage for javax.jms Session createTopic.

Prototype

Topic createTopic(String topicName) throws JMSException;

Source Link

Document

Creates a Topic object which encapsulates a specified provider-specific topic name.

Usage

From source file:org.wso2.carbon.integration.test.client.JMSPublisherClient.java

/**
 * This method will publish the data in the test data file to the given topic via ActiveMQ message broker
 *
 * @param topicName             the topic which the messages should be published under
 * @param format                format of the test data file (csv or text)
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 *//*from  w  w  w  .jav  a 2 s .c o m*/
public static void publish(String topicName, String format, String testCaseFolderName, String dataFileName) {

    if (format == null || "map".equals(format)) {
        format = "csv";
    }

    try {
        Properties properties = new Properties();

        String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
        properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
        Context context = new InitialContext(properties);
        TopicConnectionFactory connFactory = (TopicConnectionFactory) context.lookup("ConnectionFactory");
        TopicConnection topicConnection = connFactory.createTopicConnection();
        topicConnection.start();
        Session session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        Topic topic = session.createTopic(topicName);
        MessageProducer producer = session.createProducer(topic);

        List<String> messagesList = readFile(filePath);
        try {

            if (format.equalsIgnoreCase("csv")) {
                log.info("Sending Map messages on '" + topicName + "' topic");
                publishMapMessages(producer, session, messagesList);

            } else {
                log.info("Sending  " + format + " messages on '" + topicName + "' topic");
                publishTextMessage(producer, session, messagesList);
            }
        } catch (JMSException e) {
            log.error("Can not subscribe." + e.getMessage(), e);
        } finally {
            producer.close();
            session.close();
            topicConnection.stop();
            topicConnection.close();
        }
    } catch (Exception e) {
        log.error("Error when publishing messages" + e.getMessage(), e);
    }

    log.info("All Order Messages sent");
}

From source file:org.seedstack.seed.ws.internal.jms.SoapJmsUri.java

static Destination getDestination(SoapJmsUri soapJmsUri, Session session) throws NamingException, JMSException {
    Destination destination;/*from   w  ww .java 2  s . co m*/

    String lookupVariant = soapJmsUri.getLookupVariant();
    if (SoapJmsUri.JNDI_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = (Destination) getContext(soapJmsUri).lookup(soapJmsUri.getDestinationName());
    } else if (SoapJmsUri.SEED_QUEUE_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = session.createQueue(soapJmsUri.getDestinationName());
    } else if (SoapJmsUri.SEED_TOPIC_LOOKUP_VARIANT.equals(lookupVariant)) {
        destination = session.createTopic(soapJmsUri.getDestinationName());
    } else {
        throw new IllegalArgumentException(
                "Unsupported lookup variant " + lookupVariant + " for JMS URI " + soapJmsUri.toString());
    }

    return destination;
}

From source file:unic.mentoring.jms.ctrl.MessageCtrl.java

protected void sendMessage(String message, String topicName) throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
    Connection connection = connectionFactory.createConnection();
    connection.start();/* w  ww  .  j ava2 s.  c om*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(topicName);
    MessageProducer producer = session.createProducer(topic);
    TextMessage jmsMessage = session.createTextMessage();
    jmsMessage.setText(message);

    producer.send(jmsMessage);
    connection.close();
}

From source file:Log4jJMSAppenderExample.java

public Log4jJMSAppenderExample() throws Exception {
    // create a logTopic topic consumer
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616");
    Connection conn = factory.createConnection();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    conn.start();//w  w w .  j  a  va  2s.  co  m
    MessageConsumer consumer = sess.createConsumer(sess.createTopic("logTopic"));
    consumer.setMessageListener(this);
    // log a message
    Logger log = Logger.getLogger(Log4jJMSAppenderExample.class);
    log.info("Test log");
    // clean up
    Thread.sleep(1000);
    consumer.close();
    sess.close();
    conn.close();
    System.exit(1);
}

From source file:org.apache.falcon.messaging.MessageProducer.java

/**
 * @param entityInstanceMessage - Accepts a Message to be send to JMS topic, creates a new
 *                  Topic based on topic name if it does not exist or else
 *                  existing topic with the same name is used to send the message.
 * @throws JMSException//from  w w w. j a  va2s .  c  o  m
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to: {} milli-seconds", DEFAULT_TTL);
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));
}

From source file:org.apache.ivory.messaging.MessageProducer.java

/**
 * //ww w . ja v a2 s .c om
 * @param arguments
 *            - Accepts a Message to be send to JMS topic, creates a new
 *            Topic based on topic name if it does not exist or else
 *            existing topic with the same name is used to send the message.
 * @throws JMSException
 */
protected void sendMessage(EntityInstanceMessage entityInstanceMessage) throws JMSException {

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic entityTopic = session.createTopic(entityInstanceMessage.getTopicName());
    javax.jms.MessageProducer producer = session.createProducer(entityTopic);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    long messageTTL = DEFAULT_TTL;
    try {
        long messageTTLinMins = Long.parseLong(entityInstanceMessage.getBrokerTTL());
        messageTTL = messageTTLinMins * 60 * 1000;
    } catch (NumberFormatException e) {
        LOG.error("Error in parsing broker.ttl, setting TTL to:" + DEFAULT_TTL + " milli-seconds");
    }
    producer.setTimeToLive(messageTTL);
    producer.send(new EntityInstanceMessageCreator(entityInstanceMessage).createMessage(session));

}

From source file:org.seedstack.seed.ws.internal.jms.SoapJmsUri.java

static Destination getReplyToDestination(SoapJmsUri soapJmsUri, Session session)
        throws NamingException, JMSException {
    Destination destination = null;

    String lookupVariant = soapJmsUri.getLookupVariant();
    if (SoapJmsUri.JNDI_LOOKUP_VARIANT.equals(lookupVariant)) {
        String destinationName = soapJmsUri.getParameter("replyToName");
        if (destinationName != null) {
            destination = (Destination) getContext(soapJmsUri).lookup(destinationName);
        }//from w w  w.  j av  a2  s  . c  o m
    } else if (SoapJmsUri.SEED_QUEUE_LOOKUP_VARIANT.equals(lookupVariant)
            || SoapJmsUri.SEED_TOPIC_LOOKUP_VARIANT.equals(lookupVariant)) {
        String queueName = soapJmsUri.getParameter("replyToName");
        String topicName = soapJmsUri.getParameter("topicReplyToName");

        if (queueName != null) {
            destination = session.createQueue(queueName);
        } else if (topicName != null) {
            destination = session.createTopic(topicName);
        }
    } else {
        throw new IllegalArgumentException(
                "Unsupported lookup variant " + lookupVariant + " for JMS URI " + soapJmsUri.toString());
    }

    return destination;
}

From source file:org.apache.falcon.regression.core.supportClasses.JmsMessageConsumer.java

@Override
public void run() {
    try {//from  w  w w. ja  v  a 2  s  . c om
        // Getting JMS connection from the server
        Connection connection = new ActiveMQConnectionFactory(brokerURL).createConnection();
        connection.start();

        // Creating session for sending messages
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);

        try {
            LOGGER.info("Starting to receive messages.");
            int count = 0;
            for (; count < MAX_MESSAGE_COUNT; ++count) {
                Message message = consumer.receive(); //blocking call
                if (message == null) {
                    LOGGER.info("Received empty message, count = " + count);
                } else {
                    LOGGER.info("Received message, id = " + message.getJMSMessageID());
                    receivedMessages.add((MapMessage) message);
                }
            }
            if (count >= MAX_MESSAGE_COUNT) {
                LOGGER.warn("Not reading more messages, already read " + count + " messages.");
            }
        } finally {
            LOGGER.info("Stopping to receive messages.");
            connection.close();
        }
    } catch (Exception e) {
        LOGGER.info("caught exception: " + ExceptionUtils.getStackTrace(e));
    }
}

From source file:org.sakaiproject.kernel.messaging.JmsEmailMessageHandler.java

/**
 * {@inheritDoc}/*  w ww .  j  av  a2 s  .  co  m*/
 *
 * @see org.sakaiproject.kernel.api.messaging.MessageHandler#handle(java.lang.String,
 *      java.lang.String, java.lang.String, javax.jcr.Node)
 */
public void handle(String userID, String filePath, String fileName, Node node) {
    try {
        InputStream inputStream = nodeFactory.getInputStream(filePath);
        String content = IOUtils.readFully(inputStream, "UTF-8");
        Connection conn = connFactory.createConnection();
        conn.setClientID("sakai.emailmessagehandler");
        Session clientSession = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination emailTopic = clientSession.createTopic(emailQueueName);
        MessageProducer client = clientSession.createProducer(emailTopic);
        ObjectMessage mesg = clientSession.createObjectMessage(content);
        mesg.setJMSType(emailJmsType);
        client.send(mesg);
    } catch (JMSException e) {
        log.error(e.getMessage(), e);
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
    } catch (JCRNodeFactoryServiceException e) {
        log.error(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:com.opengamma.examples.analyticservice.ExampleAnalyticServiceUsage.java

private void pushTrade(String securityId, Connection connection, String destinationName,
        JmsConnector jmsConnector, JmsByteArrayMessageDispatcher jmsDispatcher) {
    String providerId = generateTrade(securityId, destinationName, jmsConnector);
    String topicStr = PREFIX + SEPARATOR + providerId + SEPARATOR + "Default" + SEPARATOR
            + ValueRequirementNames.FAIR_VALUE;
    try {//  w  w w  .j a  v  a  2 s .  c  o  m
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(topicStr);
        final MessageConsumer messageConsumer = session.createConsumer(topic);
        messageConsumer.setMessageListener(jmsDispatcher);
    } catch (JMSException e) {
        throw new OpenGammaRuntimeException("Failed to create subscription to JMS topics ", e);
    }
}