Example usage for javax.servlet Filter doFilter

List of usage examples for javax.servlet Filter doFilter

Introduction

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

Prototype

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

Source Link

Document

The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.

Usage

From source file:de.micromata.genome.tpsb.httpmockup.MockFilterChain.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse resp)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) req;
    String uri = hreq.getRequestURI();
    String localUri = uri;/*from   w  ww  .  j a va  2 s . com*/
    if (StringUtils.isNotBlank(hreq.getServletPath()) && StringUtils.isNotBlank(hreq.getPathInfo()) == true) {
        localUri = hreq.getServletPath() + hreq.getPathInfo();
    }
    final MockFiltersConfig fc = this.mockupServletContext.getFiltersConfig();

    this.filterIndex = fc.getNextFilterMapDef(localUri, this.filterIndex, this.dispatcherFlag);
    if (this.filterIndex == -1) {
        this.mockupServletContext.serveServlet((HttpServletRequest) req, (HttpServletResponse) resp);
        return;
    }
    final Filter f = fc.getFilterMapping().get(this.filterIndex).getFilterDef().getFilter();
    ++this.filterIndex;
    if (log.isDebugEnabled() == true) {
        log.debug("Filter filter: " + f.getClass().getName());
    }
    f.doFilter(req, resp, this);

}

From source file:ch.entwine.weblounge.kernel.security.SecurityFilter.java

/**
 * {@inheritDoc}/*from   w  ww.  ja v a  2s  .  co  m*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    Site site = null;
    if (!(request instanceof HttpServletRequest)) {
        logger.warn("Received plain servlet request and don't know what to do with it");
        return;
    }

    // Try to map the request to a site
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    URL url = UrlUtils.toURL(httpRequest, false, false);
    site = sites.findSiteByURL(url);
    if (site == null) {
        logger.debug("Request for {} cannot be mapped to any site", httpRequest.getRequestURL());
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Set the site in the security service
    try {
        logger.trace("Request to {} mapped to site '{}'", httpRequest.getRequestURL(), site.getIdentifier());
        securityService.setSite(site);

        // Select appropriate security filter and apply it
        Filter siteSecurityFilter = siteFilters.get(site);
        if (siteSecurityFilter != null) {
            logger.trace("Security for '{}' is handled by site specific security configuration");
            siteSecurityFilter.doFilter(request, response, chain);
        } else {
            logger.trace("Security for '{}' is handled by default security configuration");
            defaultSecurityFilter.doFilter(request, response, chain);
        }
    } finally {
        securityService.setSite(null);
    }

}

From source file:edu.northwestern.bioinformatics.studycalendar.security.plugin.cas.CasAuthenticationSystemTest.java

public void testInitializeLogoutFilter() throws Exception {
    doValidInitialize();/*from   w ww.ja va 2 s.co m*/
    Filter actual = getSystem().logoutFilter();
    assertTrue("Wrong filter type", actual instanceof LogoutFilter);
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/auth/logout");
    // Expect filter chain not continued
    FilterChain filterChain = registerMockFor(FilterChain.class);
    replayMocks();
    actual.doFilter(request, new MockHttpServletResponse(), filterChain);
    verifyMocks();
}

From source file:info.magnolia.cms.filters.MultipartRequestFilterTest.java

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);/*www .j  a  v a 2 s.  co m*/
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    req.setAttribute(isA(String.class), isA(Boolean.class));
    expect(req.getContentType()).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getHeader("Content-Type")).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
    expect(req.getQueryString()).andReturn("").anyTimes();
    expect(req.getContentLength()).andReturn(Integer.valueOf((int) multipart.getContentLength())).anyTimes();
    expect(req.getInputStream()).andReturn(servletInputStream);
    req.setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            final Object[] args = getCurrentArguments();
            checkMultipartForm((MultipartForm) args[1], expectedDocumentType);
            return null;
        }
    });
    webCtx.pop();

    replay(req, res, filterChain, webCtx);
    filter.doFilter(req, res, filterChain);
    verify(req, res, filterChain, webCtx);
}

From source file:info.magnolia.cms.filters.MultipartRequestFilterTempFileDeletionTest.java

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    //GIVEN/*from   www .j a v  a 2 s. c  o  m*/
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    //WHEN
    req.setAttribute(isA(String.class), isA(Boolean.class));
    when(req.getContentType()).thenReturn(multipart.getContentType());
    when(req.getHeader("Content-Type")).thenReturn(multipart.getContentType());
    when(req.getCharacterEncoding()).thenReturn("UTF-8");
    when(req.getQueryString()).thenReturn("");
    when(req.getContentLength()).thenReturn(Integer.valueOf((int) multipart.getContentLength()));
    when(req.getInputStream()).thenReturn(servletInputStream);

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final Object args = invocation.getArguments()[1];
            checkMultipartForm((MultipartForm) args, expectedDocumentType);
            webCtx.setPostedForm((MultipartForm) args);
            return null;
        }
    }).when(req).setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    when(file.exists()).thenReturn(true);

    webCtx.pop();

    //THEN
    filter.doFilter(req, res, filterChain);
}

From source file:org.apache.wiki.WikiSessionTest.java

/**
 * "Scaffolding" method that runs the session security filter on a mock request. We do this by creating a
 * complete mock servlet context and filter chain, and running the request through it. 
 * @param engine the wiki engine/*  www. j a  va2s  .c o  m*/
 * @param request the mock request to pass itnto the 
 * @throws ServletException
 * @throws IOException
 */
private static void runSecurityFilter(WikiEngine engine, HttpServletRequest request)
        throws ServletException, IOException {
    // Create a mock servlet context and stash the wiki engine in it
    ServletContext servletCtx = new MockServletContext("JSPWiki");
    servletCtx.setAttribute("org.apache.wiki.WikiEngine", engine);

    // Create a mock filter configuration and add the servlet context we just created
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.setFilterName("WikiServletFilter");
    filterConfig.setServletContext(servletCtx);

    // Create the security filter and run the request  through it
    Filter filter = new WikiServletFilter();
    MockFilterChain chain = new MockFilterChain();
    chain.addFilter(filter);
    Servlet servlet = new MockServlet();
    chain.setServlet(servlet);
    filter.init(filterConfig);
    filter.doFilter(request, null, chain);
}

From source file:org.impalaframework.web.servlet.invocation.InvocationChain.java

public void invoke(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    if (filterCount < filters.size()) {
        int currentCount = filterCount;
        filterCount++;/* w  w w . java 2 s  . co m*/

        Filter filter = filters.get(currentCount);

        if (logger.isDebugEnabled())
            logger.debug("Getting filter for " + currentCount + ObjectUtils.identityToString(filter));

        filter.doFilter(request, response, this);
    } else if (servlet != null) {
        servlet.service(request, response);
    } else {
        incomplete = true;
    }
}

From source file:org.impalaframework.web.servlet.invoker.ServletInvokerUtils.java

/**
 * Used to invoke either the <code>HttpServiceInvoker.invoke</code> or <code>HttpServlet.service</code>, depending on the class of target.
 * In both cases, the request and response are passed through.
 * //  w w  w.  j  ava 2s  .  c  o  m
 * @param target either an instance of <code>HttpServiceInvoker</code> or <code>HttpServlet</code>.
 * @param filterChain instanceof <code>FilterChain</code>. Applies only if target is instance of <code>Filter</code>
 */
public static void invoke(Object target, HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (target instanceof HttpServiceInvoker) {
        HttpServiceInvoker invoker = (HttpServiceInvoker) target;
        invoker.invoke(request, response, null);
    } else if (target instanceof Servlet) {
        Servlet servlet = (Servlet) target;
        servlet.service(request, response);
    } else if (target instanceof Filter) {
        Filter filter = (Filter) target;
        filter.doFilter(request, response, filterChain);
    } else {
        logger.warn("invoke called with target " + (target != null) + " which is not an instance of "
                + HttpServiceInvoker.class.getSimpleName() + ", " + HttpServlet.class.getSimpleName() + " or "
                + Filter.class.getName());
    }

}

From source file:org.jasig.cas.client.util.DelegatingFilter.java

public void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain filterChain) throws IOException, ServletException {

    final String parameter = CommonUtils.safeGetParameter((HttpServletRequest) request,
            this.requestParameterName);

    if (CommonUtils.isNotEmpty(parameter)) {
        for (final Iterator iter = this.delegators.keySet().iterator(); iter.hasNext();) {
            final String key = (String) iter.next();

            if ((parameter.equals(key) && this.exactMatch) || (parameter.matches(key) && !this.exactMatch)) {
                final Filter filter = (Filter) this.delegators.get(key);
                if (log.isDebugEnabled()) {
                    log.debug("Match found for parameter [" + this.requestParameterName + "] with value ["
                            + parameter + "]. Delegating to filter [" + filter.getClass().getName() + "]");
                }//from ww  w.  j a va  2  s.  c o  m
                filter.doFilter(request, response, filterChain);
                return;
            }
        }
    }

    log.debug(
            "No match found for parameter [" + this.requestParameterName + "] with value [" + parameter + "]");

    if (this.defaultFilter != null) {
        this.defaultFilter.doFilter(request, response, filterChain);
    } else {
        filterChain.doFilter(request, response);
    }
}

From source file:org.ops4j.pax.web.service.internal.FilterTest.java

@Test
public void filterIsCalledOnUrlPattern() throws NamespaceException, ServletException, IOException {
    Servlet servlet = createMock(Servlet.class);
    servlet.init((ServletConfig) notNull());
    servlet.destroy();//from  w  w  w .j a  v  a  2 s  .  c o  m

    Filter filter = createMock(Filter.class);
    filter.init((FilterConfig) notNull());
    filter.doFilter((ServletRequest) notNull(), (ServletResponse) notNull(), (FilterChain) notNull());
    filter.destroy();

    replay(servlet, filter);

    HttpContext context = m_httpService.createDefaultHttpContext();
    m_httpService.registerServlet("/test", servlet, null, context);
    m_httpService.registerFilter(filter, new String[] { "/*" }, null, context);

    HttpMethod method = new GetMethod("http://localhost:8080/test");
    m_client.executeMethod(method);
    method.releaseConnection();

    m_httpService.unregister("/test");
    m_httpService.unregisterFilter(filter);

    verify(servlet, filter);
}