Example usage for javax.jms Session AUTO_ACKNOWLEDGE

List of usage examples for javax.jms Session AUTO_ACKNOWLEDGE

Introduction

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

Prototype

int AUTO_ACKNOWLEDGE

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

Click Source Link

Document

With this acknowledgment mode, the session automatically acknowledges a client's receipt of a message either when the session has successfully returned from a call to receive or when the message listener the session has called to process the message successfully returns.

Usage

From source file:hermes.ext.imq.ImqAdmin.java

public ImqAdmin(Hermes hermes, ConnectionFactory connectionFactory) {
    super(hermes);
    this.connectionFactory = connectionFactory;

    LOG.debug("Building ImqAdmin");

    try {/* w w w  .  j  av  a 2 s .com*/
        connection = this.connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic destListTopic = session.createTopic(DEST_LIST_TOPIC_NAME);
        destListTopicSubscriber = session.createConsumer(destListTopic);
        destListTopicSubscriber.setMessageListener(this);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java

protected void startNotifications() throws Exception {

    if (uri == null)
        throw new NullPointerException("Please set the URI before starting notifications!");
    this.cbean = new ConsumerBean();
    cbean.setStatus(ConsumerStatus.STARTING);
    cbean.setName(getName());/*from   w  w  w.j ava  2  s  .  c o m*/
    cbean.setConsumerId(consumerId);
    cbean.setVersion(consumerVersion);
    cbean.setStartTime(System.currentTimeMillis());
    try {
        cbean.setHostName(InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        // Not fatal but would be nice...
        e.printStackTrace();
    }

    System.out.println("Running events on topic " + Constants.ALIVE_TOPIC + " to notify of '" + getName()
            + "' service being available.");

    final Thread aliveThread = new Thread(new Runnable() {
        public void run() {

            try {
                ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
                aliveConnection = connectionFactory.createConnection();
                aliveConnection.start();

                final Session session = aliveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final Topic topic = session.createTopic(Constants.ALIVE_TOPIC);
                final MessageProducer producer = session.createProducer(topic);

                final ObjectMapper mapper = new ObjectMapper();

                // Here we are sending the message out to the topic
                while (isActive()) {
                    try {
                        Thread.sleep(Constants.NOTIFICATION_FREQUENCY);

                        TextMessage temp = session.createTextMessage(mapper.writeValueAsString(cbean));
                        producer.send(temp, DeliveryMode.NON_PERSISTENT, 1, 5000);

                        if (ConsumerStatus.STARTING.equals(cbean.getStatus())) {
                            cbean.setStatus(ConsumerStatus.RUNNING);
                        }

                    } catch (InterruptedException ne) {
                        break;
                    } catch (Exception neOther) {
                        neOther.printStackTrace();
                    }
                }
            } catch (Exception ne) {
                ne.printStackTrace();
                setActive(false);
            }
        }
    });
    aliveThread.setName("Alive Notification Topic");
    aliveThread.setDaemon(true);
    aliveThread.setPriority(Thread.MIN_PRIORITY);
    aliveThread.start();
}

From source file:nl.nn.adapterframework.jms.JmsMessagingSource.java

public Destination createDestination(String destinationName) throws JmsException {
    Destination dest = null;//from  www . j  ava2  s.c om
    Session session = null;
    try {
        session = createSession(false, Session.AUTO_ACKNOWLEDGE);
        dest = session.createQueue(destinationName);
    } catch (Exception e) {
        throw new JmsException("cannot create destination", e);
    } finally {
        releaseSession(session);
    }
    return dest;
}

From source file:org.apache.falcon.messaging.JMSMessageConsumer.java

public void startSubscriber() throws FalconException {
    try {/*from  w w  w.  j a  v a2  s .c om*/
        connection = createAndGetConnection(implementation, userName, password, url);
        connection.setClientID(FALCON_CLIENT_ID);

        topicSession = (TopicSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic destination = topicSession.createTopic(topicName);
        topicSubscriber = topicSession.createDurableSubscriber(destination, FALCON_CLIENT_ID);
        topicSubscriber.setMessageListener(this);

        connection.setExceptionListener(this);
        connection.start();
    } catch (Exception e) {
        LOG.error("Error starting topicSubscriber of topic: " + this.toString(), e);
        throw new FalconException(e);
    }
}

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

public void testSendRateWithActivatingConsumers() throws Exception {
    final Destination destination = createDestination();
    final ConnectionFactory factory = createConnectionFactory();
    startInactiveConsumers(factory, destination);

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = createMessageProducer(session, destination);

    // preload the durable consumers
    double[] inactiveConsumerStats = produceMessages(destination, 500, 10, session, producer, null);
    LOG.info("With inactive consumers: ave: " + inactiveConsumerStats[1] + ", max: " + inactiveConsumerStats[0]
            + ", multiplier: " + (inactiveConsumerStats[0] / inactiveConsumerStats[1]));

    // periodically start a durable sub that has a backlog
    final int consumersToActivate = 5;
    final Object addConsumerSignal = new Object();
    Executors.newCachedThreadPool(new ThreadFactory() {
        @Override//from w  ww . ja va 2 s.co m
        public Thread newThread(Runnable r) {
            return new Thread(r, "ActivateConsumer" + this);
        }
    }).execute(new Runnable() {
        @Override
        public void run() {
            try {
                MessageConsumer consumer = null;
                for (int i = 0; i < consumersToActivate; i++) {
                    LOG.info("Waiting for add signal from producer...");
                    synchronized (addConsumerSignal) {
                        addConsumerSignal.wait(30 * 60 * 1000);
                    }
                    TimedMessageListener listener = new TimedMessageListener();
                    consumer = createDurableSubscriber(factory.createConnection(), destination,
                            "consumer" + (i + 1));
                    LOG.info("Created consumer " + consumer);
                    consumer.setMessageListener(listener);
                    consumers.put(consumer, listener);
                }
            } catch (Exception e) {
                LOG.error("failed to start consumer", e);
            }
        }
    });

    double[] statsWithActive = produceMessages(destination, 500, 10, session, producer, addConsumerSignal);

    LOG.info(" with concurrent activate, ave: " + statsWithActive[1] + ", max: " + statsWithActive[0]
            + ", multiplier: " + (statsWithActive[0] / statsWithActive[1]));

    while (consumers.size() < consumersToActivate) {
        TimeUnit.SECONDS.sleep(2);
    }

    long timeToFirstAccumulator = 0;
    for (TimedMessageListener listener : consumers.values()) {
        long time = listener.getFirstReceipt();
        timeToFirstAccumulator += time;
        LOG.info("Time to first " + time);
    }
    LOG.info("Ave time to first message =" + timeToFirstAccumulator / consumers.size());

    for (TimedMessageListener listener : consumers.values()) {
        LOG.info("Ave batch receipt time: " + listener.waitForReceivedLimit(10000) + " max receipt: "
                + listener.maxReceiptTime);
    }

    //assertTrue("max (" + statsWithActive[0] + ") within reasonable
    // multiplier of ave (" + statsWithActive[1] + ")",
    //        statsWithActive[0] < 5 * statsWithActive[1]);

    // compare no active to active
    LOG.info("Ave send time with active: " + statsWithActive[1] + " as multiplier of ave with none active: "
            + inactiveConsumerStats[1] + ", multiplier=" + (statsWithActive[1] / inactiveConsumerStats[1]));

    assertTrue(
            "Ave send time with active: " + statsWithActive[1]
                    + " within reasonable multpler of ave with none active: " + inactiveConsumerStats[1]
                    + ", multiplier " + (statsWithActive[1] / inactiveConsumerStats[1]),
            statsWithActive[1] < 15 * inactiveConsumerStats[1]);
}

From source file:org.apache.rocketmq.jms.domain.JmsBaseConnection.java

@Override
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {

    Preconditions.checkArgument(!transacted, "Not support transaction Session !");
    Preconditions.checkArgument(Session.AUTO_ACKNOWLEDGE == acknowledgeMode,
            "Not support this acknowledge mode: " + acknowledgeMode);

    if (null != this.session) {
        return this.session;
    }/* ww w . j  a v  a  2s  . c o  m*/
    synchronized (this) {
        if (null != this.session) {
            return this.session;
        }
        this.session = new JmsBaseSession(this, transacted, acknowledgeMode, context);
        if (isStarted()) {
            this.session.start();
        }
        return this.session;
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSConsumerClient.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {// w ww. j  av a 2 s .c  o m
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {

        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                messageCount++;
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    preservedEventList.add(map);
                    log.info("Received Map Message : \n" + map + "\n");
                } else if (message instanceof TextMessage) {
                    String textMessage = ((TextMessage) message).getText();
                    preservedEventList.add(textMessage);
                    log.info("Received Text Message : \n" + textMessage + "\n");
                } else {
                    preservedEventList.add(message.toString());
                    log.info("Received message : \n" + message.toString() + "\n");
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:nl.nn.adapterframework.extensions.esb.EsbUtils.java

public static String receiveMessageAndMoveToErrorStorage(EsbJmsListener esbJmsListener,
        JdbcTransactionalStorage errorStorage) {
    String result = null;//from w  w  w. j  a v  a 2 s  .  c o m

    PoolingConnectionFactory jmsConnectionFactory = null;
    PoolingDataSource jdbcDataSource = null;
    BitronixTransactionManager btm = null;
    javax.jms.Connection jmsConnection = null;

    try {
        jmsConnectionFactory = getPoolingConnectionFactory(esbJmsListener);
        if (jmsConnectionFactory != null) {
            jdbcDataSource = getPoolingDataSource(errorStorage);
            if (jdbcDataSource != null) {
                String instanceNameLc = AppConstants.getInstance().getString("instance.name.lc", null);
                String logDir = AppConstants.getInstance().getString("log.dir", null);
                TransactionManagerServices.getConfiguration().setServerId(instanceNameLc + ".tm");
                TransactionManagerServices.getConfiguration()
                        .setLogPart1Filename(logDir + File.separator + instanceNameLc + "-btm1.tlog");
                TransactionManagerServices.getConfiguration()
                        .setLogPart2Filename(logDir + File.separator + instanceNameLc + "-btm2.tlog");
                btm = TransactionManagerServices.getTransactionManager();

                jmsConnection = jmsConnectionFactory.createConnection();

                Session jmsSession = null;
                MessageConsumer jmsConsumer = null;

                java.sql.Connection jdbcConnection = null;

                btm.begin();
                log.debug("started transaction [" + btm.getCurrentTransaction().getGtrid() + "]");

                try {
                    jmsSession = jmsConnection.createSession(true, Session.AUTO_ACKNOWLEDGE);
                    String queueName = esbJmsListener.getPhysicalDestinationShortName();
                    Queue queue = jmsSession.createQueue(queueName);
                    jmsConsumer = jmsSession.createConsumer(queue);

                    jmsConnection.start();

                    long timeout = 30000;
                    log.debug("looking for message on queue [" + queueName + "] with timeout of [" + timeout
                            + "] msec");
                    Message rawMessage = jmsConsumer.receive(timeout);

                    if (rawMessage == null) {
                        log.debug("no message found on queue [" + queueName + "]");
                    } else {
                        String id = rawMessage.getJMSMessageID();
                        log.debug("found message on queue [" + queueName + "] with messageID [" + id + "]");
                        Serializable sobj = null;
                        if (rawMessage != null) {
                            if (rawMessage instanceof Serializable) {
                                sobj = (Serializable) rawMessage;
                            } else {
                                try {
                                    sobj = new MessageWrapper(rawMessage, esbJmsListener);
                                } catch (ListenerException e) {
                                    log.error("could not wrap non serializable message for messageId [" + id
                                            + "]", e);
                                    if (rawMessage instanceof TextMessage) {
                                        TextMessage textMessage = (TextMessage) rawMessage;
                                        sobj = textMessage.getText();
                                    } else {
                                        sobj = rawMessage.toString();
                                    }
                                }
                            }
                        }

                        jdbcConnection = jdbcDataSource.getConnection();

                        result = errorStorage.storeMessage(jdbcConnection, id, id,
                                new Date(System.currentTimeMillis()), "moved message", null, sobj);
                    }

                    log.debug("committing transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                    btm.commit();
                } catch (Exception e) {
                    if (btm.getCurrentTransaction() != null) {
                        log.debug("rolling back transaction [" + btm.getCurrentTransaction().getGtrid() + "]");
                        btm.rollback();
                    }
                    log.error("exception on receiving message and moving to errorStorage", e);
                } finally {
                    if (jdbcConnection != null) {
                        jdbcConnection.close();
                    }
                    if (jmsConnection != null) {
                        jmsConnection.stop();
                    }
                    if (jmsConsumer != null) {
                        jmsConsumer.close();
                    }
                    if (jmsSession != null) {
                        jmsSession.close();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("exception on receiving message and moving to errorStorage", e);
    } finally {
        if (jmsConnection != null) {
            try {
                jmsConnection.close();
            } catch (JMSException e) {
                log.warn("exception on closing connection", e);
            }
        }
        if (jmsConnectionFactory != null) {
            jmsConnectionFactory.close();
        }
        if (jdbcDataSource != null) {
            jdbcDataSource.close();
        }
        if (btm != null) {
            btm.shutdown();
        }
    }
    return result;
}

From source file:org.apache.activemq.JmsTopicSendReceiveWithTwoConnectionsTest.java

protected Session createReceiveSession(Connection receiveConnection) throws Exception {
    return receiveConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}

From source file:org.apache.servicemix.jms.AbstractJmsProcessor.java

protected void commonDoStartTasks(InitialContext ctx) throws Exception {
    channel = endpoint.getServiceUnit().getComponent().getComponentContext().getDeliveryChannel();
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    destination = endpoint.getDestination();
    if (destination == null) {
        if (endpoint.getJndiDestinationName() != null) {
            destination = (Destination) ctx.lookup(endpoint.getJndiDestinationName());
        } else if (endpoint.getJmsProviderDestinationName() != null) {
            if (STYLE_QUEUE.equals(endpoint.getDestinationStyle())) {
                destination = session.createQueue(endpoint.getJmsProviderDestinationName());
            } else {
                destination = session.createTopic(endpoint.getJmsProviderDestinationName());
            }/*ww w .  ja va 2  s  .c  om*/
        } else {
            throw new IllegalStateException("No destination provided");
        }
    }
    if (endpoint.getJndiReplyToName() != null) {
        replyToDestination = (Destination) ctx.lookup(endpoint.getJndiReplyToName());
    } else if (endpoint.getJmsProviderReplyToName() != null) {
        if (destination instanceof Queue) {
            replyToDestination = session.createQueue(endpoint.getJmsProviderReplyToName());
        } else {
            replyToDestination = session.createTopic(endpoint.getJmsProviderReplyToName());
        }
    }
}