Example usage for javax.jms Session createDurableSubscriber

List of usage examples for javax.jms Session createDurableSubscriber

Introduction

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

Prototype

TopicSubscriber createDurableSubscriber(Topic topic, String name) throws JMSException;

Source Link

Document

Creates an unshared durable subscription on the specified topic (if one does not already exist) and creates a consumer on that durable subscription.

Usage

From source file:example.topic.durable.Subscriber.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();// w w w  .  j av  a  2s .  c  o  m
    }
    System.out
            .println("\nWaiting to receive messages... Either waiting for END message or press Ctrl+C to exit");
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;
    final CountDownLatch latch = new CountDownLatch(1);

    try {

        connection = connectionFactory.createConnection();
        String clientId = System.getProperty("clientId");
        connection.setClientID(clientId);

        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Topic destination = session.createTopic("test-topic");

        MessageConsumer consumer = session.createDurableSubscriber(destination, clientId);
        consumer.setMessageListener(new Subscriber(latch));

        latch.await();
        consumer.close();
        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:com.fusesource.examples.activemq.DurableSubscriber.java

public static void main(String args[]) {
    Connection connection = null;

    try {//from  www. j  a  va 2  s  .  c o  m
        // JNDI lookup of JMS Connection Factory and JMS Destination
        Context context = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory) context.lookup(CONNECTION_FACTORY_NAME);
        connection = factory.createConnection();
        connection.setClientID(System.getProperty("clientID"));
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.CLIENT_ACKNOWLEDGE);
        String topicName = System.getProperty("topic");

        Topic topic = session.createTopic(topicName);
        MessageConsumer consumer = session.createDurableSubscriber(topic, "Test_Durable_Subscriber");

        LOG.info("Start consuming messages from " + topicName + " with " + MESSAGE_TIMEOUT_MILLISECONDS
                + "ms timeout");

        // Synchronous message consumer
        int i = 1;
        while (true) {
            Message message = consumer.receive(MESSAGE_TIMEOUT_MILLISECONDS);
            if (message != null) {
                if (message instanceof TextMessage) {
                    String text = ((TextMessage) message).getText();
                    LOG.info("Got " + (i++) + ". message: " + text);
                }
            } else {
                break;
            }
        }

        consumer.close();
        session.close();
    } catch (Throwable t) {
        LOG.error(t);
    } finally {
        // Cleanup code
        // In general, you should always close producers, consumers,
        // sessions, and connections in reverse order of creation.
        // For this simple example, a JMS connection.close will
        // clean up all other resources.
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                LOG.error(e);
            }
        }
    }
}

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

@Test(timeout = 300000)
public void testDurableWithOnePendingAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);//  w w  w . j av a 2s.co  m

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all but 1 message
    for (int i = 0; i < messageCount.get() - 1; i++) {
        durable.receive();
    }

    durable.close();

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertFalse("Should not have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }, 5000, 500));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

    assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length);

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

    assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length);

    assertNotNull(durable2.receive(5000));
}

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

@Test(timeout = 300000)
public void testDurableWithNoMessageAfterRestartAndIndexRecovery() throws Exception {
    final File persistentDir = getPersistentDir();

    broker.getBroker().addDestination(broker.getAdminConnectionContext(), new ActiveMQTopic("durable.sub"),
            false);/* w w w.  j a va2s . c  om*/

    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("myId");
    connection.start();
    final Session jmsSession = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable = jmsSession.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");
    final MessageProducer producer = jmsSession.createProducer(new ActiveMQTopic("durable.sub"));

    final int original = new ArrayList<File>(
            FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"), TrueFileFilter.INSTANCE))
                    .size();

    // 100k messages
    final byte[] data = new byte[100000];
    final Random random = new Random();
    random.nextBytes(data);

    // run test with enough messages to create a second journal file
    final AtomicInteger messageCount = new AtomicInteger();
    assertTrue("Should have added a journal file", Wait.waitFor(new Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            final ActiveMQBytesMessage message = new ActiveMQBytesMessage();
            message.setContent(new ByteSequence(data));

            for (int i = 0; i < 100; i++) {
                producer.send(message);
                messageCount.getAndIncrement();
            }

            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() > original;
        }
    }));

    // Consume all messages
    for (int i = 0; i < messageCount.get(); i++) {
        durable.receive();
    }

    durable.close();

    assertTrue("Subscription should go inactive", Wait.waitFor(new Condition() {
        @Override
        public boolean isSatisified() throws Exception {
            return broker.getAdminView().getInactiveDurableTopicSubscribers().length == 1;
        }
    }));

    // force a GC of unneeded journal files
    getBroker().getPersistenceAdapter().checkpoint(true);

    // wait until a journal file has been GC'd after receiving messages
    assertTrue("Should have garbage collected", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return new ArrayList<File>(FileUtils.listFiles(persistentDir, new WildcardFileFilter("*.log"),
                    TrueFileFilter.INSTANCE)).size() == original;
        }
    }));

    // stop the broker so we can blow away the index
    getBroker().stop();
    getBroker().waitUntilStopped();

    // delete the index so that the durables are gone from the index
    // The test passes if you take out this delete section
    for (File index : FileUtils.listFiles(persistentDir, new WildcardFileFilter("db.*"),
            TrueFileFilter.INSTANCE)) {
        FileUtils.deleteQuietly(index);
    }

    stopBroker();
    setUpBroker(false);

    assertEquals(1, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(0, broker.getAdminView().getDurableTopicSubscribers().length);

    ActiveMQConnectionFactory connectionFactory2 = new ActiveMQConnectionFactory(this.brokerConnectURI);
    ActiveMQConnection connection2 = (ActiveMQConnection) connectionFactory2.createConnection();
    connection2.setClientID("myId");
    connection2.start();
    final Session jmsSession2 = connection2.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);

    TopicSubscriber durable2 = jmsSession2.createDurableSubscriber(new ActiveMQTopic("durable.sub"), "sub");

    assertEquals(0, broker.getAdminView().getInactiveDurableTopicSubscribers().length);
    assertEquals(1, broker.getAdminView().getDurableTopicSubscribers().length);

    assertNull(durable2.receive(500));
}

From source file:org.apache.activemq.store.kahadb.MultiKahaDBTopicDeletionTest.java

@Override
protected void createConsumer(ActiveMQDestination dest) throws JMSException {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerConnectURI);
    Connection connection = factory.createConnection();
    connection.setClientID("client1");
    connection.start();//w ww. ja va  2  s.  c o  m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    session.createDurableSubscriber((Topic) dest, "sub1");
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void createInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    consumer.close();//from w  w  w  . j  a  va  2  s  .  co m
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void consumeDurableMessages(Topic topic, int count) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();//  ww  w . j ava 2  s  .com
    for (int i = 0; i < count; ++i) {
        if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) {
            fail("should have received a message");
        }
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void tryConsumeExpectNone(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();/*w  ww  .  j  a  v  a 2  s . c  om*/
    if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) {
        fail("Should be no messages for this durable.");
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private int consumeFromInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    connection.start();//from   w ww.  j  ava2  s . co  m
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");

    int count = 0;

    while (consumer.receive(10000) != null) {
        count++;
    }

    consumer.close();
    connection.close();

    return count;
}

From source file:org.apache.activemq.usecases.ConcurrentProducerDurableConsumerTest.java

protected TopicSubscriber createDurableSubscriber(Connection conn, Destination dest, String name)
        throws Exception {
    conn.setClientID(name);//from   w  ww  . j  a  v  a2 s .  co  m
    connections.add(conn);
    conn.start();

    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final TopicSubscriber consumer = sess.createDurableSubscriber((javax.jms.Topic) dest, name);

    return consumer;
}