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:eu.domibus.submission.jms.BackendJMSImpl.java

/**
 * This method is called when a message was received at the incoming queue
 *
 * @param message The incoming JMS Message
 *///w ww. j ava2 s.c  om
@Override
public void onMessage(final Message message) {
    final MapMessage map = (MapMessage) message;
    try {
        final Connection con = this.cf.createConnection();
        final Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        final MapMessage res = session.createMapMessage();
        try {
            final String messageID = this.submit(map);
            res.setStringProperty("messageId", messageID);
        } catch (final TransformationException | ValidationException e) {
            BackendJMSImpl.LOG.error("Exception occurred: ", e);
            res.setString("ErrorMessage", e.getMessage());
        }

        res.setJMSCorrelationID(map.getJMSCorrelationID());
        final MessageProducer sender = session.createProducer(this.outQueue);
        sender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        sender.send(res);
        sender.close();
        session.close();
        con.close();

    } catch (final JMSException ex) {
        BackendJMSImpl.LOG.error("Error while sending response to queue", ex);

    }
}

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

/**
 * JMS setup//from www  .ja  va2s  . c  o  m
 */
private boolean initMQ() {
    log.trace("Setting up JMS ...");

    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(FLOWPROGRAMMER_QUEUE_PROPERTY, DEFAULT_FLOWPROGRAMMER_QUEUE_NAME);
    log.info("Using the following queue for flow programming requests: " + queueName);
    try {
        flowProgrammerQueue = (Queue) ctx.lookup(queueName);
    } catch (NamingException e) {
        log.error(e.getMessage());
        releaseMQ();
        return false;
    }

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

    log.trace("Setup JMS successfully");

    return true;
}

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

private void sendJMSMessageToKickOffRoute() 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 om
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(new ActiveMQQueue("scp_transacted"));
    TextMessage message = session.createTextMessage("Some Text, messageCount:" + messageCount++);
    message.setJMSCorrelationID("pleaseCorrelate");
    producer.send(message);
    connection.close();
}

From source file:org.apache.qpid.client.ssl.SSLTest.java

/**
 * Create an SSL connection using the SSL system properties for the trust and key store, but using
 * the {@link ConnectionURL} ssl='true' option to indicate use of SSL at a Connection level,
 * overriding the false setting at the {@link ConnectionURL#OPTIONS_BROKERLIST} level.
 *//*from   ww  w. j a v a2s. c o  m*/
public void testSslConnectionOptionOverridesBrokerlistOption() throws Exception {
    if (shouldPerformTest()) {
        //Start the broker (NEEDing client certificate authentication)
        configureJavaBrokerIfNecessary(true, true, true, false);
        super.setUp();

        //Create URL enabling SSL at the connection, overriding the false at the brokerlist level
        String url = "amqp://guest:guest@test/?ssl='true'&brokerlist='tcp://localhost:%s?ssl='false''";
        url = String.format(url, QpidBrokerTestCase.DEFAULT_SSL_PORT);

        Connection con = getConnection(new AMQConnectionURL(url));
        assertNotNull("connection should be successful", con);
        Session ssn = con.createSession(false, Session.AUTO_ACKNOWLEDGE);
        assertNotNull("create session should be successful", ssn);
    }
}

From source file:org.overlord.sramp.events.jms.JMSEventProducer.java

@Override
public void startup() {
    if (SrampConfig.isJmsEnabled()) {
        try {//  w  w w  . j av  a  2  s. c om
            String connectionFactoryName = SrampConfig.getConfigProperty(
                    SrampConstants.SRAMP_CONFIG_EVENT_JMS_CONNECTIONFACTORY, "ConnectionFactory"); //$NON-NLS-1$

            // Note that both properties end up doing the same thing.  Technically, we could combine both into one
            // single sramp.config.events.jms.destinations, but leaving them split for readability.
            String topicNamesProp = SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_TOPICS,
                    ""); //$NON-NLS-1$
            String[] topicNames = new String[0];
            if (StringUtils.isNotEmpty(topicNamesProp)) {
                topicNames = topicNamesProp.split(","); //$NON-NLS-1$
            }
            String queueNamesProp = SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_QUEUES,
                    ""); //$NON-NLS-1$
            String[] queueNames = new String[0];
            if (StringUtils.isNotEmpty(queueNamesProp)) {
                queueNames = queueNamesProp.split(","); //$NON-NLS-1$
            }

            try {
                // First, see if a ConnectionFactory and Topic/Queue exists on JNDI.  If so, assume JMS is properly
                // setup in a Java EE container and simply use it.

                ConnectionFactory connectionFactory = (ConnectionFactory) jndiLookup(connectionFactoryName);
                connection = connectionFactory.createConnection();
                session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

                for (String topicName : topicNames) {
                    Topic topic = (Topic) jndiLookup(topicName);
                    destinations.add(topic);
                }

                for (String queueName : queueNames) {
                    Queue queue = (Queue) jndiLookup(queueName);
                    destinations.add(queue);
                }
            } catch (NamingException e) {
                // Otherwise, JMS wasn't setup. Assume we need to start an embedded
                // ActiveMQ broker and create the destinations.

                String bindAddress = "tcp://localhost:" //$NON-NLS-1$
                        + SrampConfig.getConfigProperty(SrampConstants.SRAMP_CONFIG_EVENT_JMS_PORT, "61616"); //$NON-NLS-1$

                LOG.warn(Messages.i18n.format("org.overlord.sramp.events.jms.embedded_broker", bindAddress)); //$NON-NLS-1$

                session = null;
                destinations.clear();

                BrokerService broker = new BrokerService();
                broker.addConnector(bindAddress);
                broker.start();

                // Event though we added a TCP connector, above, ActiveMQ also exposes the broker over the "vm"
                // protocol. It optimizes performance for connections on the same JVM.
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); //$NON-NLS-1$
                initActiveMQ(connectionFactory, topicNames, queueNames);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

From source file:org.apache.synapse.message.store.impl.jms.JmsStore.java

public MessageProducer getProducer() {
    JmsProducer producer = new JmsProducer(this);
    producer.setId(nextProducerId());//  w  w w.j  av a  2 s .c o m
    Throwable throwable = null;
    Session session = null;
    javax.jms.MessageProducer messageProducer;
    boolean error = false;
    try {
        synchronized (producerLock) {
            if (producerConnection == null) {
                boolean ok = newWriteConnection();
                if (!ok) {
                    return producer;
                }
            }
        }
        try {
            session = newSession(producerConnection(), Session.AUTO_ACKNOWLEDGE, true);
        } catch (JMSException e) {
            synchronized (producerLock) {
                boolean ok = newWriteConnection();
                if (!ok) {
                    return producer;
                }
            }
            session = newSession(producerConnection(), Session.AUTO_ACKNOWLEDGE, true);
            logger.info(nameString() + " established a connection to the broker.");
        }
        messageProducer = newProducer(session);
        producer.setConnection(producerConnection()).setSession(session).setProducer(messageProducer);
    } catch (Throwable t) {
        error = true;
        throwable = t;
    }
    if (error) {
        String errorMsg = "Could not create a Message Producer for " + nameString() + ". Error:"
                + throwable.getLocalizedMessage();
        logger.error(errorMsg, throwable);
        synchronized (producerLock) {
            cleanup(producerConnection, session, true);
            producerConnection = null;
        }
        return producer;
    }
    if (logger.isDebugEnabled()) {
        logger.debug(nameString() + " created message producer " + producer.getId());
    }
    return producer;
}

From source file:com.att.ajsc.csilogging.common.QueueConnector.java

@PostConstruct
public void init() {

    if (csiEnable && StringUtils.isNotEmpty(initialContextFactoryName)
            && StringUtils.isNotEmpty(connectionFactoryName) && StringUtils.isNotEmpty(providerURL)) {

        if (StringUtils.isNotEmpty(System.getenv(("com_att_aft_config_file")))) {
            System.setProperty("com.att.aft.config.file", System.getenv("com_att_aft_config_file"));
        }/*  w ww . ja v  a  2  s. c om*/

        if (StringUtils.isEmpty(System.getProperty("com.att.aft.config.file"))) {
            logger.error("Environment or System properties dont have the property com.att.aft.config.file");
            return;
        }

        QueueConnectionFactory queueConnectionFactory;
        InitialContext jndi = null;
        ConnectionFactory connectionFactory = null;
        try {

            Properties env = new Properties();
            env.put(Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName);
            env.put(Context.PROVIDER_URL, providerURL);
            jndi = new InitialContext(env);
            connectionFactory = (ConnectionFactory) jndi.lookup(connectionFactoryName);
            queueConnectionFactory = (QueueConnectionFactory) connectionFactory;
            if (StringUtils.isNotEmpty(auditDestinationName)) {
                auditQueueConnection = queueConnectionFactory.createQueueConnection();
                auditQueueSession = auditQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue auditQueue = (Queue) auditQueueSession.createQueue(auditDestinationName);
                auditQueueSender = auditQueueSession.createSender(auditQueue);
                auditQueueConnection.start();
                logger.info("*************CONNECTED :" + auditDestinationName + "*************");

            }

            if (StringUtils.isNotEmpty(perfDestinationName)) {
                pefQueueConnection = queueConnectionFactory.createQueueConnection();
                pefQueueSession = pefQueueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
                Queue perfQueue = (Queue) pefQueueSession.createQueue(perfDestinationName);
                pefQueueSender = pefQueueSession.createSender(perfQueue);
                pefQueueConnection.start();
                logger.info("*************CONNECTED :" + perfDestinationName + "*************");
            }

        } catch (Exception e) {
            logger.error("Error while connecting to the Queue" + e);
        }
    }

}

From source file:org.wso2.carbon.andes.event.core.internal.delivery.jms.JMSDeliveryManager.java

/**
 * {@inheritDoc}//from  w  w w.j  a v  a  2s. c om
 */
public void subscribe(Subscription subscription) throws EventBrokerException {

    if (isDeactivated()) {
        return;
    }

    // in a multi tenant environment deployment synchronize may creates subscriptions before
    // the event observer get activated.
    if (this.subscriptionIDSessionDetailsMap.containsKey(subscription.getId())) {
        log.warn(
                "There is an subscription already exists for the subscription with id " + subscription.getId());
        return;
    }
    JMSMessageListener jmsMessageListener = new JMSMessageListener(this.notificationManager, subscription);
    try {
        TopicConnection topicConnection = getTopicConnection(subscription.getOwner());
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String topicName = "";
        if (subscription.getTenantDomain() != null && (!subscription.getTenantDomain()
                .equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {

            if (!subscription.getTopicName().startsWith("/")) {
                topicName = getTopicName(subscription.getTenantDomain() + "/" + subscription.getTopicName());
            } else {
                topicName = getTopicName(subscription.getTenantDomain() + subscription.getTopicName());
            }
        } else {
            topicName = getTopicName(subscription.getTopicName());
        }
        Topic topic = topicSession.createTopic(topicName);
        //Some times we are not getting the proper topic with the required syntax, if it is not
        //appropriate we need to check and add the BURL syntax to fix the issue https://wso2.org/jira/browse/MB-185
        if (!topic.toString().startsWith("topic://amq.topic")) {
            topic = topicSession.createTopic("BURL:" + topicName);
        }
        TopicSubscriber topicSubscriber = topicSession.createDurableSubscriber(topic, subscription.getId());
        topicSubscriber.setMessageListener(jmsMessageListener);

        this.subscriptionIDSessionDetailsMap.put(subscription.getId(),
                new JMSSubscriptionDetails(topicSubscriber, topicSession, topicConnection));
    } catch (JMSException e) {
        throw new EventBrokerException(
                "Can not subscribe to topic " + subscription.getTopicName() + " " + e.getMessage(), e);
    }
}

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

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

    // Create a Connection
    testMeta.connection = connectionFactory.createConnection();
    testMeta.connection.start();//from w w  w.  j a  va  2  s  . co m

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

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

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

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();/*ww w  .j  a va 2 s . co  m*/

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