Example usage for javax.jms Session createQueue

List of usage examples for javax.jms Session createQueue

Introduction

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

Prototype

Queue createQueue(String queueName) throws JMSException;

Source Link

Document

Creates a Queue object which encapsulates a specified provider-specific queue name.

Usage

From source file:org.wso2.carbon.bpmn.extensions.jms.JMSSender.java

/**
 * Sends a message to a queue/topic using shared connections, sessions and message producers
 * @param connectionFactory// w  w w. j  a va 2 s. co  m
 * @param text
 */

public void sendMessage(JMSConnectionFactory connectionFactory, int cacheLevel, String target, String text) {

    try {

        Connection connection = connectionFactory.getConnection();
        Session session = connectionFactory.getSession(connection);
        Destination destination;

        if (connectionFactory.isQueue()) {
            destination = session.createQueue(target);
            if (destination == null) {
            }
        } else {
            destination = session.createTopic(target);
        }

        if (destination != null) {

            log.info("initializing jms message producer..");
            MessageProducer producer = connectionFactory.getMessageProducer(connection, session, destination);

            JMSMessageSender jmsMessageSender = new JMSMessageSender(connection, session, producer, destination,
                    cacheLevel, connectionFactory.isQueue());
            TextMessage message = session.createTextMessage(text);
            jmsMessageSender.send(message, null);

        } else {
            log.error("Destination not specified");
        }
    } catch (JMSException ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to retrieve message from specified message queue
 *
 * @param queueName Name of the queue/*from  w  w w.  jav a 2 s  .  co  m*/
 * @param timeout Timeout value (in milliseconds)
 * @return Retrieved message from the queue
 * @throws JMSException if error occurred
 */
public Message consumeMessageFromQueue(String queueName, long timeout) throws JMSException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

        // Create a Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageConsumer from the Session to the Topic or Queue
        consumer = session.createConsumer(destination);

        // Wait for a message
        return consumer.receive(timeout);

    } finally {
        if (consumer != null) {
            consumer.close();
        }
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.wso2.carbon.esb.scenario.test.common.jms.ActiveMQJMSClient.java

/**
 * Function to produce message to ActiveMQ Queue
 *
 * @param queueName name of the target queue
 * @param messageStr message to place/*from w  ww.  j  a v  a 2  s .c om*/
 * @throws JMSException
 */
public void produceMessageToQueue(String queueName, String messageStr) throws JMSException {

    Connection connection = null;
    Session session = null;

    try {
        // Create a ConnectionFactory
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);

        // Create a Connection
        connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);

        // Create a Session
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // Create the destination (Topic or Queue)
        Destination destination = session.createQueue(queueName);

        // Create a MessageProducer from the Session to the Topic or Queue
        MessageProducer producer = session.createProducer(destination);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

        // Create a messages
        TextMessage message = session.createTextMessage(messageStr);

        // Tell the producer to send the message
        producer.send(message);

    } finally {
        // Clean up
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.wso2.carbon.event.input.adapter.jms.internal.util.JMSTaskManager.java

/**
 * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
 *
 * @param session which is used to create the destinations if not present and if possible
 * @return the JMS Destination to which this STM listens for messages
 *///w w w. j a v  a  2s .com
private Destination getDestination(Session session) {
    if (destination == null) {
        try {
            context = getInitialContext();
            destination = JMSUtils.lookupDestination(context, getDestinationJNDIName(),
                    JMSUtils.getDestinationTypeAsString(destinationType));
            if (log.isDebugEnabled()) {
                log.debug("JMS Destination with JNDI name : " + getDestinationJNDIName()
                        + " found for event adapter " + eventAdapterName);
            }
        } catch (NamingException e) {
            try {
                switch (destinationType) {
                case JMSConstants.QUEUE: {
                    destination = session.createQueue(getDestinationJNDIName());
                    break;
                }
                case JMSConstants.TOPIC: {
                    destination = session.createTopic(getDestinationJNDIName());
                    break;
                }
                default: {
                    handleException("Error looking up JMS destination : " + getDestinationJNDIName()
                            + " using JNDI properties : " + jmsProperties, e);
                }
                }
            } catch (JMSException j) {
                handleException("Error looking up JMS destination and auto " + "creating JMS destination : "
                        + getDestinationJNDIName() + " using JNDI properties : " + jmsProperties, e);
            }
        }
    }
    return destination;
}

From source file:org.wso2.carbon.event.input.adaptor.jms.internal.util.JMSTaskManager.java

/**
 * Return the JMS Destination for the JNDI name of the Destination from the InitialContext
 *
 * @param session which is used to create the destinations if not present and if possible
 * @return the JMS Destination to which this STM listens for messages
 *///from  w w w . j a v a 2 s  .  c om
private Destination getDestination(Session session) {
    if (destination == null) {
        try {
            context = getInitialContext();
            destination = JMSUtils.lookupDestination(context, getDestinationJNDIName(),
                    JMSUtils.getDestinationTypeAsString(destinationType));
            if (log.isDebugEnabled()) {
                log.debug("JMS Destination with JNDI name : " + getDestinationJNDIName()
                        + " found for event adaptor " + eventAdaptorName);
            }
        } catch (NamingException e) {
            try {
                switch (destinationType) {
                case JMSConstants.QUEUE: {
                    destination = session.createQueue(getDestinationJNDIName());
                    break;
                }
                case JMSConstants.TOPIC: {
                    destination = session.createTopic(getDestinationJNDIName());
                    break;
                }
                default: {
                    handleException("Error looking up JMS destination : " + getDestinationJNDIName()
                            + " using JNDI properties : " + jmsProperties, e);
                }
                }
            } catch (JMSException j) {
                handleException("Error looking up JMS destination and auto " + "creating JMS destination : "
                        + getDestinationJNDIName() + " using JNDI properties : " + jmsProperties, e);
            }
        }
    }
    return destination;
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.factory.JMSConnectionFactory.java

public Destination createDestination(Session session, String destinationName) {
    Destination destination = null;
    try {/*from  www  . j a va2  s.co m*/
        if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
            destination = JMSUtils.lookupDestination(ctx, destinationName, JMSConstants.DESTINATION_TYPE_QUEUE);
        } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
            destination = JMSUtils.lookupDestination(ctx, destinationName, JMSConstants.DESTINATION_TYPE_TOPIC);
        }
    } catch (NameNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find destination '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + "'. " + e.getMessage());
            logger.debug("Creating destination '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + ".");
        }
        try {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                destination = (Queue) session.createQueue(destinationName);
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                destination = (Topic) session.createTopic(destinationName);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Created '" + destinationName + "' on connection factory for '"
                        + this.connectionFactoryString + "'.");
            }
        } catch (JMSException e1) {
            logger.error("Could not find nor create '" + destinationName + "' on connection factory for '"
                    + this.connectionFactoryString + "'. " + e1.getMessage(), e1);
        }

    } catch (NamingException e) {
        logger.error("Naming exception while obtaining connection factory for '" + this.connectionFactoryString
                + "' " + e.getMessage(), e);
    }

    return destination;
}

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 queue via ActiveMQ message broker
 *
 * @param queueName             the queue which the messages should be published under
 * @param messageFormat         messageFormat of the test data file
 * @param testCaseFolderName    Testcase folder name which is in the test artifacts folder
 * @param dataFileName          data file name with the extension to be read
 *
 */// w  ww.  j a  v  a  2 s.c  o m
public static void publishToQueue(String queueName, String messageFormat, String testCaseFolderName,
        String dataFileName) throws JMSException, IOException, NamingException {

    //create connection
    Properties properties = new Properties();
    properties.load(ClassLoader.getSystemClassLoader().getResourceAsStream("activemq.properties"));
    Context context = new InitialContext(properties);
    QueueConnectionFactory connFactory = (QueueConnectionFactory) context.lookup("ConnectionFactory");
    QueueConnection queueConnection = connFactory.createQueueConnection();
    queueConnection.start();
    Session session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(queueName);
    MessageProducer producer = session.createProducer(queue);

    //publish data
    String filePath = getTestDataFileLocation(testCaseFolderName, dataFileName);
    List<String> messagesList = readFile(filePath);
    if (messageFormat.equalsIgnoreCase("map")) {
        publishMapMessages(producer, session, messagesList);
    } else {
        publishTextMessage(producer, session, messagesList);
    }

    //close connection
    producer.close();
    session.close();
    queueConnection.stop();
    queueConnection.close();
}

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

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*from ww  w .jav a  2 s. c om*/
        queueConnection = queueConnectionFactory.createQueueConnection();

        queueConnection.start();
    } catch (JMSException e) {
        log.info("Can not create queue connection." + e);
        return;
    }
    Session session = null;
    try {

        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);

        int count = 0;
        long totalLatency = 0;
        long lastTimestamp = System.currentTimeMillis();

        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                //                    if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                long currentTime = System.currentTimeMillis();
                long sentTimestamp = (Long) mapMessage.getObject("time");

                totalLatency = totalLatency + (currentTime - sentTimestamp);

                int logCount = 1000;

                if ((count % logCount == 0) && (count > warmUpCount)) {
                    double rate = (logCount * 1000.0d / (System.currentTimeMillis() - lastTimestamp));
                    log.info("Consumer: " + consumerId + " (" + logCount + " received) rate: " + rate
                            + " Latency:" + (totalLatency / (logCount * 1.0d)));
                    //                            log.info("total latency:" + totalLatency);
                    log.info("Total rate: " + (int) (consumers * rate));
                    totalLatency = 0;
                    lastTimestamp = System.currentTimeMillis();
                }
                count++;
            }
        }
        log.info("Finished listening for messages.");

    } catch (JMSException e) {
        log.info("Can not subscribe." + e);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                log.error(e);
            }
        }
        try {
            queueConnection.stop();
            queueConnection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

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

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {//from w w w  .j  a v a 2s.  com
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueConnection.start();
    } catch (JMSException e) {
        log.error("Can not create queue connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {
        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        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();
        queueConnection.stop();
        queueConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

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

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*w ww .  j  av  a2 s  . c  o m*/
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueConnection.start();
    } catch (JMSException e) {
        log.error("Can not create queue connection." + e.getMessage(), e);
        return;
    }
    Session session;
    try {
        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages at " + queueName);
        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();
        queueConnection.stop();
        queueConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}