Example usage for org.springframework.jms.support JmsUtils closeSession

List of usage examples for org.springframework.jms.support JmsUtils closeSession

Introduction

In this page you can find the example usage for org.springframework.jms.support JmsUtils closeSession.

Prototype

public static void closeSession(@Nullable Session session) 

Source Link

Document

Close the given JMS Session and ignore any thrown exception.

Usage

From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java

@Test
public void testMessageConsumer() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=true");
    ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory);
    Connection connection = null;
    Session session = null;//from w  w w  . j  a v a  2 s. c  o m
    MessageConsumer consumer = null;
    try {
        connection = connectionFactory.createConnection();
        assertEquals(1, connectionFactory.getActiveConnectionCount());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertEquals(1, connectionFactory.getActiveSessionCount());
        Destination myQueue = session.createQueue("test-queue");
        consumer = session.createConsumer(myQueue);

        assertEquals(1, connectionFactory.getActiveMessageConsumerCount());

        consumer.receiveNoWait();

        assertEquals(0, connectionFactory.getActiveMessageProducerCount());
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
        assertEquals(0, connectionFactory.getActiveMessageConsumerCount());
        JmsUtils.closeSession(session);
        assertEquals(0, connectionFactory.getActiveSessionCount());
        JmsUtils.closeConnection(connection);
        assertEquals(0, connectionFactory.getActiveConnectionCount());
    }
}

From source file:org.apache.flink.streaming.connectors.jms.JmsQueueSink.java

@Override
public void close() throws Exception {
    super.close();
    JmsUtils.closeMessageProducer(producer);
    JmsUtils.closeSession(session);
    JmsUtils.closeConnection(connection, true);
}

From source file:fr.xebia.springframework.jms.ManagedCachingConnectionFactoryTest.java

@Test
public void testMessageProducer() throws Exception {
    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(
            "vm://localhost?broker.persistent=false&broker.useJmx=true");
    ManagedConnectionFactory connectionFactory = new ManagedConnectionFactory(activeMQConnectionFactory);
    Connection connection = null;
    Session session = null;//from  w  ww . j a v a  2s  .  c  o m
    MessageProducer messageProducer = null;
    try {
        connection = connectionFactory.createConnection();
        assertEquals(1, connectionFactory.getActiveConnectionCount());
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertEquals(1, connectionFactory.getActiveSessionCount());
        Destination myQueue = session.createQueue("test-queue");
        messageProducer = session.createProducer(myQueue);

        assertEquals(1, connectionFactory.getActiveMessageProducerCount());

        messageProducer.send(myQueue, session.createTextMessage("test"));

        assertEquals(0, connectionFactory.getActiveMessageConsumerCount());
    } finally {
        JmsUtils.closeMessageProducer(messageProducer);
        assertEquals(0, connectionFactory.getActiveMessageProducerCount());
        JmsUtils.closeSession(session);
        assertEquals(0, connectionFactory.getActiveSessionCount());
        JmsUtils.closeConnection(connection);
        assertEquals(0, connectionFactory.getActiveConnectionCount());
    }
}

From source file:org.apache.flink.streaming.connectors.jms.JmsTopicSource.java

@Override
public void run(final SourceContext<T> context) throws Exception {
    TopicSession session = null;//from  ww  w .  j  a v a  2 s  .  c  om
    TopicSubscriber consumer = null;

    try {
        session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createSubscriber(destination, messageSelector, false);

        connection.start();

        while (isRunning) {
            context.collect(convert(consumer.receive()));
        }
    } catch (JMSException e) {
        logger.error("Error receiving message from [{}]: {}", destination.getTopicName(),
                e.getLocalizedMessage());
        throw new UncategorizedJmsException(e);
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
        JmsUtils.closeSession(session);
    }
}

From source file:org.apache.flink.streaming.connectors.jms.JmsQueueSource.java

@Override
public void run(final SourceContext<T> context) throws Exception {
    QueueSession session = null;//w  w  w.ja va  2s.co  m
    QueueReceiver consumer = null;

    try {
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        consumer = session.createReceiver(destination, messageSelector);

        connection.start();

        while (isRunning) {
            context.collect(convert(consumer.receive()));
        }
    } catch (JMSException e) {
        logger.error("Error receiving message from [{}]: {}", destination.getQueueName(),
                e.getLocalizedMessage());
        throw new UncategorizedJmsException(e);
    } finally {
        JmsUtils.closeMessageConsumer(consumer);
        JmsUtils.closeSession(session);
    }
}

From source file:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * // w  ww .jav a2  s. com
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

From source file:fr.xebia.springframework.jms.support.converter.JaxbMessageConverterSpringTest.java

@After
public void after() throws Exception {
    JmsUtils.closeSession(session);
    JmsUtils.closeConnection(connection);
}

From source file:com.ccc.ccm.client.JMSTemplateAutowired.java

/**
* Execute the action specified by the given action object within a
* JMS Session. Generalized version of <code>execute(SessionCallback)</code>,
* allowing the JMS Connection to be started on the fly.
* <p>Use <code>execute(SessionCallback)</code> for the general case.
* Starting the JMS Connection is just necessary for receiving messages,
* which is preferably achieved through the <code>receive</code> methods.
* @param action callback object that exposes the Session
* @param startConnection whether to start the Connection
* @return the result object from working with the Session
* @throws JmsException if there is any problem
* @see #execute(SessionCallback)//  ww  w.jav a2  s  . c o  m
* @see #receive
*/
public <T> T execute(SessionCallback<T> action, boolean startConnection) throws JmsException {
    Assert.notNull(action, "Callback object must not be null");
    Connection conToClose = null;
    Session sessionToClose = null;
    try {
        Session sessionToUse = ConnectionFactoryUtils.doGetTransactionalSession(getConnectionFactory(),
                this.transactionalResourceFactory, startConnection);
        if (sessionToUse == null) {
            conToClose = createConnection();
            sessionToClose = createSession(conToClose);
            if (startConnection) {
                conToClose.start();
            }
            sessionToUse = sessionToClose;
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Executing callback on JMS Session: " + sessionToUse);
        }
        return action.doInJms(sessionToUse);
    } catch (JMSException ex) {
        throw convertJmsAccessException(ex);
    } finally {
        JmsUtils.closeSession(sessionToClose);
        ConnectionFactoryUtils.releaseConnection(conToClose, getConnectionFactory(), startConnection);
    }
}

From source file:org.springframework.cloud.stream.binder.jms.solace.SolaceQueueProvisioner.java

@Override
public Destinations provisionTopicAndConsumerGroup(String name, String... groups) {
    Destinations.Factory destinationsFactory = new Destinations.Factory();

    try {/* www .  j  a  va 2  s  . com*/
        Topic topic = JCSMPFactory.onlyInstance().createTopic(name);
        JCSMPSession session = sessionFactory.build();
        Connection connection = connectionFactory.createConnection();
        javax.jms.Session jmsSession = connection.createSession(false, 1);

        // Using Durable... because non-durable Solace TopicEndpoints don't have names
        TopicEndpoint topicEndpoint = new DurableTopicEndpointImpl(name);
        session.provision(topicEndpoint, null, JCSMPSession.FLAG_IGNORE_ALREADY_EXISTS);
        destinationsFactory.withTopic(jmsSession.createTopic(name));

        if (ArrayUtils.isEmpty(groups)) {
            return destinationsFactory.build();
        }

        for (String group : groups) {
            destinationsFactory.addGroup(jmsSession.createQueue(group));
            doProvision(session, topic, group);
        }

        JmsUtils.commitIfNecessary(jmsSession);
        JmsUtils.closeSession(jmsSession);
        JmsUtils.closeConnection(connection);
    } catch (JCSMPErrorResponseException e) {
        if (JCSMPErrorResponseSubcodeEx.SUBSCRIPTION_ALREADY_PRESENT != e.getSubcodeEx()) {
            throw new RuntimeException(e);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return destinationsFactory.build();
}

From source file:org.springframework.integration.jms.JmsOutboundGateway.java

private Object sendAndReceiveWithContainer(Message<?> requestMessage) throws JMSException {
    Connection connection = this.createConnection(); // NOSONAR - closed in ConnectionFactoryUtils.
    Session session = null;/*from w  w w .j  a v  a2  s . co  m*/
    Destination replyTo = this.replyContainer.getReplyDestination();
    try {
        session = this.createSession(connection);

        // convert to JMS Message
        Object objectToSend = requestMessage;
        if (this.extractRequestPayload) {
            objectToSend = requestMessage.getPayload();
        }
        javax.jms.Message jmsRequest = this.messageConverter.toMessage(objectToSend, session);

        // map headers
        this.headerMapper.fromHeaders(requestMessage.getHeaders(), jmsRequest);

        jmsRequest.setJMSReplyTo(replyTo);
        connection.start();
        if (logger.isDebugEnabled()) {
            logger.debug("ReplyTo: " + replyTo);
        }

        Integer priority = new IntegrationMessageHeaderAccessor(requestMessage).getPriority();
        if (priority == null) {
            priority = this.priority;
        }
        Destination requestDestination = this.determineRequestDestination(requestMessage, session);

        Object reply = null;
        if (this.correlationKey == null) {
            /*
             * Remove any existing correlation id that was mapped from the inbound message
             * (it will be restored in the reply by normal ARPMH header processing).
             */
            jmsRequest.setJMSCorrelationID(null);
            reply = doSendAndReceiveAsyncDefaultCorrelation(requestDestination, jmsRequest, session, priority);
        } else {
            reply = doSendAndReceiveAsync(requestDestination, jmsRequest, session, priority);
        }
        /*
         * Remove the gateway's internal correlation Id to avoid conflicts with an upstream
         * gateway.
         */
        if (reply instanceof javax.jms.Message) {
            ((javax.jms.Message) reply).setJMSCorrelationID(null);
        }
        return reply;
    } finally {
        JmsUtils.closeSession(session);
        ConnectionFactoryUtils.releaseConnection(connection, this.connectionFactory, true);
    }
}