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:com.adobe.acs.commons.quickly.impl.QuicklyFilter.java

@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain filterChain) throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (!accepts(request)) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;/*www  . ja v a2  s.c o m*/
    }

    final BufferingResponse capturedResponse = new BufferingResponse(response);

    filterChain.doFilter(request, capturedResponse);

    // Get contents
    final String contents = capturedResponse.getContents();

    if (contents != null && StringUtils.contains(response.getContentType(), "html")) {

        final int bodyIndex = contents.indexOf("</body>");
        if (bodyIndex != -1) {

            final PrintWriter printWriter = response.getWriter();

            printWriter.write(contents.substring(0, bodyIndex));
            printWriter.write(appHTML);
            printWriter.write(contents.substring(bodyIndex));

            return;
        }
    }

    if (contents != null) {
        response.getWriter().write(contents);
    }
}

From source file:eu.delving.core.util.ThemeFilter.java

/**
 * Filter Servlet requests, putting Portal Theme and Lookup in thread local
 *
 * @param request from user// w  w w.  j a  va 2 s .  com
 * @param response to user
 * @param chain the other filters
 * @throws IOException problem
 * @throws ServletException problem
 */

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final PortalTheme portalTheme = themeHandler.getByRequest(request);
    themeThreadLocal.set(portalTheme);
    lookupThreadLocal.set(localizedFieldNames.createLookup(Arrays.asList(portalTheme.getLocaliseQueryKeys())));
    chain.doFilter(request, response);
    themeThreadLocal.remove();
    lookupThreadLocal.remove();
}

From source file:org.cfr.capsicum.server.CayenneFilter.java

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

    if (conditionExcluded != null) {
        PatternsRequestCondition excluded = conditionExcluded.getMatchingCondition(request);
        if (excluded != null) {
            filterChain.doFilter(request, response);
            return;
        }//from   w  ww  .ja va2s. co m
    }

    PatternsRequestCondition result = conditionIncluded.getMatchingCondition(request);
    if (result == null) {
        filterChain.doFilter(request, response);
        return;
    }

    RequestHandler handler = cayenneRuntime.getInstance(RequestHandler.class);
    if (handler instanceof ISessionState) {
        ((ISessionState) handler).setForceNewSession(forceNewSession);
    }

    handler.requestStart(request, response);
    try {
        filterChain.doFilter(request, response);
    } finally {
        handler.requestEnd(request, response);
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.servlets.filters.ProcessCandidacyPrintAllDocumentsFilter.java

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
        throws IOException, ServletException {
    arg2.doFilter(arg0, arg1);

    HttpServletRequest request = (HttpServletRequest) arg0;

    if ("doOperation".equals(request.getParameter("method"))
            && "PRINT_ALL_DOCUMENTS".equals(request.getParameter("operationType"))) {

        try {/*from  www  . j a  v  a2s  .c om*/
            ResponseWrapper response = (ResponseWrapper) arg1;
            // clean the response html and make a DOM document out of it
            String responseHtml = clean(response.getContent());
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(new ByteArrayInputStream(responseHtml.getBytes()));

            // alter paths of link/img tags so itext can use them properly
            patchLinks(doc, request);

            // structure pdf document
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(doc, "");
            renderer.layout();

            // create the pdf
            ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
            renderer.createPDF(pdfStream);

            // concatenate with other docs
            final Person person = (Person) request.getAttribute("person");
            final StudentCandidacy candidacy = getCandidacy(request);
            ByteArrayOutputStream finalPdfStream = concatenateDocs(pdfStream.toByteArray(), person);
            byte[] pdfByteArray = finalPdfStream.toByteArray();

            // associate the summary file to the candidacy
            associateSummaryFile(pdfByteArray, person.getStudent().getNumber().toString(), candidacy);

            // redirect user to the candidacy summary page
            response.reset();
            response.sendRedirect(buildRedirectURL(request, candidacy));

            response.flushBuffer();
        } catch (ParserConfigurationException e) {
            logger.error(e.getMessage(), e);
        } catch (SAXException e) {
            logger.error(e.getMessage(), e);
        } catch (DocumentException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:com.mirth.connect.server.MethodFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    String method = ((HttpServletRequest) req).getMethod();
    // Don't allow TRACE/TRACK requests
    if (StringUtils.equalsIgnoreCase(method, "TRACE") || StringUtils.equalsIgnoreCase(method, "TRACK")) {
        ((HttpServletResponse) res).sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else {//from  w  w w . ja v a2s  .c  o  m
        chain.doFilter(req, res);
    }
}

From source file:com.pearson.developer.xapi.proxy.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    // AJAX will preflight xAPI request with OPTIONS request without Authorization header
    if ("OPTIONS".equals(req.getMethod())) {
        chain.doFilter(request, response);
        return;/*from   www  .j  a  v a 2  s .c  o  m*/
    }

    boolean authorized = false;
    try { // decode and verify the basic auth credentials
        String authHeader = req.getHeader("Authorization");
        authHeader = authHeader.substring("Basic ".length());
        String decodedAuthHeader = new String(Base64.decodeBase64(authHeader), "UTF-8");
        String[] credentials = decodedAuthHeader.split(":");
        if (credentials.length == 2) {
            String username = credentials[0];
            String password = credentials[1];
            authorized = SessionDatabase.verify(username, password);
        }
    } catch (Exception e) {
        // do nothing
    }

    // proceed to xAPI if session was authorized
    if (authorized) {
        final String targetBasicAuth = config.getInitParameter("targetBasicAuth");

        // need to give the LRS it's expected Authorization value
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(req) {
            @Override
            public String getHeader(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    return targetBasicAuth;
                }
                return super.getHeader(name);
            }

            @Override
            public Enumeration<String> getHeaders(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    List<String> values = new ArrayList<String>();
                    values.add(targetBasicAuth);
                    return Collections.enumeration(values);
                }
                return super.getHeaders(name);
            }
        };
        chain.doFilter(requestWrapper, response);
        return;
    }

    // respond with a 401 if missing auth
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.getWriter().println("401 - Unauthorized");
}

From source file:org.meruvian.yama.webapi.interceptor.LoggedInFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    HttpSession session = req.getSession(true);
    SecurityContextImpl sci = (SecurityContextImpl) session.getAttribute(SPRING_SECURITY_CONTEXT_KEY);

    if (sci == null) {
        chain.doFilter(request, response);
        return;// w ww.ja v  a  2  s  . c  o  m
    }

    res.sendRedirect(StringUtils.join(req.getContextPath(), SecurityConfig.LOGIN_SUCCESS_URL));
}

From source file:com.ctc.storefront.filters.CartRestorationFilter.java

@Override
public void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {
    if (getUserService().isAnonymousUser(getUserService().getCurrentUser())) {
        processAnonymousUser(request, response);
    } else {/*from w  ww. j av a 2s.c  om*/
        restoreCartWithNoCode();
    }

    filterChain.doFilter(request, response);
}

From source file:edu.wisc.nexus.auth.rut.RemoteUserTestingFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    final String remoteUser = StringUtils.trimToNull(FileUtils.readFileToString(this.remoteUserFile));

    if (remoteUser != null) {
        request = new RemoteUserHttpServletRequestWrapper((HttpServletRequest) request, remoteUser);
    }/*ww  w .  j a v a2s .  c om*/

    chain.doFilter(request, response);
}

From source file:org.messic.server.facade.security.TokenManagementFilter.java

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

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    if (!requiresAuthentication(request, response)) {
        chain.doFilter(request, response);
        return;//from  w w  w .  j  av a  2s .  com
    }

    try {
        Authentication authResult = attemptAuthentication(request, response);
        SecurityContextHolder.getContext().setAuthentication(authResult);
        chain.doFilter(request, response);
    } catch (InternalAuthenticationServiceException failed) {
        logger.error("An internal error occurred while trying to authenticate the user.", failed);
        unsuccessfulAuthentication(request, response, failed);
        return;
    } catch (AuthenticationException failed) {
        // Authentication failed
        unsuccessfulAuthentication(request, response, failed);
        return;
    }

}