Example usage for javax.jms Session commit

List of usage examples for javax.jms Session commit

Introduction

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

Prototype


void commit() throws JMSException;

Source Link

Document

Commits all messages done in this transaction and releases any locks currently held.

Usage

From source file:org.apache.activemq.cli.test.ArtemisTest.java

public void testSimpleRun(String folderName) throws Exception {
    File instanceFolder = temporaryFolder.newFolder(folderName);

    setupAuth(instanceFolder);//from  w ww  .  ja va 2  s  .c om
    String queues = "q1,q2";
    String addresses = "a1,a2";

    // This is usually set when run from the command line via artemis.profile
    Run.setEmbedded(true);
    Artemis.main("create", instanceFolder.getAbsolutePath(), "--force", "--silent", "--no-web", "--queues",
            queues, "--addresses", addresses, "--no-autotune", "--require-login");
    System.setProperty("artemis.instance", instanceFolder.getAbsolutePath());

    // Some exceptions may happen on the initialization, but they should be ok on start the basic core protocol
    Artemis.internalExecute("run");

    try {
        try (ServerLocator locator = ServerLocatorImpl.newLocator("tcp://localhost:61616");
                ClientSessionFactory factory = locator.createSessionFactory();
                ClientSession coreSession = factory.createSession("admin", "admin", false, true, true, false,
                        0)) {
            for (String str : queues.split(",")) {
                ClientSession.QueueQuery queryResult = coreSession.queueQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find queue " + str, queryResult.isExists());
            }
            for (String str : addresses.split(",")) {
                ClientSession.AddressQuery queryResult = coreSession
                        .addressQuery(SimpleString.toSimpleString(str));
                assertTrue("Couldn't find address " + str, queryResult.isExists());
            }
        }

        try {
            Artemis.internalExecute("data", "print");
            Assert.fail("Exception expected");
        } catch (CLIException expected) {
        }
        Artemis.internalExecute("data", "print", "--f");

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("producer", "--message-count", "100",
                "--verbose", "--user", "admin", "--password", "admin"));
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--verbose", "--break-on-null",
                "--receive-timeout", "100", "--user", "admin", "--password", "admin"));

        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        Connection connection = cf.createConnection("admin", "admin");
        Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageProducer producer = session.createProducer(
                ActiveMQDestination.createDestination("queue://TEST", ActiveMQDestination.QUEUE_TYPE));

        TextMessage message = session.createTextMessage("Banana");
        message.setStringProperty("fruit", "banana");
        producer.send(message);

        for (int i = 0; i < 100; i++) {
            message = session.createTextMessage("orange");
            message.setStringProperty("fruit", "orange");
            producer.send(message);
        }
        session.commit();

        connection.close();
        cf.close();

        assertEquals(Integer.valueOf(1), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='banana'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(100), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--filter", "fruit='orange'", "--user", "admin", "--password", "admin"));

        assertEquals(Integer.valueOf(101), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--user", "admin", "--password", "admin"));

        // should only receive 10 messages on browse as I'm setting messageCount=10
        assertEquals(Integer.valueOf(10), Artemis.internalExecute("browser", "--txt-size", "50", "--verbose",
                "--message-count", "10", "--user", "admin", "--password", "admin"));

        // Nothing was consumed until here as it was only browsing, check it's receiving again
        assertEquals(Integer.valueOf(1),
                Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose", "--break-on-null",
                        "--receive-timeout", "100", "--filter", "fruit='banana'", "--user", "admin",
                        "--password", "admin"));

        // Checking it was acked before
        assertEquals(Integer.valueOf(100), Artemis.internalExecute("consumer", "--txt-size", "50", "--verbose",
                "--break-on-null", "--receive-timeout", "100", "--user", "admin", "--password", "admin"));
    } finally {
        stopServer();
    }
}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private void sendMessage(String queueName, int count, boolean transacted) throws JMSException {
    Connection con = connectionFactory.createConnection();
    try {/*from   w ww  .j a  va2  s .co  m*/
        Session session = con.createSession(transacted,
                transacted ? Session.SESSION_TRANSACTED : Session.AUTO_ACKNOWLEDGE);
        try {
            Queue destination = session.createQueue(queueName);
            MessageProducer producer = session.createProducer(destination);
            try {
                for (int i = 0; i < count; i++) {
                    TextMessage message = session.createTextMessage();
                    message.setIntProperty("MessageId", messageCounter);
                    message.setText("Message-" + messageCounter++);
                    producer.send(message);
                }
                if (transacted) {
                    session.commit();
                }
            } finally {
                producer.close();
            }
        } finally {
            session.close();
        }
    } finally {
        con.close();
    }
}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;//from w  w w .  ja va2  s .  co m
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();/* w  w w . java  2  s .c o m*/

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putTopic(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();/*from w w w. j  av  a2 s.com*/

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

/**
 * <p>/*from   w  ww  . j av a  2s .  c  om*/
 * Dequeues a mail when it is ready to process. As JMS does not support delay scheduling out-of-the box,
 * we use a messageselector to check if a mail is ready. For this a
 * {@link MessageConsumer#receive(long)} is used with a timeout of 10
 * seconds.
 * </p>
 * <p>
 * Many JMS implementations support better solutions for this, so this
 * should get overridden by these implementations
 * </p>
 */
@Override
public MailQueueItem deQueue() throws MailQueueException {
    Session session = null;
    MessageConsumer consumer = null;

    while (true) {
        TimeMetric timeMetric = metricFactory.timer(DEQUEUED_TIMER_METRIC_NAME_PREFIX + queueName);
        try {
            session = connection.createSession(true, Session.SESSION_TRANSACTED);
            Queue queue = session.createQueue(queueName);
            consumer = session.createConsumer(queue, getMessageSelector());

            Message message = consumer.receive(10000);

            if (message != null) {
                dequeuedMailsMetric.increment();
                return createMailQueueItem(session, consumer, message);
            } else {
                session.commit();
                closeConsumer(consumer);
                closeSession(session);
            }

        } catch (Exception e) {
            rollback(session);
            closeConsumer(consumer);
            closeSession(session);
            throw new MailQueueException("Unable to dequeue next message", e);
        } finally {
            timeMetric.stopAndPublish();
        }
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void commitOrAcknowledgeMessageIfNecessary(final String sessionName, final Message message) {
    try {//from   w  w  w  . ja v a2 s .  co  m
        final Session session = _testSessions.get(sessionName);
        if (session.getTransacted()) {
            synchronized (session) {
                session.commit();
            }
        } else if (message != null && session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
            message.acknowledge();
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to commit or acknowledge message on session: " + sessionName,
                jmse);
    }
}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testTransactedSessionWithUnackMessages() throws Exception {
    _connection = getConnection();/*from   ww w  . j a v a 2 s . c  o  m*/
    _connection.start();

    boolean transactional = true;
    int numberOfMessages = 2;
    final Session session = _connection.createSession(transactional, Session.SESSION_TRANSACTED);
    final Destination destination = session.createQueue(getTestQueueName());
    final MessageConsumer consumer = session.createConsumer(destination);

    sendMessage(session, destination, numberOfMessages);
    receiveMessagesWithoutCommit(consumer, numberOfMessages);

    final ManagedConnection mBean = getConnectionMBean();
    final CompositeDataSupport row = getTheOneChannelRow(mBean);
    boolean flowBlocked = false;
    assertChannelRowData(row, numberOfMessages, transactional, flowBlocked);

    // check that commit advances the lastIoTime
    final Date initialLastIOTime = mBean.getLastIoTime();
    session.commit();
    assertTrue("commit should have caused last IO time to advance",
            mBean.getLastIoTime().after(initialLastIOTime));

    // check that channels() now returns one session with no unacknowledged messages
    final CompositeDataSupport rowAfterCommit = getTheOneChannelRow(mBean);
    final Number unackCountAfterCommit = (Number) rowAfterCommit.get(ManagedConnection.UNACKED_COUNT);
    assertEquals("Unexpected number of unacknowledged messages", 0, unackCountAfterCommit);
}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testProducerFlowBlocked() throws Exception {
    _connection = getConnection();/*from   w  w  w  . jav a2s .com*/
    _connection.start();

    String queueName = getTestQueueName();
    Session session = _connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(queueName);
    createQueueOnBroker(session, queue);

    ManagedQueue managedQueue = _jmxUtils.getManagedQueue(queueName);
    managedQueue.setFlowResumeCapacity(DEFAULT_MESSAGE_SIZE * 2l);
    managedQueue.setCapacity(DEFAULT_MESSAGE_SIZE * 3l);

    final ManagedConnection managedConnection = getConnectionMBean();

    // Check that producer flow is not block before test
    final CompositeDataSupport rowBeforeSend = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeSend, false);

    // Check that producer flow does not become block too soon
    sendMessage(session, queue, 3);
    final CompositeDataSupport rowBeforeFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeFull, false);

    // Fourth message will over-fill the queue (but as we are not sending more messages, client thread wont't block)
    sendMessage(session, queue, 1);
    final CompositeDataSupport rowAfterFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterFull, true);

    // Consume two to bring the queue down to the resume capacity
    MessageConsumer consumer = session.createConsumer(queue);
    assertNotNull("Could not receive first message", consumer.receive(1000));
    assertNotNull("Could not receive second message", consumer.receive(1000));
    session.commit();

    // Check that producer flow is no longer blocked
    final CompositeDataSupport rowAfterReceive = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterReceive, false);
}

From source file:org.apache.qpid.test.utils.QpidBrokerTestCase.java

/**
 * Send messages to the given destination.
 *
 * If session is transacted then messages will be committed before returning
 *
 * @param session the session to use for sending
 * @param destination where to send them to
 * @param count no. of messages to send//from www . ja  v  a2 s. c  o m
 *
 * @param offset offset allows the INDEX value of the message to be adjusted.
 * @param batchSize the batchSize in which to commit, 0 means no batching,
 * but a single commit at the end
 * @return the sent message
 *
 * @throws Exception
 */
public List<Message> sendMessage(Session session, Destination destination,
                                 int count, int offset, int batchSize) throws Exception
{
    List<Message> messages = new ArrayList<Message>(count);

    MessageProducer producer = session.createProducer(destination);

    int i = offset;
    for (; i < (count + offset); i++)
    {
        Message next = createNextMessage(session, i);

        producer.send(next);

        if (session.getTransacted() && batchSize > 0)
        {
            if (i % batchSize == 0)
            {
                session.commit();
            }

        }

        messages.add(next);
    }

    // Ensure we commit the last messages
    // Commit the session if we are transacted and
    // we have no batchSize or
    // our count is not divible by batchSize.
    if (session.getTransacted() &&
        ( batchSize == 0 || (i-1) % batchSize != 0))
    {
        session.commit();
    }

    return messages;
}