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:tools.ConsumerTool.java

public void parseCommandLine(String[] args) {
    CommandLineParser parser = new PosixParser();

    Options options = new Options();

    Option ackModeOpt = OptionBuilder.withLongOpt("acknowledgement-mode").withArgName("ackMode").hasArg()
            .withDescription(//www .j ava2s  .co m
                    "session acknowledgement mode: AUTO_ACKNOWLEDGE, CLIENT_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE")
            .create("a");
    options.addOption(ackModeOpt);

    Option browserOpt = OptionBuilder.withLongOpt("queue-browser").withDescription("create a queue browser")
            .create("b");
    options.addOption(browserOpt);

    Option clientIdOpt = OptionBuilder.withLongOpt("client-id").withArgName("id").hasArg()
            .withDescription("client id string that can optionally be set on a connection").create("c");
    options.addOption(clientIdOpt);

    Option durableOpt = OptionBuilder.withLongOpt("durable").withDescription("create a durable subscriber")
            .create("d");
    options.addOption(durableOpt);

    Option perMessageSleepOpt = OptionBuilder.withLongOpt("per-message-sleep").withArgName("millis").hasArg()
            .withDescription("amount of time (in ms) to sleep after receiving each message").create("e");
    options.addOption(perMessageSleepOpt);

    Option connFactOpt = OptionBuilder.withLongOpt("connection-factory-name").withArgName("name").hasArg()
            .withDescription("name of the connection factory to lookup").create("f");
    options.addOption(connFactOpt);

    Option numThreadsOpt = OptionBuilder.withLongOpt("num-threads").withArgName("num").hasArg()
            .withDescription("number of threads to run in parallel each with a connection").create("g");
    options.addOption(numThreadsOpt);

    Option helpOpt = OptionBuilder.withLongOpt("help").withDescription("show help").create("h");
    options.addOption(helpOpt);

    Option jndiDestOpt = OptionBuilder.withLongOpt("jndi-lookup-destination")
            .withDescription("lookup destinations with jndi").create("j");
    options.addOption(jndiDestOpt);

    Option selectorOpt = OptionBuilder.withLongOpt("message-selector").withArgName("selector").hasArg()
            .withDescription("message selector to use when creating consumer").create("k");
    options.addOption(selectorOpt);

    Option numMessagesOpt = OptionBuilder.withLongOpt("num-messages").withArgName("num").hasArg()
            .withDescription("number of messages to receive before stopping").create("m");
    options.addOption(numMessagesOpt);

    Option destNameOpt = OptionBuilder.withLongOpt("destination-name").withArgName("name").hasArg()
            .withDescription("name of the destination to receive from").create("n");
    options.addOption(destNameOpt);

    Option tempOpt = OptionBuilder.withLongOpt("temporary-destination")
            .withDescription("use a temporary destination").create("p");
    options.addOption(tempOpt);

    Option useQueueOpt = OptionBuilder.withLongOpt("queue-destination")
            .withDescription("use a queue destination").create("q");
    options.addOption(useQueueOpt);

    Option receiveTimeoutOpt = OptionBuilder.withLongOpt("receive-timeout").withArgName("millis").hasArg()
            .withDescription("blocking receive timeout (-1 indicates blocking receive call with no timeout)")
            .create("r");
    options.addOption(receiveTimeoutOpt);

    Option subscriptionOpt = OptionBuilder.withLongOpt("subscription-name").withArgName("subName").hasArg()
            .withDescription("subscription name to use when creating a durable subscriber").create("s");
    options.addOption(subscriptionOpt);

    Option transOpt = OptionBuilder.withLongOpt("transacted").withDescription("use a transacted session")
            .create("t");
    options.addOption(transOpt);

    Option asyncOpt = OptionBuilder.withLongOpt("async-listener")
            .withDescription("use an async message listener instead of consumer receive calls").create("y");
    options.addOption(asyncOpt);

    Option batchSizeOpt = OptionBuilder.withLongOpt("batch-size").withArgName("size").hasArg()
            .withDescription(
                    "size of the batch to ack or commit when using client ack mode or transacted sessions")
            .create("z");
    options.addOption(batchSizeOpt);

    try {
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("h")) {
            // automatically generate the help statement
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ConsumerTool", options, true);
            System.exit(0);
        }

        if (line.hasOption("a")) {
            String ackModeStr = line.getOptionValue("a");
            if (ackModeStr.equalsIgnoreCase("AUTO_ACKNOWLEDGE")) {
                acknowledgeMode = Session.AUTO_ACKNOWLEDGE;
            } else if (ackModeStr.equalsIgnoreCase("CLIENT_ACKNOWLEDGE")) {
                acknowledgeMode = Session.CLIENT_ACKNOWLEDGE;
            } else if (ackModeStr.equalsIgnoreCase("DUPS_OK_ACKNOWLEDGE")) {
                acknowledgeMode = Session.DUPS_OK_ACKNOWLEDGE;
            } else if (ackModeStr.equalsIgnoreCase("SESSION_TRANSACTED")) {
                acknowledgeMode = Session.SESSION_TRANSACTED;
            } else {
                throw new ParseException("Invalid value for acknowledge mode: " + ackModeStr);
            }
        }

        if (line.hasOption("b")) {
            useQueueBrowser = true;
        }

        if (line.hasOption("c")) {
            clientId = line.getOptionValue("c");
        }

        if (line.hasOption("d")) {
            durable = true;
        }

        if (line.hasOption("e")) {
            perMessageSleepMS = Integer.parseInt(line.getOptionValue("e"));
        }

        if (line.hasOption("f")) {
            connectionFactoryName = line.getOptionValue("f");
        }

        if (line.hasOption("g")) {
            numThreads = Integer.parseInt(line.getOptionValue("g"));
        }

        if (line.hasOption("j")) {
            jndiLookupDestinations = true;
        }

        if (line.hasOption("k")) {
            selector = line.getOptionValue("k");
        }

        if (line.hasOption("m")) {
            numMessages = Integer.parseInt(line.getOptionValue("m"));
        }

        if (line.hasOption("n")) {
            destinationName = line.getOptionValue("n");
        }

        if (line.hasOption("p")) {
            useTemporaryDestinations = true;
        }

        if (line.hasOption("q")) {
            useQueueDestinations = true;
        }

        if (line.hasOption("r")) {
            receiveTimeoutMS = Integer.parseInt(line.getOptionValue("r"));
        }

        if (line.hasOption("s")) {
            subscriptionName = line.getOptionValue("s");
        }

        if (line.hasOption("t")) {
            transacted = true;
        }

        if (line.hasOption("y")) {
            useAsyncListener = true;
        }

        if (line.hasOption("z")) {
            batchSize = Integer.parseInt(line.getOptionValue("z"));
        }

    } catch (ParseException exp) {
        LOGGER.error("Commandline parsing exception: " + exp.getMessage(), exp);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ConsumerTool", options, true);
        System.exit(-1);
    }
}

From source file:com.adaptris.core.jms.JmsProducerImpl.java

protected void acknowledge(Message msg) throws JMSException {
    if (msg == null) {
        return;/*  w w  w .j a  v  a 2s  .  c  om*/
    }
    if (configuredAcknowledgeMode() != Session.AUTO_ACKNOWLEDGE && !currentSession().getTransacted()) {
        msg.acknowledge();
    }
}

From source file:org.sakaiproject.kernel.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("unchecked")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;/* ww w .j  av a2s.c  o m*/
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    String _brokerUrl = (String) props.get(BROKER_URL);

    try {
        boolean urlEmpty = _brokerUrl == null || _brokerUrl.trim().length() == 0;
        if (!urlEmpty) {
            if (diff(brokerUrl, _brokerUrl)) {
                LOGGER.info("Creating a new ActiveMQ Connection Factory");
                connectionFactory = connFactoryService.createFactory(_brokerUrl);
            }

            if (connectionFactory != null) {
                connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                Topic dest = session.createTopic(TOPIC_NAME);
                MessageConsumer consumer = session.createConsumer(dest);
                consumer.setMessageListener(this);
                connection.start();
            }
        } else {
            LOGGER.error("Cannot create JMS connection factory with an empty URL.");
        }
        brokerUrl = _brokerUrl;
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception {
    ArrayList<String> rc = new ArrayList<String>();
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
            "tcp://localhost:" + connectPort(brokerService));
    Connection connection = factory.createConnection();
    try {/*w w  w.  ja v a 2  s . c  o  m*/
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueBrowser browser = session.createBrowser(session.createQueue("FOO"));
        Enumeration enumeration = browser.getEnumeration();
        while (enumeration.hasMoreElements()) {
            TextMessage textMessage = (TextMessage) enumeration.nextElement();
            rc.add(textMessage.getText());
        }
    } finally {
        connection.close();
    }
    return rc;
}

From source file:org.socraticgrid.taskmanager.TaskManagerImpl.java

/**
 * Queue the message to the task handler.
 *
 * @param msgObject/*from  www .j av a  2s  .  co  m*/
 * @return
 */
private QueueResponse queueMessage(java.io.Serializable msgObject) {
    QueueResponse response = new QueueResponse();
    String taskQ = null;
    QueueConnection queueConnection = null;

    try {
        //Get task queue name & queue factory
        taskQ = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE, PROPERTY_TASK_QUEUE);
        String taskQFactory = PropertyAccessor.getProperty(TASKMANAGER_PROPERTY_FILE,
                PROPERTY_TASK_QUEUE_FACTORY);

        //Get queue connection
        Context jndiContext = new InitialContext();
        QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
                .lookup(taskQFactory);
        Queue queue = (Queue) jndiContext.lookup(taskQ);

        //Create connection session
        queueConnection = queueConnectionFactory.createQueueConnection();
        QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueSender queueSender = queueSession.createSender(queue);

        //Create message
        ObjectMessage message = queueSession.createObjectMessage(msgObject);

        //Send message
        queueSender.send(message);

        //Set response info
        response.ticket = message.getJMSMessageID();
        response.detail = TASK_MESSAGE_SUCCESS;
    } catch (PropertyAccessException pae) {
        String msg = TASK_MESSAGE_FAILURE + ": error accessing task properties in file:"
                + TASKMANAGER_PROPERTY_FILE + ".";
        log.error(msg, pae);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (NamingException ne) {
        String msg = TASK_MESSAGE_FAILURE + ": error creating connection to queue: " + taskQ + ".";
        log.error(msg, ne);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } catch (JMSException jmse) {
        String msg = TASK_MESSAGE_FAILURE + ": error occurred trying to send notificaiton to task queue: "
                + taskQ + ".";
        log.error(msg, jmse);
        response.ticket = TASK_MESSAGE_FAILURE_ID;
        response.detail = msg;
    } finally {
        //Close queue
        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
            }
        }
    }

    return response;
}

From source file:org.springframework.jms.connection.SingleConnectionFactory.java

/**
 * Create a default Session for this ConnectionFactory,
 * adapting to JMS 1.0.2 style queue/topic mode if necessary.
 * @param con the JMS Connection to operate on
 * @param mode the Session acknowledgement mode
 * ({@code Session.TRANSACTED} or one of the common modes)
 * @return the newly created Session//from   w  ww. java 2 s. c  om
 * @throws JMSException if thrown by the JMS API
 */
protected Session createSession(Connection con, Integer mode) throws JMSException {
    // Determine JMS API arguments...
    boolean transacted = (mode == Session.SESSION_TRANSACTED);
    int ackMode = (transacted ? Session.AUTO_ACKNOWLEDGE : mode);
    // Now actually call the appropriate JMS factory method...
    if (Boolean.FALSE.equals(this.pubSubMode) && con instanceof QueueConnection) {
        return ((QueueConnection) con).createQueueSession(transacted, ackMode);
    } else if (Boolean.TRUE.equals(this.pubSubMode) && con instanceof TopicConnection) {
        return ((TopicConnection) con).createTopicSession(transacted, ackMode);
    } else {
        return con.createSession(transacted, ackMode);
    }
}

From source file:org.apache.activemq.artemis.tests.integration.amqp.SaslKrb5LDAPSecurityTest.java

public void dotestJAASSecurityManagerAuthorizationPositive(String jaasConfigScope, String artemisRoleName)
        throws Exception {

    createArtemisServer(jaasConfigScope);

    Set<Role> roles = new HashSet<>();
    roles.add(new Role(artemisRoleName, true, true, true, true, true, true, true, true, true, true));
    server.getConfiguration().putSecurityRoles(QUEUE_NAME, roles);
    server.start();// www.  ja v a2  s  .c  o  m

    JmsConnectionFactory jmsConnectionFactory = new JmsConnectionFactory(
            "amqp://localhost:5672?amqp.saslMechanisms=GSSAPI");
    Connection connection = jmsConnectionFactory.createConnection("client", null);

    try {
        connection.start();

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

        javax.jms.Queue queue = session.createQueue(QUEUE_NAME);

        // PRODUCE
        final String text = RandomUtil.randomString();

        try {
            MessageProducer producer = session.createProducer(queue);
            producer.send(session.createTextMessage(text));
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail("should not throw exception here");
        }

        // CONSUME
        try {
            MessageConsumer consumer = session.createConsumer(queue);
            TextMessage m = (TextMessage) consumer.receive(1000);
            Assert.assertNotNull(m);
            Assert.assertEquals(text, m.getText());
        } catch (Exception e) {
            Assert.fail("should not throw exception here");
        }
    } finally {
        connection.close();
    }
}

From source file:com.redhat.jenkins.plugins.ci.messaging.ActiveMqMessagingWorker.java

@Override
public String waitForMessage(Run<?, ?> build, String selector, String variable, Integer timeout) {
    String ip = null;//from w  ww.j a  v  a  2  s  .  c  o m
    try {
        ip = Inet4Address.getLocalHost().getHostAddress();
    } catch (UnknownHostException e) {
        log.severe("Unable to get localhost IP address.");
    }

    String ltopic = getTopic();
    if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null
            && provider.getBroker() != null) {
        log.info("Waiting for message with selector: " + selector);
        Connection connection = null;
        MessageConsumer consumer = null;
        try {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.setClientID(ip + "_" + UUID.randomUUID().toString());
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic destination = session.createTopic(ltopic);

            consumer = session.createConsumer(destination, selector);

            Message message = consumer.receive(timeout * 60 * 1000);
            if (message != null) {
                String value = getMessageBody(message);
                if (build != null) {
                    if (StringUtils.isNotEmpty(variable)) {
                        EnvVars vars = new EnvVars();
                        vars.put(variable, value);
                        build.addAction(new CIEnvironmentContributingAction(vars));

                    }
                }
                log.info("Received message with selector: " + selector + "\n" + formatMessage(message));
                return value;
            }
            log.info("Timed out waiting for message!");
        } catch (Exception e) {
            log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (Exception e) {
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                }
            }
        }
    } else {
        log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker.");
    }
    return null;
}

From source file:org.sakaiproject.nakamura.email.outgoing.OutgoingEmailMessageListener.java

protected void activate(ComponentContext ctx) {
    @SuppressWarnings("rawtypes")
    Dictionary props = ctx.getProperties();

    Integer _maxRetries = (Integer) props.get(MAX_RETRIES);
    if (_maxRetries != null) {
        if (diff(maxRetries, _maxRetries)) {
            maxRetries = _maxRetries;/*w  w  w  .  j  a  va 2s  .c  o m*/
        }
    } else {
        LOGGER.error("Maximum times to retry messages not set.");
    }

    Integer _retryInterval = (Integer) props.get(RETRY_INTERVAL);
    if (_retryInterval != null) {
        if (diff(_retryInterval, retryInterval)) {
            retryInterval = _retryInterval;
        }
    } else {
        LOGGER.error("SMTP retry interval not set.");
    }

    if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) {
        LOGGER.warn("SMTP retry window is very short.");
    }

    Integer _smtpPort = (Integer) props.get(SMTP_PORT);
    boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535;
    if (validPort) {
        if (diff(smtpPort, _smtpPort)) {
            smtpPort = _smtpPort;
        }
    } else {
        LOGGER.error("Invalid port set for SMTP");
    }

    String _smtpServer = (String) props.get(SMTP_SERVER);
    boolean smtpServerEmpty = _smtpServer == null || _smtpServer.trim().length() == 0;
    if (!smtpServerEmpty) {
        if (diff(smtpServer, _smtpServer)) {
            smtpServer = _smtpServer;
        }
    } else {
        LOGGER.error("No SMTP server set");
    }

    try {
        connection = connFactoryService.getDefaultConnectionFactory().createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue dest = session.createQueue(QUEUE_NAME);
        MessageConsumer consumer = session.createConsumer(dest);
        consumer.setMessageListener(this);
        connection.start();
    } catch (JMSException e) {
        LOGGER.error(e.getMessage(), e);
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e1) {
            }
        }
    }
}

From source file:org.jbpm.executor.impl.ExecutorImpl.java

protected void sendMessage(String messageBody, int priority) {
    if (connectionFactory == null && queue == null) {
        throw new IllegalStateException("ConnectionFactory and Queue cannot be null");
    }//  www.ja va  2  s.  c  o  m
    Connection queueConnection = null;
    Session queueSession = null;
    MessageProducer producer = null;
    try {
        queueConnection = connectionFactory.createConnection();
        queueSession = queueConnection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);

        TextMessage message = queueSession.createTextMessage(messageBody);
        producer = queueSession.createProducer(queue);
        producer.setPriority(priority);

        queueConnection.start();

        producer.send(message);
    } catch (Exception e) {
        throw new RuntimeException("Error when sending JMS message with executor job request", e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (JMSException e) {
                logger.warn("Error when closing producer", e);
            }
        }

        if (queueSession != null) {
            try {
                queueSession.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue session", e);
            }
        }

        if (queueConnection != null) {
            try {
                queueConnection.close();
            } catch (JMSException e) {
                logger.warn("Error when closing queue connection", e);
            }
        }
    }
}