Example usage for javax.jms Session createQueue

List of usage examples for javax.jms Session createQueue

Introduction

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

Prototype

Queue createQueue(String queueName) throws JMSException;

Source Link

Document

Creates a Queue object which encapsulates a specified provider-specific queue name.

Usage

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();/*from  www .  jav  a  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.bugs.AMQ6133PersistJMSRedeliveryTest.java

private void sendMessages() throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination queue = session.createQueue(QUEUE_NAME);
    Destination retainQueue = session.createQueue(QUEUE_NAME + "-retain");
    MessageProducer producer = session.createProducer(null);

    final byte[] payload = new byte[1000];
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);
    BytesMessage message = session.createBytesMessage();
    message.writeBytes(payload);/*  w w  w . java2 s  . c  o m*/

    // Build up a set of messages that will be redelivered and updated later.
    while (getLogFileCount() < 3) {
        producer.send(queue, message);
    }

    // Now create some space for files that are retained during the test.
    while (getLogFileCount() < 6) {
        producer.send(retainQueue, message);
    }

    connection.close();
}

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

private void consumerAndRollback(int iteration) throws Exception {
    Connection connection = createConnection();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    Queue queue = session.createQueue(QUEUE_NAME);
    MessageConsumer consumer = session.createConsumer(queue);

    long msgCount = getProxyToQueue(queue.getQueueName()).getQueueSize();

    for (int i = 0; i < msgCount; ++i) {
        Message message = consumer.receive(50000);
        assertNotNull(message);/*from   ww w . j  a  v a2 s.c o  m*/
        if (iteration > 0) {
            assertTrue(message.getJMSRedelivered());
        }
    }

    connection.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();/* w  w  w .j ava  2  s.c  om*/

    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 av  a  2  s  .  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.leveldb.test.ReplicatedLevelDBBrokerTest.java

@Test
@Ignore// w  ww. j  a  v a 2  s. com
public void testReplicationQuorumLoss() throws Throwable {

    System.out.println("======================================");
    System.out.println(" Start 2 ActiveMQ nodes.");
    System.out.println("======================================");
    startBrokerAsync(createBrokerNode("node-1", port));
    startBrokerAsync(createBrokerNode("node-2", port));
    BrokerService master = waitForNextMaster();
    System.out.println("======================================");
    System.out.println(" Start the producer and consumer");
    System.out.println("======================================");

    final AtomicBoolean stopClients = new AtomicBoolean(false);
    final ArrayBlockingQueue<String> errors = new ArrayBlockingQueue<String>(100);
    final AtomicLong receivedCounter = new AtomicLong();
    final AtomicLong sentCounter = new AtomicLong();
    Thread producer = startFailoverClient("producer", new Client() {
        @Override
        public void execute(Connection connection) throws Exception {
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(session.createQueue("test"));
            long actual = 0;
            while (!stopClients.get()) {
                TextMessage msg = session.createTextMessage("Hello World");
                msg.setLongProperty("id", actual++);
                producer.send(msg);
                sentCounter.incrementAndGet();
            }
        }
    });

    Thread consumer = startFailoverClient("consumer", new Client() {
        @Override
        public void execute(Connection connection) throws Exception {
            connection.start();
            Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            MessageConsumer consumer = session.createConsumer(session.createQueue("test"));
            long expected = 0;
            while (!stopClients.get()) {
                Message msg = consumer.receive(200);
                if (msg != null) {
                    long actual = msg.getLongProperty("id");
                    if (actual != expected) {
                        errors.offer("Received got unexpected msg id: " + actual + ", expected: " + expected);
                    }
                    msg.acknowledge();
                    expected = actual + 1;
                    receivedCounter.incrementAndGet();
                }
            }
        }
    });

    try {
        assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS);
        assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS);
        assertNull(errors.poll());

        System.out.println("======================================");
        System.out.println(" Master should stop once the quorum is lost.");
        System.out.println("======================================");
        ArrayList<BrokerService> stopped = stopSlaves();// stopping the slaves should kill the quorum.
        assertStopsWithin(master, 10, TimeUnit.SECONDS);
        assertNull(errors.poll()); // clients should not see an error since they are failover clients.
        stopped.add(master);

        System.out.println("======================================");
        System.out.println(" Restart the slave. Clients should make progress again..");
        System.out.println("======================================");
        startBrokersAsync(createBrokerNodes(stopped));
        assertCounterMakesProgress(sentCounter, 10, TimeUnit.SECONDS);
        assertCounterMakesProgress(receivedCounter, 5, TimeUnit.SECONDS);
        assertNull(errors.poll());
    } catch (Throwable e) {
        e.printStackTrace();
        throw e;
    } finally {
        // Wait for the clients to stop..
        stopClients.set(true);
        producer.join();
        consumer.join();
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private void sendMessage(BrokerService brokerService, String body) throws Exception {
    TransportConnector connector = brokerService.getTransportConnectors().get(0);
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connector.getConnectUri());
    Connection connection = factory.createConnection();
    try {/*from ww  w  .  j  a  va 2s  .co m*/
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(session.createQueue("FOO"));
        producer.send(session.createTextMessage(body));
    } finally {
        connection.close();
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception {
    ArrayList<String> rc = new ArrayList<String>();
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
            "tcp://localhost:" + connectPort(brokerService));
    Connection connection = factory.createConnection();
    try {/*from   w w w . j av a2s . c  o  m*/
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueBrowser browser = session.createBrowser(session.createQueue("FOO"));
        Enumeration enumeration = browser.getEnumeration();
        while (enumeration.hasMoreElements()) {
            TextMessage textMessage = (TextMessage) enumeration.nextElement();
            rc.add(textMessage.getText());
        }
    } finally {
        connection.close();
    }
    return rc;
}

From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

@SuppressWarnings({ "unchecked", "unused" })
private Object[] browseQueueWithJms(BrokerService broker) throws Exception {
    Object[] messages = null;/*  w  ww.jav  a2s  .co m*/
    Connection connection = null;
    Session session = null;

    try {
        URI brokerUri = connector.getUri();
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString());
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(queueName);
        QueueBrowser browser = session.createBrowser(destination);
        List<Message> list = new ArrayList<Message>();
        for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) {
            list.add(enumn.nextElement());
        }
        messages = list.toArray();
    } finally {
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    LOG.info("+Browsed with JMS: " + messages.length);

    return messages;
}

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  w  w .  j  a  va 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();
    }
}