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:biz.fstechnology.micro.common.jms.SyncSessionCallbackImpl.java

/**
 * @see org.springframework.jms.core.SessionCallback#doInJms(javax.jms.Session)
 *///from   ww  w . j  a  va2 s .co m
@Override
public T doInJms(Session session) throws JMSException {
    Topic destTopic = session.createTopic(topicName);
    TemporaryQueue responseQueue = session.createTemporaryQueue();

    // oh my god...
    // why MessageProducer & MessageConsumer not have AutoCloseable!!!
    try (AutoCloseableWrapper<MessageProducer> producerCont = new AutoCloseableWrapper<>(
            () -> createProducer(session, destTopic), JmsUtils::closeMessageProducer);
            AutoCloseableWrapper<MessageConsumer> consumerCont = new AutoCloseableWrapper<>(
                    () -> createConsumer(session, responseQueue), JmsUtils::closeMessageConsumer)) {

        MessageProducer producer = producerCont.unwrap();
        MessageConsumer consumer = consumerCont.unwrap();
        consumer.setMessageListener(this);

        if (getMessageCreator() == null) {
            RequestMessageCreator messageCreator = new RequestMessageCreator();
            messageCreator.setContents(getMessageObj());
            setMessageCreator(messageCreator);
        }
        if (getMessageCreator() instanceof RequestMessageCreator) {
            ((RequestMessageCreator) getMessageCreator()).setReplyTo(responseQueue);
        }
        Message requestMessage = getMessageCreator().createMessage(session);
        producer.send(destTopic, requestMessage);

        if (getMessageCreator() instanceof RequestMessageCreator) {
            return waitResponse(consumer, requestMessage);
        } else {
            return null;
        }
    }
}

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

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*w  w  w  .ja  v a  2 s .com*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(getTopicName());
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    for (int index = 0; index < outputFeedNames.length; ++index) {
        MapMessage m = (MapMessage) consumer.receive();
        System.out.println("Consumed: " + m.toString());
        assertMessage(m);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_NAMES.getName()),
                outputFeedNames[index]);
        Assert.assertEquals(m.getString(WorkflowExecutionArgs.OUTPUT_FEED_PATHS.getName()),
                outputFeedPaths[index]);
    }
    connection.close();
}

From source file:org.wso2.carbon.sample.consumer.TopicConsumer.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {/*w  w  w  .  ja va  2 s .  c o  m*/
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message : " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message : " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message : " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.sink.util.TopicConsumer.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {/*from   www. j av  a 2 s  .  c  o  m*/
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                resultContainer.eventReceived(message);
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message : " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message : " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message : " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

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

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();//from w  w  w  .  jav  a 2 s .co m

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(TOPIC_NAME);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();
    verifyMesssage(consumer);

    connection.close();
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

public String send(Email email) throws MessagingException, JMSException {
    try {/*from w w  w .  j a v  a2s .  c  om*/
        email.buildMimeMessage();
    } catch (Exception e) {
        // this is a lossy cast. This would be a commons EmailException
        // this up cast is to keep commons-email out of our direct bindings
        throw new MessagingException(e);
    }

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        email.getMimeMessage().writeTo(os);
    } catch (javax.mail.MessagingException e) {
        throw new MessagingException(e);

    } catch (IOException e) {
        throw new MessagingException(e);
    }

    String content = os.toString();
    Connection conn = connectionFactory.createTopicConnection();
    conn.setClientID(getNextId());
    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);
    // TODO finish this
    return null;

}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from   w  w  w  .  jav a2 s  . com

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

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

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//from w  w  w .j av a2s .c  o  m
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {

        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                messageCount++;
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    preservedEventList.add(map);
                    log.info("Received Map Message : \n" + map + "\n");
                } else if (message instanceof TextMessage) {
                    String textMessage = ((TextMessage) message).getText();
                    preservedEventList.add(textMessage);
                    log.info("Received Text Message : \n" + textMessage + "\n");
                } else {
                    preservedEventList.add(message.toString());
                    log.info("Received message : \n" + message.toString() + "\n");
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:io.fabric8.mq.controller.coordination.BrokerJMXPropertiesTest.java

@Test
public void testNumberOfTopicProducers() throws Exception {
    String uriString = brokerService.getDefaultSocketURIString();
    ConnectionFactory factory = new ActiveMQConnectionFactory(uriString);
    Connection connection = factory.createConnection();
    connection.start();/*from  w w w .  j a  v a2 s .c o  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    int numberOfProducers = 10;
    List<MessageProducer> producers = new ArrayList<>();
    Topic topic = session.createTopic("topic.test");
    for (int i = 0; i < numberOfProducers; i++) {

        MessageProducer producer = session.createProducer(topic);
        producers.add(producer);

    }
    ObjectName root = BrokerJmxUtils.getRoot(client);
    Assert.assertNotNull(root);
    List<ObjectName> list = BrokerJmxUtils.getDestinations(client, root, "Topic");
    Assert.assertNotNull(list);
    Assert.assertFalse(list.isEmpty());
    ObjectName result = null;
    for (ObjectName objectName : list) {
        if (objectName.getKeyProperty("destinationName").equals("topic.test")) {
            result = objectName;
        }
    }
    Assert.assertNotNull(result);
    Object producerCount = BrokerJmxUtils.getAttribute(client, result, "ProducerCount");
    Assert.assertNotNull(producerCount);
    int pc = Integer.parseInt(producerCount.toString());
    Assert.assertEquals(pc, numberOfProducers);
    connection.close();
}

From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    this.terminateConnection = connectionFactory.createConnection();
    terminateConnection.start();/*from  ww  w. ja va  2s . c o m*/

    Session session = terminateConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic topic = session.createTopic(Constants.TERMINATE_CONSUMER_TOPIC);
    final MessageConsumer consumer = session.createConsumer(topic);

    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        terminateConnection.close();
                        return;
                    }

                    if (consumerId.equals(bean.getConsumerId())) {
                        if (bean.getStatus() == ConsumerStatus.REQUEST_TERMINATE) {
                            System.out.println(getName() + " has been requested to terminate and will exit.");
                            cbean.setStatus(ConsumerStatus.REQUEST_TERMINATE);
                            Thread.currentThread().sleep(2500);
                            System.exit(0);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    consumer.setMessageListener(listener);

}