/**
   * Extract transport headers from the synapse message context.
   *
   * @param synCtx synapse message context
   * @return transport headers map
   */
  public static Map<String, Object> extractTransportProperties(MessageContext synCtx) {
    Map<String, Object> transportPropertyMap = new TreeMap<>();

    Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
    org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
    Object headers =
        axis2MessageCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    if (headers != null && headers instanceof Map) {
      Map headersMap = (Map) headers;
      Set<String> axis2PropertySet = headersMap.keySet();
      for (String entry : axis2PropertySet) {
        transportPropertyMap.put(entry, headersMap.get(entry));
      }
    }

    // Adding important transport related properties
    if (axis2MessageCtx.getTo() != null) {
      transportPropertyMap.put(SynapseConstants.HEADER_TO, axis2MessageCtx.getTo().getAddress());
    }

    if (axis2MessageCtx.getFrom() != null) {
      transportPropertyMap.put(
          SynapseConstants.HEADER_FROM, axis2MessageCtx.getFrom().getAddress());
    }

    if (axis2MessageCtx.getWSAAction() != null) {
      transportPropertyMap.put("WSAction", axis2MessageCtx.getWSAAction());
    }

    if (axis2MessageCtx.getSoapAction() != null) {
      transportPropertyMap.put("SOAPAction", axis2MessageCtx.getSoapAction());
    }

    if (axis2MessageCtx.getReplyTo() != null) {
      transportPropertyMap.put(
          SynapseConstants.HEADER_REPLY_TO, axis2MessageCtx.getReplyTo().getAddress());
    }

    if (axis2MessageCtx.getMessageID() != null) {
      transportPropertyMap.put(SynapseConstants.HEADER_MESSAGE_ID, axis2MessageCtx.getMessageID());
    }

    // Remove unnecessary properties
    if (transportPropertyMap.get("Cookie") != null) {
      transportPropertyMap.remove("Cookie");
    }

    return transportPropertyMap;
  }
 /** same as OutInAxisOperationClient */
 public void addMessageContext(MessageContext mc) throws AxisFault {
   mc.setServiceContext(sc);
   if (mc.getMessageID() == null) {
     setMessageID(mc);
   }
   axisOp.registerOperationContext(mc, oc);
 }
  private static MessageContext cloneForSend(MessageContext ori, String preserveAddressing)
      throws AxisFault {

    MessageContext newMC = MessageHelper.clonePartially(ori);

    newMC.setEnvelope(ori.getEnvelope());
    if (preserveAddressing != null && Boolean.parseBoolean(preserveAddressing)) {
      newMC.setMessageID(ori.getMessageID());
    } else {
      MessageHelper.removeAddressingHeaders(newMC);
    }

    newMC.setProperty(
        org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS,
        ori.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS));

    return newMC;
  }
  /**
   * Handle the response or error (during a failed send) message received for an outgoing request
   *
   * @param messageID Request message ID
   * @param response the Axis2 MessageContext that has been received and has to be handled
   * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above Axis2
   *     MC, that holds Synapse specific information such as the error handler stack and local
   *     properties etc.
   * @throws AxisFault if the message cannot be processed
   */
  private void handleMessage(
      String messageID,
      MessageContext response,
      org.apache.synapse.MessageContext synapseOutMsgCtx,
      AsyncCallback callback)
      throws AxisFault {
    // apply the tenant information to the out message context
    TenantInfoConfigurator configurator =
        synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.applyTenantInfo(synapseOutMsgCtx);
    }
    Object o = response.getProperty(SynapseConstants.SENDING_FAULT);
    if (o != null && Boolean.TRUE.equals(o)) {

      StatisticsReporter.reportFaultForAll(
          synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
      // there is a sending fault. propagate the fault to fault handlers.

      Stack faultStack = synapseOutMsgCtx.getFaultStack();
      if (faultStack != null && !faultStack.isEmpty()) {

        // if we have access to the full synapseOutMsgCtx.getEnvelope(), then let
        // it flow with the error details. Else, replace its envelope with the
        // fault envelope
        try {
          synapseOutMsgCtx.getEnvelope().build();
        } catch (OMException x) {
          synapseOutMsgCtx.setEnvelope(response.getEnvelope());
        }

        Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION);

        synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE));
        synapseOutMsgCtx.setProperty(
            SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL));
        synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e);

        if (log.isDebugEnabled()) {
          log.debug(
              "[Failed Request Message ID : "
                  + messageID
                  + "]"
                  + " [New to be Retried Request Message ID : "
                  + synapseOutMsgCtx.getMessageID()
                  + "]");
        }

        int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE);

        // If a timeout has occured and the timeout action of the callback is to discard the message
        if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT
            && callback.getTimeOutAction() == SynapseConstants.DISCARD) {
          // Do not execute any fault sequences. Discard message
          if (log.isWarnEnabled()) {
            log.warn(
                "Synapse timed out for the request with Message ID : "
                    + messageID
                    + ". Ignoring fault handlers since the timeout action is DISCARD");
          }
          faultStack.removeAllElements();
        } else {
          ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null);
        }
      }

    } else {

      // there can always be only one instance of an Endpoint in the faultStack of a message
      // if the send was successful, so remove it before we proceed any further
      Stack faultStack = synapseOutMsgCtx.getFaultStack();

      Endpoint successfulEndpoint = null;
      if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) {
        successfulEndpoint = (Endpoint) faultStack.pop();
      }

      if (log.isDebugEnabled()) {
        log.debug("Synapse received an asynchronous response message");
        log.debug(
            "Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null"));
        log.debug(
            "SOAPAction: "
                + (response.getSoapAction() != null ? response.getSoapAction() : "null"));
        log.debug(
            "WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null"));
        String[] cids = response.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            log.debug("Attachment : " + cid);
          }
        }
        log.debug("Body : \n" + response.getEnvelope());
      }
      MessageContext axisOutMsgCtx =
          ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();

      // Processes 'Accept-Encoding'
      ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx);

      response.setServiceContext(null);
      response.setOperationContext(axisOutMsgCtx.getOperationContext());
      response.setAxisMessage(
          axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

      // set properties on response
      response.setServerSide(true);
      response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
      response.setProperty(
          MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT));
      response.setProperty(
          org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));
      response.setTransportIn(axisOutMsgCtx.getTransportIn());
      response.setTransportOut(axisOutMsgCtx.getTransportOut());

      // If request is REST assume that the response is REST too
      response.setDoingREST(axisOutMsgCtx.isDoingREST());
      if (axisOutMsgCtx.isDoingMTOM()) {
        response.setDoingMTOM(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
      }
      if (axisOutMsgCtx.isDoingSwA()) {
        response.setDoingSwA(true);
        response.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
      }

      // when axis2 receives a soap message without addressing headers it users
      // DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing
      // headers on the response. this causes a problem for synapse if the original message
      // it receivs (from client) has addressing and the synaspse service invocation has not
      // engage addressing. in this case when synapse receives the response from the server
      // addessing In handler dissable addressing since that response does not have addressing
      // headers. synapse sends the response to its orignal client using the same message
      // context. Then this response does not have addressing headers since it already
      // disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES
      // property state to original state.
      if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES)
          != null) {

        response.setProperty(
            AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES,
            axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES));
      } else {
        response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES);
      }

      Object messageType =
          axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
      if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) {
        // copy the message type property that's used by the out message to the
        // response message
        response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType);
      }

      // compare original received message (axisOutMsgCtx) soap version with the response
      // if they are different change to original version
      if (axisOutMsgCtx.isSOAP11() != response.isSOAP11()) {
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(response);
        } else {
          SOAPUtils.convertSOAP11toSOAP12(response);
        }
      }

      if (axisOutMsgCtx.getMessageID() != null) {
        response.setRelationships(new RelatesTo[] {new RelatesTo(axisOutMsgCtx.getMessageID())});
      }

      response.setReplyTo(axisOutMsgCtx.getReplyTo());
      response.setFaultTo(axisOutMsgCtx.getFaultTo());

      if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) {
        response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE);
      }

      // create the synapse message context for the response
      Axis2MessageContext synapseInMessageContext =
          new Axis2MessageContext(
              response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment());
      synapseInMessageContext.setResponse(true);

      Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY);
      String errorOnSOAPFault = (String) obj;

      if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) {

        if (log.isDebugEnabled()) {
          log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault");
        }

        try {
          RelayUtils.buildMessage(
              ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true);
        } catch (Exception e) {
          // handleException("Error while building message", e, synapseInMessageContext);
        }

        if ((synapseInMessageContext.getEnvelope() != null)
            && synapseInMessageContext.getEnvelope().hasFault()) {

          if (log.isDebugEnabled()) {
            log.debug(
                "SOAPFault found in response message, forcing endpoint "
                    + successfulEndpoint.getName()
                    + " to fail");
          }

          // setup new pipe configuration..if failure happens (this will be setup as the source
          // writer and during the TargetContext
          // clean up operation the writer will be reset and pull to the buffer
          MessageContext axis2OUTMC =
              ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext();
          NHttpServerConnection conn =
              (NHttpServerConnection) axis2OUTMC.getProperty("pass-through.Source-Connection");
          if (conn != null) {
            SourceConfiguration sourceConfiguration =
                (SourceConfiguration) axis2OUTMC.getProperty("PASS_THROUGH_SOURCE_CONFIGURATION");
            Pipe pipe =
                new Pipe(
                    conn,
                    sourceConfiguration.getBufferFactory().getBuffer(),
                    "source",
                    sourceConfiguration);
            axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
          }

          StatisticsReporter.reportFaultForAll(
              synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response));
          synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE);
          synapseOutMsgCtx.setProperty(
              SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR);
          ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null);
          return;
        } else {
          successfulEndpoint.onSuccess();
        }

      } else if (successfulEndpoint != null) {
        successfulEndpoint.onSuccess();
      }

      synapseInMessageContext.setTo(
          new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL));
      synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState());

      // set the properties of the original MC to the new MC

      for (Object key : synapseOutMsgCtx.getPropertyKeySet()) {
        synapseInMessageContext.setProperty(
            (String) key, synapseOutMsgCtx.getProperty((String) key));
      }

      // Copy SequenceCallStack from original MC to the new MC
      if (synapseOutMsgCtx.isContinuationEnabled()) {

        // Set the message direction
        if (!synapseOutMsgCtx.isResponse()) {
          synapseInMessageContext.setResponse(false);
        }

        Stack<ContinuationState> seqContinuationStates =
            synapseOutMsgCtx.getContinuationStateStack();
        for (int i = 0; i < seqContinuationStates.size(); i++) {
          synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i));
        }
      }

      // If this response is related to session affinity endpoints -Server initiated session
      Dispatcher dispatcher =
          (Dispatcher)
              synapseOutMsgCtx.getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER);
      if (dispatcher != null && dispatcher.isServerInitiatedSession()) {
        dispatcher.updateSession(synapseInMessageContext);
      }

      StatisticsReporter.reportForAllOnResponseReceived(synapseInMessageContext);

      // send the response message through the synapse mediation flow
      try {
        synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext);
      } catch (SynapseException syne) {
        Stack stack = synapseInMessageContext.getFaultStack();
        if (stack != null && !stack.isEmpty()) {
          ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne);
        } else {
          log.error(
              "Synapse encountered an exception, "
                  + "No error handlers found - [Message Dropped]\n"
                  + syne.getMessage());
        }
      }
    }
  }
  /**
   * Everytime a response message is received this method gets invoked. It will then select the
   * outgoing *Synapse* message context for the reply we received, and determine what action to take
   * at the Synapse level
   *
   * @param messageCtx the Axis2 message context of the reply received
   * @throws AxisFault
   */
  public void receive(MessageContext messageCtx) throws AxisFault {

    String messageID = null;

    /**
     * In an Out-only scenario if the client receives a HTTP 202 accepted we need to remove the call
     * back/s registered for that request. This if will check weather this is a message sent in a
     * that scenario and remove the callback
     */
    if (messageCtx.getProperty(NhttpConstants.HTTP_202_RECEIVED) != null
        && "true".equals(messageCtx.getProperty(NhttpConstants.HTTP_202_RECEIVED))) {
      if (callbackStore.containsKey(messageCtx.getMessageID())) {
        callbackStore.remove(messageCtx.getMessageID());
        if (log.isDebugEnabled()) {
          log.debug(
              "CallBack registered with Message id : "
                  + messageCtx.getMessageID()
                  + " removed from the "
                  + "callback store since we got an accepted Notification");
        }
      }

      return;
    }

    if (messageCtx.getOptions() != null && messageCtx.getOptions().getRelatesTo() != null) {
      // never take a chance with a NPE at this stage.. so check at each level :-)
      Options options = messageCtx.getOptions();
      if (options != null) {
        RelatesTo relatesTo = options.getRelatesTo();
        if (relatesTo != null) {
          messageID = relatesTo.getValue();
        }
      }
    } else if (messageCtx.getProperty(SandeshaClientConstants.SEQUENCE_KEY) == null) {
      messageID = (String) messageCtx.getProperty(SynapseConstants.RELATES_TO_FOR_POX);
    }

    if (messageID != null) {
      AsyncCallback callback = (AsyncCallback) callbackStore.remove(messageID);
      if (log.isDebugEnabled()) {
        log.debug(
            "Callback removed for request message id : "
                + messageID
                + ". Pending callbacks count : "
                + callbackStore.size());
      }

      RelatesTo[] relates = messageCtx.getRelationships();
      if (relates != null && relates.length > 1) {
        // we set a relates to to the response message so that if WSA is not used, we
        // could still link back to the original message. But if WSA was used, this
        // gets duplicated, and we should remove it
        removeDuplicateRelatesTo(messageCtx, relates);
      }

      if (callback != null) {
        handleMessage(
            messageID,
            messageCtx,
            ((AsyncCallback) callback).getSynapseOutMsgCtx(),
            (AsyncCallback) callback);

      } else {
        // TODO invoke a generic synapse error handler for this message
        log.warn(
            "Synapse received a response for the request with message Id : "
                + messageID
                + " But a callback is not registered (anymore) to process this response");
      }

    } else if (!messageCtx.isPropertyTrue(NhttpConstants.SC_ACCEPTED)) {
      // TODO invoke a generic synapse error handler for this message
      log.warn("Synapse received a response message without a message Id");
    }
  }
  /**
   * Based on the Axis2 client code. Sends the Axis2 Message context out and returns the Axis2
   * message context for the response.
   *
   * <p>Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and 500
   * internal server error as possible responses.
   *
   * @param endpoint the endpoint being sent to, maybe null
   * @param synapseOutMessageContext the outgoing synapse message
   * @throws AxisFault on errors
   */
  public static void send(
      EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext)
      throws AxisFault {

    boolean separateListener = false;
    boolean wsSecurityEnabled = false;
    String wsSecPolicyKey = null;
    String inboundWsSecPolicyKey = null;
    String outboundWsSecPolicyKey = null;
    boolean wsRMEnabled = false;
    String wsRMPolicyKey = null;
    boolean wsAddressingEnabled = false;
    String wsAddressingVersion = null;

    if (endpoint != null) {
      separateListener = endpoint.isUseSeparateListener();
      wsSecurityEnabled = endpoint.isSecurityOn();
      wsSecPolicyKey = endpoint.getWsSecPolicyKey();
      inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey();
      outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey();
      wsRMEnabled = endpoint.isReliableMessagingOn();
      wsRMPolicyKey = endpoint.getWsRMPolicyKey();
      wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled;
      wsAddressingVersion = endpoint.getAddressingVersion();
    }

    if (log.isDebugEnabled()) {
      String to;
      if (endpoint != null && endpoint.getAddress() != null) {
        to = endpoint.getAddress(synapseOutMessageContext);
      } else {
        to = synapseOutMessageContext.getTo().toString();
      }

      log.debug(
          "Sending [add = "
              + wsAddressingEnabled
              + "] [sec = "
              + wsSecurityEnabled
              + "] [rm = "
              + wsRMEnabled
              + (endpoint != null
                  ? "] [mtom = "
                      + endpoint.isUseMTOM()
                      + "] [swa = "
                      + endpoint.isUseSwa()
                      + "] [format = "
                      + endpoint.getFormat()
                      + "] [force soap11="
                      + endpoint.isForceSOAP11()
                      + "] [force soap12="
                      + endpoint.isForceSOAP12()
                      + "] [pox="
                      + endpoint.isForcePOX()
                      + "] [get="
                      + endpoint.isForceGET()
                      + "] [encoding="
                      + endpoint.getCharSetEncoding()
                  : "")
              + "] [to="
              + to
              + "]");
    }

    // save the original message context without altering it, so we can tie the response
    MessageContext originalInMsgCtx =
        ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext();

    // TODO Temp hack: ESB removes the session id from request in a random manner.
    Map headers = (Map) originalInMsgCtx.getProperty(MessageContext.TRANSPORT_HEADERS);
    String session = (String) synapseOutMessageContext.getProperty("LB_COOKIE_HEADER");
    if (session != null) {
      headers.put("Cookie", session);
    }

    // create a new MessageContext to be sent out as this should not corrupt the original
    // we need to create the response to the original message later on
    String preserveAddressingProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_WS_ADDRESSING);
    MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx, preserveAddressingProperty);

    if (log.isDebugEnabled()) {
      log.debug(
          "Message [Original Request Message ID : "
              + synapseOutMessageContext.getMessageID()
              + "]"
              + " [New Cloned Request Message ID : "
              + axisOutMsgCtx.getMessageID()
              + "]");
    }
    // set all the details of the endpoint only to the cloned message context
    // so that we can use the original message context for resending through different endpoints
    if (endpoint != null) {

      if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CONTENT_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);

        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML);
        }

      } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(true);
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET);
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.MESSAGE_TYPE,
            org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_X_WWW_FORM);

      } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (!axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_TEXT_XML);
        }

      } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) {
        axisOutMsgCtx.setDoingREST(false);
        axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
        // We need to set this explicitly here in case the request was not a POST
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST);
        if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) {
          axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction());
        }
        if (axisOutMsgCtx.isSOAP11()) {
          SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx);
        }
        Object o =
            axisOutMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        Map _headers = (Map) o;
        if (_headers != null) {
          _headers.remove(HTTP.CONTENT_TYPE);
          _headers.put(
              HTTP.CONTENT_TYPE,
              org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_SOAP_XML);
        }

      } else if (SynapseConstants.FORMAT_REST.equals(endpoint.getFormat())) {
        /*format=rest is kept only backword compatibility. We no longer needed that.*/
        /* Remove Message Type  for GET and DELETE Request */
        if (originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD) != null) {
          if (originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_GET)
              || originalInMsgCtx
                  .getProperty(Constants.Configuration.HTTP_METHOD)
                  .toString()
                  .equals(Constants.Configuration.HTTP_METHOD_DELETE)) {
            axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
          }
        }
        axisOutMsgCtx.setDoingREST(true);
      } else {
        processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
      }

      if (endpoint.isUseMTOM()) {
        axisOutMsgCtx.setDoingMTOM(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_MTOM,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingMTOM(true);

      } else if (endpoint.isUseSwa()) {
        axisOutMsgCtx.setDoingSwA(true);
        // fix / workaround for AXIS2-1798
        axisOutMsgCtx.setProperty(
            org.apache.axis2.Constants.Configuration.ENABLE_SWA,
            org.apache.axis2.Constants.VALUE_TRUE);
        axisOutMsgCtx.setDoingSwA(true);
      }

      if (endpoint.getCharSetEncoding() != null) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding());
        // Need to Clean this up. TargetRequest line 176 contains a code block which over writes the
        // Content-Type returned by the message formatter with the Content-Type in
        // TRANSPORT_HEADERS. Because of that, even when
        // the Character set encoding is set by the message formatter, it will be replaced by the
        // Content-Type header in TRANSPORT_HEADERS.
        // So Im setting a property to check in TargetRequest before over writing the header.
        axisOutMsgCtx.setProperty("EndpointCharEncodingSet", "true");
      }

      // HTTP Endpoint : use the specified HTTP method and remove REST_URL_POSTFIX, it's not
      // supported in HTTP Endpoint
      if (endpoint.isHTTPEndpoint()) {
        axisOutMsgCtx.setProperty(
            Constants.Configuration.HTTP_METHOD,
            synapseOutMessageContext.getProperty(Constants.Configuration.HTTP_METHOD));
        axisOutMsgCtx.removeProperty(NhttpConstants.REST_URL_POSTFIX);
      }

      // add rest request' suffix URI
      String restSuffix = (String) axisOutMsgCtx.getProperty(NhttpConstants.REST_URL_POSTFIX);
      boolean isRest = SynapseConstants.FORMAT_REST.equals(endpoint.getFormat());

      if (!isRest && !endpoint.isForceSOAP11() && !endpoint.isForceSOAP12()) {
        isRest = isRequestRest(originalInMsgCtx);
      }

      if (endpoint.getAddress() != null) {
        String address = endpoint.getAddress(synapseOutMessageContext);
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {

          String url;
          if (!address.endsWith("/")
              && !restSuffix.startsWith("/")
              && !restSuffix.startsWith("?")) {
            url = address + "/" + restSuffix;
          } else if (address.endsWith("/") && restSuffix.startsWith("/")) {
            url = address + restSuffix.substring(1);
          } else if (address.endsWith("/") && restSuffix.startsWith("?")) {
            url = address.substring(0, address.length() - 1) + restSuffix;
          } else {
            url = address + restSuffix;
          }
          axisOutMsgCtx.setTo(new EndpointReference(url));

        } else {
          axisOutMsgCtx.setTo(new EndpointReference(address));
        }
        axisOutMsgCtx.setProperty(NhttpConstants.ENDPOINT_PREFIX, address);
        synapseOutMessageContext.setProperty(SynapseConstants.ENDPOINT_PREFIX, address);
      } else {
        // Supporting RESTful invocation
        if (isRest && restSuffix != null && !"".equals(restSuffix)) {
          EndpointReference epr = axisOutMsgCtx.getTo();
          if (epr != null) {
            String address = epr.getAddress();
            String url;
            if (!address.endsWith("/")
                && !restSuffix.startsWith("/")
                && !restSuffix.startsWith("?")) {
              url = address + "/" + restSuffix;
            } else {
              url = address + restSuffix;
            }
            axisOutMsgCtx.setTo(new EndpointReference(url));
          }
        }
      }

      if (endpoint.isUseSeparateListener()) {
        axisOutMsgCtx.getOptions().setUseSeparateListener(true);
      }
    } else {
      processWSDL2RESTRequestMessageType(originalInMsgCtx, axisOutMsgCtx);
    }

    // only put whttp:location for the REST (GET) requests, otherwise causes issues for POX messages
    if (axisOutMsgCtx.isDoingREST()
        && HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(
            axisOutMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
      if (axisOutMsgCtx.getProperty(WSDL2Constants.ATTR_WHTTP_LOCATION) == null
          && axisOutMsgCtx.getEnvelope().getBody().getFirstElement() != null) {
        axisOutMsgCtx.setProperty(
            WSDL2Constants.ATTR_WHTTP_LOCATION,
            axisOutMsgCtx.getEnvelope().getBody().getFirstElement().getQName().getLocalPart());
      }
    }

    if (wsAddressingEnabled) {

      if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION,
            AddressingConstants.Submission.WSA_NAMESPACE);

      } else if (wsAddressingVersion != null
          && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) {

        axisOutMsgCtx.setProperty(
            AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE);
      }

      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE);
    } else {
      axisOutMsgCtx.setProperty(
          AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE);
    }

    // remove the headers if we don't need to preserve them.
    // determine weather we need to preserve the processed headers
    String preserveHeaderProperty =
        (String) synapseOutMessageContext.getProperty(SynapseConstants.PRESERVE_PROCESSED_HEADERS);
    if (preserveHeaderProperty == null || !Boolean.parseBoolean(preserveHeaderProperty)) {
      // default behaviour is to remove the headers
      MessageHelper.removeProcessedHeaders(
          axisOutMsgCtx,
          (preserveAddressingProperty != null && Boolean.parseBoolean(preserveAddressingProperty)));
    }

    ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext();
    AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration();

    AxisService anoymousService =
        AnonymousServiceFactory.getAnonymousService(
            synapseOutMessageContext.getConfiguration(),
            axisCfg,
            wsAddressingEnabled,
            wsRMEnabled,
            wsSecurityEnabled);
    // mark the anon services created to be used in the client side of synapse as hidden
    // from the server side of synapse point of view
    anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true");
    ServiceGroupContext sgc =
        new ServiceGroupContext(axisCfgCtx, (AxisServiceGroup) anoymousService.getParent());
    ServiceContext serviceCtx = sgc.getServiceContext(anoymousService);

    boolean outOnlyMessage =
        "true".equals(synapseOutMessageContext.getProperty(SynapseConstants.OUT_ONLY));

    // get a reference to the DYNAMIC operation of the Anonymous Axis2 service
    AxisOperation axisAnonymousOperation =
        anoymousService.getOperation(
            outOnlyMessage
                ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION)
                : new QName(AnonymousServiceFactory.OUT_IN_OPERATION));

    Options clientOptions = MessageHelper.cloneOptions(originalInMsgCtx.getOptions());
    clientOptions.setUseSeparateListener(separateListener);
    // if RM is requested,
    if (wsRMEnabled) {
      // if a WS-RM policy is specified, use it
      if (wsRMPolicyKey != null) {
        Object property = synapseOutMessageContext.getEntry(wsRMPolicyKey);
        if (property instanceof OMElement) {
          OMElement policyOMElement = (OMElement) property;
          RMAssertionBuilder builder = new RMAssertionBuilder();
          SandeshaPolicyBean sandeshaPolicyBean =
              (SandeshaPolicyBean) builder.build(policyOMElement, null);
          Parameter policyParam =
              new Parameter(Sandesha2Constants.SANDESHA_PROPERTY_BEAN, sandeshaPolicyBean);
          anoymousService.addParameter(policyParam);
        }
      }
    }

    // if security is enabled,
    if (wsSecurityEnabled) {
      // if a WS-Sec policy is specified, use it
      if (wsSecPolicyKey != null) {
        clientOptions.setProperty(
            SynapseConstants.RAMPART_POLICY,
            MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey));
      } else {
        if (inboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_IN_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, inboundWsSecPolicyKey));
        }
        if (outboundWsSecPolicyKey != null) {
          clientOptions.setProperty(
              SynapseConstants.RAMPART_OUT_POLICY,
              MessageHelper.getPolicy(synapseOutMessageContext, outboundWsSecPolicyKey));
        }
      }
      // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197
      if (axisOutMsgCtx.getEnvelope().getHeader() == null) {
        SOAPFactory fac =
            axisOutMsgCtx.isSOAP11()
                ? OMAbstractFactory.getSOAP11Factory()
                : OMAbstractFactory.getSOAP12Factory();
        fac.createSOAPHeader(axisOutMsgCtx.getEnvelope());
      }
    }

    OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions);
    mepClient.addMessageContext(axisOutMsgCtx);
    axisOutMsgCtx.setAxisMessage(
        axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE));

    // set the SEND_TIMEOUT for transport sender
    if (endpoint != null && endpoint.getTimeoutDuration() > 0) {
      axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration());
    }

    // always set a callback as we decide if the send it blocking or non blocking within
    // the MEP client. This does not cause an overhead, as we simply create a 'holder'
    // object with a reference to the outgoing synapse message context
    // synapseOutMessageContext
    AsyncCallback callback = new AsyncCallback(axisOutMsgCtx, synapseOutMessageContext);
    if (!outOnlyMessage) {
      if (endpoint != null) {
        // set the timeout time and the timeout action to the callback, so that the
        // TimeoutHandler can detect timed out callbacks and take approprite action.
        callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration());
        callback.setTimeOutAction(endpoint.getTimeoutAction());
      } else {
        callback.setTimeOutOn(System.currentTimeMillis());
      }
    }
    mepClient.setCallback(callback);
    //
    //        if (Utils.isClientThreadNonBlockingPropertySet(axisOutMsgCtx)) {
    //            SynapseCallbackReceiver synapseCallbackReceiver = (SynapseCallbackReceiver)
    // axisOutMsgCtx.getAxisOperation().getMessageReceiver();
    //            synapseCallbackReceiver.addCallback(axisOutMsgCtx.getMessageID(), new
    // FaultCallback(axisOutMsgCtx, synapseOutMessageContext));
    //        }

    // this is a temporary fix for converting messages from HTTP 1.1 chunking to HTTP 1.0.
    // Without this HTTP transport can block & become unresponsive because we are streaming
    // HTTP 1.1 messages and HTTP 1.0 require the whole message to caculate the content length
    if (originalInMsgCtx.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0)) {
      synapseOutMessageContext.getEnvelope().toString();
    }

    // with the nio transport, this causes the listener not to write a 202
    // Accepted response, as this implies that Synapse does not yet know if
    // a 202 or 200 response would be written back.
    originalInMsgCtx
        .getOperationContext()
        .setProperty(org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP");

    // if the transport out is explicitly set use it
    Object o = originalInMsgCtx.getProperty("TRANSPORT_OUT_DESCRIPTION");
    if (o != null && o instanceof TransportOutDescription) {
      axisOutMsgCtx.setTransportOut((TransportOutDescription) o);
      clientOptions.setTransportOut((TransportOutDescription) o);
      clientOptions.setProperty("TRANSPORT_OUT_DESCRIPTION", o);
    }

    mepClient.execute(true);
    if (wsRMEnabled) {
      Object rm11 = clientOptions.getProperty(SandeshaClientConstants.RM_SPEC_VERSION);
      if ((rm11 != null) && rm11.equals(Sandesha2Constants.SPEC_VERSIONS.v1_1)) {
        ServiceClient serviceClient =
            new ServiceClient(
                axisOutMsgCtx.getConfigurationContext(), axisOutMsgCtx.getAxisService());
        serviceClient.setTargetEPR(
            new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        serviceClient.setOptions(clientOptions);
        serviceClient
            .getOptions()
            .setTo(new EndpointReference(endpoint.getAddress(synapseOutMessageContext)));
        SandeshaClient.terminateSequence(serviceClient);
      }
    }
  }
  @Override
  public Handler.InvocationResponse invoke(MessageContext messageContext) throws AxisFault {

    SystemStatisticsUtil systemStatisticsUtil;
    SystemStatistics systemStatistics;

    try {
      int tenantID = PublisherUtil.getTenantId(messageContext);
      Map<Integer, EventConfigNStreamDef> tenantSpecificEventConfig =
          TenantEventConfigData.getTenantSpecificEventingConfigData();
      EventConfigNStreamDef eventingConfigData = tenantSpecificEventConfig.get(tenantID);

      // Check service stats enable -- if true -- go
      if (eventingConfigData != null && eventingConfigData.isServiceStatsEnable()) {

        systemStatisticsUtil = StatisticsServiceComponent.getSystemStatisticsUtil();
        systemStatistics = systemStatisticsUtil.getSystemStatistics(messageContext);
        AxisOperation axisOperation = messageContext.getAxisOperation();

        AxisService axisService = messageContext.getAxisService();
        if (axisService == null
            || SystemFilter.isFilteredOutService(axisService.getAxisServiceGroup())
            || axisService.isClientSide()) {
          return Handler.InvocationResponse.CONTINUE;
        }

        MessageContext inMessageContext = MessageContext.getCurrentMessageContext();

        // If already set in the activity handlers get it or create new publish data
        /*
                        PublishData publishData = (PublishData) messageContext.getProperty(
                                BAMDataPublisherConstants.PUBLISH_DATA);

                        EventData eventData;
                        if (publishData != null) {
                            eventData = publishData.getEventData();
                        } else {
                            publishData = new PublishData();
                            eventData = new EventData();
                            Date date = new Date();
                            Timestamp timestamp = new Timestamp(date.getTime());
                            eventData.setTimestamp(timestamp);
                            if (axisOperation != null) {
                                eventData.setOperationName(axisOperation.getName().getLocalPart());
                            } else {
                                eventData.setOperationName(null);
                            }

                            if (axisService != null) {
                                eventData.setServiceName(messageContext.getAxisService().getName());
                            } else {
                                eventData.setServiceName(null);
                            }

                            //This is a hack for setting message id when sending request to a non-existing operation.
                            if (eventingConfigData.isMsgDumpingEnable() && axisService != null &&
                                axisOperation == null) {
                                eventData.setOutMessageId(new ActivityOutHandler().getUniqueId());
                            }

                        }
        */

        PublishData publishData = new PublishData();
        EventData eventData = new EventData();
        /*                Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        eventData.setTimestamp(timestamp);*/
        if (axisOperation != null) {
          eventData.setOperationName(axisOperation.getName().getLocalPart());
        } else {
          eventData.setOperationName(null);
        }

        if (axisService != null) {
          eventData.setServiceName(messageContext.getAxisService().getName());
        } else {
          eventData.setServiceName(null);
        }

        // This is a hack for setting message id when sending request to a non-existing operation.
        /*                if (eventingConfigData.isMsgDumpingEnable() && axisService != null &&
            axisOperation == null) {
            eventData.setOutMessageId(new ActivityOutHandler().getUniqueId());
        }*/

        // Skip resetting same info if already set by activity in/out handlers
        /*                if (!eventingConfigData.isMsgDumpingEnable()) {

            Timestamp timestamp = null;
            if (inMessageContext != null) {
                timestamp = new Timestamp(Long.parseLong(inMessageContext.getProperty(
                        StatisticsConstants.REQUEST_RECEIVED_TIME).toString()));
                Object requestProperty = inMessageContext.getProperty(
                        HTTPConstants.MC_HTTP_SERVLETREQUEST);
                ServiceAgentUtil.extractInfoFromHttpHeaders(eventData, requestProperty);
            } else {
                Date date = new Date();
                timestamp = new Timestamp(date.getTime());
            }

            eventData.setTimestamp(timestamp);

        }*/

        Timestamp timestamp = null;
        if (inMessageContext != null) {
          timestamp =
              new Timestamp(
                  Long.parseLong(
                      inMessageContext
                          .getProperty(StatisticsConstants.REQUEST_RECEIVED_TIME)
                          .toString()));
          Object requestProperty =
              inMessageContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
          ServiceAgentUtil.extractInfoFromHttpHeaders(eventData, requestProperty);
        } else {
          Date date = new Date();
          timestamp = new Timestamp(date.getTime());
        }

        eventData.setTimestamp(timestamp);

        eventData.setSystemStatistics(systemStatistics);

        publishData.setEventData(eventData);

        // Skip if bam server info already set at activity handlers
        if (!eventingConfigData.isMsgDumpingEnable()) {
          BAMServerInfo bamServerInfo = ServiceAgentUtil.addBAMServerInfo(eventingConfigData);
          publishData.setBamServerInfo(bamServerInfo);
        }

        Event event = ServiceAgentUtil.makeEventList(publishData, eventingConfigData);
        EventPublisher publisher = new EventPublisher();
        publisher.publish(event, eventingConfigData);
      }
    } catch (Throwable ignore) {
      log.error(
          "Error at SystemStatisticsOutHandler. "
              + "But continuing message processing for message id: "
              + messageContext.getMessageID(),
          ignore);
    }

    return Handler.InvocationResponse.CONTINUE;
  }
    public void executeImpl(boolean block) throws AxisFault {

      // if the MEP is completed, throw a fault
      if (completed) {
        throw new AxisFault(Messages.getMessage("mepiscomplted"));
      }

      // if the OUT message is not set on the operation context, throw a fault
      MessageContext outMsgCtx = oc.getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
      if (outMsgCtx == null) {
        throw new AxisFault(Messages.getMessage("outmsgctxnull"));
      }

      ConfigurationContext cfgCtx = sc.getConfigurationContext();

      // set ClientOptions to the current outgoing message
      outMsgCtx.setOptions(options);

      // do Target Resolution
      TargetResolver tr = cfgCtx.getAxisConfiguration().getTargetResolverChain();
      if (tr != null) {
        tr.resolveTarget(outMsgCtx);
      }

      // if the transport to use for sending is not specified, try to find it from the URL
      TransportOutDescription transportOut = options.getTransportOut();
      if (transportOut == null) {
        EndpointReference toEPR = (options.getTo() != null) ? options.getTo() : outMsgCtx.getTo();
        transportOut =
            ClientUtils.inferOutTransport(cfgCtx.getAxisConfiguration(), toEPR, outMsgCtx);
      }
      outMsgCtx.setTransportOut(transportOut);

      if (options.getTransportIn() == null && outMsgCtx.getTransportIn() == null) {
        outMsgCtx.setTransportIn(
            ClientUtils.inferInTransport(cfgCtx.getAxisConfiguration(), options, outMsgCtx));
      } else if (outMsgCtx.getTransportIn() == null) {
        outMsgCtx.setTransportIn(options.getTransportIn());
      }

      // add reference parameters to To EPR
      addReferenceParameters(outMsgCtx);

      if (options.isUseSeparateListener()) {

        options.setTransportIn(
            outMsgCtx
                .getConfigurationContext()
                .getAxisConfiguration()
                .getTransportIn(Constants.TRANSPORT_HTTP));

        SynapseCallbackReceiver callbackReceiver =
            (SynapseCallbackReceiver) axisOp.getMessageReceiver();

        ((Axis2MessageContext) ((AsyncCallback) axisCallback).getSynapseOutMsgCtx())
            .getAxis2MessageContext()
            .setProperty(NhttpConstants.IGNORE_SC_ACCEPTED, Constants.VALUE_TRUE);
        callbackReceiver.addCallback(outMsgCtx.getMessageID(), axisCallback);

        EndpointReference replyToFromTransport =
            outMsgCtx
                .getConfigurationContext()
                .getListenerManager()
                .getEPRforService(
                    sc.getAxisService().getName(),
                    axisOp.getName().getLocalPart(),
                    outMsgCtx.getTransportOut().getName());

        if (outMsgCtx.getReplyTo() == null) {
          outMsgCtx.setReplyTo(replyToFromTransport);
        } else {
          outMsgCtx.getReplyTo().setAddress(replyToFromTransport.getAddress());
        }

        outMsgCtx.getConfigurationContext().registerOperationContext(outMsgCtx.getMessageID(), oc);

        AxisEngine.send(outMsgCtx);

        // Options object reused so soapAction needs to be removed so
        // that soapAction+wsa:Action on response don't conflict
        options.setAction("");

      } else {

        SynapseCallbackReceiver callbackReceiver =
            (SynapseCallbackReceiver) axisOp.getMessageReceiver();
        callbackReceiver.addCallback(outMsgCtx.getMessageID(), axisCallback);
        send(outMsgCtx);
      }
    }
    private void send(MessageContext msgctx) throws AxisFault {

      // create the responseMessageContext and set that its related to the current outgoing
      // message, so that it could be tied back to the original request even if the response
      // envelope does not contain addressing headers
      MessageContext responseMessageContext = new MessageContext();
      responseMessageContext.setMessageID(msgctx.getMessageID());
      responseMessageContext.setProperty(
          SynapseConstants.RELATES_TO_FOR_POX, msgctx.getMessageID());
      responseMessageContext.setOptions(options);
      responseMessageContext.setServerSide(true);
      addMessageContext(responseMessageContext);
      responseMessageContext.setProperty("synapse.send", "true");

      AxisEngine.send(msgctx);

      // did the engine receive a immediate synchronous response?
      // e.g. sometimes the transport sender may listen for a syncronous reply
      if (msgctx.getProperty(MessageContext.TRANSPORT_IN) != null) {

        responseMessageContext.setOperationContext(msgctx.getOperationContext());
        responseMessageContext.setAxisMessage(
            msgctx
                .getOperationContext()
                .getAxisOperation()
                .getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE));
        responseMessageContext.setAxisService(msgctx.getAxisService());

        responseMessageContext.setProperty(
            MessageContext.TRANSPORT_OUT, msgctx.getProperty(MessageContext.TRANSPORT_OUT));
        responseMessageContext.setProperty(
            org.apache.axis2.Constants.OUT_TRANSPORT_INFO,
            msgctx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO));

        responseMessageContext.setProperty(
            org.apache.synapse.SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE);
        responseMessageContext.setTransportIn(msgctx.getTransportIn());
        responseMessageContext.setTransportOut(msgctx.getTransportOut());

        // If request is REST assume that the responseMessageContext is REST too
        responseMessageContext.setDoingREST(msgctx.isDoingREST());

        responseMessageContext.setProperty(
            MessageContext.TRANSPORT_IN, msgctx.getProperty(MessageContext.TRANSPORT_IN));
        responseMessageContext.setTransportIn(msgctx.getTransportIn());
        responseMessageContext.setTransportOut(msgctx.getTransportOut());

        // Options object reused above so soapAction needs to be removed so
        // that soapAction+wsa:Action on response don't conflict
        responseMessageContext.setSoapAction("");

        if (responseMessageContext.getEnvelope() == null) {
          // If request is REST we assume the responseMessageContext is
          // REST, so set the variable

          Options options = responseMessageContext.getOptions();
          if (options != null) {
            RelatesTo relatesTo = options.getRelatesTo();
            if (relatesTo != null) {
              relatesTo.setValue(msgctx.getMessageID());
            } else {
              options.addRelatesTo(new RelatesTo(msgctx.getMessageID()));
            }
          }

          SOAPEnvelope resenvelope = TransportUtils.createSOAPMessage(responseMessageContext);

          if (resenvelope != null) {
            responseMessageContext.setEnvelope(resenvelope);
            AxisEngine.receive(responseMessageContext);
            if (responseMessageContext.getReplyTo() != null) {
              sc.setTargetEPR(responseMessageContext.getReplyTo());
            }

            complete(msgctx);
          } else {
            throw new AxisFault(Messages.getMessage("blockingInvocationExpectsResponse"));
          }
        }
      }
    }
Beispiel #10
0
  /** Process the incoming request */
  @SuppressWarnings({"unchecked"})
  public void run() {

    String method = request.getRequestLine().getMethod().toUpperCase();
    msgContext.setProperty(
        Constants.Configuration.HTTP_METHOD, request.getRequestLine().getMethod());

    if (NHttpConfiguration.getInstance().isHttpMethodDisabled(method)) {
      handleException("Unsupported method : " + method, null);
    }

    // String uri = request.getRequestLine().getUri();
    String oriUri = request.getRequestLine().getUri();
    String restUrlPostfix = NhttpUtil.getRestUrlPostfix(oriUri, cfgCtx.getServicePath());

    msgContext.setProperty(NhttpConstants.REST_URL_POSTFIX, restUrlPostfix);
    String servicePrefix = oriUri.substring(0, oriUri.indexOf(restUrlPostfix));
    if (servicePrefix.indexOf("://") == -1) {
      HttpInetConnection inetConn = (HttpInetConnection) conn;
      InetAddress localAddr = inetConn.getLocalAddress();
      if (localAddr != null) {
        servicePrefix =
            schemeName
                + "://"
                + localAddr.getHostName()
                + ":"
                + inetConn.getLocalPort()
                + servicePrefix;
      }

      if (inetConn.getLocalPort() > 0) {
        msgContext.setProperty(NhttpConstants.SERVER_PORT, inetConn.getLocalPort());
      }
    }
    msgContext.setProperty(NhttpConstants.SERVICE_PREFIX, servicePrefix);

    if ("GET".equals(method)) {
      httpGetRequestProcessor.process(request, response, msgContext, conn, os, isRestDispatching);
    } else if ("POST".equals(method)) {
      processEntityEnclosingMethod();
    } else if ("PUT".equals(method)) {
      processEntityEnclosingMethod();
    } else if ("HEAD".equals(method)) {
      processNonEntityEnclosingMethod();
    } else if ("OPTIONS".equals(method)) {
      processNonEntityEnclosingMethod();
    } else if ("DELETE".equals(method)) {
      processGetAndDelete("DELETE");
    } else if ("TRACE".equals(method)) {
      processNonEntityEnclosingMethod();
    } else {
      handleException("Unsupported method : " + method, null);
    }

    // here the RequestResponseTransport plays an important role when it comes to
    // dual channel invocation. This is becasue we need to ACK to the request once the request
    // is received to synapse. Otherwise we will not be able to support the single channel
    // invocation within the actual service and synapse for a dual channel request from the
    // client.
    if (isAckRequired()) {
      String respWritten = "";
      if (msgContext.getOperationContext() != null) {
        respWritten =
            (String) msgContext.getOperationContext().getProperty(Constants.RESPONSE_WRITTEN);
      }
      boolean respWillFollow =
          !Constants.VALUE_TRUE.equals(respWritten) && !"SKIP".equals(respWritten);
      boolean acked =
          (((RequestResponseTransport)
                      msgContext.getProperty(RequestResponseTransport.TRANSPORT_CONTROL))
                  .getStatus()
              == RequestResponseTransport.RequestResponseTransportStatus.ACKED);
      boolean forced = msgContext.isPropertyTrue(NhttpConstants.FORCE_SC_ACCEPTED);
      boolean nioAck = msgContext.isPropertyTrue("NIO-ACK-Requested", false);

      if (respWillFollow || acked || forced || nioAck) {

        if (!nioAck) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Sending 202 Accepted response for MessageID : "
                    + msgContext.getMessageID()
                    + " response written : "
                    + respWritten
                    + " response will follow : "
                    + respWillFollow
                    + " acked : "
                    + acked
                    + " forced ack : "
                    + forced);
          }
          response.setStatusCode(HttpStatus.SC_ACCEPTED);
        } else {
          if (log.isDebugEnabled()) {
            log.debug(
                "Sending ACK response with status "
                    + msgContext.getProperty(NhttpConstants.HTTP_SC)
                    + ", for MessageID : "
                    + msgContext.getMessageID());
          }
          response.setStatusCode(
              Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString()));
          Map<String, String> responseHeaders =
              (Map<String, String>) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
          if (responseHeaders != null) {
            for (String headerName : responseHeaders.keySet()) {
              response.addHeader(headerName, responseHeaders.get(headerName));

              String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

              Map map = (Map) msgContext.getProperty(excessProp);
              if (map != null) {
                log.debug(
                    "Number of excess values for "
                        + headerName
                        + " header is : "
                        + ((Collection) (map.get(headerName))).size());

                for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {
                  String key = (String) iterator.next();

                  for (String excessVal : (Collection<String>) map.get(key)) {
                    response.addHeader(headerName, (String) excessVal);
                  }
                }
              }
            }
          }
        }

        if (metrics != null) {
          metrics.incrementMessagesSent();
        }

        try {

          /*
           * Remove Content-Length and Transfer-Encoding headers, if already present.
           * */
          response.removeHeaders(HTTP.TRANSFER_ENCODING);
          response.removeHeaders(HTTP.CONTENT_LEN);

          serverHandler.commitResponse(conn, response);

        } catch (HttpException e) {
          if (metrics != null) {
            metrics.incrementFaultsSending();
          }
          handleException("Unexpected HTTP protocol error : " + e.getMessage(), e);
        } catch (ConnectionClosedException e) {
          if (metrics != null) {
            metrics.incrementFaultsSending();
          }
          log.warn("Connection closed by client (Connection closed)");
        } catch (IllegalStateException e) {
          if (metrics != null) {
            metrics.incrementFaultsSending();
          }
          log.warn("Connection closed by client (Buffer closed)");
        } catch (IOException e) {
          if (metrics != null) {
            metrics.incrementFaultsSending();
          }
          handleException("IO Error sending response message", e);
        } catch (Exception e) {
          if (metrics != null) {
            metrics.incrementFaultsSending();
          }
          handleException("General Error sending response message", e);
        }

        if (is != null) {
          try {
            is.close();
          } catch (IOException ignore) {
          }
        }

        // make sure that the output stream is flushed and closed properly
        try {
          os.flush();
          os.close();
        } catch (IOException ignore) {
        }
      }
    }
  }