Example usage for javax.jms Session CLIENT_ACKNOWLEDGE

List of usage examples for javax.jms Session CLIENT_ACKNOWLEDGE

Introduction

In this page you can find the example usage for javax.jms Session CLIENT_ACKNOWLEDGE.

Prototype

int CLIENT_ACKNOWLEDGE

To view the source code for javax.jms Session CLIENT_ACKNOWLEDGE.

Click Source Link

Document

With this acknowledgment mode, the client acknowledges a consumed message by calling the message's acknowledge method.

Usage

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Set ackMode state. */
public void setAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.CLIENT_ACKNOWLEDGE;
    }/*from  w  w  w . j a va  2s .  c o  m*/
    if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.AUTO_ACKNOWLEDGE;
    }
    if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        this.ackMode = Session.DUPS_OK_ACKNOWLEDGE;
    }
    if ("SESSION_TRANSACTED".equals(ackMode)) {
        this.ackMode = Session.SESSION_TRANSACTED;
    }
}

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

/**
 * Commit/Acknowledge messages that have been received.<br/>
 * @throws javax.jms.JMSException//from ww w.ja va2s  .c om
 */
protected void acknowledge() throws JMSException {
    if (isTransacted()) {
        getSession().commit();
    } else if (getSessionAckMode(getAckMode()) == Session.CLIENT_ACKNOWLEDGE) {
        lastMsg.acknowledge(); // acknowledge all consumed messages till now
    }
}

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

public void testBug895() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    try {// w  ww  . j a  v  a 2s .c om
        broker.start();
        AdaptrisMessage msg = AdaptrisMessageFactory.getDefaultInstance().newMessage();

        msg.addMetadata(JmsConstants.JMS_PRIORITY, "9");
        msg.addMetadata(JmsConstants.JMS_TYPE, "idaho");
        Session session = broker.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
        trans.setMoveJmsHeaders(true);
        start(trans, session);

        Message jmsMsg = trans.translate(msg);

        assertNotSame("JMS Priorities should be different", jmsMsg.getJMSPriority(), 9);
        assertEquals("JMSType should be equal", "idaho", jmsMsg.getJMSType());
    } finally {
        stop(trans);
        broker.destroy();

    }
}

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(/* w w  w . j  a  va2s.c  o  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:org.frameworkset.mq.ReceiveDispatcher.java

public boolean isClientAcknowledge() throws JMSException {

    return session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE;
}

From source file:nl.nn.adapterframework.jms.PullingJmsListener.java

public void afterMessageProcessed(PipeLineResult plr, Object rawMessage, Map threadContext)
        throws ListenerException {
    String cid = (String) threadContext.get(IPipeLineSession.technicalCorrelationIdKey);

    if (log.isDebugEnabled())
        log.debug(getLogPrefix() + "in PullingJmsListener.afterMessageProcessed()");

    try {/*w  w  w  .j  a  v a 2 s.c  o m*/
        Destination replyTo = (Destination) threadContext.get("replyTo");

        // handle reply
        if (isUseReplyTo() && (replyTo != null)) {
            Session session = null;

            log.debug(getLogPrefix() + "sending reply message with correlationID [" + cid + "], replyTo ["
                    + replyTo.toString() + "]");
            long timeToLive = getReplyMessageTimeToLive();
            boolean ignoreInvalidDestinationException = false;
            if (timeToLive == 0) {
                Message messageSent = (Message) rawMessage;
                long expiration = messageSent.getJMSExpiration();
                if (expiration != 0) {
                    timeToLive = expiration - new Date().getTime();
                    if (timeToLive <= 0) {
                        log.warn(getLogPrefix() + "message [" + cid + "] expired [" + timeToLive
                                + "]ms, sending response with 1 second time to live");
                        timeToLive = 1000;
                        // In case of a temporary queue it might already
                        // have disappeared.
                        ignoreInvalidDestinationException = true;
                    }
                }
            }
            if (threadContext != null) {
                session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
            }
            if (session == null) {
                try {
                    session = getSession(threadContext);
                    send(session, replyTo, cid, prepareReply(plr.getResult(), threadContext),
                            getReplyMessageType(), timeToLive, stringToDeliveryMode(getReplyDeliveryMode()),
                            getReplyPriority(), ignoreInvalidDestinationException);
                } finally {
                    releaseSession(session);
                }
            } else {
                send(session, replyTo, cid, plr.getResult(), getReplyMessageType(), timeToLive,
                        stringToDeliveryMode(getReplyDeliveryMode()), getReplyPriority(),
                        ignoreInvalidDestinationException);
            }
        } else {
            if (getSender() == null) {
                log.debug(getLogPrefix()
                        + "itself has no sender to send the result (An enclosing Receiver might still have one).");
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(getLogPrefix()
                            + "no replyTo address found or not configured to use replyTo, using default destination"
                            + "sending message with correlationID[" + cid + "] [" + plr.getResult() + "]");
                }
                getSender().sendMessage(cid, plr.getResult());
            }
        }

        // TODO Do we still need this? Should we rollback too? See
        // PushingJmsListener.afterMessageProcessed() too (which does a
        // rollback, but no commit).
        if (!isTransacted()) {
            if (isJmsTransacted()) {
                // the following if transacted using transacted sessions, instead of XA-enabled sessions.
                Session session = (Session) threadContext.get(THREAD_CONTEXT_SESSION_KEY);
                if (session == null) {
                    log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                            + "] has no session to commit or rollback");
                } else {
                    String successState = getCommitOnState();
                    if (successState != null && successState.equals(plr.getState())) {
                        session.commit();
                    } else {
                        log.warn("Listener [" + getName() + "] message [" + (String) threadContext.get("id")
                                + "] not committed nor rolled back either");
                        //TODO: enable rollback, or remove support for JmsTransacted altogether (XA-transactions should do it all)
                        // session.rollback();
                    }
                    if (isSessionsArePooled()) {
                        threadContext.remove(THREAD_CONTEXT_SESSION_KEY);
                        releaseSession(session);
                    }
                }
            } else {
                // TODO: dit weghalen. Het hoort hier niet, en zit ook al in getIdFromRawMessage. Daar hoort het ook niet, overigens...
                if (getAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                    log.debug("[" + getName() + "] acknowledges message with id [" + cid + "]");
                    ((TextMessage) rawMessage).acknowledge();
                }
            }
        }
    } catch (Exception e) {
        throw new ListenerException(e);
    }
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void commitOrAcknowledgeMessageIfNecessary(final String sessionName, final Message message) {
    try {/* ww  w .  jav a 2s  .c om*/
        final Session session = _testSessions.get(sessionName);
        if (session.getTransacted()) {
            synchronized (session) {
                session.commit();
            }
        } else if (message != null && session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
            message.acknowledge();
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to commit or acknowledge message on session: " + sessionName,
                jmse);
    }
}

From source file:com.mirth.connect.connectors.jms.JmsDispatcher.java

/**
 * Retrieve the dispatcherId specific JmsSession from the cache. If the JmsSession does not
 * exist, create a new one from the connection.
 *//*  w  w w  . j av  a 2  s.c  o m*/
private JmsSession getJmsSession(JmsConnection jmsConnection, Long dispatcherId) throws Exception {
    Map<Long, JmsSession> jmsSessions = jmsConnection.getJmsSessions();
    JmsSession jmsSession = jmsSessions.get(dispatcherId);

    if (jmsSession == null) {
        Session session = jmsConnection.getConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(null);

        jmsSession = new JmsSession(session, producer);
        jmsSessions.put(dispatcherId, jmsSession);
    }

    return jmsSession;
}

From source file:net.timewalker.ffmq4.listeners.ClientProcessor.java

private CreateSessionResponse processCreateSession(CreateSessionQuery query) throws JMSException {
    // Note : acknowledgeMode is forced to CLIENT_ACKNOWLEDGE because we need the autoacknowledge feature
    //        to happen on the remote side
    LocalSession localSession = (LocalSession) getLocalConnection().createSession(query.getSessionId(),
            query.isTransacted(), Session.CLIENT_ACKNOWLEDGE
    /*query.getAcknowledgeMode()*/);

    // Unregister client inactivity watchdog
    if (!hasCreatedASession) {
        hasCreatedASession = true;//from  ww w.j  a  v  a  2 s  .  c o m
        ActivityWatchdog.getInstance().unregister(this);
    }

    // Use an internal hook to bridge the local session to the remote peer
    localSession.setNotificationProxy(new RemoteNotificationProxy(localSession.getId(), transport));

    return new CreateSessionResponse();
}

From source file:org.apache.qpid.disttest.jms.ClientJmsDelegate.java

public void rollbackOrRecoverIfNecessary(String sessionName) {
    try {//w ww.j a  v a  2s. c  o  m
        final Session session = _testSessions.get(sessionName);
        synchronized (session) {
            if (session.getTransacted()) {
                session.rollback();
            } else if (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE) {
                session.recover();
            }
        }
    } catch (final JMSException jmse) {
        throw new DistributedTestException("Unable to rollback or recover on session: " + sessionName, jmse);
    }
}