Example usage for javax.jms Session CLIENT_ACKNOWLEDGE

List of usage examples for javax.jms Session CLIENT_ACKNOWLEDGE

Introduction

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

Prototype

int CLIENT_ACKNOWLEDGE

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

Click Source Link

Document

With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method.

Usage

From source file:org.jbpm.bpel.integration.jms.IntegrationControl.java

public Session createJmsSession() throws JMSException {
    return jmsConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
}

From source file:com.microsoft.azure.servicebus.samples.jmstopicquickstart.JmsTopicQuickstart.java

private void receiveFromSubscription(ConnectionStringBuilder csb, Context context, ConnectionFactory cf,
        String name) throws NamingException, JMSException, InterruptedException {
    AtomicInteger totalReceived = new AtomicInteger(0);
    System.out.printf("Subscription %s: \n", name);

    Destination subscription = (Destination) context.lookup(name);
    // Create Connection
    Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
    connection.start();//from  w w w. j a  va2  s. c  o  m
    // Create Session, no transaction, client ack
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    // Create consumer
    MessageConsumer consumer = session.createConsumer(subscription);
    // Set callback listener. Gets called for each received message.
    consumer.setMessageListener(message -> {
        try {
            System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the counter
                    message.getJMSMessageID());
            message.acknowledge();
        } catch (Exception e) {
            System.out.printf("%s", e.toString());
        }
    });

    // wait on the main thread until all sent messages have been received
    while (totalReceived.get() < totalSend) {
        Thread.sleep(1000);
    }
    consumer.close();
    session.close();
    connection.stop();
    connection.close();
}

From source file:com.adaptris.core.jms.MetadataCorrelationIdSourceTest.java

public void testJmsCorrelationIdToAdaptrisMessageMetadata() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {/*  w w  w  .  j av  a  2  s  .co  m*/
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        TextMessage jmsMsg = session.createTextMessage();
        jmsMsg.setJMSCorrelationID(TEXT2);
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource(CORRELATIONID_KEY);
        mcs.processCorrelationId(jmsMsg, adpMsg);
        assertEquals("Check Correlation Id Keys", jmsMsg.getJMSCorrelationID(),
                adpMsg.getMetadataValue(CORRELATIONID_KEY));
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

From source file:com.datatorrent.lib.io.jms.JMSStringInputOperatorTest.java

private void produceMsg(int numMessages) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();//from w w  w  . ja  va 2  s  .c o m

    // Create a Session
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

    // Create the destination (Topic or Queue)
    Destination destination = session.createQueue("TEST.FOO");

    // Create a MessageProducer from the Session to the Topic or Queue
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);

    // Create a messages
    String text = "Hello world! From tester producer";
    TextMessage message = session.createTextMessage(text);
    for (int i = 0; i < numMessages; i++) {
        producer.send(message);
    }

    // Clean up
    session.close();
    connection.close();

}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();/* w  w  w .  ja  v  a2s . c  om*/

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }

    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();

    List<Message> messages = new ArrayList<Message>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }

    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }

    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > 200);

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

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 av a2s.  c  o  m*/
        if (iteration > 0) {
            assertTrue(message.getJMSRedelivered());
        }
    }

    connection.close();
}

From source file:com.adaptris.core.jms.activemq.BlobMessageTranslatorTest.java

public void testMoveMetadataAdaptrisMessageToJmsMessage() throws Exception {
    MessageTypeTranslatorImp trans = new BlobMessageTranslator();
    EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
    JmsConnection conn = null;/*w  w  w .  j  ava2 s . c o m*/
    try {
        activeMqBroker.start();
        conn = activeMqBroker.getJmsConnection(new BasicActiveMqImplementation());
        start(conn);

        AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();

        addMetadata(msg);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        trans.registerSession(session);
        trans.registerMessageFactory(new DefaultMessageFactory());
        start(trans);

        Message jmsMsg = trans.translate(msg);
        assertJmsProperties(jmsMsg);
    } finally {
        stop(trans);
        stop(conn);
        activeMqBroker.destroy();
    }

}

From source file:com.adaptris.core.jms.MetadataCorrelationIdSourceTest.java

public void testJmsCorrelationIdToAdaptrisMessageMetadata_NoMetadataKey() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {//from   w  ww . j  a va 2 s.c o m
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        TextMessage jmsMsg = session.createTextMessage();
        jmsMsg.setJMSCorrelationID(TEXT2);
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource();
        mcs.processCorrelationId(jmsMsg, adpMsg);
        assertNotSame(jmsMsg.getJMSCorrelationID(), adpMsg.getMetadataValue(CORRELATIONID_KEY));
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

From source file:org.jengine.mbean.FTPHL7Client.java

private void initializeQueueConnection() {
    try {//w w w  . j a va2s  . c  o m
        if (session != null)
            session.close();
        ctx = getInitialContext();
        factory = (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY);
        connection = factory.createQueueConnection();
        session = connection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);

        StringTokenizer st = new StringTokenizer(QueueNames, ":");
        while (st.hasMoreElements()) {
            queue = (Queue) ctx.lookup("queue/" + st.nextElement());
            Queues.add(queue);
            qSender = session.createSender(queue);
            QSenders.add(qSender);
        }
    } catch (JMSException je) {
        je.printStackTrace();

    } catch (NamingException ne) {
        ne.printStackTrace();

    }

}

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

@Test
@Ignore// ww w  .j av a 2 s.c  o  m
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();
    }
}