Example usage for javax.jms Session SESSION_TRANSACTED

List of usage examples for javax.jms Session SESSION_TRANSACTED

Introduction

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

Prototype

int SESSION_TRANSACTED

To view the source code for javax.jms Session SESSION_TRANSACTED.

Click Source Link

Document

This value may be passed as the argument to the method createSession(int sessionMode) on the Connection object to specify that the session should use a local transaction.

Usage

From source file:net.timewalker.ffmq4.admin.RemoteAdministrationThread.java

@Override
public void run() {
    log.info("Starting remote administration thread ...");

    try {//from   ww  w . j av  a 2  s  . c om
        LocalQueue inputQueue = engine.getLocalQueue(FFMQConstants.ADM_REQUEST_QUEUE);
        LocalQueue outputQueue = engine.getLocalQueue(FFMQConstants.ADM_REPLY_QUEUE);

        conn = new LocalQueueConnection(engine, null, null);
        session = conn.createQueueSession(true, Session.SESSION_TRANSACTED);
        receiver = session.createReceiver(inputQueue);
        sender = session.createSender(outputQueue);

        conn.start();

        // Flush input queue on startup
        inputQueue.purge(null);
        outputQueue.purge(null);

        // Enter listening loop
        notifyStartup();
        while (!stopRequired) {
            Message message = receiver.receive();
            if (message == null)
                break; // Interrupted
            log.debug("Received message " + message);

            try {
                // Process the command
                String errorMsg = process(message);

                // Build response message
                Message response = session.createMessage();
                response.setJMSCorrelationID(message.getJMSMessageID());
                if (errorMsg != null)
                    response.setStringProperty(FFMQAdminConstants.ADM_HEADER_ERRMSG, errorMsg);

                sender.send(response, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY,
                        Message.DEFAULT_TIME_TO_LIVE);
            } catch (JMSException e) {
                log.error("Cannot process admin command", e);
            } finally {
                session.commit();
            }
        }

        log.debug("Remote administration thread has stopped");
    } catch (Throwable e) {
        log.fatal("Administration thread failed", e);
        notifyStartup();
    } finally {
        try {
            if (sender != null)
                sender.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (receiver != null)
                receiver.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (session != null)
                session.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }

        try {
            if (conn != null)
                conn.close();
        } catch (JMSException e) {
            ErrorTools.log(e, log);
        }
    }
}

From source file:net.timewalker.ffmq4.common.session.AbstractSession.java

@Override
public final int getAcknowledgeMode() throws JMSException {
    if (transacted)
        return Session.SESSION_TRANSACTED; // [JMS Spec]
    return acknowledgeMode;
}

From source file:net.timewalker.ffmq4.remote.connection.RemoteConnection.java

@Override
public final Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
    if (!transacted && acknowledgeMode == Session.SESSION_TRANSACTED)
        throw new FFMQException(
                "Acknowledge mode SESSION_TRANSACTED cannot be used for an non-transacted session",
                "INVALID_ACK_MODE");

    externalAccessLock.readLock().lock();
    try {//from   w  w w.  ja  va 2s.  com
        checkNotClosed();
        RemoteSession session = new RemoteSession(idProvider.createID(), this, transportHub.createEndpoint(),
                transacted, acknowledgeMode);
        registerSession(session);
        session.remoteInit();
        return session;
    } finally {
        externalAccessLock.readLock().unlock();
    }
}

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);/*from  ww  w.j av a2 s  .  c om*/
    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:org.apache.activemq.bugs.AMQ7067Test.java

@Test
public void testCommit() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/*from  w  w  w  .  j a v a 2s . co  m*/

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue holdKahaDb = session.createQueue("holdKahaDb");
    MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb);
    TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    Queue queue = session.createQueue("test");
    produce(connection, queue, 100, 512 * 1024);
    session.commit();
    produce(connection, queue, 100, 512 * 1024);

    System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
            getQueueSize(holdKahaDb.getQueueName())));
    purgeQueue(queue.getQueueName());
    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    // force gc
    broker.getPersistenceAdapter().checkpoint(true);

    connection.close();
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();
    broker.waitUntilStarted();

    while (true) {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
                    getQueueSize(holdKahaDb.getQueueName())));
            break;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            break;
        }
    }

    // THIS SHOULD NOT FAIL AS THERE SHOULD BE ONLY 1 TRANSACTION!
    assertEquals(1, getQueueSize(holdKahaDb.getQueueName()));
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

@Test
public void testRollback() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();//  w  w  w  .j a v  a2s .  co m

    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue holdKahaDb = session.createQueue("holdKahaDb");
    MessageProducer holdKahaDbProducer = session.createProducer(holdKahaDb);
    TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", 10));
    holdKahaDbProducer.send(helloMessage);
    Queue queue = session.createQueue("test");
    produce(connection, queue, 100, 512 * 1024);
    session.rollback();
    produce(connection, queue, 100, 512 * 1024);

    System.out.println(String.format("QueueSize %s: %d", holdKahaDb.getQueueName(),
            getQueueSize(holdKahaDb.getQueueName())));
    purgeQueue(queue.getQueueName());

    Wait.waitFor(new Wait.Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return 0 == getQueueSize(queue.getQueueName());
        }
    });

    // force gc
    broker.getPersistenceAdapter().checkpoint(true);

    connection.close();
    curruptIndexFile(getDataDirectory());

    broker.stop();
    broker.waitUntilStopped();
    createBroker();
    broker.waitUntilStarted();

    // no sign of the test queue on recovery, rollback is the default for any inflight
    // this test serves as a sanity check on existing behaviour
    try {
        getQueueSize(holdKahaDb.getQueueName());
        fail("expect InstanceNotFoundException");
    } catch (UndeclaredThrowableException expected) {
        assertTrue(expected.getCause() instanceof InstanceNotFoundException);
    }
}

From source file:org.apache.activemq.bugs.AMQ7067Test.java

protected static void produce(Connection connection, Queue queue, int messageCount, int messageSize)
        throws JMSException, IOException, XAException {
    Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
    MessageProducer producer = session.createProducer(queue);

    for (int i = 0; i < messageCount; i++) {
        TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize));
        producer.send(helloMessage);/*from  w w w  .j a v  a 2  s. co  m*/
        session.commit();

    }
}

From source file:org.apache.activemq.bugs.VMTransportClosureTest.java

/**
 * This test demonstrates how the "disposeOnDisonnect" feature of
 * VMTransportServer can incorrectly close all VM connections to the local
 * broker.//www  . j a v  a 2s .  c o m
 */
public void testPrematureClosure() throws Exception {

    // Open a persistent connection to the local broker. The persistent
    // connection is maintained through the test and should prevent the
    // VMTransportServer from stopping itself when the local transport is
    // closed.
    ActiveMQConnection persistentConn = (ActiveMQConnection) createConnection();
    persistentConn.start();
    Session session = persistentConn.createSession(true, Session.SESSION_TRANSACTED);
    MessageProducer producer = session.createProducer(destination);

    for (int i = 0; i < NUM_ATTEMPTS; i++) {
        LOG.info("Attempt: " + i);

        // Open and close a local transport connection. As is done by by
        // most users of the transport, ensure that the transport is stopped
        // when closed by the peer (via ShutdownInfo). Closing the local
        // transport should not affect the persistent connection.
        final Transport localTransport = TransportFactory.connect(broker.getVmConnectorURI());
        localTransport.setTransportListener(new TransportListener() {
            public void onCommand(Object command) {
                if (command instanceof ShutdownInfo) {
                    try {
                        localTransport.stop();
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }

            public void onException(IOException error) {
                // ignore
            }

            public void transportInterupted() {
                // ignore
            }

            public void transportResumed() {
                // ignore
            }
        });

        localTransport.start();
        localTransport.stop();

        // Ensure that the persistent connection is still usable.
        producer.send(session.createMessage());
        session.rollback();
    }

    persistentConn.close();
}

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  ww w  .  j a v  a  2  s .  com*/
    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   ww w .ja v  a  2  s  . c o 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();
    }
}