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.sakaiproject.kernel.messaging.activemq.ActiveMQEmailDeliveryT.java

public void testCommonsEmailOneWaySeparateSessions() {

    Queue emailQueue = null;//from   w ww.  ja  va  2  s  .  c  o m
    MessageConsumer consumer = null;
    MessageProducer producer = null;
    Session clientSession = null;
    Session listenerSession = null;
    // it is not necessary to use the Email interface here
    // Email is used here just to allow for multiple types of emails to
    // occupy
    // the same varaible. SimpleEmail etc can each be used directly.
    List<Email> emails = new ArrayList<Email>();
    EmailMessagingService messagingService = new EmailMessagingService(vmURL, emailQueueName, emailType, null,
            null, null, null);
    emails.add(new SimpleEmail(messagingService));
    emails.add(new MultiPartEmail(messagingService));
    emails.add(new HtmlEmail(messagingService));
    try {

        listenerSession = listenerConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = listenerSession.createQueue(emailQueueName);

        consumer = listenerSession.createConsumer(emailQueue);

        consumer.setMessageListener(new EmailListener());

        listenerConn.start();

        listenerSession.run();

    } catch (JMSException e2) {
        e2.printStackTrace();
        Assert.assertTrue(false);
    }

    Wiser smtpServer = new Wiser();
    smtpServer.setPort(smtpTestPort);
    smtpServer.start();

    try {
        clientSession = clientConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        emailQueue = clientSession.createQueue(emailQueueName);
        producer = clientSession.createProducer(emailQueue);

        clientConn.start();
        clientSession.run();

    } catch (JMSException e) {
        e.printStackTrace();
        Assert.assertTrue(false);
    }

    for (Email em : emails) {

        try {
            em.addTo(TEST_EMAIL_TO);
            em.setFrom(TEST_EMAIL_FROM_ADDRESS, TEST_EMAIL_FROM_LABEL);
            // host and port will be ignored since the email session is
            // established
            // by
            // the listener
            em.setHostName("localhost");
            em.setSmtpPort(smtpTestPort);
            em.setSubject(TEST_EMAIL_SUBJECT);
            if (em instanceof HtmlEmail) {
                em.setMsg(TEST_EMAIL_BODY_HTMLEMAIL);
            } else if (em instanceof MultiPartEmail) {
                em.setMsg(TEST_EMAIL_BODY_MULTIPARTEMAIL);
            } else if (em instanceof SimpleEmail) {
                em.setMsg(TEST_EMAIL_BODY_SIMPLEEMAIL);
            }

        } catch (EmailException e1) {
            Assert.assertTrue(false);
            e1.printStackTrace();
        }

        try {
            em.buildMimeMessage();
        } catch (EmailException e1) {
            e1.printStackTrace();
            Assert.assertTrue(false);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {

            em.getMimeMessage().writeTo(os);
        } catch (javax.mail.MessagingException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        } catch (IOException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

        String content = os.toString();

        ObjectMessage om;
        try {
            om = clientSession.createObjectMessage(content);

            om.setJMSType(emailType);

            LOG.info("Client: Sending test message....");
            producer.send(om);
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }

    }

    long start = System.currentTimeMillis();
    while (listenerMessagesProcessed < 3 && System.currentTimeMillis() - start < 10000L) {
        // wait for transport
    }
    Assert.assertTrue(listenerMessagesProcessed == 3);

    List<WiserMessage> messages = smtpServer.getMessages();
    Assert.assertTrue(messages.size() + " != expected value of 3", messages.size() == 3);

    for (WiserMessage wisermsg : messages) {
        String body = null;
        String subject = null;
        MimeMessage testmail = null;

        try {
            testmail = wisermsg.getMimeMessage();
        } catch (MessagingException e) {
            Assert.assertTrue(false);
            e.printStackTrace();
        }

        if (testmail != null) {
            LOG.info("SMTP server: test email received: ");
            try {
                LOG.info("To: " + testmail.getHeader("To", ","));

                LOG.info("Subject: " + testmail.getHeader("Subject", ","));
                body = getBodyAsString(testmail.getContent());
                subject = testmail.getHeader("Subject", ",");
            } catch (MessagingException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            } catch (IOException e) {
                Assert.assertTrue(false);
                e.printStackTrace();
            }
            LOG.info("Body: " + body);
            Assert.assertTrue(subject.contains(TEST_EMAIL_SUBJECT));
            Assert.assertTrue(body.contains("This is a Commons"));
        } else {
            Assert.assertTrue(false);
        }
    }

    if (clientSession != null) {
        try {
            clientSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        clientSession = null;
    }

    if (listenerSession != null) {
        try {
            listenerSession.close();
        } catch (JMSException e) {
            e.printStackTrace();
            Assert.assertTrue(false);
        }
        listenerSession = null;
    }

    smtpServer.stop();

}

From source file:org.jbpm.ejb.CommandListenerBean.java

private void sendResult(Serializable result, Destination destination, String correlationId)
        throws JMSException {
    if (log.isDebugEnabled())
        log.debug("sending " + result + " to " + destination);

    Connection jmsConnection = jmsConnectionFactory.createConnection();
    try {//w  ww  .  jav a  2s . c om
        /*
         * if the connection supports xa, the session will be transacted, else the session will
         * auto acknowledge; in either case no explicit transaction control must be performed -
         * see ejb 2.1 - 17.3.5
         */
        Session jmsSession = jmsConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Message resultMessage = jmsSession.createObjectMessage(result);
        resultMessage.setJMSCorrelationID(correlationId);
        MessageProducer producer = jmsSession.createProducer(destination);
        producer.send(resultMessage);
    } finally {
        // there is no need to close the sessions and producers of a closed connection
        // http://download.oracle.com/javaee/1.4/api/javax/jms/Connection.html#close()
        try {
            jmsConnection.close();
        } catch (JMSException e) {
            log.warn("failed to close jms connection", e);
        }
    }
}

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

public void publish(Message message, String topicName, int deliveryMode) throws EventBrokerException {

    if (isDeactivated()) {
        return;//w ww  .  j  ava 2  s .c  om
    }

    try {
        String userName = getLoggedInUserName();
        if ((userName == null) || (userName.equals(""))) {
            // use the system user name
            userName = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
        }

        TopicConnection topicConnection = getTopicConnection(userName);
        TopicSession topicSession = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        String tenantDomain = EventBrokerHolder.getInstance().getTenantDomain();
        if (tenantDomain != null
                && (!tenantDomain.equals(org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME))) {
            if (!topicName.startsWith("/")) {
                topicName = getTopicName(tenantDomain + "/" + topicName);
            } else {
                topicName = getTopicName(tenantDomain + topicName);
            }
        } else {
            topicName = getTopicName(topicName);
        }

        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);
        }
        TopicPublisher topicPublisher = topicSession.createPublisher(topic);
        topicPublisher.setDeliveryMode(deliveryMode);
        TextMessage textMessage = topicSession.createTextMessage(message.getMessage().toString());

        Map<String, String> properties = message.getProperties();
        for (String key : properties.keySet()) {
            textMessage.setStringProperty(key, properties.get(key));
        }

        // saving the domain to be used send with the soap header
        if (CarbonContext.getThreadLocalCarbonContext().getTenantDomain() != null) {
            textMessage.setStringProperty(MultitenantConstants.TENANT_DOMAIN_HEADER_NAME,
                    CarbonContext.getThreadLocalCarbonContext().getTenantDomain());
        }

        topicPublisher.publish(textMessage);
        topicPublisher.close();
        topicSession.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        throw new EventBrokerException("Can not publish to topic " + topicName + " " + e.getMessage(), e);
    }
}

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

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

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    final int toSend = 100;
    final int numIterations = 5;

    double[] noConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    startConsumers(factory, destination);
    LOG.info("Activated consumer");

    double[] withConsumerStats = produceMessages(destination, toSend, numIterations, session, producer, null);

    LOG.info("With consumer: " + withConsumerStats[1] + " , with noConsumer: " + noConsumerStats[1]
            + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]));
    final int reasonableMultiplier = 15; // not so reasonable but improving
    assertTrue(/*w  w w  . j a v  a 2 s.  c o m*/
            "max X times as slow with consumer: " + withConsumerStats[1] + ", with no Consumer: "
                    + noConsumerStats[1] + ", multiplier: " + (withConsumerStats[1] / noConsumerStats[1]),
            withConsumerStats[1] < noConsumerStats[1] * reasonableMultiplier);

    final int toReceive = toSend * numIterations * consumerCount * 2;
    Wait.waitFor(new Wait.Condition() {
        public boolean isSatisified() throws Exception {
            LOG.info("count: " + allMessagesList.getMessageCount());
            return toReceive == allMessagesList.getMessageCount();
        }
    }, 60 * 1000);

    assertEquals("got all messages", toReceive, allMessagesList.getMessageCount());
}

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

private void consumer() throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*from  ww  w .  j  a  v a  2  s  . co  m*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(TOPIC_NAME);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();
    verifyMesssage(consumer);

    connection.close();
}

From source file:org.apache.falcon.oozie.workflow.FalconPostProcessingTest.java

private void consumer(String brokerUrl, String topic, boolean checkUserMessage) throws JMSException {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    Connection connection = connectionFactory.createConnection();
    connection.start();/*  w  w w  . j  av a2  s .c  o m*/

    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createTopic(topic);
    MessageConsumer consumer = session.createConsumer(destination);

    latch.countDown();

    // Verify user message
    if (checkUserMessage) {
        verifyMesssage(consumer);
    }

    // Verify falcon message
    verifyMesssage(consumer);

    connection.close();
}

From source file:org.apache.servicemix.wsn.jms.JmsSubscription.java

protected void start() throws SubscribeCreationFailedFault {
    try {//  w ww .  jav  a 2s  .  c om

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        if (session == null) {
            System.out.println("jmsTopic:" + jmsTopic);
            MessageConsumer consumer = session.createConsumer(jmsTopic);
            consumer.setMessageListener(this);
        }
    } catch (JMSException e) {
        SubscribeCreationFailedFaultType fault = new SubscribeCreationFailedFaultType();
        throw new SubscribeCreationFailedFault("Error starting subscription", fault, e);
    }
}

From source file:org.openhie.openempi.notification.impl.NotificationServiceImpl.java

public void registerListener(List<String> eventTypeNames, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;/*from w ww  .  ja va2s.  c om*/
    }

    if (!isValidHandler(handler)) {
        return;
    }

    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    Connection connection = null;
    try {
        connection = connectionFactory.createConnection();
        connection.setClientID(handler.getClientId());
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }

    for (String eventTypeName : eventTypeNames) {
        log.info("Registering handler for event " + eventTypeName);
        Topic topic = topicMap.get(eventTypeName);
        if (topic == null) {
            log.error("Caller attempted to register interest to events of unknown type " + eventTypeName);
            throw new RuntimeException("Unknown event type specified in registration request.");
        }

        if (isListenerRegistered(handler, eventTypeName)) {
            log.warn("Caller attempted to register interest for the same event again.");
            return;
        }

        try {
            Session topicSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, topic.getTopicName());
            MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber,
                    handler);
            saveListenerRegistration(listener, eventTypeName);
            subscriber.setMessageListener(listener);
        } catch (JMSException e) {
            log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
            throw new RuntimeException(
                    "Unable to setup registration for event notification: " + e.getMessage());
        }
    }

    try {
        connection.start();
    } catch (JMSException e) {
        log.error("Failed while setting up a registrant for notification events. Error: " + e, e);
        throw new RuntimeException("Unable to setup registration for event notification: " + e.getMessage());
    }
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

public JMSMailQueue(ConnectionFactory connectionFactory,
        MailQueueItemDecoratorFactory mailQueueItemDecoratorFactory, String queueName,
        MetricFactory metricFactory, GaugeRegistry gaugeRegistry) {
    try {// w  w w . j  ava  2  s  .c  o  m
        connection = connectionFactory.createConnection();
        connection.start();
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
    this.mailQueueItemDecoratorFactory = mailQueueItemDecoratorFactory;
    this.queueName = queueName;
    this.metricFactory = metricFactory;
    this.enqueuedMailsMetric = metricFactory.generate(ENQUEUED_METRIC_NAME_PREFIX + queueName);
    this.dequeuedMailsMetric = metricFactory.generate(DEQUEUED_METRIC_NAME_PREFIX + queueName);

    this.gaugeRegistry = gaugeRegistry;
    this.gaugeRegistry.register(QUEUE_SIZE_METRIC_NAME_PREFIX + queueName, queueSizeGauge());

    this.joiner = Joiner.on(JAMES_MAIL_SEPARATOR).skipNulls();
    this.splitter = Splitter.on(JAMES_MAIL_SEPARATOR).omitEmptyStrings() // ignore null values. See JAMES-1294
            .trimResults();
    try {
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = session.createQueue(queueName);
        producer = session.createProducer(queue);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.enterprise.server.drift.DriftManagerBean.java

@Override
@TransactionAttribute(REQUIRES_NEW)/* w w w .ja va2  s .  com*/
public void addFiles(Subject subject, int resourceId, String driftDefName, String token, long zipSize,
        InputStream zipStream) throws Exception {

    Connection connection = factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(fileQueue);
    ObjectMessage msg = session
            .createObjectMessage(new DriftUploadRequest(resourceId, driftDefName, token, zipSize, zipStream));
    producer.send(msg);
    connection.close();
}