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.jbpm.jms.JmsConnectorService.java

final void sendMessage(Job job) throws JMSException {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    try {/*from   w w  w.j  a  v  a  2  s.  c om*/
        Message message = session.createMessage();
        populateMessage(message, job);

        MessageProducer messageProducer = session.createProducer(serviceFactory.getDestination());
        messageProducer.send(message);
    } finally {
        // there is no need to close the producers of a closed session
        session.close();
    }
}

From source file:org.mot.common.mq.ActiveMQFactory.java

/**
 * Method for closing the session ... make sure to call each time a session is opened
 * /*  w w w  . j av  a 2s  .  c  om*/
 * @param session
 */
private void closeSession(Session session) {
    try {
        session.close();
    } catch (JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.mule.modules.jmsbatchmessaging.JmsBatchMessagingConnector.java

/**
 * Complete the batch operation and release all resources (including closing any open transactions.)
 * <p/>//from  ww  w. j  a v  a  2s  . com
 * {@sample.xml ../../../doc/jms-batch-messaging-connector.xml.sample
 * jms-batch-messaging:complete}
 *
 * @param muleMessage the current MuleMessage
 * @throws Exception
 */
@Processor
@Inject
public void complete(MuleMessage muleMessage) throws Exception {
    Session session = muleMessage.getInboundProperty("session");
    MessageConsumer consumer = muleMessage.getInboundProperty("consumer");

    Boolean isTransactional = muleMessage.getInboundProperty("transactional");

    if (isTransactional) {
        session.commit();
    }
    session.close();
    consumer.close();
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public void send(Scenario scenario) throws Exception {
    Connection connection = null;
    try {//from   w  ww.  java 2s  . c  om
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createInputDestination(session, scenario);
            MessageProducer producer = null;
            try {
                producer = session.createProducer(destination);
                if (scenario.isPersistent()) {
                    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                }
                scenario.send(session, producer);
            } finally {
                if (producer != null) {
                    producer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

public Message receive(Scenario scenario) throws Exception {
    assertNotNull("scenario is null!", scenario);
    Connection connection = null;
    try {//from www.java2 s  . co m
        connection = getConnection(false, false);
        connection.start();
        Session session = null;
        try {
            session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge());
            Destination destination = createOutputDestination(session, scenario);
            MessageConsumer consumer = null;
            try {
                consumer = session.createConsumer(destination);
                return scenario.receive(session, consumer);
            } finally {
                if (consumer != null) {
                    consumer.close();
                }
            }
        } finally {
            if (session != null) {
                session.close();
            }
        }
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Purge destinations for clean test setup. Especially applicable to WMQ tests, as messages from
 * other tests may still exist from other tests' runs.
 * <p/>//www  .j av a 2 s.co m
 * Well-behaving tests should drain both inbound and outbound destinations, as well as any intermediary ones.
 * @param destination destination name without any protocol specifics
 */
protected void purge(final String destination) throws JMSException {
    Connection c = null;
    Session s = null;
    try {
        logger.debug("purging queue : " + destination);
        c = getConnection(false, false);
        assertNotNull(c);
        c.start();

        s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination d = s.createQueue(destination);
        MessageConsumer consumer = s.createConsumer(d);

        while (consumer.receiveNoWait() != null) {
            logger.debug("Destination " + destination + " isn't empty, draining it");
        }
    } catch (Exception e) {
        logger.error("unable to purge : " + destination);
    } finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
}

From source file:org.mule.transport.jms.integration.AbstractJmsFunctionalTestCase.java

/**
 * Clear the specified topic/*from w  ww  .j  a  va 2 s .  c o m*/
 */
protected void purgeTopic(String destination, String topic) throws Exception {
    Connection c = null;
    Session s = null;

    try {
        logger.debug("purging topic : " + topic);
        c = getConnection(true, false);
        if (c == null) {
            logger.debug("could not create a connection to topic : " + destination);
        }

        c.start();
        s = ((TopicConnection) c).createTopicSession(true, Session.SESSION_TRANSACTED);

        logger.debug("created topic session");
        Topic dest = s.createTopic(destination);
        logger.debug("created topic destination");

        if (client != null) {
            client.dispose();
        }

        MessageConsumer consumer = null;

        try {
            consumer = s.createDurableSubscriber(dest, topic);
            logger.debug("created consumer");
            while (consumer.receiveNoWait() != null) {
                logger.debug("Topic " + topic + " isn't empty, draining it");
            }
            logger.debug("topic should be empty");
            consumer.close();
            s.unsubscribe(topic);
        } catch (JMSException e) {
            logger.debug("could not unsubscribe : " + topic);
        }
    }

    finally {
        if (c != null) {
            c.stop();
            if (s != null) {
                s.close();
            }
            try {
                c.close();
            } catch (JMSException e) {
                logger.warn("Failed to close jms connection: " + e.getMessage());
            }
        }
    }
    logger.debug("completed draining topic :" + topic);
}

From source file:org.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;//ww w .  ja v a2  s .co  m
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

From source file:org.sofun.core.messaging.SofunMessagingServiceImpl.java

@Override
public void sendMessage(Serializable message, String destination) {

    Connection connection = null;
    Session session = null;
    MessageProducer sender = null;/*  w w w  .  java2 s . c om*/
    Queue q = getQueueFor(destination);
    if (q == null) {
        log.error("Cannot find associated queue for destination=" + destination);
    }
    try {
        connection = connFactory.createConnection(SofunMessagingCredentials.USERNAME,
                SofunMessagingCredentials.PASSWORD);
        session = connection.createSession(true, 0);
        sender = session.createProducer(q);
        ObjectMessage msg = session.createObjectMessage(message);
        sender.send(msg);
    } catch (Exception e) {
        log.error(e.getMessage());
    } finally {
        try {
            if (sender != null) {
                sender.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            log.error(e.getMessage());
        }

    }

}

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

/**
 * Obtain a JMS Session that is synchronized with the current transaction, if any.
 * @param connectionFactory the JMS ConnectionFactory to bind for
 * (used as TransactionSynchronizationManager key)
 * @param resourceFactory the ResourceFactory to use for extracting or creating
 * JMS resources//ww w  .  j  a  v a2s  .  c o  m
 * @param startConnection whether the underlying JMS Connection approach should be
 * started in order to allow for receiving messages. Note that a reused Connection
 * may already have been started before, even if this flag is {@code false}.
 * @return the transactional Session, or {@code null} if none found
 * @throws JMSException in case of JMS failure
 */
@Nullable
public static Session doGetTransactionalSession(ConnectionFactory connectionFactory,
        ResourceFactory resourceFactory, boolean startConnection) throws JMSException {

    Assert.notNull(connectionFactory, "ConnectionFactory must not be null");
    Assert.notNull(resourceFactory, "ResourceFactory must not be null");

    JmsResourceHolder resourceHolder = (JmsResourceHolder) TransactionSynchronizationManager
            .getResource(connectionFactory);
    if (resourceHolder != null) {
        Session session = resourceFactory.getSession(resourceHolder);
        if (session != null) {
            if (startConnection) {
                Connection con = resourceFactory.getConnection(resourceHolder);
                if (con != null) {
                    con.start();
                }
            }
            return session;
        }
        if (resourceHolder.isFrozen()) {
            return null;
        }
    }
    if (!TransactionSynchronizationManager.isSynchronizationActive()) {
        return null;
    }
    JmsResourceHolder resourceHolderToUse = resourceHolder;
    if (resourceHolderToUse == null) {
        resourceHolderToUse = new JmsResourceHolder(connectionFactory);
    }
    Connection con = resourceFactory.getConnection(resourceHolderToUse);
    Session session = null;
    try {
        boolean isExistingCon = (con != null);
        if (!isExistingCon) {
            con = resourceFactory.createConnection();
            resourceHolderToUse.addConnection(con);
        }
        session = resourceFactory.createSession(con);
        resourceHolderToUse.addSession(session, con);
        if (startConnection) {
            con.start();
        }
    } catch (JMSException ex) {
        if (session != null) {
            try {
                session.close();
            } catch (Throwable ex2) {
                // ignore
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (Throwable ex2) {
                // ignore
            }
        }
        throw ex;
    }
    if (resourceHolderToUse != resourceHolder) {
        TransactionSynchronizationManager.registerSynchronization(new JmsResourceSynchronization(
                resourceHolderToUse, connectionFactory, resourceFactory.isSynchedLocalTransactionAllowed()));
        resourceHolderToUse.setSynchronizedWithTransaction(true);
        TransactionSynchronizationManager.bindResource(connectionFactory, resourceHolderToUse);
    }
    return session;
}