Example usage for javax.jms Session close

List of usage examples for javax.jms Session close

Introduction

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

Prototype


void close() throws JMSException;

Source Link

Document

Closes the session.

Usage

From source file:org.springframework.jms.connection.JmsResourceHolder.java

public void closeAll() {
    for (Session session : this.sessions) {
        try {/*ww w .jav a 2  s. c om*/
            session.close();
        } catch (Throwable ex) {
            logger.debug("Could not close synchronized JMS Session after transaction", ex);
        }
    }
    for (Connection con : this.connections) {
        ConnectionFactoryUtils.releaseConnection(con, this.connectionFactory, true);
    }
    this.connections.clear();
    this.sessions.clear();
    this.sessionsPerConnection.clear();
}

From source file:org.springframework.jms.support.JmsUtils.java

/**
 * Close the given JMS Session and ignore any thrown exception.
 * This is useful for typical {@code finally} blocks in manual JMS code.
 * @param session the JMS Session to close (may be {@code null})
 *///from   w  ww  .ja  v a 2  s .c  o m
public static void closeSession(@Nullable Session session) {
    if (session != null) {
        try {
            session.close();
        } catch (JMSException ex) {
            logger.trace("Could not close JMS Session", ex);
        } catch (Throwable ex) {
            // We don't trust the JMS provider: It might throw RuntimeException or Error.
            logger.trace("Unexpected exception on closing JMS Session", 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// www . j a va2s  . c  o  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  w  w. j av a2s .c o m*/
 * @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.inbound.endpoint.protocol.jms.factory.CachedJMSConnectionFactory.java

public boolean closeSession(Session session, boolean forcefully) {
    try {//w w w. j  av a  2 s.co m
        if (this.cacheLevel < JMSConstants.CACHE_SESSION || forcefully) {
            session.close();
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while closing the consumer.");
    }
    return false;
}

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

/**
 * Send the reply back to the response queue/topic
 * *///  w  w w  .j ava 2s  .c  om
public void sendBack(MessageContext synCtx) {
    log.debug("Begin sending reply to the destination queue.");
    MessageProducer producer = null;
    Session session = null;
    try {
        Connection connection = cachedJMSConnectionFactory.getConnection(strUserName, strPassword);
        session = cachedJMSConnectionFactory.getSession(connection);
        producer = cachedJMSConnectionFactory.createProducer(session, replyTo, true);
        Message message = createJMSMessage(synCtx, session, null);
        producer.send(message);
    } catch (JMSException e) {
        log.error("Error sending JMS response", e);
    } catch (Exception e) {
        log.error("Error sending JMS response", e);
    } finally {
        try {
            producer.close();
        } catch (Exception e) {
            log.debug("ERROR: Unable to close the producer");
        }
        try {
            session.close();
        } catch (Exception e) {
            log.debug("ERROR: Unable to close the session");
        }
    }
}

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.ja  v a2 s . co  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: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   www.  j a  v  a 2s  . 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.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
 *
 *//*from  www .  j  a v  a  2s  .  c  om*/
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.registry.caching.invalidator.connection.JMSNotification.java

@Override
public void publish(Object message) {
    Session pubSession = null;
    try {/*www .j  a v a 2 s . co  m*/
        if (connection != null) {
            pubSession = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
            MessageProducer publisher = pubSession.createProducer(destination);
            BytesMessage bytesMessage = pubSession.createBytesMessage();
            bytesMessage.writeBytes((byte[]) message);
            publisher.send(bytesMessage);
        }
    } catch (JMSException e) {
        log.error("Global cache invalidation: Error in publishing the message", e);
    } finally {
        if (pubSession != null) {
            try {
                pubSession.close();
            } catch (JMSException e) {
                log.error("Global cache invalidation: Error in publishing the message", e);
            }
        }
    }
}