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.apache.activemq.usecases.DurableSubscriptionHangTestCase.java

private Message collectMessagesFromDurableSubscriptionForOneMinute() throws Exception {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://" + brokerName);
    TopicConnection connection = connectionFactory.createTopicConnection();

    connection.setClientID(clientID);/*from  w ww  .  j  a  v  a  2s  .c  o m*/
    TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic topic = topicSession.createTopic(topicName);
    connection.start();
    TopicSubscriber subscriber = topicSession.createDurableSubscriber(topic, durableSubName);
    LOG.info("About to receive messages");
    Message message = subscriber.receive(120000);
    subscriber.close();
    connection.close();
    LOG.info("collectMessagesFromDurableSubscriptionForOneMinute done");

    return message;
}

From source file:pl.psnc.synat.wrdz.zu.certificate.CertificateChecker.java

/**
 * Notifies the system monitor that the given user has a certificate that's beyond the expiration threshold.
 * /*from w w  w .  ja  va2 s  .  c o  m*/
 * @param username
 *            name of the user with the (nearly) expired certificate
 */
private void notifyExpirationCheckFail(String username) {
    QueueConnection connection = null;
    try {
        connection = queueConnectionFactory.createQueueConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage message = session.createTextMessage();
        message.setText(username);
        session.createProducer(certificateQueue).send(message);
    } catch (JMSException e) {
        logger.error("Sending message to the JMS queue failed", e);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                logger.error("Error while closing a connection.", e);
            }
        }
    }
}

From source file:org.apache.ode.extension.jmseventlistener.JmsBpelEventListener.java

public void startup(Properties configProperties) {
    if (configProperties == null) {
        logger.info("No configuration properties given. Initialization aborted.");
        return;//from   w  w w.j a  va 2  s.c o m
    }
    topicName = configProperties.getProperty(TOPIC_NAME_KEY, "org.apache.ode.events");
    url = configProperties.getProperty(MQ_URL_KEY, "tcp://localhost:61616");

    try {
        factory = new ActiveMQConnectionFactory(url);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        publisher = session.createProducer(topic);
        publisher.setDeliveryMode(DeliveryMode.PERSISTENT);
        initialized = true;
    } catch (JMSException e) {
        logger.error("Initialization failed.", e);
    }
    logger.info("JMS BPEL event has been started.");
}

From source file:com.jim.im.config.GenericMQConfig.java

/**
 * ?????,MQ???/*from   ww  w. j  ava2s  . c  o m*/
 *
 * @param topicName
 * @param messageListener
 * @return
 */
public MessageListenerContainer mqMessageReceiver(String topicName, MessageListener messageListener) {
    DefaultMessageListenerContainer container = new DefaultMessageListenerContainer();
    container.setConnectionFactory(jmsConnectionFactory());
    container.setDestinationName(topicName);
    container.setPubSubDomain(true);
    container.setPubSubNoLocal(true);
    container.setMessageListener(messageListener);
    container.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
    return container;
}

From source file:org.audit4j.core.AsyncAuditEngine.java

/**
 * Initialize if needed.//from   ww  w. j  a  v  a2 s . co  m
 */
private synchronized void initializeIfNeeded() {
    try {
        if (session == null) {
            // Create a ConnectionFactory
            connectionFactory = new ActiveMQConnectionFactory("vm://localhost");
            connection = connectionFactory.createConnection();
            connection.start();
            connection.setExceptionListener(this);
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            destination = session.createQueue(queueName);
        } else {
            log.trace("messageListener already defined");
        }

    } catch (final JMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.kernel.messaging.email.EmailMessagingService.java

private void createSessions() {
    int sessionsPerConnection = 1;
    Session sess = null;// w  w  w  . ja  v a  2  s .co  m
    for (Connection conn : connections) {
        for (int i = 0; i < sessionsPerConnection; ++i) {
            sess = null;
            try {
                sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                sessions.put(conn.getClientID(), sess);
            } catch (JMSException e) {
                try {
                    LOG.error("Fail to create connection[" + i + "]: " + conn.getClientID());
                } catch (JMSException e1) {
                    // TMI
                }
                e.printStackTrace();
            }
        }
    }

}

From source file:org.apache.flume.source.jms.TestIntegrationActiveMQ.java

private void putQueue(List<String> events) throws Exception {
    ConnectionFactory factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_BIND_URL);
    Connection connection = factory.createConnection();
    connection.start();//from w  ww . j av  a 2 s .  c o  m

    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(DESTINATION_NAME);
    MessageProducer producer = session.createProducer(destination);

    for (String event : events) {
        TextMessage message = session.createTextMessage();
        message.setText(event);
        producer.send(message);
    }
    session.commit();
    session.close();
    connection.close();
}

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

public void testEncoding() throws Exception {
    JmsEndpoint ep = new JmsEndpoint();
    ep.setService(ReceiverComponent.SERVICE);
    ep.setEndpoint("jms");
    ep.setTargetService(ReceiverComponent.SERVICE);
    ep.setTargetEndpoint(ReceiverComponent.ENDPOINT);
    ep.setRole(MessageExchange.Role.CONSUMER);
    ep.setDestinationStyle(AbstractJmsProcessor.STYLE_QUEUE);
    ep.setDestination(queue);//from ww  w  .j  ava2  s  .co  m
    ep.setDefaultMep(JbiConstants.IN_ONLY);
    ep.setMarshaler(new DefaultJmsMarshaler(ep));

    QueueConnection qConn = connectionFactory.createQueueConnection();
    QueueSession qSess = qConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

    // Test character encoding.
    String defaultCharset = SourceTransformer.getDefaultCharset();
    try {
        SourceTransformer.setDefaultCharset("ISO-8859-1");

        SourceTransformer sourceTransformer = new SourceTransformer();
        SoapMarshaler marshaler = new SoapMarshaler(true);
        SoapMessage soapMessage = marshaler.createReader()
                .read(getClass().getResourceAsStream("charsettest.xml"));
        soapMessage.setHeaders(null);
        soapMessage.setBodyName(null);
        soapMessage.setEnvelopeName(null);

        soapMessage.setSource(sourceTransformer.toDOMSource(soapMessage.getSource()));
        TextMessage m = (TextMessage) ep.getMarshaler().toJMS(soapMessage, null, qSess);

        assertEquals("Messages match", new SourceTransformer().toString(soapMessage.getSource()),
                m.getText().replace('\'', '"'));
    } finally {
        SourceTransformer.setDefaultCharset(defaultCharset);
    }
}

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

public void registerListener(String eventTypeName, MessageHandler handler) {
    if (brokerService == null || !brokerInitialized) {
        log.debug("The broker service is not running in registerListener.");
        return;/* w  ww . j  a  v a 2 s. c o  m*/
    }

    log.info("Registering handler for event " + eventTypeName);
    if (!isValidHandler(handler)) {
        return;
    }

    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;
    }
    ConnectionFactory connectionFactory = jmsTemplate.getConnectionFactory();
    try {
        TopicConnection connection = (TopicConnection) connectionFactory.createConnection();
        if (connection.getClientID() == null) {
            connection.setClientID(handler.getClientId());
        }
        log.debug("Connection is of type " + connection);
        TopicSession topicSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        TopicSubscriber subscriber = topicSession.createSubscriber(topic);
        MessageListenerImpl listener = new MessageListenerImpl(connection, topicSession, subscriber, handler);
        saveListenerRegistration(listener, eventTypeName);
        subscriber.setMessageListener(listener);
        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.juddi.subscription.notify.AMQPNotifier.java

@Override
public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body)
        throws DispositionReportFaultMessage, RemoteException {
    Connection connection = null;
    Context context = null;//ww w .ja  va 2s . co m
    boolean success = false;
    String err = null;
    try {
        if (destination != null && exchangeType != null && exchangeName != null) {
            log.info("Sending notification AMQP to " + destination);
            Properties properties = new Properties();

            properties.put("java.naming.factory.initial",
                    "org.apache.qpid.jndi.PropertiesFileInitialContextFactory");
            properties.put("connectionfactory.qpidConnectionfactory", destination);
            properties.put("destination." + exchangeName, exchangeType);

            context = new InitialContext(properties);

            ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup("qpidConnectionfactory");
            connection = connectionFactory.createConnection();
            connection.start();

            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destinationLocal = (Destination) context.lookup(exchangeName);

            MessageProducer messageProducer = session.createProducer(destinationLocal);

            String subscriptionResultXML = JAXBMarshaller.marshallToString(body,
                    JAXBMarshaller.PACKAGE_SUBSCR_RES);
            TextMessage message = session.createTextMessage(subscriptionResultXML);
            messageProducer.send(message);
            success = true;

        }
    } catch (Exception e) {
        e.printStackTrace();
        log.error("Error deliverying AMQP subscription " + e.getMessage());
        log.debug("Error deliverying AMQP subscription " + e.getMessage(), e);
        err = e.getMessage();

    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException ex) {
            log.error(null, ex);
        }
        try {
            if (context != null) {
                context.close();
            }
        } catch (NamingException ex) {
            log.error(null, ex);
        }
    }
    if (!success) {
        throw new DispositionReportFaultMessage(err, null);
    }
    DispositionReport dr = new DispositionReport();
    Result res = new Result();
    dr.getResult().add(res);

    return dr;
}