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:com.fusesource.examples.activemq.DurableSubscriber.java

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

    try {//from   w  ww  . j  a  v  a2  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:qpid.MulticastMain.java

public static void main(String[] args) {
    Options options = getOptions();/*from  www  .ja v  a  2s .  co  m*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        String queueName = strArg(cmd, 'u', "");
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int consumerCount = intArg(cmd, 'y', 1);
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        long confirm = intArg(cmd, 'c', -1);
        boolean autoAck = cmd.hasOption('a');
        int multiAckEvery = intArg(cmd, 'A', 0);
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        String uri = strArg(cmd, 'h', "amqp://guest:guest@/?brokerlist='localhost'");

        boolean exclusive = "".equals(queueName);
        boolean autoDelete = !exclusive;

        //setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval, producerCount > 0, consumerCount > 0,
                (flags.contains("mandatory") || flags.contains("immediate")), confirm != -1);

        System.setProperty("qpid.amqp.version", "0-91");

        Thread[] consumerThreads = new Thread[consumerCount];
        AMQConnection[] consumerConnections = new AMQConnection[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            AMQConnection conn = new AMQConnection(uri);
            consumerConnections[i] = conn;
            AMQSession channel = (AMQSession) conn.createSession(consumerTxSize > 0,
                    autoAck ? Session.AUTO_ACKNOWLEDGE : Session.CLIENT_ACKNOWLEDGE,
                    prefetchCount > 0 ? prefetchCount : 500);
            AMQDestination destination = new AMQAnyDestination(new AMQShortString(exchangeName),
                    new AMQShortString(exchangeType), new AMQShortString(id), exclusive, autoDelete,
                    queueName.equals("") ? null : new AMQShortString(queueName), flags.contains("persistent"),
                    null);
            channel.declareAndBind(destination);
            Thread t = new Thread(new Consumer(channel, id, destination, consumerTxSize, autoAck, multiAckEvery,
                    stats, timeLimit));
            conn.start();
            consumerThreads[i] = t;
        }
        Thread[] producerThreads = new Thread[producerCount];
        AMQConnection[] producerConnections = new AMQConnection[producerCount];
        AMQSession[] producerChannels = new AMQSession[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            AMQConnection conn = new AMQConnection(uri);
            producerConnections[i] = conn;
            AMQSession channel = (AMQSession) conn.createSession(producerTxSize > 0, Session.AUTO_ACKNOWLEDGE,
                    500);
            producerChannels[i] = channel;
            if (confirm >= 0) {
                throw new UnsupportedOperationException("Publisher confirms not supported by Qpid");
            }
            AMQDestination destination = new AMQAnyDestination(new AMQShortString(exchangeName),
                    new AMQShortString(exchangeType), new AMQShortString(id), false, false, null,
                    flags.contains("persistent"), null);
            channel.declareExchange(destination.getExchangeName(), destination.getExchangeClass(), false);
            final Producer p = new Producer(channel, destination, id, flags, producerTxSize, rateLimit,
                    minMsgSize, timeLimit, confirm, stats);
            /*
            channel.addReturnListener(p);
            channel.addConfirmListener(p);
            */
            Thread t = new Thread(p);
            conn.start();
            producerThreads[i] = t;
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            /*
            producerChannels[i].clearReturnListeners();
            producerChannels[i].clearConfirmListeners();
            */
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

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

public void testAdaptrisMessageMetadataToJmsCorrelationId() throws Exception {

    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    JmsConnection conn = broker.getJmsConnection();
    try {//from   w  w  w . j  a  v a  2  s.  co m
        broker.start();
        start(conn);
        Session session = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        AdaptrisMessage adpMsg = AdaptrisMessageFactory.getDefaultInstance().newMessage(TEXT);
        adpMsg.addMetadata(CORRELATIONID_KEY, TEXT2);
        TextMessage jmsMsg = session.createTextMessage();
        MetadataCorrelationIdSource mcs = new MetadataCorrelationIdSource(CORRELATIONID_KEY);
        mcs.processCorrelationId(adpMsg, jmsMsg);
        assertEquals(adpMsg.getMetadataValue(CORRELATIONID_KEY), jmsMsg.getJMSCorrelationID());
        session.close();
    } finally {
        stop(conn);
        broker.destroy();
    }
}

From source file:org.apache.storm.jms.spout.JmsSpoutTest.java

@Test
public void testFailure() throws JMSException, Exception {
    JmsSpout spout = new JmsSpout();
    JmsProvider mockProvider = new MockJmsProvider();
    MockSpoutOutputCollector mockCollector = new MockSpoutOutputCollector();
    SpoutOutputCollector collector = new SpoutOutputCollector(mockCollector);
    spout.setJmsProvider(new MockJmsProvider());
    spout.setJmsTupleProducer(new MockTupleProducer());
    spout.setJmsAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
    spout.setRecoveryPeriod(10); // Rapid recovery for testing.
    spout.open(new HashMap<String, String>(), null, collector);
    Message msg = this.sendMessage(mockProvider.connectionFactory(), mockProvider.destination());
    Thread.sleep(100);//from   w  w w  .  j a  v a2s  . com
    spout.nextTuple(); // Pretend to be storm.
    Assert.assertTrue(mockCollector.emitted);

    mockCollector.reset();
    spout.fail(msg.getJMSMessageID()); // Mock failure
    Thread.sleep(5000);
    spout.nextTuple(); // Pretend to be storm.
    Thread.sleep(5000);
    Assert.assertTrue(mockCollector.emitted); // Should have been re-emitted
}

From source file:com.microsoft.azure.servicebus.samples.jmsqueuequickstart.JmsQueueQuickstart.java

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up JNDI context
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("queue.QUEUE", "BasicQueue");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);
    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up queue
    Destination queue = (Destination) context.lookup("QUEUE");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side separately with minimal clutter
    {/*from  ww  w  .  j a  v a 2  s .c o  m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(queue);

        // Send messages
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    {
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        // Create consumer
        MessageConsumer consumer = session.createConsumer(queue);
        // create a listener callback to receive the messages
        consumer.setMessageListener(message -> {
            try {
                // receives message is passed to callback
                System.out.printf("Received message %d with sq#: %s\n", totalReceived.incrementAndGet(), // increments the tracking counter
                        message.getJMSMessageID());
                message.acknowledge();
            } catch (Exception e) {
                logger.error(e);
            }
        });

        // 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();
    }

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}

From source file:io.datalayer.activemq.consumer.SpringConsumer.java

public void start() throws JMSException {
    String selector = "next = '" + myId + "'";

    try {//from   w  w w.j a  v a  2  s  . com
        ConnectionFactory factory = template.getConnectionFactory();
        connection = factory.createConnection();

        // we might be a reusable connection in spring
        // so lets only set the client ID once if its not set
        synchronized (connection) {
            if (connection.getClientID() == null) {
                connection.setClientID(myId);
            }
        }

        connection.start();

        session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
        consumer = session.createConsumer(destination, selector, false);
        consumer.setMessageListener(this);
    } catch (JMSException ex) {
        LOG.error("", ex);
        throw ex;
    }
}

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

public void produceMsg(String text) throws Exception {
    // Create a ConnectionFactory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost");

    // Create a Connection
    Connection connection = connectionFactory.createConnection();
    connection.start();//from w ww.  j ava  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
    TextMessage message = session.createTextMessage(text);
    producer.send(message);

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

From source file:org.sakaiproject.nakamura.grouper.event.SyncJMSMessageConsumer.java

@Activate
public void activate(Map<?, ?> props) {
    try {//from  w w w  . j a va  2 s  . c o  m
        if (connection == null) {
            connection = connFactoryService.getDefaultPooledConnectionFactory().createConnection();
            jmsSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            Destination destination = jmsSession.createQueue(SyncJMSMessageProducer.QUEUE_NAME);
            consumer = jmsSession.createConsumer(destination);
            consumer.setMessageListener(this);
            connection.start();
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.servicemix.jbi.cluster.requestor.AbstractPollingRequestorPool.java

public void setTransacted(Transacted transacted) {
    this.transacted = transacted;
    switch (transacted) {
    case None:/*from   ww w  .ja  v  a  2s  . c  o  m*/
        setSessionTransacted(false);
        setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
        break;
    case ClientAck:
        setSessionTransacted(false);
        setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
        break;
    case Jms:
    case Xa:
        setSessionTransacted(true);
        break;
    }
}

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

public void run(String connectionString) throws Exception {

    // The connection string builder is the only part of the azure-servicebus SDK library 
    // we use in this JMS sample and for the purpose of robustly parsing the Service Bus 
    // connection string. 
    ConnectionStringBuilder csb = new ConnectionStringBuilder(connectionString);

    // set up the JNDI context 
    Hashtable<String, String> hashtable = new Hashtable<>();
    hashtable.put("connectionfactory.SBCF",
            "amqps://" + csb.getEndpoint().getHost() + "?amqp.idleTimeout=120000&amqp.traceFrames=true");
    hashtable.put("topic.TOPIC", "BasicTopic");
    hashtable.put("queue.SUBSCRIPTION1", "BasicTopic/Subscriptions/Subscription1");
    hashtable.put("queue.SUBSCRIPTION2", "BasicTopic/Subscriptions/Subscription2");
    hashtable.put("queue.SUBSCRIPTION3", "BasicTopic/Subscriptions/Subscription3");
    hashtable.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.qpid.jms.jndi.JmsInitialContextFactory");
    Context context = new InitialContext(hashtable);

    ConnectionFactory cf = (ConnectionFactory) context.lookup("SBCF");

    // Look up the topic
    Destination topic = (Destination) context.lookup("TOPIC");

    // we create a scope here so we can use the same set of local variables cleanly 
    // again to show the receive side seperately with minimal clutter
    {/*from  www.  j  a v a 2s .  c o m*/
        // Create Connection
        Connection connection = cf.createConnection(csb.getSasKeyName(), csb.getSasKey());
        connection.start();
        // Create Session, no transaction, client ack
        Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

        // Create producer
        MessageProducer producer = session.createProducer(topic);

        // Send messaGES
        for (int i = 0; i < totalSend; i++) {
            BytesMessage message = session.createBytesMessage();
            message.writeBytes(String.valueOf(i).getBytes());
            producer.send(message);
            System.out.printf("Sent message %d.\n", i + 1);
        }

        producer.close();
        session.close();
        connection.stop();
        connection.close();
    }

    // Look up the subscription (pretending it's a queue)
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION1");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION2");
    receiveFromSubscription(csb, context, cf, "SUBSCRIPTION3");

    System.out.printf("Received all messages, exiting the sample.\n");
    System.out.printf("Closing queue client.\n");
}