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.mirth.connect.connectors.jms.JmsClient.java

/**
 * Starts a JMS connection and session.//from ww  w . ja  v  a  2 s  .  c om
 */
public void start() throws ConnectorTaskException {
    final String channelId = connector.getChannelId();
    String channelName = connector.getChannel().getName();
    Map<String, String> connectionProperties = replacer
            .replaceValues(connectorProperties.getConnectionProperties(), channelId, channelName);
    ConnectionFactory connectionFactory = null;

    if (connectorProperties.isUseJndi()) {
        try {
            connectionFactory = lookupConnectionFactoryWithJndi();
        } catch (Exception e) {
            throw new ConnectorTaskException("Failed to obtain the connection factory via JNDI", e);
        }
    } else {
        String className = replacer.replaceValues(connectorProperties.getConnectionFactoryClass(), channelId,
                channelName);

        try {
            MirthContextFactory contextFactory = contextFactoryController.getContextFactory(resourceIds);
            connectionFactory = (ConnectionFactory) Class
                    .forName(className, true, contextFactory.getApplicationClassLoader()).newInstance();
        } catch (Exception e) {
            throw new ConnectorTaskException("Failed to instantiate ConnectionFactory class: " + className, e);
        }
    }

    BeanUtil.setProperties(connectionFactory, connectionProperties);

    try {
        logger.debug("Creating JMS connection and session");
        connection = connectionFactory.createConnection(
                replacer.replaceValues(connectorProperties.getUsername(), channelId, channelName),
                replacer.replaceValues(connectorProperties.getPassword(), channelId, channelName));
        String clientId = replacer.replaceValues(connectorProperties.getClientId(), channelId, channelName);

        if (!clientId.isEmpty()) {
            connection.setClientID(clientId);
        }

        connection.setExceptionListener(this);

        logger.debug("Starting JMS connection");
        connection.start();

        logger.debug("Creating JMS session");
        session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
        logger.debug("JMS session created");
    } catch (JMSException e) {
        try {
            stop();
        } catch (Exception e1) {
        }

        throw new ConnectorTaskException("Failed to establish a JMS connection", e);
    }

    connected.set(true);
}

From source file:com.amazon.sqs.javamessaging.SQSConnection.java

/**
 * Creates a <code>Session</code>
 * //from ww  w  . j a  v a2  s .  c om
 * @param transacted
 *            Only false is supported.
 * @param acknowledgeMode
 *            Legal values are <code>Session.AUTO_ACKNOWLEDGE</code>,
 *            <code>Session.CLIENT_ACKNOWLEDGE</code>,
 *            <code>Session.DUPS_OK_ACKNOWLEDGE</code>, and
 *            <code>SQSSession.UNORDERED_ACKNOWLEDGE</code>
 * @return a new session.
 * @throws JMSException
 *             If the QueueConnection object fails to create a session due
 *             to some internal error or lack of support for the specific
 *             transaction and acknowledge mode.
 */
@Override
public Session createSession(boolean transacted, int acknowledgeMode) throws JMSException {
    checkClosed();
    actionOnConnectionTaken = true;
    if (transacted || acknowledgeMode == Session.SESSION_TRANSACTED)
        throw new JMSException("SQSSession does not support transacted");

    SQSSession sqsSession;
    if (acknowledgeMode == Session.AUTO_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_AUTO.withOriginalAcknowledgeMode(acknowledgeMode));
    } else if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE
            || acknowledgeMode == Session.DUPS_OK_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_RANGE.withOriginalAcknowledgeMode(acknowledgeMode));
    } else if (acknowledgeMode == SQSSession.UNORDERED_ACKNOWLEDGE) {
        sqsSession = new SQSSession(this,
                AcknowledgeMode.ACK_UNORDERED.withOriginalAcknowledgeMode(acknowledgeMode));
    } else {
        LOG.error("Unrecognized acknowledgeMode. Cannot create Session.");
        throw new JMSException("Unrecognized acknowledgeMode. Cannot create Session.");
    }
    synchronized (stateLock) {
        checkClosing();
        sessions.add(sqsSession);

        /**
         * Any new sessions created on a started connection should be
         * started on creation
         */
        if (running) {
            sqsSession.start();
        }
    }

    return sqsSession;
}

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

/**
 * Put message into messageQueue and update information.
 *///from  ww  w  . j  a v a 2s. c o m
public void onMessage(Message message) {
    messagesReceived++;
    try {
        if (message instanceof ObjectMessage) {
            ObjectMessage objMsg = (ObjectMessage) message;
            BSPMessagesPack msgPack = (BSPMessagesPack) objMsg.getObject();
            IMessage bspMsg;
            Iterator<IMessage> iter = msgPack.getPack().iterator();
            while (iter.hasNext()) {
                bspMsg = iter.next();
                String vertexID = bspMsg.getDstVertexID();
                this.messageQueues.incomeAMessage(vertexID, bspMsg);
                this.messageCount++;
                this.messageBytesCount += bspMsg.size();
            }
        } else {
            // Message received is not ObjectMessage.
            LOG.error("[ConsumerTool] Message received is not ObjectMessage!");
        }
        if (message.getJMSReplyTo() != null) {
            replyProducer.send(message.getJMSReplyTo(),
                    session.createTextMessage("Reply: " + message.getJMSMessageID()));
        }
        if (transacted) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Commiting transaction for last " + batch + " messages; messages so far = "
                        + messagesReceived);
                session.commit();
            }
        } else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
            if ((messagesReceived % batch) == 0) {
                LOG.info("Acknowledging last " + batch + " messages; messages so far = " + messagesReceived);
                message.acknowledge();
            }
        }
    } catch (JMSException e) {
        throw new RuntimeException("[ConsumerTool] caught: ", e);
    } finally {
        if (sleepTime > 0) {
            try {
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                LOG.error("[ConsumerTool] Message received not ObjectMessage!", e);
                throw new RuntimeException("[ConsumerTool] Message received not ObjectMessage! s", e);
            }
        }
    }
}

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

public void testMoveMetadata_JmsMessageToAdaptrisMessage_WithFilter() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    RegexMetadataFilter regexp = new RegexMetadataFilter();
    regexp.addExcludePattern("IntegerMetadataKey");
    trans.setMetadataFilter(regexp);//from   w w w  .ja  v a2  s .com
    try {
        broker.start();
        Session session = broker.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Message jmsMsg = createMessage(session);
        addProperties(jmsMsg);
        start(trans, session);
        AdaptrisMessage msg = trans.translate(jmsMsg);
        assertMetadata(msg, new MetadataElement(STRING_METADATA, STRING_VALUE));
        assertMetadata(msg, new MetadataElement(BOOLEAN_METADATA, BOOLEAN_VALUE));
        assertFalse(msg.containsKey(INTEGER_METADATA));
    } finally {
        stop(trans);
        broker.destroy();
    }

}

From source file:org.codehaus.stomp.jms.ProtocolConverter.java

protected void onStompConnect(StompFrame command) throws IOException, JMSException {
    if (noneXaSession != null) {
        throw new ProtocolException("Already connected.");
    }//from  w  ww  . jav  a2s  . c o  m

    Map<String, Object> headers = command.getHeaders();
    login = (String) headers.get(Stomp.Headers.Connect.LOGIN);
    passcode = (String) headers.get(Stomp.Headers.Connect.PASSCODE);
    clientId = (String) headers.get(Stomp.Headers.Connect.CLIENT_ID);

    Connection noneXaConnection;
    if (login != null) {
        noneXaConnection = noneXAConnectionFactory.createConnection(login, passcode);
    } else {
        noneXaConnection = noneXAConnectionFactory.createConnection();
    }
    if (clientId != null) {
        noneXaConnection.setClientID(clientId);
    }

    noneXaConnection.start();

    Session session = noneXaConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    if (log.isDebugEnabled()) {
        log.debug("Created session with ack mode: " + session.getAcknowledgeMode());
    }
    this.noneXaSession = new StompSession(initialContext, this, session, noneXaConnection);

    Map<String, Object> responseHeaders = new HashMap<String, Object>();

    responseHeaders.put(Stomp.Headers.Connected.SESSION, clientId);
    String requestId = (String) headers.get(Stomp.Headers.Connect.REQUEST_ID);
    if (requestId == null) {
        // TODO legacy
        requestId = (String) headers.get(Stomp.Headers.RECEIPT_REQUESTED);
    }
    if (requestId != null) {
        // TODO legacy
        responseHeaders.put(Stomp.Headers.Connected.RESPONSE_ID, requestId);
        responseHeaders.put(Stomp.Headers.Response.RECEIPT_ID, requestId);
    }

    StompFrame sc = new StompFrame();
    sc.setAction(Stomp.Responses.CONNECTED);
    sc.setHeaders(responseHeaders);
    sendToStomp(sc);
}

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

/**
 *  Get session acknowledge.//from   w  w  w . j  a v  a2  s  . com
 *  Converts acknowledge string into JMS Session variable.
 */
public int getSessionAckMode(String ackMode) {
    if ("CLIENT_ACKNOWLEDGE".equals(ackMode)) {
        return Session.CLIENT_ACKNOWLEDGE;
    } else if ("AUTO_ACKNOWLEDGE".equals(ackMode)) {
        return Session.AUTO_ACKNOWLEDGE;
    } else if ("DUPS_OK_ACKNOWLEDGE".equals(ackMode)) {
        return Session.DUPS_OK_ACKNOWLEDGE;
    } else if ("SESSION_TRANSACTED".equals(ackMode)) {
        return Session.SESSION_TRANSACTED;
    } else {
        return Session.CLIENT_ACKNOWLEDGE; // default
    }
}

From source file:org.wso2.carbon.inbound.endpoint.protocol.jms.JMSPollingConsumer.java

/**
 * Create connection with broker and retrieve the messages. Then inject
 * according to the registered handler/*from   w  w  w  .jav  a2s . c om*/
 */
public Message poll() {
    logger.debug("Polling JMS messages.");

    try {
        connection = jmsConnectionFactory.getConnection(strUserName, strPassword);
        if (connection == null) {
            logger.warn("Inbound JMS endpoint unable to get a connection.");
            isConnected = false;
            return null;
        }
        if (retryIteration != 0) {
            logger.info("Reconnection attempt: " + retryIteration + " for the JMS Inbound: " + name
                    + " was successful!");
            this.retryIteration = 0;
            this.retryDuration = 1;
        }
        isConnected = true;
        session = jmsConnectionFactory.getSession(connection);
        //Fixing ESBJAVA-4446
        //Closing the connection if we cannot get a session.
        //Then in the next poll iteration it will create a new connection
        //instead of using cached connection
        if (session == null) {
            logger.warn("Inbound JMS endpoint unable to get a session.");
            jmsConnectionFactory.closeConnection();
            return null;
        }
        destination = jmsConnectionFactory.getDestination(session);
        if (replyDestinationName != null && !replyDestinationName.trim().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Using the reply destination as " + replyDestinationName + " in inbound endpoint.");
            }
            replyDestination = jmsConnectionFactory.createDestination(session, replyDestinationName);
        }
        messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination);
        Message msg = receiveMessage(messageConsumer);
        if (msg == null) {
            logger.debug("Inbound JMS Endpoint. No JMS message received.");
            return null;
        }
        while (msg != null) {
            if (!JMSUtils.inferJMSMessageType(msg).equals(TextMessage.class.getName())) {
                logger.error("JMS " + "Inbound transport support JMS TextMessage type only. Found message type "
                        + JMSUtils.inferJMSMessageType(msg));
                return null;
            }

            if (injectHandler != null) {

                boolean commitOrAck = true;
                // Set the reply destination and connection
                if (replyDestination != null) {
                    injectHandler.setReplyDestination(replyDestination);
                }
                injectHandler.setConnection(connection);
                commitOrAck = injectHandler.invoke(msg, name);
                // if client acknowledgement is selected, and processing
                // requested ACK
                if (jmsConnectionFactory.getSessionAckMode() == Session.CLIENT_ACKNOWLEDGE) {
                    if (commitOrAck) {
                        try {
                            msg.acknowledge();
                            if (logger.isDebugEnabled()) {
                                logger.debug("Message : " + msg.getJMSMessageID() + " acknowledged");
                            }
                        } catch (JMSException e) {
                            logger.error("Error acknowledging message : " + msg.getJMSMessageID(), e);
                        }
                    } else {
                        // Need to create a new consumer and session since
                        // we need to rollback the message
                        if (messageConsumer != null) {
                            jmsConnectionFactory.closeConsumer(messageConsumer);
                        }
                        if (session != null) {
                            jmsConnectionFactory.closeSession(session);
                        }
                        session = jmsConnectionFactory.getSession(connection);
                        messageConsumer = jmsConnectionFactory.getMessageConsumer(session, destination);
                    }
                }
                // if session was transacted, commit it or rollback
                if (jmsConnectionFactory.isTransactedSession()) {
                    try {
                        if (session.getTransacted()) {
                            if (commitOrAck) {
                                session.commit();
                                if (logger.isDebugEnabled()) {
                                    logger.debug(
                                            "Session for message : " + msg.getJMSMessageID() + " committed");
                                }
                            } else {
                                session.rollback();
                                if (logger.isDebugEnabled()) {
                                    logger.debug(
                                            "Session for message : " + msg.getJMSMessageID() + " rolled back");
                                }
                            }
                        }
                    } catch (JMSException e) {
                        logger.error("Error " + (commitOrAck ? "committing" : "rolling back")
                                + " local session txn for message : " + msg.getJMSMessageID(), e);
                    }
                }
            } else {
                return msg;
            }
            msg = receiveMessage(messageConsumer);
        }

    } catch (JMSException e) {
        logger.error("Error while receiving JMS message. " + e.getMessage(), e);
    } catch (Exception e) {
        logger.error("Error while receiving JMS message. " + e.getMessage(), e);
    } finally {
        if (!isConnected) {
            if (reconnectDuration != null) {
                retryDuration = reconnectDuration;
                logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name
                        + " failed. Next retry in " + (retryDuration / 1000) + " seconds. (Fixed Interval)");
            } else {
                retryDuration = (long) (retryDuration * reconnectionProgressionFactor);
                if (retryDuration > maxReconnectDuration) {
                    retryDuration = maxReconnectDuration;
                    logger.info("InitialReconnectDuration reached to MaxReconnectDuration.");
                }
                logger.error("Reconnection attempt : " + (retryIteration++) + " for JMS Inbound : " + name
                        + " failed. Next retry in " + (retryDuration / 1000) + " seconds");
            }
            try {
                Thread.sleep(retryDuration);
            } catch (InterruptedException ignore) {
            }
        }
        if (messageConsumer != null) {
            jmsConnectionFactory.closeConsumer(messageConsumer);
        }
        if (session != null) {
            jmsConnectionFactory.closeSession(session);
        }
        if (connection != null) {
            jmsConnectionFactory.closeConnection(connection);
        }
    }
    return null;
}

From source file:org.springframework.jms.support.JmsAccessor.java

/**
 * Determine whether the given Session is in client acknowledge mode.
 * <p>This implementation uses JMS 1.1 API.
 * @param session the JMS Session to check
 * @return whether the given Session is in client acknowledge mode
 * @throws javax.jms.JMSException if thrown by JMS API methods
 * @see javax.jms.Session#getAcknowledgeMode()
 * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
 *//*from   w ww . ja va  2  s . c o m*/
protected boolean isClientAcknowledge(Session session) throws JMSException {
    return (session.getAcknowledgeMode() == Session.CLIENT_ACKNOWLEDGE);
}

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

public void testMoveJmsHeadersJmsMessageToAdaptrisMessage() throws Exception {
    EmbeddedActiveMq broker = new EmbeddedActiveMq();
    MessageTypeTranslatorImp trans = createTranslator();
    try {//  w w w  . ja v  a 2s  .c  o  m
        Session session = broker.createConnection().createSession(false, Session.CLIENT_ACKNOWLEDGE);
        Message jmsMsg = createMessage(session);
        jmsMsg.setJMSCorrelationID("ABC");
        jmsMsg.setJMSDeliveryMode(1);
        jmsMsg.setJMSPriority(4);
        addProperties(jmsMsg);
        long timestamp = System.currentTimeMillis();
        jmsMsg.setJMSTimestamp(timestamp);

        trans.setMoveJmsHeaders(true);
        start(trans, session);

        AdaptrisMessage msg = trans.translate(jmsMsg);
        assertMetadata(msg);
        assertEquals("ABC", msg.getMetadataValue(JmsConstants.JMS_CORRELATION_ID));
        assertEquals("1", msg.getMetadataValue(JmsConstants.JMS_DELIVERY_MODE));
        assertEquals("4", msg.getMetadataValue(JmsConstants.JMS_PRIORITY));
        assertEquals(String.valueOf(timestamp), msg.getMetadataValue(JmsConstants.JMS_TIMESTAMP));
    } finally {
        stop(trans);
        broker.destroy();
    }

}

From source file:tools.ConsumerTool.java

public void handleMessage(Session session, Message message, int perConsumerReceivedMessages) {
    try {//from   w  ww  . j a va 2 s.  c o  m
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            String text = textMessage.getText();
            LOGGER.info("Received text message: " + text);
        } else {
            LOGGER.info("Received message: " + message);
        }
        if (perMessageSleepMS > 0) {
            try {
                Thread.sleep(perMessageSleepMS);
            } catch (InterruptedException e) {
                LOGGER.debug("Interrupted while sleeping", e);
            }
        }
        if (acknowledgeMode == Session.CLIENT_ACKNOWLEDGE) {
            if (perConsumerReceivedMessages % batchSize == 0) {
                message.acknowledge();
            }
        }
        if (transacted) {
            if (perConsumerReceivedMessages % batchSize == 0) {
                session.commit();
            }
        }
    } catch (JMSException e) {
        LOGGER.error("JMSException handling message: " + e.getMessage(), e);
    }
}