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:eu.freme.broker.tools.loggingfilter.LoggingFilter.java

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

    if (logger.isInfoEnabled()) {
        long requestId = id.incrementAndGet();
        request = new RequestWrapper(requestId, request);
        response = new ResponseWrapper(requestId, response);
    }//from   w  ww.  j a  v a 2s.  c o m
    try {
        filterChain.doFilter(request, response);
        //            response.flushBuffer();
    } finally {
        if (logger.isInfoEnabled()) {
            logRequest(request);
            logResponse((ResponseWrapper) response);
        }
    }

}

From source file:com.adobe.acs.commons.dam.impl.AssetsFolderPropertiesSupport.java

/**
 * This method is responsible for post processing POSTs to the FolderShareHandler PostOperation (:operation = dam.share.folder).
 * This method will store a whitelisted set of request parameters to their relative location off of the [sling:*Folder] node.
 *
 * Note, this is executed AFTER the OOTB FolderShareHandler PostOperation.
 *
 * At this time this method only supports single-value Strings and ignores all @typeHints.
 *
 * This method must fail fast via the accepts(...) method.
 *
 * @param servletRequest the request object
 * @param servletResponse the response object
 * @param chain the filter chain/*from  w ww. jav a2  s.c o  m*/
 * @throws IOException
 * @throws ServletException
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    final SlingHttpServletRequest request = (SlingHttpServletRequest) servletRequest;
    final SlingHttpServletResponse response = (SlingHttpServletResponse) servletResponse;

    if (!accepts(request)) {
        chain.doFilter(request, response);
        return;
    }

    log.trace("ACS AEM Commons Assets Folder Properties Support applied to POST Request");
    chain.doFilter(new AssetsFolderPropertiesSupportRequest(request, null), response);
}

From source file:testapp.web.OpenSessionInViewInterceptorFilter.java

/**
 * @see OpenSessionInViewInterceptor//from ww  w  .  j  ava2  s. co m
 * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    log.debug("###### Opening session for request ########");
    OpenSessionInViewInterceptor interceptor = (OpenSessionInViewInterceptor) getApplicationContext()
            .getBean(getInterceptorBeanName());
    WebRequest webRequest = new ServletWebRequest((HttpServletRequest) request);
    interceptor.preHandle(webRequest);
    try {
        chain.doFilter(request, response);
        interceptor.postHandle(webRequest, null);
    } finally {
        interceptor.afterCompletion(webRequest, null);
        log.debug("############ Session closed ###########");
    }
}

From source file:com.mnt.base.web.filter.WebAccessRouterFilter.java

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

    WebUtils.setupContext(req, resp);//from w w  w  .j a va2 s . c  o  m

    if (!WebUtils.checkAuth(req, resp)) {
        return;
    }

    if (req.getRequestURI().matches(SKIPPABLE_RES)) {
        chain.doFilter(request, response);
        return;
    }

    String requestUri = req.getRequestURI();
    if (!webActionControllerManager.dispatchRequest(requestUri, req.getMethod(),
            new PageResponseHandler(resp, BaseConfiguration.getResponseContentType()))) {
        chain.doFilter(request, response);
    }

    WebUtils.clearContext();
}

From source file:com.sonymobile.jenkins.plugins.kerberossso.KerberosSSOFilter.java

/**
 * Filters every request made to the server to determine and set authentication of the user.
 * 1. Find out if the user is already authenticated (by checking the securityContext).
 * 2. Otherwise, authenticate the user from his Kerberos ticket and,
 * 3. Set him as authenticated by setting a new securityContext.
 * During the negotiation process used by Spnego, none of the filters after this one in the chain
 * will be allowed to execute./* w w  w . j a v a  2 s. c om*/
 *
 * @param request the Servlet request to serve
 * @param response the Servlet response to serve
 * @param chain the filter chain determining which filter will execute after ours.
 * @throws IOException if redirection goes wrong or if another filter in the chain fails.
 * @throws ServletException if the authentication fails.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if ((!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse))
            || containsBypassHeader(request)) {
        chain.doFilter(request, response);
        return;
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String userContentPath = httpRequest.getContextPath() + "/userContent";

    if (httpRequest.getRequestURI().startsWith(userContentPath)) {
        chain.doFilter(request, response);
        return;
    }

    SpnegoHttpServletResponse spnegoHttpResponse = new SpnegoHttpServletResponse(
            (HttpServletResponse) response);

    if (PluginImpl.getInstance().isRedirectEnabled()
            && !httpRequest.getLocalAddr().equals(httpRequest.getRemoteAddr())) {
        // If Local and Remote address is the same, the user is Localhost and shouldn't be redirected.

        String requestedDomain = new URL(httpRequest.getRequestURL().toString()).getHost();
        String requestedURL = httpRequest.getRequestURL().toString();
        if (!requestedDomain.toLowerCase().contains(PluginImpl.getInstance().getRedirect().toLowerCase())) {

            String redirect = requestedURL.replaceFirst(requestedDomain,
                    requestedDomain + "." + PluginImpl.getInstance().getRedirect());
            spnegoHttpResponse.sendRedirect(redirect);
        }
    }

    // A user is "always" authenticated by Jenkins as anonymous when not authenticated in any other way.
    if (SecurityContextHolder.getContext().getAuthentication() == null
            || !SecurityContextHolder.getContext().getAuthentication().isAuthenticated()
            || Functions.isAnonymous()) {
        Functions.advertiseHeaders((HttpServletResponse) response); //Adds headers for CLI

        Principal principal;

        try {
            principal = authenticator.authenticate(httpRequest, spnegoHttpResponse);
        } catch (LoginException e) {
            logger.log(Level.WARNING, "Failed to fetch spnegoPrincipal name for user");
            chain.doFilter(request, spnegoHttpResponse);
            return;
        }

        // Expecting negotiation
        if (principal == null) {
            return;
        }

        String principalName = principal.getName();

        if (principalName.contains("@")) {
            principalName = principalName.substring(0, principalName.indexOf("@"));
        }

        try {
            SecurityRealm realm = Jenkins.getInstance().getSecurityRealm();
            UserDetails userDetails = realm.loadUserByUsername(principalName);
            Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
                    userDetails.getPassword(), userDetails.getAuthorities());

            ACL.impersonate(authToken);
            if (Jenkins.getVersion().isNewerThan(new VersionNumber("1.568"))) {
                try {
                    Method fireLoggedIn = SecurityListener.class.getMethod("fireLoggedIn", String.class);
                    fireLoggedIn.invoke(null, userDetails.getUsername());
                } catch (Exception e) {
                    logger.log(Level.WARNING, "Failed to invoke fireLoggedIn method", e);
                }
            }
            logger.log(Level.FINE, "Authenticated user {0}", userDetails.getUsername());
        } catch (UsernameNotFoundException e) {
            logger.log(Level.WARNING, "Username {0} not registered by Jenkins", principalName);
        } catch (NullPointerException e) {
            logger.log(Level.WARNING, "User authentication failed");
            e.printStackTrace();
        } catch (DataAccessException e) {
            logger.log(Level.WARNING, "No access to user database");
            e.printStackTrace();
        }
    }

    chain.doFilter(request, response);
}

From source file:org.ovirt.engine.api.common.security.CSRFProtectionFilter.java

private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // If protection is globally disabled then we don't need to do anything else, jump directly to the next filter
    // in the chain:
    boolean enabled = Config.getValue(ConfigValues.CSRFProtection);
    if (!enabled) {
        chain.doFilter(request, response);
        return;/*  w  ww  .  ja va 2  s  .co m*/
    }

    // If there is already a session then we need to process it immediately, before letting other filters or the
    // application see or touch the request:
    HttpSession session = request.getSession(false);
    if (session != null) {
        doFilterExistingSession(session, request, response, chain);
        return;
    }

    // At this point we know that protection is globally enabled, and that there isn't a session already created. So
    // we should first let the other filters and the application do their work. As a result a new session may be
    // created. In that case we need to check if protection has been requested for that session and store the result
    // for use in future requests.
    try {
        chain.doFilter(request, response);
    } finally {
        session = request.getSession(false);
        if (session != null) {
            enabled = isProtectionRequested(request);
            session.setAttribute(ENABLED_ATTRIBUTE, enabled);
        }
    }
}

From source file:edu.vt.middleware.servlet.filter.RequestDumperFilter.java

/** {@inheritDoc} */
@SuppressWarnings(value = "unchecked")
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    if (this.config == null) {
        return;//from ww w .  j  a v a2  s.co  m
    }

    // Just pass through to next filter if we're not at TRACE level
    if (!logger.isTraceEnabled()) {
        chain.doFilter(request, response);
        return;
    }

    // Create a variable to hold the (possibly different) request
    // passed to downstream filters
    ServletRequest downstreamRequest = request;

    // Render the generic servlet request properties
    final StringWriter sw = new StringWriter();
    final PrintWriter writer = new PrintWriter(sw);
    writer.println("Dumping request...");
    writer.println("-----------------------------------------------------");
    writer.println("REQUEST received " + Calendar.getInstance().getTime());
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");

    final Enumeration<Locale> locales = request.getLocales();
    for (int i = 0; locales.hasMoreElements(); i++) {
        if (i > 0) {
            writer.print(", ");
        }
        writer.print(locales.nextElement());
    }
    writer.println();

    final Enumeration<String> paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
        final String name = paramNames.nextElement();
        writer.print("         parameter=" + name + "=");

        final String[] values = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                writer.print(", ");
            }
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        final HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());

        Cookie[] cookies = hrequest.getCookies();
        if (cookies == null) {
            cookies = new Cookie[0];
        }
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }

        final Enumeration<String> headerNames = hrequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            final String name = headerNames.nextElement();
            final String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());

        // Create a wrapped request that contains the request body
        // and that we will pass to downstream filters
        final ByteArrayRequestWrapper wrappedRequest = new ByteArrayRequestWrapper(hrequest);
        downstreamRequest = wrappedRequest;
        writer.println(wrappedRequest.getRequestBodyAsString());
    }
    writer.println("-----------------------------------------------------");

    // Log the resulting string
    writer.flush();
    logger.trace(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(downstreamRequest, response);
}

From source file:jp.co.opentone.bsol.framework.web.filter.FeedAuthenticationFilter.java

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

    AuthUser u = authenticate(req, res);
    if (u == null) {
        res.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*ww w . j a  v  a 2  s .  c o m*/
    }
    storeAuthenticateUser(req, res, u);
    chain.doFilter(request, response);
}

From source file:be.fedict.eid.idp.webapp.XSSProtectionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    Boolean xssProtection = this.configuration.getValue(ConfigProperty.XSS_PROTECTION, Boolean.class);
    if (null != xssProtection) {
        if (xssProtection.equals(Boolean.TRUE)) {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            httpServletResponse.setHeader("X-XSS-Protection", "1; mode=block");
        }/*w  ww.j av a  2s.c  om*/
    }
    chain.doFilter(request, response);
}

From source file:com.sg.rest.filters.CorsFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    // TODO Auto-generated method stub
    HttpServletResponse response = (HttpServletResponse) resp;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Authorization");

    chain.doFilter(req, resp);
}