/**
   * Throttle out the request
   *
   * @param request
   * @param accessToken
   * @return
   * @throws APIFaultException
   */
  public boolean doThrottle(Request request, String accessToken) throws APIFaultException {

    String apiName = request.getContextPath();
    String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
    String apiIdentifier = apiName + "-" + apiVersion;

    APIThrottleHandler throttleHandler = null;
    ConfigurationContext cc = DataHolder.getServerConfigContext();

    if (cc.getProperty(apiIdentifier) == null) {
      throttleHandler = new APIThrottleHandler();
      /* Add the Throttle handler to ConfigContext against API Identifier */
      cc.setProperty(apiIdentifier, throttleHandler);
    } else {
      throttleHandler = (APIThrottleHandler) cc.getProperty(apiIdentifier);
    }

    if (throttleHandler.doThrottle(request, apiKeyValidationDTO, accessToken)) {
      return true;
    } else {
      throw new APIFaultException(
          APIManagerErrorConstants.API_THROTTLE_OUT, "You have exceeded your quota");
    }
  }
Пример #2
0
  /**
   * Log the interesting request parameters, invoke the next Valve in the sequence, and log the
   * interesting response parameters.
   *
   * @param request The servlet request to be processed
   * @param response The servlet response to be created
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet error occurs
   */
  public void invoke(Request request, Response response) throws IOException, ServletException {

    Log log = container.getLogger();

    // Log pre-service information
    log.info("REQUEST URI       =" + request.getRequestURI());
    log.info("          authType=" + request.getAuthType());
    log.info(" characterEncoding=" + request.getCharacterEncoding());
    log.info("     contentLength=" + request.getContentLength());
    log.info("       contentType=" + request.getContentType());
    log.info("       contextPath=" + request.getContextPath());
    Cookie cookies[] = request.getCookies();
    if (cookies != null) {
      for (int i = 0; i < cookies.length; i++)
        log.info("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
    }
    Enumeration hnames = request.getHeaderNames();
    while (hnames.hasMoreElements()) {
      String hname = (String) hnames.nextElement();
      Enumeration hvalues = request.getHeaders(hname);
      while (hvalues.hasMoreElements()) {
        String hvalue = (String) hvalues.nextElement();
        log.info("            header=" + hname + "=" + hvalue);
      }
    }
    log.info("            locale=" + request.getLocale());
    log.info("            method=" + request.getMethod());
    Enumeration pnames = request.getParameterNames();
    while (pnames.hasMoreElements()) {
      String pname = (String) pnames.nextElement();
      String pvalues[] = request.getParameterValues(pname);
      StringBuffer result = new StringBuffer(pname);
      result.append('=');
      for (int i = 0; i < pvalues.length; i++) {
        if (i > 0) result.append(", ");
        result.append(pvalues[i]);
      }
      log.info("         parameter=" + result.toString());
    }
    log.info("          pathInfo=" + request.getPathInfo());
    log.info("          protocol=" + request.getProtocol());
    log.info("       queryString=" + request.getQueryString());
    log.info("        remoteAddr=" + request.getRemoteAddr());
    log.info("        remoteHost=" + request.getRemoteHost());
    log.info("        remoteUser="******"requestedSessionId=" + request.getRequestedSessionId());
    log.info("            scheme=" + request.getScheme());
    log.info("        serverName=" + request.getServerName());
    log.info("        serverPort=" + request.getServerPort());
    log.info("       servletPath=" + request.getServletPath());
    log.info("          isSecure=" + request.isSecure());
    log.info("---------------------------------------------------------------");

    // Perform the request
    getNext().invoke(request, response);

    // Log post-service information
    log.info("---------------------------------------------------------------");
    log.info("          authType=" + request.getAuthType());
    log.info("     contentLength=" + response.getContentLength());
    log.info("       contentType=" + response.getContentType());
    Cookie rcookies[] = response.getCookies();
    for (int i = 0; i < rcookies.length; i++) {
      log.info(
          "            cookie="
              + rcookies[i].getName()
              + "="
              + rcookies[i].getValue()
              + "; domain="
              + rcookies[i].getDomain()
              + "; path="
              + rcookies[i].getPath());
    }
    String rhnames[] = response.getHeaderNames();
    for (int i = 0; i < rhnames.length; i++) {
      String rhvalues[] = response.getHeaderValues(rhnames[i]);
      for (int j = 0; j < rhvalues.length; j++)
        log.info("            header=" + rhnames[i] + "=" + rhvalues[j]);
    }
    log.info("           message=" + response.getMessage());
    log.info("        remoteUser="******"            status=" + response.getStatus());
    log.info("===============================================================");
  }
  public void invoke(Request request, Response response, CompositeValve compositeValve) {

    if (authenticator == null) {
      authenticator = new APITokenAuthenticator();
    }

    String context = request.getContextPath();
    if (context == null || context.equals("")) {
      // Invoke next valve in pipe.
      getNext().invoke(request, response, compositeValve);
      return;
    }

    // todo remove version from context - special case for apps
    //        context = stripVersionfromContext(context);

    boolean contextExist;
    Boolean contextValueInCache = null;
    if (APIUtil.getAPIContextCache().get(context) != null) {
      contextValueInCache =
          Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
    }

    if (contextValueInCache != null) {
      contextExist = contextValueInCache;
    } else {
      contextExist = ApiMgtDAO.isContextExist(context);
      APIUtil.getAPIContextCache().put(context, contextExist);
    }

    if (!contextExist) {
      getNext().invoke(request, response, compositeValve);
      return;
    }

    handleWSDLGetRequest(request, response, compositeValve, context);

    String dispatcherPath = null;
    boolean forwardingRequired = false;

    long requestTime = System.currentTimeMillis();
    APIManagerInterceptorOps interceptorOps = new APIManagerInterceptorOps();
    UsageStatConfiguration statConfiguration = new UsageStatConfiguration();
    if (contextExist) {
      // Use embedded API Management
      if (log.isDebugEnabled()) {
        log.debug("API Manager Interceptor Valve Got invoked!!");
      }

      String bearerToken = request.getHeader(APIConstants.OperationParameter.AUTH_PARAM_NAME);
      String accessToken = null;

      /* Authenticate*/
      try {
        if (bearerToken != null) {
          accessToken = APIManagetInterceptorUtils.getBearerToken(bearerToken);
        } else {
          // There can be some API published with None Auth Type
          /*
           * throw new
           * APIFaultException(APIConstants.KeyValidationStatus
           * .API_AUTH_INVALID_CREDENTIALS,
           * "Invalid format for Authorization header. Expected 'Bearer <token>'"
           * );
           */
        }

        String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
        dispatcherPath = apiVersion;
        // todo get proper version
        // handling version for web-application API mgmt

        if (!APIManagerInterceptorConstant.DEFAULT_API_VERSION.equals(apiVersion)
            || "".equals(apiVersion)) {
          apiVersion = APIManagerInterceptorConstant.DEFAULT_API_VERSION;
        } else {
          forwardingRequired = true;
        }

        String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
        String authLevel =
            authenticator.getResourceAuthenticationScheme(
                context, apiVersion, request.getRequestURI(), request.getMethod());
        if (authLevel.equals(APIConstants.NO_MATCHING_AUTH_SCHEME)) {
          APIManagetInterceptorUtils.handleNoMatchAuthSchemeCallForRestService(
              response, request.getMethod(), request.getRequestURI(), apiVersion, context);
          return;
        } else {
          interceptorOps.doAuthenticate(
              context,
              APIConstants.DEFAULT_VERSION_PREFIX + apiVersion,
              accessToken,
              authLevel,
              domain);
        }
      } catch (APIManagementException e) {
        // ignore
      } catch (APIFaultException e) {
          /* If !isAuthorized APIFaultException is thrown*/
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_SECURITY_NS,
            APIManagerErrorConstants.API_SECURITY_NS_PREFIX,
            response);
        return;
      }
      /* Throttle*/
      try {
        interceptorOps.doThrottle(request, accessToken);
      } catch (APIFaultException e) {
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_THROTTLE_NS,
            APIManagerErrorConstants.API_THROTTLE_NS_PREFIX,
            response);
        return;
      }
      /* Publish Statistic if enabled*/
      if (statConfiguration.isStatsPublishingEnabled()) {
        try {
          interceptorOps.publishStatistics(request, requestTime, false);
        } catch (APIManagementException e) {
          log.error("Error occurred when publishing stats", e);
        }
      }
    }

    if (forwardingRequired) {
      try {
        request
            .getRequestDispatcher(
                request.getContextPath() + "/services/customers/customerservice/customers/123")
            .forward(request, response);
        //                response.sendRedirect(request.getContextPath() +
        // "/services/customers/customerservice/customers/123");
        //                return;
      } catch (ServletException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // Invoke next valve in pipe.
    getNext().invoke(request, response, compositeValve);

    // Handle Responses
    if (contextExist && statConfiguration.isStatsPublishingEnabled()) {
      try {
        interceptorOps.publishStatistics(request, requestTime, true);
      } catch (APIManagementException e) {
        log.error("Error occurred when publishing stats", e);
      }
    }
  }
  public void invoke(Request request, Response response, CompositeValve compositeValve) {

    String context = request.getContextPath();
    if (context == null || context.equals("")) {
      // Invoke next valve in pipe.
      getNext().invoke(request, response, compositeValve);
      return;
    }

    boolean contextExist;
    Boolean contextValueInCache = null;
    if (APIUtil.getAPIContextCache().get(context) != null) {
      contextValueInCache =
          Boolean.parseBoolean(APIUtil.getAPIContextCache().get(context).toString());
    }

    if (contextValueInCache != null) {
      contextExist = contextValueInCache;
    } else {
      contextExist = ApiMgtDAO.isContextExist(context);
      APIUtil.getAPIContextCache().put(context, contextExist);
    }

    if (!contextExist) {
      getNext().invoke(request, response, compositeValve);
      return;
    }

    handleWSDLGetRequest(request, response, compositeValve, context);

    long requestTime = System.currentTimeMillis();
    APIManagerInterceptorOps interceptorOps = new APIManagerInterceptorOps();
    UsageStatConfiguration statConfiguration = new UsageStatConfiguration();
    if (contextExist) {
      // Use embedded WebApp Management
      if (log.isDebugEnabled()) {
        log.debug("WebApp Manager Interceptor Valve Got invoked!!");
      }

      String bearerToken = request.getHeader(APIConstants.OperationParameter.AUTH_PARAM_NAME);
      String accessToken = null;

      /* Authenticate*/
      try {
        if (bearerToken != null) {
          accessToken = APIManagetInterceptorUtils.getBearerToken(bearerToken);
        } else {
          // There can be some WebApp published with None Auth Type
          /*
           * throw new
           * APIFaultException(APIConstants.KeyValidationStatus
           * .API_AUTH_INVALID_CREDENTIALS,
           * "Invalid format for Authorization header. Expected 'Bearer <token>'"
           * );
           */
        }

        String apiVersion = APIManagetInterceptorUtils.getAPIVersion(request);
        String domain = request.getHeader(APITokenValidator.getAPIManagerClientDomainHeader());
        String authLevel =
            authenticator.getResourceAuthenticationScheme(
                context, apiVersion, request.getRequestURI(), request.getMethod());
        if (authLevel == APIConstants.NO_MATCHING_AUTH_SCHEME) {
          APIManagetInterceptorUtils.handleNoMatchAuthSchemeCallForRestService(
              response, request.getMethod(), request.getRequestURI(), apiVersion, context);
          return;
        } else {
          interceptorOps.doAuthenticate(context, apiVersion, accessToken, authLevel, domain);
        }
      } catch (APIManagementException e) {
        // ignore
      } catch (APIFaultException e) {
          /* If !isAuthorized APIFaultException is thrown*/
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_SECURITY_NS,
            APIManagerErrorConstants.API_SECURITY_NS_PREFIX,
            response);
        return;
      }
      /* Throttle*/
      try {
        interceptorOps.doThrottle(request, accessToken);
      } catch (APIFaultException e) {
        APIManagetInterceptorUtils.handleAPIFaultForRestService(
            e,
            APIManagerErrorConstants.API_THROTTLE_NS,
            APIManagerErrorConstants.API_THROTTLE_NS_PREFIX,
            response);
        return;
      }
      /* Publish Statistic if enabled*/
      if (statConfiguration.isStatsPublishingEnabled()) {
        try {
          interceptorOps.publishStatistics(request, requestTime, false);
        } catch (APIManagementException e) {
          log.error("Error occured when publishing stats", e);
        }
      }
    }

    // Invoke next valve in pipe.
    getNext().invoke(request, response, compositeValve);

    // Handle Responses
    if (contextExist && statConfiguration.isStatsPublishingEnabled()) {
      try {
        interceptorOps.publishStatistics(request, requestTime, true);
      } catch (APIManagementException e) {
        log.error("Error occured when publishing stats", e);
      }
    }
  }