Example usage for javax.servlet FilterChain doFilter

List of usage examples for javax.servlet FilterChain doFilter

Introduction

In this page you can find the example usage for javax.servlet FilterChain doFilter.

Prototype

public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException;

Source Link

Document

Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked.

Usage

From source file:eionet.gdem.web.filters.SetCharacterEncodingFilter.java

/**
 * Select and set (if specified) the character encoding to be used to interpret request parameters for this request.
 *
 * @param request/*from ww  w.j a va2s.c  o  m*/
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param chain
 *            The filter chain we are processing
 *
 * @exception IOException
 *                if an input/output error occurs
 * @exception ServletException
 *                if a servlet error occurs
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
        String encoding = selectEncoding(request);
        if (encoding != null)
            request.setCharacterEncoding(encoding);
    }

    // Pass control on to the next filter
    try {
        chain.doFilter(request, response);
    } catch (Exception e) {
        // Logging unhandled exception
        LOGGER.error("Unhandled exception caught", e);
        throw new ServletException(e);
    }

}

From source file:com.mtgi.analytics.servlet.BehaviorTrackingFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    //wrap the response so that we can intercept response status if the application
    //sets it./*from w  w w  .ja  va2 s .  c om*/
    BehaviorTrackingResponse btr = new BehaviorTrackingResponse((HttpServletResponse) response);
    BehaviorEvent event = delegate.start(request);
    try {
        chain.doFilter(request, btr);

        //log response codes.
        EventDataElement data = event.getData();
        data.add("response-status", btr.status);
        data.add("response-message", btr.message);

        //if an error code is being sent back, populate the 'error' field of the event with relevant info.
        if (btr.status != null && btr.status >= 400)
            event.setError(btr.status + ": " + btr.message);

    } catch (Throwable error) {
        //log exception messages to event data.
        handleServerError(event, error);
    } finally {
        delegate.stop(event);
    }
}

From source file:com.surfs.storage.web.filter.LoginFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    String uriStr = req.getRequestURI();
    String path = req.getContextPath();
    System.out.println(uriStr);/*from w  ww . j  av a2  s.  co m*/
    if (excludes_Pattern != null) {
        for (Pattern exclude_Pattern : excludes_Pattern) {
            if (exclude_Pattern.matcher(uriStr).find()) {
                chain.doFilter(request, response);
                return;
            }
        }
    }

    Object user = req.getSession().getAttribute("user");
    if (user == null) {
        resp.sendRedirect(path + "/home.jsp?status=access_error");
        return;
    }
    chain.doFilter(request, response);
}

From source file:eu.freme.broker.tools.internationalization.EInternationalizationFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    if (!(req instanceof HttpServletRequest) || !(res instanceof HttpServletResponse)) {
        chain.doFilter(req, res);
        return;// w  w w.j  a  va  2  s. co m
    }

    HttpServletRequest httpRequest = (HttpServletRequest) req;
    HttpServletResponse httpResponse = (HttpServletResponse) res;

    if (httpRequest.getMethod().equals("OPTIONS")) {
        chain.doFilter(req, res);
        return;
    }

    String uri = httpRequest.getRequestURI();
    for (Pattern pattern : endpointBlacklistRegex) {
        if (pattern.matcher(uri).matches()) {
            chain.doFilter(req, res);
            return;
        }
    }

    String informat = getInformat(httpRequest);
    String outformat = getOutformat(httpRequest);

    if (outformat != null && (informat == null || !outformat.equals(informat))) {
        Exception exception = new BadRequestException("Can only convert to outformat \"" + outformat
                + "\" when informat is also \"" + outformat + "\"");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (outformat != null && !outputFormats.contains(outformat)) {
        Exception exception = new BadRequestException("\"" + outformat + "\" is not a valid output format");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    if (informat == null) {
        chain.doFilter(req, res);
        return;
    }

    boolean roundtripping = false;
    if (outformat != null) {
        roundtripping = true;
        logger.debug("convert from " + informat + " to " + outformat);
    } else {
        logger.debug("convert input from " + informat + " to nif");
    }

    // do conversion of informat to nif
    // create BodySwappingServletRequest

    String inputQueryString = req.getParameter("input");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try (InputStream requestInputStream = inputQueryString == null ? /*
                                                                     * read
                                                                     * data
                                                                     * from
                                                                     * request
                                                                     * body
                                                                     */req.getInputStream()
            : /*
              * read data from query string input
              * parameter
              */new ReaderInputStream(new StringReader(inputQueryString), "UTF-8")) {
        // copy request content to buffer
        IOUtils.copy(requestInputStream, baos);
    }

    // create request wrapper that converts the body of the request from the
    // original format to turtle
    Reader nif;

    byte[] baosData = baos.toByteArray();
    if (baosData.length == 0) {
        Exception exception = new BadRequestException("No input data found in request.");
        exceptionHandlerService.writeExceptionToResponse(httpRequest, httpResponse, exception);
        return;
    }

    ByteArrayInputStream bais = new ByteArrayInputStream(baosData);
    try {
        nif = eInternationalizationApi.convertToTurtle(bais, informat.toLowerCase());
    } catch (ConversionException e) {
        logger.error("Error", e);
        throw new InternalServerErrorException("Conversion from \"" + informat + "\" to NIF failed");
    }

    BodySwappingServletRequest bssr = new BodySwappingServletRequest((HttpServletRequest) req, nif,
            roundtripping);

    if (!roundtripping) {
        chain.doFilter(bssr, res);
        return;
    }

    ConversionHttpServletResponseWrapper dummyResponse;

    try {
        dummyResponse = new ConversionHttpServletResponseWrapper(httpResponse, eInternationalizationApi,
                new ByteArrayInputStream(baosData), informat, outformat);

        chain.doFilter(bssr, dummyResponse);

        ServletOutputStream sos = httpResponse.getOutputStream();

        byte[] data = dummyResponse.writeBackToClient();
        httpResponse.setContentLength(data.length);
        sos.write(data);
        sos.flush();
        sos.close();

    } catch (ConversionException e) {
        e.printStackTrace();
        // exceptionHandlerService.writeExceptionToResponse((HttpServletResponse)res,new
        // InternalServerErrorException());
    }
}

From source file:examples.jsf.util.RequestDumpFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (config == null) {
        return;//from   w  ww  .j  a  va  2  s .co m
    }
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        log.debug(LF + LF + "** before *****************************************: " + gerServletPath(request)
                + LF + dumpRequest(hrequest));
        try {
            chain.doFilter(request, response);
        } finally {
            final StringBuffer sb = new StringBuffer();
            RequestDumpUtil.dumpRequestAttributes(sb, hrequest, LF, INDENT);
            RequestDumpUtil.dumpCookies(sb, hrequest, LF, INDENT);
            RequestDumpUtil.dumpSessionAttributes(sb, hrequest, LF, INDENT);
            RequestDumpUtil.dumpContextAttributes(sb, config.getServletContext(), LF, INDENT);
            log.debug(LF + LF + "** after *****************************************: " + gerServletPath(request)
                    + LF + sb.toString());
        }
    } else {
        chain.doFilter(request, response);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.filters.CachingResponseFilter.java

private void produceCacheableResponse(HttpServletRequest req, HttpServletResponse resp, FilterChain chain,
        String etag) throws IOException, ServletException {
    log.debug("Produce cacheable response: etag='" + etag + "'");
    resp.addHeader("ETag", etag);
    resp.addHeader("Vary", "Accept-Language");
    chain.doFilter(req, resp);
}

From source file:com.ateam.login.UserSession.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) request).getSession();
    String redirectUrl = (String) session.getAttribute(LAST_URL_REDIRECT_KEY);
    if (isAuthenticated() && (redirectUrl != null) && !redirectUrl.isEmpty()) {
        session.removeAttribute(LAST_URL_REDIRECT_KEY);
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendRedirect(redirectUrl);//from w w  w. j a v  a 2  s  .  c  om
    } else {
        chain.doFilter(request, response);
    }
}

From source file:br.com.edo.atmlist.config.CsrfHeaderFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (csrf != null) {
        Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
        String token = csrf.getToken();
        if (cookie == null || token != null && !token.equals(cookie.getValue())) {
            cookie = new Cookie("XSRF-TOKEN", token);
            cookie.setPath("/");
            response.addCookie(cookie);/* w  ww  .j a v a 2  s .c  om*/
        }
    }
    filterChain.doFilter(request, response);
}

From source file:com.appdynamics.cloudfoundry.appdservicebroker.BrokerApiVersionFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {

    String header = request.getHeader(HEADER);
    if (header == null) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;// www . j a va 2 s  .  co  m
    }

    Integer[] parsed = parse(header);
    Version version = Version.forIntegers(parsed[0], parsed[1]);
    if (!version.satisfies(VALID_VERSIONS)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    filterChain.doFilter(request, response);
}

From source file:io.jmnarloch.spring.request.correlation.filter.RequestCorrelationFilter.java

/**
 * {@inheritDoc}//from w w w  .j  a  va  2 s .  c  o m
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
        doHttpFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
    } else {
        // otherwise just pass through
        chain.doFilter(request, response);
    }
}