Example usage for javax.jms Connection createSession

List of usage examples for javax.jms Connection createSession

Introduction

In this page you can find the example usage for javax.jms Connection createSession.

Prototype


Session createSession(boolean transacted, int acknowledgeMode) throws JMSException;

Source Link

Document

Creates a Session object, specifying transacted and acknowledgeMode .

Usage

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

protected Session createSession(Connection connection) {
    try {// w w w .j  a va2  s .  c o  m
        if (JMSConstants.JMS_SPEC_VERSION_1_1.equals(jmsSpec)
                || JMSConstants.JMS_SPEC_VERSION_2_0.equals(jmsSpec)) {
            return connection.createSession(transactedSession, sessionAckMode);
        } else {
            if (this.destinationType.equals(JMSConstants.JMSDestinationType.QUEUE)) {
                return (QueueSession) ((QueueConnection) (connection)).createQueueSession(transactedSession,
                        sessionAckMode);
            } else if (this.destinationType.equals(JMSConstants.JMSDestinationType.TOPIC)) {
                return (TopicSession) ((TopicConnection) (connection)).createTopicSession(transactedSession,
                        sessionAckMode);
            }
        }
    } catch (JMSException e) {
        logger.error("JMS Exception while obtaining session for factory '" + this.connectionFactoryString + "' "
                + e.getMessage(), e);
    }

    return null;
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testScheduledStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/*from   w  w w .  j  ava2s  .  c o  m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.setDeliveryDelay(2000);
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyScheduledStats(defaultQueueName, 1, publishedMessageSize.get());

    consumeTestQueueMessages(1);

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyScheduledStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testQueueLargeMessageSize() throws Exception {

    ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf;
    acf.setMinLargeMessageSize(1000);//from  w  w  w. jav  a 2  s  . c  o m
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    String testText = StringUtils.repeat("t", 5000);
    ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText);
    session.createProducer(session.createQueue(defaultQueueName)).send(message);

    verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());

    connection.close();

    this.killServer();
    this.restartServer();

    verifyPendingStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 1, message.getCoreMessage().getPersistentSize());

}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();/*  www . jav a 2 s  .  co m*/
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyDeliveringStats(defaultQueueName, 0, 0);

    MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
    Message msg = consumer.receive();
    verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
    msg.acknowledge();

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyDeliveringStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testQueueLargeMessageSizeTX() throws Exception {

    ActiveMQConnectionFactory acf = (ActiveMQConnectionFactory) cf;
    acf.setMinLargeMessageSize(1000);//  w ww.j  av  a 2s.  c  o m
    Connection connection = cf.createConnection();
    connection.start();
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);

    String testText = StringUtils.repeat("t", 2000);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    ActiveMQTextMessage message = (ActiveMQTextMessage) session.createTextMessage(testText);
    for (int i = 0; i < 10; i++) {
        producer.send(message);
    }

    //not commited so should be 0
    verifyPendingStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 0, message.getCoreMessage().getPersistentSize() * 10);

    session.commit();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize() * 10);

    connection.close();

    this.killServer();
    this.restartServer();

    verifyPendingStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
    verifyPendingDurableStats(defaultQueueName, 10, message.getCoreMessage().getPersistentSize());
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Run of Thread. */
public void run() {
    try {//from w w  w  .ja va  2s.c  om
        running = true;
        this.url = "failover://vm://" + this.brokerName;
        BSPActiveMQConnFactory connectionFactory = new BSPActiveMQConnFactoryImpl();
        connectionFactory.activeMQConnFactoryMethod(url);
        connectionFactory.setOptimizeAcknowledge(true);
        Connection connection = connectionFactory.createConnection();
        if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) {
            connection.setClientID(clientId);
        }
        connection.setExceptionListener(this);
        connection.start();
        session = connection.createSession(transacted, ackMode);
        if (topic) {
            destination = session.createTopic(subject);
        } else {
            destination = session.createQueue(subject);
        }
        replyProducer = session.createProducer(null);
        replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        if (durable && topic) {
            consumer = session.createDurableSubscriber((Topic) destination, consumerName);
        } else {
            consumer = session.createConsumer(destination);
        }
        consumeMessages(connection, session, consumer, receiveTimeOut);
        LOG.info("[ConsumerTool] has received " + this.messagesReceived + " object messages from <"
                + this.subject + ">.");
        LOG.info("[ConsumerTool] has received " + this.messageCount + " BSP messages from <" + this.subject
                + ">.");
        this.receiver.addMessageCount(this.messageCount);
        this.receiver.addMessageBytesCount(messageBytesCount);
    } catch (Exception e) {
        throw new RuntimeException("[ConsumerTool] caught: ", e);
    }
}

From source file:org.springframework.jms.core.JmsTemplate.java

/**
 * Create a JMS Session for the given Connection.
 * <p>This implementation uses JMS 1.1 API.
 * @param con the JMS Connection to create a Session for
 * @return the new JMS Session//from  w  w  w . ja  v a  2  s .com
 * @throws JMSException if thrown by JMS API methods
 */
protected Session createSession(Connection con) throws JMSException {
    return con.createSession(isSessionTransacted(), getSessionAcknowledgeMode());
}

From source file:tools.ConsumerTool.java

@Override
public void run() {
    Connection connection = null;
    Session session = null;/*  w  w w  .  j  av a2 s. c om*/
    try {
        connection = connectionFactory.createConnection();
        if (clientId != null) {
            connection.setClientID(clientId);
        }
        connection.start();
        session = connection.createSession(transacted, acknowledgeMode);
        Destination destination = null;
        if (jndiLookupDestinations) {
            destination = (Destination) context.lookup(destinationName);
        } else {
            if (useQueueDestinations) {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryQueue();
                } else {
                    destination = session.createQueue(destinationName);
                }
            } else {
                if (useTemporaryDestinations) {
                    destination = session.createTemporaryTopic();
                } else {
                    destination = session.createTopic(destinationName);
                }
            }
        }

        if (useQueueBrowser) {
            runQueueBrowser(session, (Queue) destination);
        } else {
            MessageConsumer consumer = null;
            if (useQueueDestinations) { //Queues
                if (selector != null) {
                    consumer = session.createConsumer(destination, selector);
                } else {
                    consumer = session.createConsumer(destination);
                }
            } else { //Queues
                if (durable) { //Durable Subscribers
                    if (selector != null) {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName,
                                selector, false);
                    } else {
                        consumer = session.createDurableSubscriber((Topic) destination, subscriptionName);
                    }
                } else { //Non-Durable Subscribers
                    if (selector != null) {
                        consumer = session.createConsumer(destination, selector);
                    } else {
                        consumer = session.createConsumer(destination);
                    }
                }
            }

            if (useAsyncListener) {
                final Session consumerSession = session;

                final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0);
                consumer.setMessageListener(new MessageListener() {

                    @Override
                    public void onMessage(Message message) {
                        perConsumerReceivedMessages.incrementAndGet();
                        handleMessage(consumerSession, message, perConsumerReceivedMessages.get());
                    }
                });
                while (perConsumerReceivedMessages.get() < numMessages) {
                    Thread.sleep(100);
                }
            } else {
                int perConsumerReceivedMessages = 0;
                while (perConsumerReceivedMessages < numMessages) {

                    Message message = null;
                    if (receiveTimeoutMS > -1) {
                        message = consumer.receive(receiveTimeoutMS);
                    } else {
                        message = consumer.receive();
                    }

                    if (message != null) {
                        perConsumerReceivedMessages++;
                        handleMessage(session, message, perConsumerReceivedMessages);
                    }
                }
            }
            consumer.close();
        }

    } catch (Exception ex) {
        LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex);
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing session", e);
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOGGER.error("JMSException closing connection", e);
            }
        }
    }
}

From source file:org.apache.james.queue.activemq.ActiveMQMailQueue.java

/**
 * Try to use ActiveMQ StatisticsPlugin to get size and if that fails
 * fallback to {@link JMSMailQueue#getSize()}
 *//*from w  ww .j a  v a2s  . c o m*/
@Override
public long getSize() throws MailQueueException {

    Connection connection = null;
    Session session = null;
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    TemporaryQueue replyTo = null;
    long size = -1;

    try {
        connection = connectionFactory.createConnection();
        connection.start();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        replyTo = session.createTemporaryQueue();
        consumer = session.createConsumer(replyTo);

        Queue myQueue = session.createQueue(queuename);
        producer = session.createProducer(null);

        String queueName = "ActiveMQ.Statistics.Destination." + myQueue.getQueueName();
        Queue query = session.createQueue(queueName);

        Message msg = session.createMessage();
        msg.setJMSReplyTo(replyTo);
        producer.send(query, msg);
        MapMessage reply = (MapMessage) consumer.receive(2000);
        if (reply != null && reply.itemExists("size")) {
            try {
                size = reply.getLong("size");
                return size;
            } catch (NumberFormatException e) {
                // if we hit this we can't calculate the size so just catch
                // it
            }
        }

    } catch (Exception e) {
        throw new MailQueueException("Unable to remove mails", e);

    } finally {

        if (consumer != null) {

            try {
                consumer.close();
            } catch (JMSException e1) {
                e1.printStackTrace();
                // ignore on rollback
            }
        }

        if (producer != null) {

            try {
                producer.close();
            } catch (JMSException e1) {
                // ignore on rollback
            }
        }

        if (replyTo != null) {
            try {

                // we need to delete the temporary queue to be sure we will
                // free up memory if thats not done and a pool is used
                // its possible that we will register a new mbean in jmx for
                // every TemporaryQueue which will never get unregistered
                replyTo.delete();
            } catch (JMSException e) {
            }
        }
        try {
            if (session != null)
                session.close();
        } catch (JMSException e1) {
            // ignore here
        }

        try {
            if (connection != null)
                connection.close();
        } catch (JMSException e1) {
            // ignore here
        }
    }

    // if we came to this point we should just fallback to super method
    return super.getSize();
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testTopicNonPersistentMessageSize() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*  w  ww  .ja  va  2s .  c om*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, DeliveryMode.NON_PERSISTENT, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());

    // consume all messages
    consumeTestMessages(consumer, 200);

    // All messages should now be gone
    verifyPendingStats(defaultTopicName, 0, 0);

    connection.close();
}