private void sendUsingOutputStream(MessageContext msgContext) throws AxisFault {

    OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext);
    MessageFormatter messageFormatter =
        MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext);
    OutputStream out = (OutputStream) msgContext.getProperty(MessageContext.TRANSPORT_OUT);

    if (msgContext.isServerSide()) {
      OutTransportInfo transportInfo =
          (OutTransportInfo) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO);

      if (transportInfo != null) {
        transportInfo.setContentType(
            messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
      } else {
        throw new AxisFault(Constants.OUT_TRANSPORT_INFO + " has not been set");
      }
    }

    try {
      messageFormatter.writeTo(msgContext, format, out, false);
      out.close();
    } catch (IOException e) {
      handleException("IO Error sending response message", e);
    }
  }
  /**
   * Whether the original request received by the synapse is REST
   *
   * @param originalInMsgCtx request message
   * @return <code>true</code> if the request was a REST request
   */
  private static boolean isRequestRest(MessageContext originalInMsgCtx) {

    boolean isRestRequest =
        originalInMsgCtx.getProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE) != null;

    if (!isRestRequest) {

      String httpMethod =
          (String) originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD);

      isRestRequest =
          Constants.Configuration.HTTP_METHOD_GET.equals(httpMethod)
              || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpMethod)
              || Constants.Configuration.HTTP_METHOD_PUT.equals(httpMethod)
              || RESTConstants.METHOD_OPTIONS.equals(httpMethod)
              || Constants.Configuration.HTTP_METHOD_HEAD.equals(httpMethod);

      if (!isRestRequest) {

        isRestRequest =
            Constants.Configuration.HTTP_METHOD_POST.equals(httpMethod)
                && HTTPTransportUtils.isRESTRequest(
                    String.valueOf(
                        originalInMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE)));

        if (!isRestRequest) {
          isRestRequest =
              (String.valueOf(originalInMsgCtx.getProperty(Constants.Configuration.MESSAGE_TYPE))
                      .equals(HTTPConstants.MEDIA_TYPE_TEXT_XML)
                  && originalInMsgCtx.getSoapAction() == null);
        }
      }
    }
    return isRestRequest;
  }
Beispiel #3
0
 private void processJSONPayload(MessageContext synCtx, ScriptMessageContext scriptMC)
     throws ScriptException {
   if (!(synCtx instanceof Axis2MessageContext)) {
     return;
   }
   org.apache.axis2.context.MessageContext messageContext =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   String contentType = (String) messageContext.getProperty(Constants.Configuration.MESSAGE_TYPE);
   if ("application/json".equals(contentType)) {
     String jsonString = (String) messageContext.getProperty("JSON_STRING");
     InputStream jsonStream = (InputStream) messageContext.getProperty("JSON_STREAM");
     String jsonPayload = "{}";
     prepareForJSON(scriptMC);
     if (jsonString != null) {
       jsonPayload = jsonParser.parse(jsonString).toString();
     } else if (jsonStream != null) {
       try {
         jsonString =
             IOUtils.toString(
                 jsonStream,
                 (String)
                     messageContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING));
         jsonPayload = jsonParser.parse(jsonString).toString();
       } catch (IOException e) {
         handleException("Failed to get the JSON payload string from the input stream.");
       }
       messageContext.setProperty("JSON_STRING", jsonPayload);
     }
     Object jsonObject = scriptEngine.eval('(' + jsonPayload + ')');
     synCtx.setProperty("JSON_OBJECT", jsonObject);
   }
 }
  /**
   * This is is a workaround for axis2 RestUtils behaviour Based on an internal property and the
   * http method, we set the message type
   *
   * @param originalInMsgCtx IN message
   * @param axisOutMsgCtx Out message
   */
  private static void processWSDL2RESTRequestMessageType(
      MessageContext originalInMsgCtx, MessageContext axisOutMsgCtx) {

    // TODO - this is a workaround for axis2 RestUtils behaviour
    Object restContentType = originalInMsgCtx.getProperty(NhttpConstants.REST_REQUEST_CONTENT_TYPE);

    if (restContentType == null) {

      String httpMethod =
          (String) originalInMsgCtx.getProperty(Constants.Configuration.HTTP_METHOD);
      if (Constants.Configuration.HTTP_METHOD_GET.equals(httpMethod)
          || Constants.Configuration.HTTP_METHOD_DELETE.equals(httpMethod)) {
        restContentType = HTTPConstants.MEDIA_TYPE_X_WWW_FORM;
      }
    }
    // Removed ESB 4.7.0 PPT 2013-06-28
    //        if (restContentType != null && restContentType instanceof String) {
    //            String contentType = TransportUtils.getContentType((String) restContentType,
    // originalInMsgCtx);
    //            axisOutMsgCtx.setProperty(
    //                    org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, contentType);
    //            originalInMsgCtx.setProperty(
    //                    org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, contentType);
    //        }
  }
  /**
   * Remove unwanted headers from the http response of outgoing request. These are headers which
   * should be dictated by the transport and not the user. We remove these as these may get copied
   * from the request messages
   *
   * @param msgContext the Axis2 Message context from which these headers should be removed
   */
  private void removeUnwantedHeaders(MessageContext msgContext) {
    Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    Map excessHeaders = (Map) msgContext.getProperty(NhttpConstants.EXCESS_TRANSPORT_HEADERS);

    if (transportHeaders != null && !transportHeaders.isEmpty()) {
      removeUnwantedHeadersFromHeaderMap(transportHeaders, cfg);
    }

    if (excessHeaders != null && !excessHeaders.isEmpty()) {
      removeUnwantedHeadersFromHeaderMap(excessHeaders, cfg);
    }
  }
Beispiel #6
0
  private String getHostHeader(org.apache.axis2.context.MessageContext msgCtx) {
    Map transportHeaders =
        (Map) msgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    String hostHeader = null;
    if (transportHeaders != null) {
      hostHeader = (String) transportHeaders.get(HTTP.TARGET_HOST);
    }

    if (hostHeader == null) {
      hostHeader = (String) msgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
    }
    return hostHeader;
  }
  /**
   * Determine the HttpStatusCodedepending on the message type processed <br>
   * (normal response versus fault response) as well as Axis2 message context properties set via
   * Synapse configuration or MessageBuilders.
   *
   * @see org.apache.synapse.transport.nhttp.NhttpConstants#FAULTS_AS_HTTP_200
   * @see org.apache.synapse.transport.nhttp.NhttpConstants#HTTP_SC
   * @param msgContext the Axis2 message context
   * @param response the HTTP response object
   * @return the HTTP status code to set in the HTTP response object
   */
  private int determineHttpStatusCode(MessageContext msgContext, HttpResponse response) {

    int httpStatus = HttpStatus.SC_OK;

    // retrieve original status code (if present)
    if (response.getStatusLine() != null) {
      httpStatus = response.getStatusLine().getStatusCode();
    }

    // if this is a dummy message to handle http 202 case with non-blocking IO
    // set the status code to 202
    if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED)) {
      httpStatus = HttpStatus.SC_ACCEPTED;
    } else {

      // is this a fault message
      boolean handleFault =
          msgContext.getEnvelope().getBody().hasFault() || msgContext.isProcessingFault();

      // shall faults be transmitted with HTTP 200
      boolean faultsAsHttp200 =
          NhttpConstants.TRUE.equalsIgnoreCase(
              (String) msgContext.getProperty(NhttpConstants.FAULTS_AS_HTTP_200));

      // Set HTTP status code to 500 if this is a fault case and we shall not use HTTP 200
      if (handleFault && !faultsAsHttp200) {
        httpStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR;
      } else if (handleFault & faultsAsHttp200) {
        return HttpStatus.SC_OK;
      }

      /*
       * Any status code previously set shall be overwritten with the value of the following
       * message context property if it is set.
       */
      Object statusCode = msgContext.getProperty(NhttpConstants.HTTP_SC);
      if (statusCode != null) {
        try {
          httpStatus = Integer.parseInt(msgContext.getProperty(NhttpConstants.HTTP_SC).toString());
        } catch (NumberFormatException e) {
          log.warn(
              "Unable to set the HTTP status code from the property "
                  + NhttpConstants.HTTP_SC
                  + " with value: "
                  + statusCode);
        }
      }
    }

    return httpStatus;
  }
  private String getRedirectionReadyFullRequestPath(MessageContext messageContext) {

    String fullResourceURL =
        (String) messageContext.getProperty(RESTConstants.REST_FULL_REQUEST_PATH);

    // If the request has come though the default Synapse API (without versioning) remove the
    // version part of the URL.
    org.apache.axis2.context.MessageContext axis2MessageContext =
        ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map<String, Object> headers =
        (Map<String, Object>)
            axis2MessageContext.getProperty(
                org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    String hasRequestedThoughDefaultVersion =
        (String) headers.get(AppMConstants.GATEWAY_DEFAULT_VERSION_INDICATION_HEADER_NAME);

    if (hasRequestedThoughDefaultVersion != null
        && Boolean.parseBoolean(hasRequestedThoughDefaultVersion)) {
      String webAppVersion =
          (String) messageContext.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
      return fullResourceURL.replaceFirst("/" + webAppVersion, "");
    }

    return fullResourceURL;
  }
 /**
  * Take the data from temporary storage and write it to the output stream
  *
  * @param out output stream output stream
  * @param msgContext messagecontext
  * @throws IOException if an exception occurred while writing data
  */
 private void writeMessageFromTempData(OutputStream out, MessageContext msgContext)
     throws IOException {
   TemporaryData serialized =
       (TemporaryData) msgContext.getProperty(NhttpConstants.SERIALIZED_BYTES);
   try {
     serialized.writeTo(out);
   } finally {
     serialized.release();
   }
 }
  protected String getSetCookieHeader(MessageContext axis2MessageContext) {

    Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    if (o != null && o instanceof Map) {
      Map headerMap = (Map) o;
      return (String) headerMap.get(SET_COOKIE);
    }
    return null;
  }
 private void addTransportHeader(
     MessageContext messageContext, String headerName, String headerValue) {
   org.apache.axis2.context.MessageContext axis2MessageContext =
       ((Axis2MessageContext) messageContext).getAxis2MessageContext();
   Map<String, Object> headers =
       (Map<String, Object>)
           axis2MessageContext.getProperty(
               org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
   headers.put(headerName, headerValue);
   messageContext.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headers);
 }
 // This is copied from PropertyMediator, required to change Content-Type
 private void handleSpecialProperties(
     Object resultValue, org.apache.axis2.context.MessageContext axis2MessageCtx) {
   axis2MessageCtx.setProperty(org.apache.axis2.Constants.Configuration.CONTENT_TYPE, resultValue);
   Object o =
       axis2MessageCtx.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, resultValue);
   }
 }
  protected void setSessionID(MessageContext axis2MessageContext, String value) {

    if (value == null) {
      return;
    }
    Map map = (Map) axis2MessageContext.getProperty(HTTPConstants.HTTP_HEADERS);
    if (map == null) {
      map = new HashMap();
      axis2MessageContext.setProperty(HTTPConstants.HTTP_HEADERS, map);
    }
    map.put(COOKIE, value);
  }
  /**
   * transport sender invocation from Axis2 core
   *
   * @param msgContext message to be sent
   * @return the invocation response (always InvocationResponse.CONTINUE)
   * @throws AxisFault on error
   */
  public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {

    // remove unwanted HTTP headers (if any from the current message)
    removeUnwantedHeaders(msgContext);

    if (AddressingHelper.isReplyRedirected(msgContext)
        && !msgContext.getReplyTo().hasNoneAddress()) {

      msgContext.setProperty(NhttpConstants.IGNORE_SC_ACCEPTED, Constants.VALUE_TRUE);
    }

    EndpointReference epr = NhttpUtil.getDestinationEPR(msgContext);
    if (epr != null) {
      if (!epr.hasNoneAddress()) {
        sendAsyncRequest(epr, msgContext);
      } else {
        handleException("Cannot send message to " + AddressingConstants.Final.WSA_NONE_URI);
      }
    } else {

      if (msgContext.getProperty(Constants.OUT_TRANSPORT_INFO) != null) {
        if (msgContext.getProperty(Constants.OUT_TRANSPORT_INFO) instanceof ServerWorker) {
          sendAsyncResponse(msgContext);
        } else {
          sendUsingOutputStream(msgContext);
        }
      } else {
        handleException("No valid destination EPR or OutputStream to send message");
      }
    }

    if (msgContext.getOperationContext() != null) {
      msgContext
          .getOperationContext()
          .setProperty(Constants.RESPONSE_WRITTEN, Constants.VALUE_TRUE);
    }

    return InvocationResponse.CONTINUE;
  }
 /**
  * Sets the content type based on the request content type and payload factory media type. This
  * should be called at the end before returning from the mediate() function.
  *
  * @param synCtx
  */
 private void setContentType(MessageContext synCtx) {
   org.apache.axis2.context.MessageContext a2mc =
       ((Axis2MessageContext) synCtx).getAxis2MessageContext();
   if (mediaType.equals(XML_TYPE)) {
     if (!XML_CONTENT_TYPE.equals(a2mc.getProperty(Constants.Configuration.MESSAGE_TYPE))
         && !SOAP11_CONTENT_TYPE.equals(a2mc.getProperty(Constants.Configuration.MESSAGE_TYPE))
         && !SOAP12_CONTENT_TYPE.equals(a2mc.getProperty(Constants.Configuration.MESSAGE_TYPE))) {
       a2mc.setProperty(Constants.Configuration.MESSAGE_TYPE, XML_CONTENT_TYPE);
       a2mc.setProperty(Constants.Configuration.CONTENT_TYPE, XML_CONTENT_TYPE);
       handleSpecialProperties(XML_CONTENT_TYPE, a2mc);
     }
   } else if (mediaType.equals(JSON_TYPE)) {
     a2mc.setProperty(Constants.Configuration.MESSAGE_TYPE, JSON_CONTENT_TYPE);
     a2mc.setProperty(Constants.Configuration.CONTENT_TYPE, JSON_CONTENT_TYPE);
     handleSpecialProperties(JSON_CONTENT_TYPE, a2mc);
   } else if (mediaType.equals(TEXT_TYPE)) {
     a2mc.setProperty(Constants.Configuration.MESSAGE_TYPE, TEXT_CONTENT_TYPE);
     a2mc.setProperty(Constants.Configuration.CONTENT_TYPE, TEXT_CONTENT_TYPE);
     handleSpecialProperties(TEXT_CONTENT_TYPE, a2mc);
   }
   a2mc.removeProperty("NO_ENTITY_BODY");
 }
  /**
   * 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;
  }
  protected String extractSessionID(MessageContext axis2MessageContext) {

    Object o = axis2MessageContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    if (o != null && o instanceof Map) {
      Map headerMap = (Map) o;
      String cookie = (String) headerMap.get(SET_COOKIE);
      if (cookie == null) {
        cookie = (String) headerMap.get(COOKIE);
      } else {
        cookie = cookie.split(";")[0];
      }
      return cookie;
    }
    return null;
  }
  public boolean register(Registrant registrant) throws CartridgeAgentException {

    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    ConfigurationContext configurationContext = messageContext.getConfigurationContext();
    ClusteringClient clusteringClient =
        (ClusteringClient)
            configurationContext.getProperty(CartridgeAgentConstants.CLUSTERING_CLIENT);
    if (registrant.getRemoteHost() == null || registrant.getRemoteHost().isEmpty()) {
      String remoteAddr = (String) messageContext.getProperty("REMOTE_ADDR");
      registrant.setRemoteHost(remoteAddr);
    }
    log.info("Trying to add new registrant " + registrant + "...");
    clusteringClient.joinGroup(registrant, configurationContext);
    //        Main.getHealthChecker().start(registrant);
    DataHolder.getHealthChecker().start(registrant);
    return true;
  }
  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;
  }
Beispiel #20
0
 public OMElement processDocument(InputStream inputStream, String s, MessageContext messageContext)
     throws AxisFault {
   messageContext.setProperty(JsonConstant.IS_JSON_STREAM, true);
   JsonReader jsonReader;
   String charSetEncoding = null;
   try {
     charSetEncoding =
         (String) messageContext.getProperty(Constants.Configuration.CHARACTER_SET_ENCODING);
     jsonReader = new JsonReader(new InputStreamReader(inputStream, charSetEncoding));
     GsonXMLStreamReader gsonXMLStreamReader = new GsonXMLStreamReader(jsonReader);
     messageContext.setProperty(JsonConstant.GSON_XML_STREAM_READER, gsonXMLStreamReader);
     // dummy envelop
     SOAPFactory soapFactory = OMAbstractFactory.getSOAP11Factory();
     return soapFactory.getDefaultEnvelope();
   } catch (UnsupportedEncodingException e) {
     throw new AxisFault(
         charSetEncoding + " encoding is may not supported by json inputStream ", e);
   }
 }
Beispiel #21
0
  /** @param synCtx */
  public void evaluate(MessageContext synCtx) {
    String result;
    if (value != null) {
      result = value;
    } else if (expression != null) {
      result = expression.stringValueOf(synCtx);
    } else {
      throw new SynapseException("A value or expression must be specified");
    }

    if (scope == null || XMLConfigConstants.SCOPE_DEFAULT.equals(scope)) {
      synCtx.setProperty(name, result);
    } else if (XMLConfigConstants.SCOPE_AXIS2.equals(scope)) {
      // Setting property into the  Axis2 Message Context
      Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
      org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
      axis2MessageCtx.setProperty(name, result);
    } else if (XMLConfigConstants.SCOPE_CLIENT.equals(scope)) {
      // Setting property into the  Axis2 Message Context client options
      Axis2MessageContext axis2smc = (Axis2MessageContext) synCtx;
      org.apache.axis2.context.MessageContext axis2MessageCtx = axis2smc.getAxis2MessageContext();
      axis2MessageCtx.getOptions().setProperty(name, result);
    } else if (XMLConfigConstants.SCOPE_TRANSPORT.equals(scope)) {
      // Setting Transport Headers
      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;
        headersMap.put(name, result);
      }
      if (headers == null) {
        Map headersMap = new HashMap();
        headersMap.put(name, result);
        axis2MessageCtx.setProperty(
            org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
      }
    }
  }
  private Session getSession(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MessageContext =
        ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map<String, Object> headers =
        (Map<String, Object>)
            axis2MessageContext.getProperty(
                org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    String cookieHeaderValue = (String) headers.get(HTTPConstants.HEADER_COOKIE);

    if (cookieHeaderValue != null) {

      Map<String, String> cookies = parseRequestCookieHeader(cookieHeaderValue);

      if (cookies.get(AppMConstants.APPM_SAML2_COOKIE) != null) {
        if (log.isDebugEnabled()) {
          GatewayUtils.logWithRequestInfo(
              log,
              messageContext,
              String.format(
                  "Cookie '%s' is available in the request.", AppMConstants.APPM_SAML2_COOKIE));
        }
        messageContext.setProperty(
            AppMConstants.APPM_SAML2_COOKIE, cookies.get(AppMConstants.APPM_SAML2_COOKIE));
      } else {
        if (log.isDebugEnabled()) {
          GatewayUtils.logWithRequestInfo(
              log,
              messageContext,
              String.format(
                  "Cookie '%s' is not available in the request.", AppMConstants.APPM_SAML2_COOKIE));
        }
      }
    }

    return GatewayUtils.getSession(messageContext, true);
  }
  public boolean handleRequest(MessageContext messageContext) {

    org.apache.axis2.context.MessageContext axis2MessageContext =
        ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Object headers =
        axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    if (headers != null && headers instanceof Map) {
      Map headersMap = (Map) headers;
      if (headersMap.get("Authorization") == null) {
        headersMap.clear();
        axis2MessageContext.setProperty("HTTP_SC", "401");
        headersMap.put("WWW-Authenticate", "Basic realm=\"WSO2 ESB\"");
        axis2MessageContext.setProperty("NO_ENTITY_BODY", new Boolean("true"));
        messageContext.setProperty("RESPONSE", "true");
        messageContext.setTo(null);
        Axis2Sender.sendBack(messageContext);
        return false;

      } else {
        String authHeader = (String) headersMap.get("Authorization");
        String credentials = authHeader.substring(6).trim();
        if (processSecurity(credentials, messageContext)) {
          return true;
        } else {
          headersMap.clear();
          axis2MessageContext.setProperty("HTTP_SC", "403");
          axis2MessageContext.setProperty("NO_ENTITY_BODY", new Boolean("true"));
          messageContext.setProperty("RESPONSE", "true");
          messageContext.setTo(null);
          Axis2Sender.sendBack(messageContext);
          return false;
        }
      }
    }
    return true;
  }
  /**
   * Extract the content length from the incoming message
   *
   * @param msgContext current MessageContext
   * @return the length of the message
   */
  private int extractContentLength(MessageContext msgContext) {
    Map headers = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);

    if (headers == null || headers.isEmpty()) {
      return -1;
    }

    for (Object o : headers.keySet()) {
      String headerName = (String) o;
      if (HTTP.CONTENT_LEN.equalsIgnoreCase(headerName)) {
        Object value = headers.get(headerName);

        if (value != null && value instanceof String) {
          try {
            return Integer.parseInt((String) value);
          } catch (NumberFormatException e) {
            return -1;
          }
        }
      }
    }

    return -1;
  }
  public boolean handleRequest_old(MessageContext messageContext) {
    System.out.println("Entro nel handler");

    org.apache.axis2.context.MessageContext axis2MessageContext =
        ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Object headers =
        axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);

    if (headers != null && headers instanceof Map) {
      Map headersMap = (Map) headers;

      if (headersMap.get("Authorization") == null) {
        System.out.println("TRUE1"); // non ho fornito nessun tipo di autenticazione
        return true;

      } else {
        String authHeader = (String) headersMap.get("Authorization");
        String credentials = authHeader.substring(6).trim();
        if (processSecurity(credentials, messageContext)) {
          System.out.println("TRUE2");
          return true;
        } else {
          headersMap.clear();
          axis2MessageContext.setProperty("HTTP_SC", "403");
          axis2MessageContext.setProperty("NO_ENTITY_BODY", new Boolean("true"));
          messageContext.setProperty("RESPONSE", "true");
          messageContext.setTo(null);
          Axis2Sender.sendBack(messageContext);
          System.out.println("FALSE");
          return false;
        }
      }
    }
    System.out.println("TRU0E3");
    return true;
  }
Beispiel #26
0
  /**
   * processing through the throttle 1) concurrent throttling 2) access rate based throttling -
   * domain or ip
   *
   * @param throttle The Throttle object - holds all configuration and state data of the throttle
   * @param messageContext The MessageContext , that holds all data per message basis
   * @throws AxisFault Throws when access must deny for caller
   * @throws ThrottleException ThrottleException
   */
  public void process(Throttle throttle, MessageContext messageContext)
      throws ThrottleException, AxisFault {

    String throttleId = throttle.getId();
    ConfigurationContext cc = messageContext.getConfigurationContext();

    // check the env - whether clustered  or not
    boolean isClusteringEnable = false;
    ClusteringAgent clusteringAgent = null;
    if (cc != null) {
      clusteringAgent = cc.getAxisConfiguration().getClusteringAgent();
    }
    if (clusteringAgent != null && clusteringAgent.getStateManager() != null) {
      isClusteringEnable = true;
    }

    // Get the concurrent access controller
    ConcurrentAccessController cac;
    String key = null;
    if (isClusteringEnable) {
      // for clustered  env.,gets it from axis configuration context
      key = ThrottleConstants.THROTTLE_PROPERTY_PREFIX + throttleId + ThrottleConstants.CAC_SUFFIX;
      cac = (ConcurrentAccessController) cc.getProperty(key);
    } else {
      // for non-clustered  env.,gets it from axis configuration context
      cac = throttle.getConcurrentAccessController();
    }

    // check for concurrent access
    boolean canAccess = doConcurrentThrottling(cac, messageContext);

    if (canAccess) {
      // if the concurrent access is success then
      // do the access rate based throttling

      if (messageContext.getFLOW() == MessageContext.IN_FLOW) {
        // gets the remote caller domain name
        String domain = null;
        HttpServletRequest request =
            (HttpServletRequest)
                messageContext.getPropertyNonReplicable(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
          domain = request.getRemoteHost();
        }

        // Domain name based throttling
        // check whether a configuration has been defined for this domain name or not
        String callerId = null;
        if (domain != null) {
          // loads the ThrottleContext
          ThrottleContext context =
              throttle.getThrottleContext(ThrottleConstants.DOMAIN_BASED_THROTTLE_KEY);
          if (context != null) {
            // Loads the ThrottleConfiguration
            ThrottleConfiguration config = context.getThrottleConfiguration();
            if (config != null) {
              // check for configuration for this caller
              callerId = config.getConfigurationKeyOfCaller(domain);
              if (callerId != null) {
                // If this is a clustered env.
                if (isClusteringEnable) {
                  context.setConfigurationContext(cc);
                  context.setThrottleId(throttleId);
                }
                AccessInformation infor =
                    accessRateController.canAccess(
                        context, callerId, ThrottleConstants.DOMAIN_BASE);
                StatCollector.collect(infor, domain, ThrottleConstants.DOMAIN_BASE);

                // check for the permission for access
                if (!infor.isAccessAllowed()) {

                  // In the case of both of concurrency throttling and
                  // rate based throttling have enabled ,
                  // if the access rate less than maximum concurrent access ,
                  // then it is possible to occur death situation.To avoid that reset,
                  // if the access has denied by rate based throttling
                  if (cac != null) {
                    cac.incrementAndGet();
                    // set back if this is a clustered env
                    if (isClusteringEnable) {
                      cc.setProperty(key, cac);
                      // replicate the current state of ConcurrentAccessController
                      try {
                        if (debugOn) {
                          log.debug(
                              "Going to replicates the "
                                  + "states of the ConcurrentAccessController"
                                  + " with key : "
                                  + key);
                        }
                        Replicator.replicate(cc, new String[] {key});
                      } catch (ClusteringFault clusteringFault) {
                        log.error("Error during replicating states ", clusteringFault);
                      }
                    }
                  }
                  throw new AxisFault(
                      " Access deny for a "
                          + "caller with Domain "
                          + domain
                          + " "
                          + " : Reason : "
                          + infor.getFaultReason());
                }
              } else {
                if (debugOn) {
                  log.debug(
                      "Could not find the Throttle Context for domain-Based "
                          + "Throttling for domain name "
                          + domain
                          + " Throttling for this "
                          + "domain name may not be configured from policy");
                }
              }
            }
          }
        } else {
          if (debugOn) {
            log.debug("Could not find the domain of the caller - IP-based throttling may occur");
          }
        }

        // IP based throttling - Only if there is no configuration for caller domain name

        if (callerId == null) {
          String ip = (String) messageContext.getProperty(MessageContext.REMOTE_ADDR);
          if (ip != null) {
            // loads IP based throttle context
            ThrottleContext context =
                throttle.getThrottleContext(ThrottleConstants.IP_BASED_THROTTLE_KEY);
            if (context != null) {
              // Loads the ThrottleConfiguration
              ThrottleConfiguration config = context.getThrottleConfiguration();
              if (config != null) {
                // check for configuration for this ip
                callerId = config.getConfigurationKeyOfCaller(ip);
                if (callerId != null) {
                  // for clustered env.
                  if (isClusteringEnable) {
                    context.setConfigurationContext(cc);
                    context.setThrottleId(throttleId);
                  }
                  AccessInformation infor =
                      accessRateController.canAccess(context, callerId, ThrottleConstants.IP_BASE);
                  // check for the permission for access
                  StatCollector.collect(infor, ip, ThrottleConstants.IP_BASE);
                  if (!infor.isAccessAllowed()) {

                    // In the case of both of concurrency throttling and
                    // rate based throttling have enabled ,
                    // if the access rate less than maximum concurrent access ,
                    // then it is possible to occur death situation.To avoid that reset,
                    // if the access has denied by rate based throttling
                    if (cac != null) {
                      cac.incrementAndGet();
                      // set back if this is a clustered env
                      if (isClusteringEnable) {
                        cc.setProperty(key, cac);
                        // replicate the current state of ConcurrentAccessController
                        try {
                          if (debugOn) {
                            log.debug(
                                "Going to replicates the "
                                    + "states of the ConcurrentAccessController"
                                    + " with key : "
                                    + key);
                          }
                          Replicator.replicate(cc, new String[] {key});
                        } catch (ClusteringFault clusteringFault) {
                          log.error("Error during replicating states ", clusteringFault);
                        }
                      }
                    }
                    throw new AxisFault(
                        " Access deny for a "
                            + "caller with IP "
                            + ip
                            + " "
                            + " : Reason : "
                            + infor.getFaultReason());
                  }
                }
              }
            } else {
              if (debugOn) {
                log.debug("Could not find the throttle Context for IP-Based throttling");
              }
            }
          } else {
            if (debugOn) {
              log.debug(
                  "Could not find the IP address of the caller " + "- throttling will not occur");
            }
          }
        }
      }
      // all the replication functionality of the access rate based throttling handles by itself
      // just replicate the current state of ConcurrentAccessController
      if (isClusteringEnable && cac != null) {
        try {
          if (debugOn) {
            log.debug(
                "Going to replicates the states of the ConcurrentAccessController"
                    + " with key : "
                    + key);
          }
          Replicator.replicate(cc, new String[] {key});
        } catch (ClusteringFault clusteringFault) {
          log.error("Error during replicating states ", clusteringFault);
        }
      }

      // finally engage rolebased access throttling if available
      doRoleBasedAccessThrottling(throttle, messageContext, isClusteringEnable);
    } else {
      // replicate the current state of ConcurrentAccessController
      if (isClusteringEnable) {
        try {
          if (debugOn) {
            log.debug(
                "Going to replicates the states of the ConcurrentAccessController"
                    + " with key : "
                    + key);
          }
          Replicator.replicate(cc, new String[] {key});
        } catch (ClusteringFault clusteringFault) {
          log.error("Error during replicating states ", clusteringFault);
        }
      }
      throw new AxisFault(
          "Access has currently been denied since " + " maximum concurrent access have exceeded");
    }
  }
  /**
   * 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");
    }
  }
  public void receive(org.apache.axis2.context.MessageContext mc) throws AxisFault {

    boolean traceOn = proxy.getAspectConfiguration().isTracingEnabled();
    boolean traceOrDebugOn = traceOn || log.isDebugEnabled();

    CustomLogSetter.getInstance().setLogAppender(proxy.getArtifactContainerName());

    String remoteAddr =
        (String) mc.getProperty(org.apache.axis2.context.MessageContext.REMOTE_ADDR);

    if (traceOrDebugOn) {
      traceOrDebug(
          traceOn,
          "Proxy Service "
              + name
              + " received a new message"
              + (remoteAddr != null ? " from : " + remoteAddr : "..."));
      traceOrDebug(
          traceOn, ("Message To: " + (mc.getTo() != null ? mc.getTo().getAddress() : "null")));
      traceOrDebug(
          traceOn, ("SOAPAction: " + (mc.getSoapAction() != null ? mc.getSoapAction() : "null")));
      traceOrDebug(
          traceOn, ("WSA-Action: " + (mc.getWSAAction() != null ? mc.getWSAAction() : "null")));

      if (traceOn && trace.isTraceEnabled()) {
        String[] cids = mc.getAttachmentMap().getAllContentIDs();
        if (cids != null && cids.length > 0) {
          for (String cid : cids) {
            trace.trace("With attachment content ID : " + cid);
          }
        }
        trace.trace("Envelope : " + mc.getEnvelope());
      }
    }

    MessageContext synCtx = MessageContextCreatorForAxis2.getSynapseMessageContext(mc);
    Integer statisticReportingIndex = null;
    // Statistic reporting
    boolean isStatisticsEnabled = RuntimeStatisticCollector.isStatisticsEnabled();
    if (isStatisticsEnabled) {
      statisticReportingIndex =
          OpenEventCollector.reportEntryEvent(
              synCtx, this.name, proxy.getAspectConfiguration(), ComponentType.PROXYSERVICE);
    }

    Object inboundServiceParam =
        proxy.getParameterMap().get(SynapseConstants.INBOUND_PROXY_SERVICE_PARAM);
    Object inboundMsgCtxParam = mc.getProperty(SynapseConstants.IS_INBOUND);

    // check whether the message is from Inbound EP
    if (inboundMsgCtxParam == null || !(boolean) inboundMsgCtxParam) {
      // check whether service parameter is set to true or null, then block this request
      if (inboundServiceParam != null && (Boolean.valueOf((String) inboundServiceParam))) {
        /*
        return because same proxy is exposed via InboundEP and service parameter(inbound.only) is set to
        true, which disable normal http transport proxy
        */
        if (!synCtx.getFaultStack().isEmpty()) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Executing fault handler - message discarded due to the proxy is allowed only via InboundEP");
          }
          (synCtx.getFaultStack().pop())
              .handleFault(
                  synCtx,
                  new Exception(
                      "Proxy Service "
                          + name
                          + " message discarded due to the proxy is allowed only via InboundEP"));
        } else {
          if (log.isDebugEnabled()) {
            log.debug(
                "Proxy Service "
                    + name
                    + " message discarded due to the proxy is "
                    + "allowed only via InboundEP");
          }
        }
        return;
      }
    }

    TenantInfoConfigurator configurator = synCtx.getEnvironment().getTenantInfoConfigurator();
    if (configurator != null) {
      configurator.extractTenantInfo(synCtx);
    }
    TransportInDescription trpInDesc = mc.getTransportIn();
    if (trpInDesc != null) {
      synCtx.setProperty(SynapseConstants.TRANSPORT_IN_NAME, trpInDesc.getName());
    }

    // get service log for this message and attach to the message context also set proxy name
    Log serviceLog = LogFactory.getLog(SynapseConstants.SERVICE_LOGGER_PREFIX + name);
    ((Axis2MessageContext) synCtx).setServiceLog(serviceLog);

    synCtx.setProperty(SynapseConstants.PROXY_SERVICE, name);
    //        synCtx.setTracingState(proxy.getTraceState());

    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_REST, mc.isDoingREST());
    synCtx.setProperty(SynapseConstants.IS_CLIENT_DOING_SOAP11, mc.isSOAP11());

    try {
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.acquireMediationFlowLock();
        debugManager.advertiseMediationFlowStartPoint(synCtx);
        if (!synCtx.isResponse()) {
          SynapseWireLogHolder wireLogHolder =
              (SynapseWireLogHolder)
                  ((Axis2MessageContext) synCtx)
                      .getAxis2MessageContext()
                      .getProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY);
          if (wireLogHolder == null) {
            wireLogHolder = new SynapseWireLogHolder();
          }
          if (synCtx.getProperty(SynapseConstants.PROXY_SERVICE) != null
              && !synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString().isEmpty()) {
            wireLogHolder.setProxyName(
                synCtx.getProperty(SynapseConstants.PROXY_SERVICE).toString());
          }
          ((Axis2MessageContext) synCtx)
              .getAxis2MessageContext()
              .setProperty(SynapseDebugInfoHolder.SYNAPSE_WIRE_LOG_HOLDER_PROPERTY, wireLogHolder);
        }
      }
      synCtx.setProperty(SynapseConstants.RESPONSE_STATE, new ResponseState());
      List handlers = synCtx.getEnvironment().getSynapseHandlers();
      Iterator<SynapseHandler> iterator = handlers.iterator();
      while (iterator.hasNext()) {
        SynapseHandler handler = iterator.next();
        if (!handler.handleRequestInFlow(synCtx)) {
          return;
        }
      }

      Mediator mandatorySeq = synCtx.getConfiguration().getMandatorySequence();
      if (mandatorySeq != null) {
        if (log.isDebugEnabled()) {
          log.debug(
              "Start mediating the message in the "
                  + "pre-mediate state using the mandatory sequence");
        }

        if (!mandatorySeq.mediate(synCtx)) {
          if (log.isDebugEnabled()) {
            log.debug(
                "Request message for the proxy service "
                    + name
                    + " dropped in "
                    + "the pre-mediation state by the mandatory sequence : \n"
                    + synCtx);
          }
          return;
        }
      }

      // setup fault sequence - i.e. what happens when something goes wrong with this message
      proxy.registerFaultHandler(synCtx);

      boolean inSequenceResult = true;

      // Using inSequence for the incoming message mediation
      if (proxy.getTargetInSequence() != null) {

        Mediator inSequence = synCtx.getSequence(proxy.getTargetInSequence());
        if (inSequence != null) {
          traceOrDebug(
              traceOn,
              "Using sequence named : "
                  + proxy.getTargetInSequence()
                  + " for incoming message mediation");
          inSequenceResult = inSequence.mediate(synCtx);

        } else {
          handleException("Unable to find in-sequence : " + proxy.getTargetInSequence(), synCtx);
        }

      } else if (proxy.getTargetInLineInSequence() != null) {
        traceOrDebug(
            traceOn, "Using the anonymous " + "in-sequence of the proxy service for mediation");
        inSequenceResult = proxy.getTargetInLineInSequence().mediate(synCtx);
      }

      // if inSequence returns true, forward message to endpoint
      if (inSequenceResult) {
        if (proxy.getTargetEndpoint() != null) {
          Endpoint endpoint = synCtx.getEndpoint(proxy.getTargetEndpoint());

          if (endpoint != null) {
            traceOrDebug(
                traceOn, "Forwarding message to the endpoint : " + proxy.getTargetEndpoint());
            endpoint.send(synCtx);

          } else {
            handleException(
                "Unable to find the endpoint specified : " + proxy.getTargetEndpoint(), synCtx);
          }

        } else if (proxy.getTargetInLineEndpoint() != null) {
          traceOrDebug(
              traceOn,
              "Forwarding the message to the anonymous " + "endpoint of the proxy service");
          proxy.getTargetInLineEndpoint().send(synCtx);
        }
      }

    } catch (SynapseException syne) {

      if (!synCtx.getFaultStack().isEmpty()) {
        warn(traceOn, "Executing fault handler due to exception encountered", synCtx);
        ((FaultHandler) synCtx.getFaultStack().pop()).handleFault(synCtx, syne);

      } else {
        warn(
            traceOn,
            "Exception encountered but no fault handler found - " + "message dropped",
            synCtx);
      }
    } finally {
      // Statistic reporting
      if (isStatisticsEnabled) {
        CloseEventCollector.tryEndFlow(
            synCtx, this.name, ComponentType.PROXYSERVICE, statisticReportingIndex, true);
      }
      if (synCtx.getEnvironment().isDebuggerEnabled()) {
        SynapseDebugManager debugManager = synCtx.getEnvironment().getSynapseDebugManager();
        debugManager.advertiseMediationFlowTerminatePoint(synCtx);
        debugManager.releaseMediationFlowLock();
      }
    }
  }
  /**
   * Create a one time MessageProducer for this JMS OutTransport information. For simplicity and
   * best compatibility, this method uses only JMS 1.0.2b API. Please be cautious when making any
   * changes
   *
   * @return a JMSSender based on one-time use resources
   * @throws JMSException on errors, to be handled and logged by the caller
   */
  public JMSMessageSender createJMSSender(MessageContext msgCtx) throws JMSException {

    // digest the targetAddress and locate CF from the EPR
    loadConnectionFactoryFromProperties();

    // create a one time connection and session to be used
    String user = properties != null ? properties.get(JMSConstants.PARAM_JMS_USERNAME) : null;
    String pass = properties != null ? properties.get(JMSConstants.PARAM_JMS_PASSWORD) : null;

    QueueConnectionFactory qConFac = null;
    TopicConnectionFactory tConFac = null;

    int destType = -1;
    // TODO: there is something missing here for destination type generic
    if (JMSConstants.DESTINATION_TYPE_QUEUE.equals(destinationType)) {
      destType = JMSConstants.QUEUE;
      qConFac = (QueueConnectionFactory) connectionFactory;

    } else if (JMSConstants.DESTINATION_TYPE_TOPIC.equals(destinationType)) {
      destType = JMSConstants.TOPIC;
      tConFac = (TopicConnectionFactory) connectionFactory;
    } else {
      // treat jmsdestination type=queue(default is queue)
      destType = JMSConstants.QUEUE;
      qConFac = (QueueConnectionFactory) connectionFactory;
    }

    if (msgCtx.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER) != null) {
      XAConnection connection = null;
      if (user != null && pass != null) {
        if (qConFac != null) {
          connection = ((XAConnectionFactory) qConFac).createXAConnection(user, pass);
        } else if (tConFac != null) {
          connection = ((XAConnectionFactory) tConFac).createXAConnection(user, pass);
        }
      } else {
        if (qConFac != null) {
          connection = ((XAConnectionFactory) qConFac).createXAConnection();
        } else if (tConFac != null) {
          connection = ((XAConnectionFactory) tConFac).createXAConnection();
        }
      }

      if (connection == null) {
        connection = ((XAConnectionFactory) qConFac).createXAConnection();
      }

      XASession session = null;
      MessageProducer producer = null;

      if (connection != null) {
        if (destType == JMSConstants.QUEUE) {
          session = connection.createXASession();
          producer = session.createProducer(destination);
        } else {
          session = connection.createXASession();
          producer = session.createProducer(destination);
        }
      }

      XAResource xaResource = session.getXAResource();
      TransactionManager tx = null;
      Xid xid1 = null;
      Transaction transaction = null;
      java.util.UUID uuid = java.util.UUID.randomUUID();

      try {
        tx = (TransactionManager) msgCtx.getProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER);
        transaction = tx.getTransaction();
        msgCtx.setProperty(JMSConstants.JMS_XA_TRANSACTION_MANAGER, tx);
        msgCtx.setProperty(JMSConstants.JMS_XA_TRANSACTION, transaction);
        xid1 =
            new JMSXid(
                JMSConstants.JMS_XA_TRANSACTION_PREFIX.getBytes(StandardCharsets.UTF_8),
                1,
                uuid.toString().getBytes());
        msgCtx.setProperty("XID", xid1);
        xaResource.start(xid1, XAResource.TMNOFLAGS);
      } catch (SystemException e) {
        handleException("Error Occurred during starting getting Transaction.", e);
      } catch (XAException e) {
        handleException("Error Occurred during starting XA resource.", e);
      }
      return new JMSMessageSender(
          connection,
          session,
          producer,
          destination,
          jmsConnectionFactory == null ? this.cacheLevel : jmsConnectionFactory.getCacheLevel(),
          jmsSpecVersion,
          destType == -1 ? null : destType == JMSConstants.QUEUE ? Boolean.TRUE : Boolean.FALSE,
          transaction,
          xid1,
          xaResource);
    } else {
      Connection connection = null;
      if (user != null && pass != null) {
        if (qConFac != null) {
          connection = qConFac.createQueueConnection(user, pass);
        } else if (tConFac != null) {
          connection = tConFac.createTopicConnection(user, pass);
        }
      } else {
        if (qConFac != null) {
          connection = qConFac.createQueueConnection();
        } else if (tConFac != null) {
          connection = tConFac.createTopicConnection();
        }
      }

      if (connection == null) {
        connection = jmsConnectionFactory != null ? jmsConnectionFactory.getConnection() : null;
      }

      Session session = null;
      MessageProducer producer = null;

      if (connection != null) {
        if (destType == JMSConstants.QUEUE) {
          session =
              ((QueueConnection) connection).createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
          producer = ((QueueSession) session).createSender((Queue) destination);
        } else {
          session =
              ((TopicConnection) connection).createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
          producer = ((TopicSession) session).createPublisher((Topic) destination);
        }
      }
      return new JMSMessageSender(
          connection,
          session,
          producer,
          destination,
          jmsConnectionFactory == null ? this.cacheLevel : jmsConnectionFactory.getCacheLevel(),
          jmsSpecVersion,
          destType == -1 ? null : destType == JMSConstants.QUEUE ? Boolean.TRUE : Boolean.FALSE);
    }
  }