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.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

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

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();//from  w w  w  .j  av a2 s.  co m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(session.createTopic(defaultTopicName));

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 0, 0);

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

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

    connection.close();
}

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

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

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

    publishTestTopicMessages(100, DeliveryMode.NON_PERSISTENT, publishedNonPersistentMessageSize);
    publishTestTopicMessages(100, DeliveryMode.PERSISTENT, publishedMessageSize);

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

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

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

    connection.close();
}

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

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

    Connection connection = cf.createConnection();
    connection.setClientID("clientId");
    connection.start();/*from w w w  . jav a 2s.c  om*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");
    MessageConsumer consumer2 = session.createSharedConsumer(session.createTopic(defaultTopicName), "sub1");

    publishTestTopicMessages(200, publishedMessageSize);

    verifyPendingStats(defaultTopicName, 200, publishedMessageSize.get());
    verifyPendingDurableStats(defaultTopicName, 0, 0);
    consumer2.close();

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

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

    connection.close();
}

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();//from w  ww  .j  ava  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.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

@Test
public void testCommit() throws Exception {
    final Connection connection = ACTIVE_MQ_NON_XA_CONNECTION_FACTORY.createConnection();
    connection.start();/* ww  w .  j av  a 2 s  . com*/

    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:com.aol.advertising.qiao.emitter.AMQEmitter.java

/**
 * Create JMS connectins, sessions, producers, destination objects. (one
 * producer per connection)/* ww w  .j  av a  2 s  . c  o  m*/
 *
 * @throws Exception
 */
protected void createJmsResources() throws Exception {

    Connection conn;
    Session session;
    MessageProducer producer;

    // create connections
    logger.info("creating producers...");
    for (int i = 0; i < numProducer; i++) {
        conn = connectionFactory.createConnection();
        connList.add(conn);

        // create sessions for a connection
        session = conn.createSession(transacted, ackMode);

        if (destination == null) {
            if (isQueue) {
                destination = session.createQueue(destinationName);
            } else {
                destination = session.createTopic(destinationName);
            }
        }

        producer = session.createProducer(destination);
        producer.setDeliveryMode(deliveryMode);

        Producer p = new Producer(session, producer);
        producersPool.add(p);
        producersStack.add(p);
    }

    logger.info("AMQ producer(s) created, count=" + producersStack.size());
}

From source file:org.jbpm.msg.jms.JmsMessageServiceFactoryImpl.java

public Service openService() {
    Connection connection = null;
    Session session = null;/*from ww  w  .ja v a2s.c  o m*/

    try {
        connection = connectionFactory.createConnection();

        // If you use an XA connection factory in JBoss, the parameters will be ignored.  It will always take part in the global JTA transaction.
        // If you use a non XQ connection factory, the first parameter specifies whether you want to have all message productions and 
        // consumptions as part of one transaction (TRUE) or whether you want all productions and consumptions to be instantanious (FALSE)
        // Of course, we never want messages to be received before the current jbpm transaction commits so we just set it to true.
        session = connection.createSession(true, Session.SESSION_TRANSACTED);

    } catch (JMSException e) {
        throw new JbpmException("couldn't open jms message session", e);
    }

    return new JmsMessageServiceImpl(connection, session, destination, isCommitEnabled);
}

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

protected void publishTestTopicMessages(int publishSize, int deliveryMode, AtomicLong publishedMessageSize)
        throws Exception {
    // create a new queue
    Connection connection = cf.createConnection();
    connection.setClientID("clientId2");
    connection.start();/*w w  w . java2  s .c  o m*/

    // Start the connection
    Session session = connection.createSession(false, TopicSession.AUTO_ACKNOWLEDGE);
    Topic topic = session.createTopic(defaultTopicName);

    try {
        // publish a bunch of non-persistent messages to fill up the temp
        // store
        MessageProducer prod = session.createProducer(topic);
        prod.setDeliveryMode(deliveryMode);
        for (int i = 0; i < publishSize; i++) {
            prod.send(
                    createMessage(i, session, JournalPendingMessageTest.maxMessageSize, publishedMessageSize));
        }

    } finally {
        connection.close();
    }
}

From source file:org.jbpm.executor.impl.ExecutorImpl.java

protected void sendMessage(String messageBody, int priority) {
    if (connectionFactory == null && queue == null) {
        throw new IllegalStateException("ConnectionFactory and Queue cannot be null");
    }/*from w  ww. j a v a  2  s.  c  o  m*/
    Connection queueConnection = null;
    Session queueSession = null;
    MessageProducer producer = null;
    try {
        queueConnection = connectionFactory.createConnection();
        queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        TextMessage message = queueSession.createTextMessage(messageBody);
        producer = queueSession.createProducer(queue);
        producer.setPriority(priority);

        queueConnection.start();

        producer.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Error when sending JMS message with executor job request", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                logger.warn("Error when closing producer", e);
            }
        }

        if (queueSession != null) {
            try {
                queueSession.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue session", e);
            }
        }

        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue connection", e);
            }
        }
    }
}

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. ja  v  a 2 s.co m*/
    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();
    }
}