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.poscoict.license.security.AjaxSessionTimeoutFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    if (isAjaxRequest(req)) {
        try {//from   w  w w. j  a  v  a  2s.c o m
            String user = (String) req.getSession().getAttribute("USER_NO");
            if (user == null) {
                throw new AccessDeniedException(" ");
            } else {
                chain.doFilter(req, res);
            }
        } catch (AccessDeniedException e) {
            System.out.println(e.getMessage());
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
        } catch (AuthenticationException e) {
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        chain.doFilter(req, res);
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.IpAddressFilter.java

/**
 * {@inheritDoc}/*from   w w  w .j  a  va2 s. c o  m*/
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *    javax.servlet.FilterChain)
 */
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

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

    if (!isAllowed(request)) {
        // send 404 to hide the existence of the resource
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    chain.doFilter(request, response);
}

From source file:jp.co.opentone.bsol.linkbinder.view.filter.UploadFileFilter.java

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

    // ????/*w  w w  .  ja v  a2 s .  c  o m*/
    if (!(req instanceof HttpServletRequest)) {
        chain.doFilter(req, res);
        return;
    }

    HttpServletRequest httpReq = (HttpServletRequest) req;
    // ??????????
    if (!ServletFileUpload.isMultipartContent(httpReq)) {
        chain.doFilter(req, res);
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    factory.setSizeThreshold(thresholdSize);
    sfu.setSizeMax(maxSize); //
    sfu.setHeaderEncoding(req.getCharacterEncoding());

    try {
        @SuppressWarnings("unchecked")
        Iterator<FileItem> ite = sfu.parseRequest(httpReq).iterator();
        List<String> keys = new ArrayList<String>();
        List<String> names = new ArrayList<String>();
        List<String> fieldNames = new ArrayList<String>();
        List<Long> fileSize = new ArrayList<Long>();

        while (ite.hasNext()) {
            String name = null;
            FileItem item = ite.next();

            // ????
            if (!(item.isFormField())) {
                name = item.getName();
                name = name.substring(name.lastIndexOf('\\') + 1);
                if (StringUtils.isEmpty(name)) {
                    continue;
                }
                File f = null;
                // CHECKSTYLE:OFF
                // ??????????.
                while ((f = new File(createTempFilePath())).exists()) {
                }
                // CHECKSTYLE:ON
                if (!validateByteLength(name, maxFilenameLength, minFilenameLength)) {
                    // ????
                    names.add(name);
                    keys.add(UploadedFile.KEY_FILENAME_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (item.getSize() == 0) {
                    // 0
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_ZERO);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else if (maxFileSize > 0 && item.getSize() > maxFileSize) {
                    // ?
                    // ?0??????Validation
                    names.add(name);
                    keys.add(UploadedFile.KEY_SIZE_OVER);
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                } else {
                    item.write(f);
                    names.add(name);
                    keys.add(f.getName());
                    fieldNames.add(item.getFieldName());
                    fileSize.add(item.getSize());
                }
                f.deleteOnExit();
            }
        }

        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_OK);
        result.setNames(names.toArray(new String[names.size()]));
        result.setKeys(keys.toArray(new String[keys.size()]));
        result.setFieldNames(fieldNames.toArray(new String[fieldNames.size()]));
        result.setFileSize(fileSize.toArray(new Long[fileSize.size()]));
        writeResponse(req, res, result);
    } catch (Exception e) {
        e.printStackTrace();
        // 
        UploadFileFilterResult result = new UploadFileFilterResult();
        result.setResult(UploadFileFilterResult.RESULT_NG);
        writeResponse(req, res, result);
    }
}

From source file:com.appeligo.search.entity.SetPermissionsInViewFilter.java

/**
 * // ww  w. j av a  2  s .com
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    User user = null;

    if (request instanceof HttpServletRequest) {
        String username = ((HttpServletRequest) request).getRemoteUser();
        if (username != null) {
            user = User.findByUsername(username);
        }
    }
    Permissions.setCurrentUser(user);
    try {
        chain.doFilter(request, response);
    } catch (ServletException se) {
        String message = se.toString();
        if (se.getRootCause() != null) {
            message = se.getRootCause().toString();
        }
        if (message != null && ((message.indexOf("ClientAbortException") >= 0)
                || (message.indexOf("Connection reset by peer") >= 0))) {
            log.warn(message);
        } else {
            if (printFullExceptions) {
                log.error("Caught servlet exception:");
                if (se.getRootCause() != null) {
                    log.error(message, se.getRootCause());
                } else {
                    log.error(message, se);
                }
            } else {
                log.error(message);
            }
            throw se;
        }
    } catch (Throwable t) {
        if (printFullExceptions) {
            log.error(t.getMessage(), t);
        } else {
            log.error(t.toString());
        }
        throw new ServletException(t);
    } finally {
        Permissions.setCurrentUser(null);
    }
}

From source file:org.intalio.tempo.web.LoginFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        if (req.getRequestURI().endsWith("/login.htm") || req.getRequestURI().endsWith("/login")) {
            // don't protect login page
            chain.doFilter(request, response);
            return;
        }/*  ww w.  ja v  a  2 s  .  co  m*/

        String secureSession = LoginController.getSecureRandomSession(req);
        String secureCookie = LoginController.getSecureRandomCookie(req);
        if (secureSession != null) {
            if (secureSession.equals(secureCookie)) {
                // already authenticated
                chain.doFilter(request, response);
                return;
            }
        }

        WebApplicationContext context = WebApplicationContextUtils
                .getRequiredWebApplicationContext(req.getSession().getServletContext());
        LoginController login = (LoginController) context.getBean("loginController");
        if (login == null)
            throw new IllegalStateException("Missing 'loginController' object in Spring webapp context");

        User user = login.getCurrentUser(req);
        if (user == null) {
            // authentication failed or not available
            LOG.info("User not logged in, redirecting to login page: " + login.getLoginPageURL());
            LoginController.setRedirectAfterLoginCookie(resp, req.getRequestURI());
            resp.sendRedirect(login.getLoginPageURL());
        } else {
            // authenticated: synchronize secure random
            if (secureCookie != null) {
                LoginController.setSecureRandomSession(req, secureCookie);
            } else {
                LoginController.generateSecureRandom(req, resp);
            }
            ApplicationState state = login.getApplicationState(req);
            if (state != null) {
                state.setCurrentUser(user);
            }
            chain.doFilter(request, response);
        }
    } else {
        LOG.warn("ServletRequest was not HttpServletRequest; ignoring request.");
    }
}

From source file:ar.com.zauber.commons.web.filter.webkit.WebKitContentTypeFilter.java

/**
 * @see OncePerRequestFilter#doFilterInternal(HttpServletRequest,
 *      HttpServletResponse, FilterChain)
 *///from w  ww  .j ava  2s.  c om
@Override
protected final void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain filterChain) throws ServletException, IOException {
    Validate.notNull(response);
    String userAgent = request.getHeader(USER_AGENT_HEADER);
    if (userAgent != null && userAgent.contains(USER_AGENT_APPLE_WEB_KIT) && wrongMediaType(request)) {
        // si es web kit y tiene el orden de media types desordenados:
        HttpServletRequest touchedRequest = new WebkitHttpServletRequestWrapper(request);
        filterChain.doFilter(touchedRequest, response);
    } else {
        // para cualquier otro
        filterChain.doFilter(request, response);
    }
}

From source file:jp.xet.uncommons.web.HtmlCompressionFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {
    OutputStreamResponseWrapper wrappedResponse = new OutputStreamResponseWrapper(response);

    filterChain.doFilter(request, wrappedResponse);

    ByteArrayOutputStream baos = wrappedResponse.getRealOutputStream();

    if (enabled && Strings.nullToEmpty(response.getContentType()).startsWith("text/html")) {
        HtmlCompressor compressor = new HtmlCompressor();
        compressor.setEnabled(enabled);/*  w  w  w.j av  a  2 s  . co  m*/
        compressor.setRemoveComments(removeComments);
        compressor.setRemoveMultiSpaces(removeMultiSpaces);
        compressor.setRemoveIntertagSpaces(removeIntertagSpaces);
        compressor.setRemoveQuotes(removeQuotes);
        compressor.setCompressJavaScript(compressJavaScript);
        compressor.setCompressCss(compressCss);
        compressor.setYuiJsNoMunge(yuiJsNoMunge);
        compressor.setYuiJsPreserveAllSemiColons(yuiJsPreserveAllSemiColons);
        compressor.setYuiJsDisableOptimizations(yuiJsDisableOptimizations);
        compressor.setYuiJsLineBreak(yuiJsLineBreak);
        compressor.setYuiCssLineBreak(yuiCssLineBreak);

        PrintWriter writer = null;
        try {
            String compressed = compressor.compress(baos.toString());
            response.setContentLength(compressed.length());
            writer = response.getWriter();
            writer.write(compressed);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    } else if (baos != null) {
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(baos.toByteArray());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }
}

From source file:com.ait.tooling.server.core.servlet.filter.HeaderInjectorFilter.java

@Override
public void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    for (IHeaderInjector injector : getInjectors()) {
        if (null != injector) {
            try {
                injector.inject(request, response);
            } catch (Throwable t) {
                logger.error("Could not inject headers " + injector.getClass().getName(), t);
            }/*  w  w  w .  ja  va 2  s  . c o  m*/
        }
    }
    chain.doFilter(request, response);
}

From source file:com.idega.servlet.filter.CacheFilter.java

@Override
public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain chain)
        throws ServletException {
    HttpServletRequest request = (HttpServletRequest) sRequest;
    HttpServletResponse response = (HttpServletResponse) sResponse;

    if (cacheRequest(request, response)) {
        super.doFilter(sRequest, sResponse, chain);
    } else {/* w ww .  j  a  v  a 2s .  c om*/
        try {
            chain.doFilter(sRequest, sResponse);
        } catch (IOException e) {
            throw new ServletException(e);
        }
    }
}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (!isHttp(request, response)) {
        return;// w ww.j  a  va 2 s.  com
    }

    Tuple2<Mapping, String> mapped = mapUrlProxyToHidden(request);
    if (mapped.isNull()) {
        chain.doFilter(request, response);
        return;
    }

    executeRequest(response, mapped.e1, mapped.e2, ((HttpServletRequest) request));
}