/**
  * Extract payload from the synapse message context.
  *
  * @param messageContext synapse message context
  * @return payload
  */
 public static String collectPayload(MessageContext messageContext) {
   String payload = null;
   try {
     org.apache.axis2.context.MessageContext a2mc =
         ((Axis2MessageContext) messageContext).getAxis2MessageContext();
     if (JsonUtil.hasAJsonPayload(a2mc)) {
       payload = JsonUtil.jsonPayloadToString(a2mc);
     } else {
       payload = messageContext.getEnvelope().toString();
     }
   } catch (Exception e) {
     // SOAP envelop is not created yet
     payload = "NONE";
   }
   return payload;
 }
  public boolean dispatch(MessageContext messageContext) {

    if (log.isDebugEnabled()) {
      log.debug(
          "Sending the message to client with message processor ["
              + messageProcessor.getName()
              + "]");
    }

    // The below code is just for keeping the backward compatibility with the old code.
    if (targetEndpoint == null) {
      targetEndpoint =
          (String) messageContext.getProperty(ForwardingProcessorConstants.TARGET_ENDPOINT);
    }

    MessageContext outCtx = null;
    SOAPEnvelope originalEnvelop = messageContext.getEnvelope();

    if (targetEndpoint != null) {
      Endpoint ep = messageContext.getEndpoint(targetEndpoint);

      try {

        // Send message to the client
        while (!isSuccessful && !isTerminated) {
          try {
            // For each retry we need to have a fresh copy of the actual message. otherwise retry
            // may not
            // work as expected.
            messageContext.setEnvelope(MessageHelper.cloneSOAPEnvelope(originalEnvelop));
            OMElement firstChild = null; //
            org.apache.axis2.context.MessageContext origAxis2Ctx =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();
            if (JsonUtil.hasAJsonPayload(origAxis2Ctx)) {
              firstChild = origAxis2Ctx.getEnvelope().getBody().getFirstElement();
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            if (JsonUtil.hasAJsonPayload(firstChild)) { //
              OMElement clonedFirstElement =
                  messageContext.getEnvelope().getBody().getFirstElement();
              if (clonedFirstElement != null) {
                clonedFirstElement.detach();
                messageContext.getEnvelope().getBody().addChild(firstChild);
              }
            } // Had to do this because MessageHelper#cloneSOAPEnvelope does not clone
            // OMSourcedElemImpl correctly.
            origAxis2Ctx.setProperty(
                HTTPConstants.NON_ERROR_HTTP_STATUS_CODES, getNonRetryStatusCodes());
            outCtx = sender.send(ep, messageContext);
            isSuccessful = true;

          } catch (Exception e) {

            // this means send has failed due to some reason so we have to retry it
            if (e instanceof SynapseException) {
              isSuccessful = isNonRetryErrorCode(e.getCause().getMessage());
            }
            if (!isSuccessful) {
              log.error(
                  "BlockingMessageSender of message processor ["
                      + this.messageProcessor.getName()
                      + "] failed to send message to the endpoint");
            }
          }

          if (isSuccessful) {
            if (outCtx != null) {
              if ("true"
                  .equals(outCtx.getProperty(ForwardingProcessorConstants.BLOCKING_SENDER_ERROR))) {

                // this means send has failed due to some reason so we have to retry it
                isSuccessful =
                    isNonRetryErrorCode(
                        (String) outCtx.getProperty(SynapseConstants.ERROR_MESSAGE));

                if (isSuccessful) {
                  sendThroughReplySeq(outCtx);
                } else {
                  // This means some error has occurred so must try to send down the fault sequence.
                  log.error(
                      "BlockingMessageSender of message processor ["
                          + this.messageProcessor.getName()
                          + "] failed to send message to the endpoint");
                  sendThroughFaultSeq(outCtx);
                }
              } else {
                // Send the message down the reply sequence if there is one
                sendThroughReplySeq(outCtx);
                messageConsumer.ack();
                attemptCount = 0;
                isSuccessful = true;

                if (log.isDebugEnabled()) {
                  log.debug(
                      "Successfully sent the message to endpoint ["
                          + ep.getName()
                          + "]"
                          + " with message processor ["
                          + messageProcessor.getName()
                          + "]");
                }
              }
            } else {
              // This Means we have invoked an out only operation
              // remove the message and reset the count
              messageConsumer.ack();
              attemptCount = 0;
              isSuccessful = true;

              if (log.isDebugEnabled()) {
                log.debug(
                    "Successfully sent the message to endpoint ["
                        + ep.getName()
                        + "]"
                        + " with message processor ["
                        + messageProcessor.getName()
                        + "]");
              }
            }
          }

          if (!isSuccessful) {
            // Then we have to retry sending the message to the client.
            prepareToRetry();
          } else {
            if (messageProcessor.isPaused()) {
              this.messageProcessor.resumeService();
              log.info(
                  "Resuming the service of message processor [" + messageProcessor.getName() + "]");
            }
          }
        }
      } catch (Exception e) {
        log.error(
            "Message processor ["
                + messageProcessor.getName()
                + "] failed to send the message to"
                + " client",
            e);
      }
    } else {
      // No Target Endpoint defined for the Message
      // So we do not have a place to deliver.
      // Here we log a warning and remove the message
      // todo: we can improve this by implementing a target inferring mechanism

      log.warn(
          "Property "
              + ForwardingProcessorConstants.TARGET_ENDPOINT
              + " not found in the message context , Hence removing the message ");

      messageConsumer.ack();
    }

    return true;
  }
 private boolean isDoingJson(MessageContext messageContext) {
   return JsonUtil.hasAJsonPayload(
       ((Axis2MessageContext) messageContext).getAxis2MessageContext());
 }