public void forward(ServletRequest request, ServletResponse response) {
   Assert.notNull(request, "Request must not be null");
   Assert.notNull(response, "Response must not be null");
   if (response.isCommitted()) {
     throw new IllegalStateException("Cannot perform forward - response is already committed");
   }
   getMockHttpServletResponse(response).setForwardedUrl(this.url);
   if (logger.isDebugEnabled()) {
     logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
   }
 }
  private ServletResponse getResponse(ServletRequest request, ServletResponse response) {
    if (response.isCommitted() || request.getAttribute(PROCESSED_ATTR) != null) {
      LOGGER.trace("No Compression: Response committed or filter has already been applied");
      return response;
    }

    if (!(response instanceof HttpServletResponse) || !(request instanceof HttpServletRequest)) {
      LOGGER.trace("No Compression: non http request/response");
      return response;
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String acceptEncoding = httpRequest.getHeader(HTTP_ACCEPT_ENCODING_HEADER);

    String contentEncoding = getAppropriateContentEncoding(acceptEncoding);

    if (contentEncoding == null) {
      LOGGER.trace("No Compression: Accept encoding is : {}", acceptEncoding);
      return response;
    }

    String requestURI = httpRequest.getRequestURI();
    if (!isURLAccepted(requestURI)) {
      LOGGER.trace("No Compression: For path: ", requestURI);
      return response;
    }
    if (!isQueryStringAccepted(httpRequest.getQueryString())) {
      LOGGER.trace("No Compression: For Query String: ", httpRequest.getQueryString());
      return response;
    }
    String userAgent = httpRequest.getHeader(Constants.HTTP_USER_AGENT_HEADER);
    if (!isUserAgentAccepted(userAgent)) {
      LOGGER.trace("No Compression: For User-Agent: {}", userAgent);
      return response;
    }

    EncodedStreamsFactory encodedStreamsFactory =
        EncodedStreamsFactory.getFactoryForContentEncoding(contentEncoding);

    LOGGER.debug("Compressing response: content encoding : {}", contentEncoding);

    return new CompressedHttpServletResponseWrapper(
        httpResponse, encodedStreamsFactory, contentEncoding, compressionThreshold, this);
  }
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) {
      // Client accepts zipped content
      if (log.isTraceEnabled()) {
        log.trace("{} Written with gzip compression", httpRequest.getRequestURL());
      }

      // Create a gzip stream
      final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
      final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

      // Handle the request
      final GZipServletResponseWrapper wrapper =
          new GZipServletResponseWrapper(httpResponse, gzout);
      wrapper.setDisableFlushBuffer(true);
      chain.doFilter(request, wrapper);
      wrapper.flush();

      gzout.close();

      // double check one more time before writing out
      // repsonse might have been committed due to error
      if (response.isCommitted()) {
        return;
      }

      // return on these special cases when content is empty or unchanged
      switch (wrapper.getStatus()) {
        case HttpServletResponse.SC_NO_CONTENT:
        case HttpServletResponse.SC_RESET_CONTENT:
        case HttpServletResponse.SC_NOT_MODIFIED:
          return;
        default:
      }

      // Saneness checks
      byte[] compressedBytes = compressed.toByteArray();
      boolean shouldGzippedBodyBeZero =
          GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest);
      boolean shouldBodyBeZero =
          GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus());
      if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
        // No reason to add GZIP headers or write body if no content was written or status code
        // specifies no
        // content
        response.setContentLength(0);
        return;
      }

      // Write the zipped body
      GZipResponseUtil.addGzipHeader(httpResponse);

      response.setContentLength(compressedBytes.length);

      response.getOutputStream().write(compressedBytes);

    } else {
      // Client does not accept zipped content - don't bother zipping
      if (log.isTraceEnabled()) {
        log.trace(
            "{} Written without gzip compression because the request does not accept gzip",
            httpRequest.getRequestURL());
      }
      chain.doFilter(request, response);
    }
  }
Example #4
0
  /**
   * This is Wicket's main method to execute a request
   *
   * @param request
   * @param response
   * @param chain
   * @return false, if the request could not be processed
   * @throws IOException
   * @throws ServletException
   */
  boolean processRequest(
      ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final ThreadContext previousThreadContext = ThreadContext.detach();

    // Assume we are able to handle the request
    boolean res = true;

    final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader();
    final ClassLoader newClassLoader = getClassLoader();

    try {
      if (previousClassLoader != newClassLoader) {
        Thread.currentThread().setContextClassLoader(newClassLoader);
      }

      HttpServletRequest httpServletRequest = (HttpServletRequest) request;
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;

      // Make sure getFilterPath() gets called before checkIfRedirectRequired()
      String filterPath = getFilterPath(httpServletRequest);

      if (filterPath == null) {
        throw new IllegalStateException("filter path was not configured");
      }

      if (shouldIgnorePath(httpServletRequest)) {
        log.debug("Ignoring request {}", httpServletRequest.getRequestURL());
        if (chain != null) {
          chain.doFilter(request, response);
        }
        return false;
      }

      String redirectURL = checkIfRedirectRequired(httpServletRequest);
      if (redirectURL == null) {
        // No redirect; process the request
        ThreadContext.setApplication(application);

        WebRequest webRequest = application.createWebRequest(httpServletRequest, filterPath);
        WebResponse webResponse = application.createWebResponse(webRequest, httpServletResponse);

        RequestCycle requestCycle = application.createRequestCycle(webRequest, webResponse);
        if (!requestCycle.processRequestAndDetach()) {
          if (chain != null) {
            chain.doFilter(request, response);
          }
          res = false;
        } else {
          webResponse.flush();
        }
      } else {
        if (Strings.isEmpty(httpServletRequest.getQueryString()) == false) {
          redirectURL += "?" + httpServletRequest.getQueryString();
        }

        try {
          // send redirect - this will discard POST parameters if the request is POST
          // - still better than getting an error because of lacking trailing slash
          httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(redirectURL));
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    } finally {
      ThreadContext.restore(previousThreadContext);

      if (newClassLoader != previousClassLoader) {
        Thread.currentThread().setContextClassLoader(previousClassLoader);
      }

      if (response.isCommitted()) {
        response.flushBuffer();
      }
    }
    return res;
  }
Example #5
0
 public boolean isCommitted() {
   return response.isCommitted();
 }
Example #6
0
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    listenerCallBack.fireOnRequest(project, request, response);
    if (response.isCommitted()) {
      return;
    }

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET")) {
      method = new ExtendedGetMethod();
    } else if (httpRequest.getMethod().equals("POST")) {
      method = new ExtendedPostMethod();
    } else if (httpRequest.getMethod().equals("PUT")) {
      method = new ExtendedPutMethod();
    } else if (httpRequest.getMethod().equals("HEAD")) {
      method = new ExtendedHeadMethod();
    } else if (httpRequest.getMethod().equals("OPTIONS")) {
      method = new ExtendedOptionsMethod();
    } else if (httpRequest.getMethod().equals("TRACE")) {
      method = new ExtendedTraceMethod();
    } else if (httpRequest.getMethod().equals("PATCH")) {
      method = new ExtendedPatchMethod();
    } else {
      method = new ExtendedGenericMethod(httpRequest.getMethod());
    }

    method.setDecompress(false);

    ByteArrayOutputStream requestBody = null;
    if (method instanceof HttpEntityEnclosingRequest) {
      requestBody = Tools.readAll(request.getInputStream(), 0);
      ByteArrayEntity entity = new ByteArrayEntity(requestBody.toByteArray());
      entity.setContentType(request.getContentType());
      ((HttpEntityEnclosingRequest) method).setEntity(entity);
    }

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData =
        new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setQueryParameters(httpRequest.getQueryString());
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    //		CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() );

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
      connectionHeader = connectionHeader.toLowerCase();
      if (!connectionHeader.contains("keep-alive") && !connectionHeader.contains("close")) {
        connectionHeader = null;
      }
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String hdr = (String) headerNames.nextElement();
      String lhdr = hdr.toLowerCase();

      if (dontProxyHeaders.contains(lhdr)) {
        continue;
      }
      if (connectionHeader != null && connectionHeader.contains(lhdr)) {
        continue;
      }

      Enumeration<?> vals = httpRequest.getHeaders(hdr);
      while (vals.hasMoreElements()) {
        String val = (String) vals.nextElement();
        if (val != null) {
          method.setHeader(lhdr, val);
          xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
        }
      }
    }

    // Proxy headers
    method.setHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor) {
      method.addHeader("X-Forwarded-For", request.getRemoteAddr());
    }

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80) {
      url.append(":" + httpRequest.getServerPort());
    }

    if (httpRequest.getServletPath() != null) {
      url.append(httpRequest.getServletPath());
      try {
        method.setURI(new java.net.URI(url.toString().replaceAll(" ", "%20")));
      } catch (URISyntaxException e) {
        SoapUI.logError(e);
      }

      if (httpRequest.getQueryString() != null) {
        url.append("?" + httpRequest.getQueryString());
        try {
          method.setURI(new java.net.URI(url.toString()));
        } catch (URISyntaxException e) {
          SoapUI.logError(e);
        }
      }
    }

    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    setProtocolversion(method, request.getProtocol());
    ProxyUtils.setForceDirectConnection(method.getParams());
    listenerCallBack.fireBeforeProxy(project, request, response, method);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
      if (httpState == null) {
        httpState = new BasicHttpContext();
      }
      HttpClientSupport.execute(method, httpState);
    } else {
      HttpClientSupport.execute(method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(requestBody == null ? null : requestBody.toByteArray());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method.getHttpResponse());
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), requestBody));
    capturedData.setRawResponseData(getResponseToBytes(method, capturedData.getRawResponseBody()));
    byte[] decompressedResponseBody = method.getDecompressedResponseBody();
    capturedData.setResponseContent(
        decompressedResponseBody != null ? new String(decompressedResponseBody) : "");
    capturedData.setResponseStatusCode(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().getStatusCode() : null);
    capturedData.setResponseStatusLine(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().toString() : null);

    listenerCallBack.fireAfterProxy(project, request, response, method, capturedData);

    ((HttpServletResponse) response)
        .setStatus(
            method.hasHttpResponse()
                ? method.getHttpResponse().getStatusLine().getStatusCode()
                : null);

    if (!response.isCommitted()) {
      StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
      // capturedData = null;

      // copy headers to response
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;
      for (Map.Entry<String, List<String>> headerEntry : responseHeaders.entrySet()) {
        for (String header : headerEntry.getValue()) {
          httpServletResponse.addHeader(headerEntry.getKey(), header);
        }
      }

      if (capturedData.getRawResponseBody() != null) {
        IO.copy(
            new ByteArrayInputStream(capturedData.getRawResponseBody()),
            httpServletResponse.getOutputStream());
      }
    }

    synchronized (this) {
      if (contentTypeMatches(method)) {
        listenerCallBack.fireAddMessageExchange(capturedData);
      }
    }
  }
Example #7
0
  /** @see javax.faces.context.ExternalContext#isResponseCommitted() */
  @Override
  public boolean isResponseCommitted() {

    return response.isCommitted();
  }