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:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * WARNING - starts infinite loop - you have to kill 
 * @param uri/*from w  w w  .j a v a 2s.c  o m*/
 * @param submitQName
 * @param statusTName
 * @param statusQName
 * @throws Exception
 */
private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName)
        throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(submitQName);

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    System.out.println("Starting consumer for submissions to queue " + submitQName);
    while (isActive()) { // You have to kill it or call stop() to stop it!

        try {

            // Consumes messages from the queue.
            Message m = consumer.receive(1000);
            if (m != null) {

                // TODO FIXME Check if we have the max number of processes
                // exceeded and wait until we dont...

                TextMessage t = (TextMessage) m;
                ObjectMapper mapper = new ObjectMapper();

                final StatusBean bean = mapper.readValue(t.getText(), getBeanClass());

                if (bean != null) { // We add this to the status list so that it can be rendered in the UI

                    if (!isHandled(bean))
                        continue; // Consume it and move on

                    // Now we put the bean in the status queue and we 
                    // start the process
                    RemoteSubmission factory = new RemoteSubmission(uri);
                    factory.setLifeTime(t.getJMSExpiration());
                    factory.setPriority(t.getJMSPriority());
                    factory.setTimestamp(t.getJMSTimestamp());
                    factory.setQueueName(statusQName); // Move the message over to a status queue.

                    factory.submit(bean, false);

                    final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean);
                    if (process != null) {
                        if (process.isBlocking()) {
                            System.out.println("About to run job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                        processCount++;
                        process.start();
                        if (process.isBlocking()) {
                            System.out.println(
                                    "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")");
                        } else {
                            System.out.println("Started job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                    }

                }
            }

        } catch (Throwable ne) {
            // Really basic error reporting, they have to pipe to file.
            ne.printStackTrace();
            setActive(false);
        }
    }

}

From source file:org.apache.activemq.camel.JmsJdbcXARollbackTest.java

private boolean consumedFrom(String qName) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://testXA");
    factory.setWatchTopicAdvisories(false);
    Connection connection = factory.createConnection();
    connection.start();/*  w w w .ja v a 2  s  . c  o m*/
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(new ActiveMQQueue(qName));
    Message message = consumer.receive(500);
    LOG.info("Got from queue:{} {}", qName, message);
    connection.close();
    return message != null;
}

From source file:org.firstopen.singularity.util.JMSUtil.java

public static Connection registerListenerOnQueue(MessageListener listener, String queueName) throws Exception {
    InitialContext jndiContext = JNDIUtil.getInitialContext();
    Queue queue = (Queue) jndiContext.lookup("queue/" + queueName);
    ConnectionFactory qcf = (ConnectionFactory) jndiContext.lookup("ConnectionFactory");
    Connection connection = qcf.createConnection();
    Session m_session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer m_receiver = m_session.createConsumer(queue);
    m_receiver.setMessageListener(listener);
    return connection;
}

From source file:org.openengsb.opencit.core.projectmanager.internal.ProjectManagerImpl.java

private void initJms() throws JMSException {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(URL);
    connection = connectionFactory.createConnection();
    connection.start();//from w  w w . j av  a  2s. c  om

    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    feedbackQueue = session.createQueue(feedbackQueueName);
    feedbackConsumer = session.createConsumer(feedbackQueue);
    feedbackConsumer.setMessageListener(this);
}

From source file:org.sdnmq.jms.PacketForwarder.java

/**
 * Setup MQ//ww w  .  j av a2  s  . c  om
 */
private boolean initMQ() {
    log.trace("Setting up MQ system");

    Properties jndiProps = JNDIHelper.getJNDIProperties();

    Context ctx = null;
    try {
        ctx = new InitialContext(jndiProps);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    QueueConnectionFactory queueFactory = null;
    try {
        queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        connection = queueFactory.createQueueConnection();
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    String queueName = System.getProperty(PACKETOUT_QUEUE_PROPERTY, DEFAULT_PACKETOUT_QUEUE_NAME);
    log.info("Using the following queue for packet forwarding requests: " + queueName);
    try {
        packetOutQueue = (Queue) ctx.lookup(queueName);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    try {
        receiver = session.createReceiver(packetOutQueue);
    } catch (JMSException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

    return true;
}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Monitors a given bean in the status queue. 
 * If the bean is not there throws exception.
 * If the bean is in a final state, returns the bean straight away.
 * /*from ww w. j a va  2 s .  co  m*/
 * Polls the queue for the unique id of the bean we want until it
 * encounters a final state of that bean.
 * 
 * Polling rate is less than 1s
 * 
 * NOTE this class can poll forever if the job it is looking at never finishes.
 * 
 * @param obean
 * @param string
 * @return the bean once it is in a final state.
 * @throws exception if broker or queue absent
 */
public StatusBean monitor(StatusBean obean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);

    Class clazz = obean.getClass();
    ObjectMapper mapper = new ObjectMapper();

    try {
        POLL: while (true) {

            Thread.sleep(500);

            @SuppressWarnings("rawtypes")
            Enumeration e = qb.getEnumeration();

            while (e.hasMoreElements()) { // We must final the bean somewhere.
                Message m = (Message) e.nextElement();
                if (m == null)
                    continue;
                if (m instanceof TextMessage) {
                    TextMessage t = (TextMessage) m;
                    final StatusBean bean = mapper.readValue(t.getText(), clazz);
                    if (bean.getUniqueId().equals(obean.getUniqueId())) {
                        if (bean.getStatus().isFinal())
                            return bean;
                        System.out.println(bean.getPercentComplete());
                        continue POLL;
                    }
                }
            }

            throw new Exception(
                    "The bean with id " + obean.getUniqueId() + " does not exist in " + getQueueName() + "!");

        }
    } finally {
        qCon.close();
    }
}

From source file:org.wso2.andes.systest.GlobalQueuesTest.java

/**
 * Test that setting messageCount takes affect on a durable Consumer
 *
 * Ensure we set the delete-persistent option
 *
 * We send 10 messages and disconnect at 9
 *
 * @throws Exception//w  w w  . ja  v  a2  s.  com
 */

public void testTopicDurableConsumerMessageCount() throws Exception {
    MAX_QUEUE_MESSAGE_COUNT = 10;

    setConfig("messageCount", String.valueOf(MAX_QUEUE_MESSAGE_COUNT - 1), true);

    //Start the broker
    startBroker();

    topicConsumer(Session.AUTO_ACKNOWLEDGE, true);
}

From source file:com.googlecode.fascinator.common.PythonUtils.java

public PythonUtils(JsonSimpleConfig config) throws PluginException {
    this.config = config;
    // Security//from  w w w.  j a  v a 2  s.c  om
    String accessControlType = "accessmanager";
    access = PluginManager.getAccessManager(accessControlType);
    access.init(config.toString());

    // XML parsing
    namespaces = new HashMap<String, String>();
    DocumentFactory docFactory = new DocumentFactory();
    docFactory.setXPathNamespaceURIs(namespaces);
    saxReader = new SAXReader(docFactory);

    // Message Queues
    String brokerUrl = config.getString(ActiveMQConnectionFactory.DEFAULT_BROKER_BIND_URL, "messaging", "url");
    connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    try {
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // create single producer for multiple destinations
        producer = session.createProducer(null);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        // cache destinations
        destinations = new HashMap<String, Destination>();
    } catch (JMSException ex) {
        throw new PluginException(ex);
    }
    String access_plugin = config.getString(DEFAULT_ACCESS_PLUGIN, "accesscontrol", "type");
    if (access_plugin.indexOf(",") >= 0) {
        String[] plugin_list = access_plugin.split(",");
        current_access_plugin = plugin_list[0];
    } else {
        current_access_plugin = access_plugin;
    }
}

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

protected void createTerminateListener() throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    this.terminateConnection = connectionFactory.createConnection();
    terminateConnection.start();/*  www  .j  a  v  a2s.  c om*/

    Session session = terminateConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);

    final Topic topic = session.createTopic(Constants.TERMINATE_CONSUMER_TOPIC);
    final MessageConsumer consumer = session.createConsumer(topic);

    final ObjectMapper mapper = new ObjectMapper();

    MessageListener listener = new MessageListener() {
        public void onMessage(Message message) {
            try {
                if (message instanceof TextMessage) {
                    TextMessage t = (TextMessage) message;
                    final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class);

                    if (bean.getStatus().isFinal()) { // Something else already happened
                        terminateConnection.close();
                        return;
                    }

                    if (consumerId.equals(bean.getConsumerId())) {
                        if (bean.getStatus() == ConsumerStatus.REQUEST_TERMINATE) {
                            System.out.println(getName() + " has been requested to terminate and will exit.");
                            cbean.setStatus(ConsumerStatus.REQUEST_TERMINATE);
                            Thread.currentThread().sleep(2500);
                            System.exit(0);
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    };
    consumer.setMessageListener(listener);

}

From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java

public void init() {
    try {/*from  w  w w  .j a v a2  s .  c  om*/
        connection = connectionFactory.createConnection();
        connection.setClientID("bitsofproof supernode");
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        transactionProducer = session.createProducer(session.createTopic("transaction"));
        trunkProducer = session.createProducer(session.createTopic("trunk"));
        addNewTransactionListener();
        addNewBlockListener();
        addBlockrequestListener();
        addTransactionRequestListener();
        addColorRequestListener();
        addNewColorListener();
        addBloomFilterListener();
        addBloomScanListener();
        addMatchScanListener();
    } catch (JMSException e) {
        log.error("Error creating JMS producer", e);
    }
}