@Test
    public void shouldParseInclusiveStatusCodeRestrictions() {
      final HttpLogFormatter formatter = new HttpLogFormatter("%200,201U");
      final String expected = "http://some.place.net/u/r/l";

      when(response.getStatus()).thenReturn(200);
      assertEquals(expected, formatter.format(request, response));
      when(response.getStatus()).thenReturn(401);
      assertEquals("-", formatter.format(request, response));
    }
  @Override
  protected void doFilterInternal(
      HttpServletRequest request, HttpServletResponse response, FilterChain chain)
      throws ServletException, IOException {

    long start = System.currentTimeMillis();
    try {
      log.info(
          "Request: {} {}",
          request.getMethod(),
          request.getQueryString() == null
              ? request.getRequestURI()
              : request.getRequestURI() + "?" + request.getQueryString());
      log.info("Remote host: {} {}", request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
      log.info("User-Agent: {}", request.getHeader("User-Agent"));

      chain.doFilter(request, response);

    } finally {
      HttpStatus status = HttpStatus.valueOf(response.getStatus());
      log.info(
          "{} {}, in {}ms",
          status.value(),
          status.getReasonPhrase(),
          System.currentTimeMillis() - start);
    }
  }
 private int getStatus(HttpServletResponse response) {
   try {
     return response.getStatus();
   } catch (Exception ex) {
     return UNDEFINED_HTTP_STATUS;
   }
 }
 public void afterCompletion(
     HttpServletRequest request, HttpServletResponse response, Object handler, Exception arg3)
     throws Exception {
   if (request.getRequestURI().endsWith("products/add") && response.getStatus() == 302) {
     logger.info(
         String.format("A New product[%s] Added by %son %s", productId, user, getCurrentTime()));
   }
 }
 /** @return true if the view for this GrailsWebRequest should be rendered */
 public boolean isRenderView() {
   final HttpServletRequest currentRequest = getCurrentRequest();
   HttpServletResponse currentResponse = getCurrentResponse();
   return renderView
       && !currentResponse.isCommitted()
       && currentResponse.getStatus() < 300
       && currentRequest.getAttribute(REDIRECT_CALLED) == null;
 }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   // Only set the status on the first call (the dispatch will trigger
   // another call to this Servlet)
   if (resp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
     resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
     AsyncContext ac = req.startAsync();
     ac.dispatch();
   }
 }
Example #7
0
  private Response serviceViaOSGIPlugin(
      final HttpServletRequest request,
      final InputStream inputStream,
      final HttpServletResponse response,
      final ServletContext servletContext,
      final ServletConfig servletConfig)
      throws ServletException, IOException {
    prepareOSGIRequest(request, servletContext, servletConfig);
    osgiServlet.service(
        new OSGIServletRequestWrapper(request, inputStream),
        new OSGIServletResponseWrapper(response));

    if (response.isCommitted()) {
      if (response.getStatus() >= 400) {
        log.warn("{} responded {}", request.getPathInfo(), response.getStatus());
      }
      // Jersey will want to return 204, but the servlet should have done the right thing already
      return null;
    } else {
      return Response.status(response.getStatus()).build();
    }
  }
  @Override
  public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    final StatusCodeMatcher matchedCode =
        getMatchingStatusCode(String.valueOf(response.getStatus()));
    final MutableHttpServletRequest mutableRequest = MutableHttpServletRequest.wrap(request);
    MediaRangeProcessor processor =
        new MediaRangeProcessor(mutableRequest.getPreferredHeaders("Accept", DEFAULT_TYPE));

    if (!isInitialized()) {
      response.sendError(
          HttpStatusCode.SERVICE_UNAVAIL.intValue(), "Error creating Response Messaging service.");
    } else {

      if (matchedCode != null) {

        HttpLogFormatter formatter = null;
        Message message = null;
        List<MediaType> mediaTypes = processor.process();

        message = MessageFilter.filterByMediaType(matchedCode.getMessage(), mediaTypes);

        if (message != null) {
          formatter = getHttpLogFormatter(matchedCode, message.getMediaType());

          if (formatter != null) {

            if (!(configSetToIfEmpty(matchedCode) && hasBody(response))) {

              final String formattedOutput = formatter.format("", request, response).trim();

              overwriteResponseBody(response, formattedOutput, message.getContentType());
            }
          } else {
            LOG.info(
                "No formatter found for message code.  Skipping Response Message Service formatting for status code regex "
                    + matchedCode.getCodeRegex());
          }
        } else {

          LOG.info(
              "Message for Matched code is empty. Matched Code is :" + matchedCode.getCodeRegex());
        }
      }
    }
  }
  @Test
  public void flashMap() throws Exception {
    RedirectView rv = new RedirectView();
    rv.setUrl("http://url.somewhere.com/path");
    rv.setHttp10Compatible(false);
    MockHttpServletRequest request = createRequest();
    HttpServletResponse response = new MockHttpServletResponse();
    FlashMap flashMap = new FlashMap();
    flashMap.put("successMessage", "yay!");
    request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, flashMap);
    ModelMap model = new ModelMap("id", "1");
    rv.render(model, request, response);
    assertEquals(303, response.getStatus());
    assertEquals("http://url.somewhere.com/path?id=1", response.getHeader("Location"));

    assertEquals("/path", flashMap.getTargetRequestPath());
    assertEquals(model, flashMap.getTargetRequestParams().toSingleValueMap());
  }
  /**
   * @see
   *     org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.web.servlet.ModelAndView)
   */
  @Override
  public void postHandle(
      HttpServletRequest request,
      HttpServletResponse response,
      Object handler,
      ModelAndView modelAndView)
      throws Exception {
    if (LOGGER.isTraceEnabled()) {
      StringBuilder responseRepresentation = new StringBuilder();

      responseRepresentation.append(request.getMethod());

      responseRepresentation.append(" url=");
      responseRepresentation.append(request.getRequestURL());
      if (request.getQueryString() != null) {
        responseRepresentation.append('?');
        responseRepresentation.append(request.getQueryString());
      }

      responseRepresentation.append(",status=");
      responseRepresentation.append(response.getStatus());

      responseRepresentation.append(",headers={");
      Iterator<String> headerNames = response.getHeaderNames().iterator();
      while (headerNames.hasNext()) {
        String headerName = headerNames.next();

        responseRepresentation.append(headerName);
        responseRepresentation.append(": ");
        responseRepresentation.append(response.getHeader(headerName));

        if (headerNames.hasNext()) responseRepresentation.append(", ");
      }
      responseRepresentation.append('}');

      /*
       * Note: We don't currently log the body/message content. It's
       * tricky to get, and I don't (yet) have a need for it.
       */

      LOGGER.trace("Response: {}", responseRepresentation.toString());
    }
  }
 @Override
 public void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   RestRequest restRequest = new RestRequest(req, "");
   SilverTrace.info("peasUtil", "RestOnlineFileServer.doPost", "root.MSG_GEN_ENTER_METHOD");
   try {
     SilverpeasFile file = getWantedFile(restRequest);
     if (file != null) {
       sendFile(res, file);
       return;
     }
   } catch (IllegalAccessException ex) {
     res.setStatus(HttpServletResponse.SC_FORBIDDEN);
     res.sendError(res.getStatus());
     return;
   } catch (Exception ex) {
     throw new ServletException(ex);
   }
   displayWarningHtmlCode(res);
 }
  private void publishRequestHandledEvent(
      HttpServletRequest request,
      HttpServletResponse response,
      long startTime,
      Throwable failureCause) {

    if (this.publishEvents) {
      // Whether or not we succeeded, publish an event.
      long processingTime = System.currentTimeMillis() - startTime;
      int statusCode = (responseGetStatusAvailable ? response.getStatus() : -1);
      this.webApplicationContext.publishEvent(
          new ServletRequestHandledEvent(
              this,
              request.getRequestURI(),
              request.getRemoteAddr(),
              request.getMethod(),
              getServletConfig().getServletName(),
              WebUtils.getSessionId(request),
              getUsernameForRequest(request),
              processingTime,
              failureCause,
              statusCode));
    }
  }
 @Override
 public int getStatus() {
   return response.getStatus();
 }
Example #14
0
  @Override
  protected void doGet(final HttpServletRequest request, final HttpServletResponse response) {

    final Authenticator auth = config.getAuthenticator();
    final SecurityContext securityContext;
    final App app;

    try {
      String path = request.getPathInfo();

      // check for registration (has its own tx because of write access
      if (checkRegistration(auth, request, response, path)) {

        return;
      }

      // isolate request authentication in a transaction
      try (final Tx tx = StructrApp.getInstance().tx()) {
        securityContext = auth.initializeAndExamineRequest(request, response);
        tx.success();
      }

      app = StructrApp.getInstance(securityContext);

      try (final Tx tx = app.tx()) {

        // Ensure access mode is frontend
        securityContext.setAccessMode(AccessMode.Frontend);

        request.setCharacterEncoding("UTF-8");

        // Important: Set character encoding before calling response.getWriter() !!, see Servlet
        // Spec 5.4
        response.setCharacterEncoding("UTF-8");

        boolean dontCache = false;

        logger.log(Level.FINE, "Path info {0}", path);

        // don't continue on redirects
        if (response.getStatus() == 302) {
          return;
        }

        Principal user = securityContext.getUser(false);
        if (user != null) {

          // Don't cache if a user is logged in
          dontCache = true;
        }

        final RenderContext renderContext =
            RenderContext.getInstance(request, response, getEffectiveLocale(request));

        renderContext.setResourceProvider(config.getResourceProvider());

        EditMode edit = renderContext.getEditMode(user);

        DOMNode rootElement = null;
        AbstractNode dataNode = null;

        String[] uriParts = PathHelper.getParts(path);
        if ((uriParts == null) || (uriParts.length == 0)) {

          // find a visible page
          rootElement = findIndexPage(securityContext);

          logger.log(Level.FINE, "No path supplied, trying to find index page");

        } else {

          if (rootElement == null) {

            rootElement = findPage(securityContext, request, path);

          } else {
            dontCache = true;
          }
        }

        if (rootElement == null) { // No page found

          // Look for a file
          File file = findFile(securityContext, request, path);
          if (file != null) {

            streamFile(securityContext, file, request, response, edit);
            return;
          }

          // store remaining path parts in request
          Matcher matcher = threadLocalUUIDMatcher.get();
          boolean requestUriContainsUuids = false;

          for (int i = 0; i < uriParts.length; i++) {

            request.setAttribute(uriParts[i], i);
            matcher.reset(uriParts[i]);

            // set to "true" if part matches UUID pattern
            requestUriContainsUuids |= matcher.matches();
          }

          if (!requestUriContainsUuids) {

            // Try to find a data node by name
            dataNode = findFirstNodeByName(securityContext, request, path);

          } else {

            dataNode = findNodeByUuid(securityContext, PathHelper.getName(path));
          }

          if (dataNode != null) {

            // Last path part matches a data node
            // Remove last path part and try again searching for a page
            // clear possible entry points
            request.removeAttribute(POSSIBLE_ENTRY_POINTS);

            rootElement =
                findPage(
                    securityContext,
                    request,
                    StringUtils.substringBeforeLast(path, PathHelper.PATH_SEP));

            renderContext.setDetailsDataObject(dataNode);

            // Start rendering on data node
            if (rootElement == null && dataNode instanceof DOMNode) {

              rootElement = ((DOMNode) dataNode);
            }
          }
        }

        // Still nothing found, do error handling
        if (rootElement == null) {

          // Check if security context has set an 401 status
          if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {

            try {

              UiAuthenticator.writeUnauthorized(response);

            } catch (IllegalStateException ise) {
            }

          } else {

            rootElement = notFound(response, securityContext);
          }
        }

        if (rootElement == null) {
          return;
        }

        if (EditMode.WIDGET.equals(edit) || dontCache) {

          setNoCacheHeaders(response);
        }

        if (!securityContext.isVisible(rootElement)) {

          rootElement = notFound(response, securityContext);
          if (rootElement == null) {
            return;
          }
        }

        if (securityContext.isVisible(rootElement)) {

          if (!EditMode.WIDGET.equals(edit)
              && !dontCache
              && notModifiedSince(request, response, rootElement, dontCache)) {

            ServletOutputStream out = response.getOutputStream();
            out.flush();
            // response.flushBuffer();
            out.close();

          } else {

            // prepare response
            response.setCharacterEncoding("UTF-8");

            String contentType = rootElement.getProperty(Page.contentType);

            if (contentType != null && contentType.equals("text/html")) {

              contentType = contentType.concat(";charset=UTF-8");
              response.setContentType(contentType);

            } else {

              // Default
              response.setContentType("text/html;charset=UTF-8");
            }

            response.setHeader("Strict-Transport-Security", "max-age=60");
            response.setHeader("X-Content-Type-Options", "nosniff");
            response.setHeader("X-Frame-Options", "SAMEORIGIN");
            response.setHeader("X-XSS-Protection", "1; mode=block");

            // async or not?
            boolean isAsync =
                HttpService.parseBoolean(
                    Services.getBaseConfiguration().getProperty(HttpService.ASYNC), true);
            if (isAsync) {

              final AsyncContext async = request.startAsync();
              final ServletOutputStream out = async.getResponse().getOutputStream();
              final AtomicBoolean finished = new AtomicBoolean(false);
              final DOMNode rootNode = rootElement;

              threadPool.submit(
                  new Runnable() {

                    @Override
                    public void run() {

                      try (final Tx tx = app.tx()) {

                        // final long start = System.currentTimeMillis();

                        // render
                        rootNode.render(securityContext, renderContext, 0);
                        finished.set(true);

                        // final long end = System.currentTimeMillis();
                        // System.out.println("Done in " + (end-start) + " ms");

                        tx.success();

                      } catch (Throwable t) {
                        t.printStackTrace();
                        final String errorMsg = t.getMessage();
                        try {
                          // response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                          response.sendError(
                              HttpServletResponse.SC_INTERNAL_SERVER_ERROR, errorMsg);
                          finished.set(true);
                        } catch (IOException ex) {
                          ex.printStackTrace();
                        }
                      }
                    }
                  });

              // start output write listener
              out.setWriteListener(
                  new WriteListener() {

                    @Override
                    public void onWritePossible() throws IOException {

                      try {

                        final Queue<String> queue = renderContext.getBuffer().getQueue();
                        while (out.isReady()) {

                          String buffer = null;

                          synchronized (queue) {
                            buffer = queue.poll();
                          }

                          if (buffer != null) {

                            out.print(buffer);

                          } else {

                            if (finished.get()) {

                              async.complete();
                              response.setStatus(HttpServletResponse.SC_OK);

                              // prevent this block from being called again
                              break;
                            }

                            Thread.sleep(1);
                          }
                        }

                      } catch (Throwable t) {
                        t.printStackTrace();
                      }
                    }

                    @Override
                    public void onError(Throwable t) {
                      t.printStackTrace();
                    }
                  });

            } else {

              final StringRenderBuffer buffer = new StringRenderBuffer();
              renderContext.setBuffer(buffer);

              // render
              rootElement.render(securityContext, renderContext, 0);

              response.getOutputStream().write(buffer.getBuffer().toString().getBytes("utf-8"));
              response.getOutputStream().flush();
              response.getOutputStream().close();
            }
          }

        } else {

          notFound(response, securityContext);
        }

        tx.success();

      } catch (FrameworkException fex) {
        fex.printStackTrace();
        logger.log(Level.SEVERE, "Exception while processing request", fex);
      }

    } catch (IOException | FrameworkException t) {

      t.printStackTrace();
      logger.log(Level.SEVERE, "Exception while processing request", t);
      UiAuthenticator.writeInternalServerError(response);
    }
  }
 @RequestMapping(value = PATH)
 ErrorJson error(HttpServletRequest request, HttpServletResponse response) {
   // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring.
   // Here we just define response body.
   return new ErrorJson(response.getStatus(), getErrorAttributes(request, true));
 }
Example #16
0
  /**
   * Serve the specified resource, optionally including the data content.
   *
   * @param request The servlet request we are processing
   * @param response The servlet response we are creating
   * @param content Should the content be included?
   * @param encoding The encoding to use if it is necessary to access the source as characters
   *     rather than as bytes
   * @exception IOException if an input/output error occurs
   * @exception ServletException if a servlet-specified error occurs
   */
  protected void serveResource(
      HttpServletRequest request, HttpServletResponse response, boolean content, String encoding)
      throws IOException, ServletException {

    boolean serveContent = content;
    boolean debug = log.isDebug();

    // Identify the requested resource path
    String path = getRelativePath(request);
    if (debug) {
      if (serveContent)
        log.debug(
            "DefaultServlet.serveResource:  Serving resource '" + path + "' headers and data");
      else log.debug("DefaultServlet.serveResource:  Serving resource '" + path + "' headers only");
    }

    WebResourceRoot resources = getResources(request);
    WebResource resource = resources.getResource(path);

    if (!resource.exists()) {
      // Check if we're included so we can return the appropriate
      // missing resource name in the error
      String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
      if (requestUri == null) {
        requestUri = request.getRequestURI();
      } else {
        // We're included
        // SRV.9.3 says we must throw a FNFE
        throw new FileNotFoundException("defaultServlet.missingResource");
      }

      response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
      return;
    }

    // If the resource is not a collection, and the resource path
    // ends with "/" or "\", return NOT FOUND
    if (resource.isFile() && path.endsWith("/") || path.endsWith("\\")) {
      // Check if we're included so we can return the appropriate
      // missing resource name in the error
      String requestUri = (String) request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI);
      if (requestUri == null) {
        requestUri = request.getRequestURI();
      }
      response.sendError(HttpServletResponse.SC_NOT_FOUND, requestUri);
      return;
    }

    boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST;

    boolean included = false;
    // Check if the conditions specified in the optional If headers are
    // satisfied.
    if (resource.isFile()) {
      // Checking If headers
      included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null);
      if (!included && !isError && !checkIfHeaders(request, response, resource)) {
        return;
      }
    }

    // Find content type.
    String contentType = resource.getMimeType();
    if (contentType == null) {
      contentType = request.getServletContext().getMimeType(resource.getName());
      resource.setMimeType(contentType);
    }

    // These need to reflect the original resource, not the potentially
    // gzip'd version of the resource so get them now if they are going to
    // be needed later
    String eTag = null;
    String lastModifiedHttp = null;
    if (resource.isFile() && !isError) {
      eTag = resource.getETag();
      lastModifiedHttp = resource.getLastModifiedHttp();
    }

    // Serve a gzipped version of the file if present
    boolean usingGzippedVersion = false;
    if (gzip && !included && resource.isFile() && !path.endsWith(".gz")) {
      WebResource gzipResource = resources.getResource(path + ".gz");
      if (gzipResource.exists() && gzipResource.isFile()) {
        Collection<String> varyHeaders = response.getHeaders("Vary");
        boolean addRequired = true;
        for (String varyHeader : varyHeaders) {
          if ("*".equals(varyHeader) || "accept-encoding".equalsIgnoreCase(varyHeader)) {
            addRequired = false;
            break;
          }
        }
        if (addRequired) {
          response.addHeader("Vary", "accept-encoding");
        }
        if (checkIfGzip(request)) {
          response.addHeader("Content-Encoding", "gzip");
          resource = gzipResource;
          usingGzippedVersion = true;
        }
      }
    }

    ArrayList<Range> ranges = null;
    long contentLength = -1L;

    if (resource.isDirectory()) {
      contentType = "text/html;charset=UTF-8";
    } else {
      if (!isError) {
        if (useAcceptRanges) {
          // Accept ranges header
          response.setHeader("Accept-Ranges", "bytes");
        }

        // Parse range specifier
        ranges = parseRange(request, response, resource);

        // ETag header
        response.setHeader("ETag", eTag);

        // Last-Modified header
        response.setHeader("Last-Modified", lastModifiedHttp);
      }

      // Get content length
      contentLength = resource.getContentLength();
      // Special case for zero length files, which would cause a
      // (silent) ISE when setting the output buffer size
      if (contentLength == 0L) {
        serveContent = false;
      }
    }

    ServletOutputStream ostream = null;
    PrintWriter writer = null;

    if (serveContent) {
      // Trying to retrieve the servlet output stream
      try {
        ostream = response.getOutputStream();
      } catch (IllegalStateException e) {
        // If it fails, we try to get a Writer instead if we're
        // trying to serve a text file
        if (!usingGzippedVersion
            && ((contentType == null)
                || (contentType.startsWith("text"))
                || (contentType.endsWith("xml"))
                || (contentType.contains("/javascript")))) {
          writer = response.getWriter();
          // Cannot reliably serve partial content with a Writer
          ranges = FULL;
        } else {
          throw e;
        }
      }
    }

    // Check to see if a Filter, Valve of wrapper has written some content.
    // If it has, disable range requests and setting of a content length
    // since neither can be done reliably.
    ServletResponse r = response;
    long contentWritten = 0;
    while (r instanceof ServletResponseWrapper) {
      r = ((ServletResponseWrapper) r).getResponse();
    }

    if (contentWritten > 0) {
      ranges = FULL;
    }

    if (resource.isDirectory()
        || isError
        || ((ranges == null || ranges.isEmpty()) && request.getHeader("Range") == null)
        || ranges == FULL) {

      // Set the appropriate output headers
      if (contentType != null) {
        if (debug) log.debug("DefaultServlet.serveFile:  contentType='" + contentType + "'");
        response.setContentType(contentType);
      }
      if (resource.isFile() && contentLength >= 0 && (!serveContent || ostream != null)) {
        if (debug) log.debug("DefaultServlet.serveFile:  contentLength=" + contentLength);
        // Don't set a content length if something else has already
        // written to the response.
        if (contentWritten == 0) {
          response.setContentLengthLong(contentLength);
        }
      }

      InputStream renderResult = null;
      if (resource.isDirectory()) {
        if (serveContent) {
          // Serve the directory browser
          renderResult = null; // TODO tomcat render(getPathPrefix(request), resource);
        }
      }

      // Copy the input stream to our output stream (if requested)
      if (serveContent) {
        resource.increaseDownloadCount();

        try {
          response.setBufferSize(output);
        } catch (IllegalStateException e) {
          // Silent catch
        }

        if (ostream == null) {
          // Output via a writer so can't use sendfile or write
          // content directly.
          if (resource.isDirectory()) {
            renderResult = null; // render(getPathPrefix(request), resource);
          } else {
            renderResult = resource.getInputStream();
          }
          copy(resource, renderResult, writer, encoding);
        } else {
          // Output is via an InputStream
          if (resource.isDirectory()) {
            renderResult = null; // render(getPathPrefix(request), resource);
          } else {
            renderResult = resource.getInputStream();
          }
          // If a stream was configured, it needs to be copied to
          // the output (this method closes the stream)
          if (renderResult != null) {
            copy(renderResult, ostream);
          }
        }
      }

    } else {
      // download counter
      resource.increaseDownloadCount();

      if ((ranges == null) || (ranges.isEmpty())) return;

      // Partial content response.

      response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

      if (ranges.size() == 1) {

        Range range = ranges.get(0);
        response.addHeader(
            "Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length);
        long length = range.end - range.start + 1;
        response.setContentLengthLong(length);

        if (contentType != null) {
          if (debug) log.debug("DefaultServlet.serveFile:  contentType='" + contentType + "'");
          response.setContentType(contentType);
        }

        if (serveContent) {
          try {
            response.setBufferSize(output);
          } catch (IllegalStateException e) {
            // Silent catch
          }
          if (ostream != null) {
            copy(resource, ostream, range);
          } else {
            // we should not get here
            throw new IllegalStateException();
          }
        }
      } else {
        response.setContentType("multipart/byteranges; boundary=" + mimeSeparation);
        if (serveContent) {
          try {
            response.setBufferSize(output);
          } catch (IllegalStateException e) {
            // Silent catch
          }
          if (ostream != null) {
            copy(resource, ostream, ranges.iterator(), contentType);
          } else {
            // we should not get here
            throw new IllegalStateException();
          }
        }
      }
    }
  }
Example #17
0
  /**
   * This method checks all configured external authentication services.
   *
   * @param request
   * @param response
   * @return user
   */
  protected static Principal checkExternalAuthentication(
      final HttpServletRequest request, final HttpServletResponse response)
      throws FrameworkException {

    final String path = PathHelper.clean(request.getPathInfo());
    final String[] uriParts = PathHelper.getParts(path);

    logger.log(Level.FINE, "Checking external authentication ...");

    if (uriParts == null || uriParts.length != 3 || !("oauth".equals(uriParts[0]))) {

      logger.log(Level.FINE, "Incorrect URI parts for OAuth process, need /oauth/<name>/<action>");
      return null;
    }

    final String name = uriParts[1];
    final String action = uriParts[2];

    // Try to getValue an OAuth2 server for the given name
    final StructrOAuthClient oauthServer = StructrOAuthClient.getServer(name);

    if (oauthServer == null) {

      logger.log(Level.FINE, "No OAuth2 authentication server configured for {0}", path);
      return null;
    }

    if ("login".equals(action)) {

      try {

        response.sendRedirect(oauthServer.getEndUserAuthorizationRequestUri(request));
        return null;

      } catch (Exception ex) {

        logger.log(Level.SEVERE, "Could not send redirect to authorization server", ex);
      }

    } else if ("auth".equals(action)) {

      final String accessToken = oauthServer.getAccessToken(request);
      final SecurityContext superUserContext = SecurityContext.getSuperUserInstance();

      if (accessToken != null) {

        logger.log(Level.FINE, "Got access token {0}", accessToken);
        // securityContext.setAttribute("OAuthAccessToken", accessToken);

        String value = oauthServer.getCredential(request);
        logger.log(Level.FINE, "Got credential value: {0}", new Object[] {value});

        if (value != null) {

          PropertyKey credentialKey = oauthServer.getCredentialKey();

          Principal user = AuthHelper.getPrincipalForCredential(credentialKey, value);

          if (user == null && userAutoCreate) {

            user =
                RegistrationResource.createUser(
                    superUserContext, credentialKey, value, true, userClass);
          }

          if (user != null) {

            AuthHelper.doLogin(request, user);
            HtmlServlet.setNoCacheHeaders(response);

            try {

              logger.log(Level.FINE, "Response status: {0}", response.getStatus());

              response.sendRedirect(oauthServer.getReturnUri());

            } catch (IOException ex) {

              logger.log(
                  Level.SEVERE,
                  "Could not redirect to {0}: {1}",
                  new Object[] {oauthServer.getReturnUri(), ex});
            }
            return user;
          }
        }
      }
    }

    try {

      response.sendRedirect(oauthServer.getErrorUri());

    } catch (IOException ex) {

      logger.log(
          Level.SEVERE,
          "Could not redirect to {0}: {1}",
          new Object[] {oauthServer.getReturnUri(), ex});
    }

    return null;
  }
Example #18
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    // 设定请求开始时间
    FilterHelpers.getRequestTime(req);

    if (request.getAttribute(alreadyFilteredAttributeName) != null || shouldNotFilter(req)) {
      // Proceed without invoking this filter...
      chain.doFilter(request, response);
    } else {
      // Do invoke this filter...
      request.setAttribute(alreadyFilteredAttributeName, Boolean.TRUE);
      CharsetDetectRequestWrapper reqWrapper = new CharsetDetectRequestWrapper(req);
      boolean gzip = false;
      // 是否启用GZip压缩
      if (enableGZip) {
        String encoding = req.getHeader("Accept-Encoding");
        if (encoding != null && encoding.contains("gzip")) {
          gzip = true;
        }
      }
      BufferedResponseWrapper resWrapper = new BufferedResponseWrapper(res, gzip);
      try {
        // XXX: 生成traceId,需要请求_traceId的参数,所以必须放到CharsetEncodingHandler后面
        fillTraceContext(reqWrapper);
        chain.doFilter(reqWrapper, resWrapper);
        if (TraceContext.get().isColor()) {
          Cookie cookie = new Cookie("_color", "1");
          cookie.setMaxAge(3600);
          cookie.setPath("/");
          resWrapper.addCookie(cookie);
        }
      } catch (Exception e) {
        LOG.error("{}", req.getRequestURL(), e);
        resWrapper.setStatus(500);
        // 这里把异常抛出去,针对服务端异常,接入层nginx可以统计到,否则就统计不到
        throw new ServletException(
            req.getRequestURL() + ", message: " + e.getMessage(), e.getCause());
      } finally {
        request.removeAttribute(alreadyFilteredAttributeName);
        try {
          if (resWrapper.getLocation() != null) {
            res.sendRedirect(resWrapper.getLocation());
          } else {
            setContentType(res);
            try {
              copyResponse(res, resWrapper);
            } catch (Exception e) {
              long cost = FilterHelpers.getCostTime(req);
              LOG.error("{}, cost={}ms", req.getRequestURL(), cost, e);
            }
          }
        } finally {
          TraceContext c = TraceContext.get();
          TraceContext.remove();
          // 染色日志发送到总线上
          if (c.isColor()) {
            sendTrace(req, c, resWrapper);
          }
          // 统计页面状态信息
          PageStatusReporter.getInstance().stat(req, c.getCost(), res.getStatus(), c.isSpider());
        }
      }
    }
  }
 /**
  * Get the http status code of the response, 200, 404, etc.
  *
  * @return
  */
 public int getResponseStatusCode() {
   return response.getStatus();
 }
 @Override
 public int getStatus() {
   return wrap.getStatus();
 }