protected JMSMessageListenerWrapper(
      final ActiveMQConnection connection,
      final ActiveMQSession session,
      final ClientConsumer consumer,
      final MessageListener listener,
      final int ackMode) {
    this.connection = connection;

    this.session = session;

    this.consumer = consumer;

    this.listener = listener;

    transactedOrClientAck =
        (ackMode == Session.SESSION_TRANSACTED || ackMode == Session.CLIENT_ACKNOWLEDGE)
            || session.isXA();

    individualACK = (ackMode == ActiveMQJMSConstants.INDIVIDUAL_ACKNOWLEDGE);
  }
  /** In this method we apply the JMS acknowledgement and redelivery semantics as per JMS spec */
  @Override
  public void onMessage(final ClientMessage message) {
    ActiveMQMessage msg = ActiveMQMessage.createMessage(message, session.getCoreSession());

    if (individualACK) {
      msg.setIndividualAcknowledge();
    }

    try {
      msg.doBeforeReceive();
    } catch (Exception e) {
      ActiveMQJMSClientLogger.LOGGER.errorPreparingMessageForReceipt(
          msg.getCoreMessage().toString(), e);

      return;
    }

    if (transactedOrClientAck) {
      try {
        message.acknowledge();
      } catch (ActiveMQException e) {
        ((ClientSessionInternal) session.getCoreSession()).markRollbackOnly();
        ActiveMQJMSClientLogger.LOGGER.errorProcessingMessage(e);
      }
    }

    try {
      connection.getThreadAwareContext().setCurrentThread(false);
      listener.onMessage(msg);
    } catch (RuntimeException e) {
      // See JMS 1.1 spec, section 4.5.2

      ActiveMQJMSClientLogger.LOGGER.onMessageError(e);

      if (!transactedOrClientAck) {
        try {
          if (individualACK) {
            message.individualAcknowledge();
          }

          session.getCoreSession().rollback(true);

          session.setRecoverCalled(true);
        } catch (Exception e2) {
          ActiveMQJMSClientLogger.LOGGER.errorRecoveringSession(e2);
        }
      }
    } finally {
      connection.getThreadAwareContext().clearCurrentThread(false);
    }
    if (!session.isRecoverCalled() && !individualACK) {
      try {
        // We don't want to call this if the consumer was closed from inside onMessage
        if (!consumer.isClosed() && !transactedOrClientAck) {
          message.acknowledge();
        }
      } catch (ActiveMQException e) {
        ((ClientSessionInternal) session.getCoreSession()).markRollbackOnly();
        ActiveMQJMSClientLogger.LOGGER.errorProcessingMessage(e);
      }
    }

    session.setRecoverCalled(false);
  }