Example usage for javax.jms Session createTextMessage

List of usage examples for javax.jms Session createTextMessage

Introduction

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

Prototype


TextMessage createTextMessage(String text) throws JMSException;

Source Link

Document

Creates an initialized TextMessage object.

Usage

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);//ww  w  .  j a  v  a2s. 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: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 ww .j  a  v a  2s  . co  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 testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();//ww w  .  ja  va  2  s  . c o  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.broker.jmx.ConcurrentMoveTest.java

public void testConcurrentMove() throws Exception {

    // Send some messages
    connection = connectionFactory.createConnection();
    connection.start();//from  www  .j a  v  a2  s. c om
    Session session = connection.createSession(transacted, authMode);
    destination = createDestination();
    MessageProducer producer = session.createProducer(destination);
    for (int i = 0; i < messageCount; i++) {
        Message message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    long usageBeforMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage:" + usageBeforMove);

    // Now get the QueueViewMBean and purge
    String objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + getDestinationString();
    ObjectName queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    final QueueViewMBean proxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    final ActiveMQQueue to = new ActiveMQQueue("TO");
    ((RegionBroker) broker.getRegionBroker()).addDestination(broker.getAdminConnectionContext(), to, false);

    ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 50; i++) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    proxy.moveMatchingMessagesTo(null, to.getPhysicalName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.MINUTES);

    long count = proxy.getQueueSize();
    assertEquals("Queue size", count, 0);
    assertEquals("Browse size", proxy.browseMessages().size(), 0);

    objectNameStr = broker.getBrokerObjectName().toString();
    objectNameStr += ",destinationType=Queue,destinationName=" + to.getQueueName();
    queueViewMBeanName = assertRegisteredObjectName(objectNameStr);
    QueueViewMBean toProxy = (QueueViewMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServer,
            queueViewMBeanName, QueueViewMBean.class, true);

    count = toProxy.getQueueSize();
    assertEquals("Queue size", count, messageCount);

    long usageAfterMove = broker.getPersistenceAdapter().size();
    LOG.info("Store usage, before: " + usageBeforMove + ", after:" + usageAfterMove);
    LOG.info("Store size increase:" + FileUtils.byteCountToDisplaySize(usageAfterMove - usageBeforMove));

    assertTrue("Usage not more than doubled", usageAfterMove < (usageBeforMove * 3));

    producer.close();
}

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.  ja va2s  . 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();/*from   w  w w  .  ja v a  2s .c o 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  ava2s . co m*/
        session.commit();

    }
}

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

protected static boolean produce(Session session, Topic topic, int messageCount, int messageSize)
        throws JMSException {
    MessageProducer producer = session.createProducer(topic);

    for (int i = 0; i < messageCount; i++) {
        TextMessage helloMessage = session.createTextMessage(StringUtils.repeat("a", messageSize));

        try {//  w ww .  j  a  v a  2 s  .  c om
            producer.send(helloMessage);
        } catch (ResourceAllocationException e) {
            return false;
        }
    }

    return true;
}

From source file:org.apache.activemq.camel.JmsJdbcXARollbackTest.java

private void sendJMSMessageToKickOffRoute() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testXA");
    factory.setWatchTopicAdvisories(false);
    Connection connection = factory.createConnection();
    connection.start();/*from w ww .  j av a 2  s  . c  o m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(new ActiveMQQueue("scp_transacted"));
    TextMessage message = session.createTextMessage("Some Text, messageCount:" + messageCount++);
    message.setJMSCorrelationID("pleaseCorrelate");
    producer.send(message);
    connection.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  w w w . j av a2 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();
    }
}