Example usage for javax.servlet Filter Filter

List of usage examples for javax.servlet Filter Filter

Introduction

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

Prototype

Filter

Source Link

Usage

From source file:com.xst.bigwhite.BigwhiteApplication.java

@Bean
FilterRegistrationBean corsFilter(@Value("${tagit.origin:http://localhost:8080}") String origin) {
    return new FilterRegistrationBean(new Filter() {
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
                throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            String method = request.getMethod();
            // this origin value could just as easily have come from a
            // database
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
            response.setHeader("Access-Control-Max-Age", Long.toString(60 * 60));
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin,Accept,X-Requested-With,Content-Type,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
            if ("OPTIONS".equals(method)) {
                response.setStatus(HttpStatus.OK.value());
            } else {
                chain.doFilter(req, res);
            }//w  ww  .j ava2 s. c  om
        }

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }
    });
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void faultyFilterCausesStartFailure() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    factory.addInitializers((servletContext) -> servletContext.addFilter("faulty", new Filter() {

        @Override/*from www  .  java 2s .c om*/
        public void init(FilterConfig filterConfig) throws ServletException {
            throw new ServletException("Faulty filter");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }

    }));
    this.thrown.expect(WebServerException.class);
    factory.getWebServer().start();
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration16() throws Exception {
    Filter initError = new Filter() {

        @Override/*from   w  ww .ja  va  2 s. c  o m*/
        public void init(FilterConfig filterConfig) throws ServletException {
            throw new IllegalStateException("Init error.");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // nothing
        }

        @Override
        public void destroy() {
            // nothing
        }
    };
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/foo", initError, null, null);
        fail("Expected an init failure.");
    } catch (IllegalStateException e) {
        //expected
        assertEquals("Wrong exception message.", "Init error.", e.getMessage());
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration17() throws Exception {
    Filter initError = new Filter() {

        @Override//from   www.  j av a  2  s . com
        public void init(FilterConfig filterConfig) throws ServletException {
            throw new ServletException("Init error.");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // nothing
        }

        @Override
        public void destroy() {
            // nothing
        }
    };
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/foo", initError, null, null);
        fail("Expected an init failure.");
    } catch (ServletException e) {
        //expected
        assertEquals("Wrong exception message.", "Init error.", e.getMessage());
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_RegistrationTCCL1() {
    final Set<String> filterTCCL = Collections.synchronizedSet(new HashSet<String>());
    final Set<String> servletTCCL = Collections.synchronizedSet(new HashSet<String>());
    Filter tcclFilter = new Filter() {

        @Override//w  w  w.j a v  a2s . c om
        public void init(FilterConfig filterConfig) throws ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
            filterTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }
    };
    HttpServlet tcclServlet = new HttpServlet() {

        @Override
        public void destroy() {
            super.destroy();
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        @Override
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

        private static final long serialVersionUID = 1L;

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            servletTCCL.add(Thread.currentThread().getContextClassLoader().getClass().getName());
            response.getWriter().print(Thread.currentThread().getContextClassLoader().getClass().getName());
        }

    };

    ClassLoader originalTCCL = Thread.currentThread().getContextClassLoader();
    ClassLoader dummy = new ClassLoader() {
    };
    Thread.currentThread().setContextClassLoader(dummy);
    String expected = dummy.getClass().getName();
    String actual = null;
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/tccl", tcclFilter, null, null);
        extendedHttpService.registerServlet("/tccl", tcclServlet, null, null);
        actual = requestAdvisor.request("tccl");
    } catch (Exception e) {
        fail("Unexpected exception: " + e);
    } finally {
        Thread.currentThread().setContextClassLoader(originalTCCL);
        try {
            extendedHttpService.unregister("/tccl");
            extendedHttpService.unregisterFilter(tcclFilter);
        } catch (IllegalArgumentException e) {
            // ignore
        }
    }
    assertEquals(expected, actual);
    assertEquals("Wrong filterTCCL size: " + filterTCCL, 1, filterTCCL.size());
    assertTrue("Wrong filterTCCL: " + filterTCCL, filterTCCL.contains(expected));
    assertEquals("Wrong httpTCCL size: " + servletTCCL, 1, servletTCCL.size());
    assertTrue("Wrong servletTCCL: " + servletTCCL, servletTCCL.contains(expected));

}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_ServletContextHelper13() throws Exception {
    BundleContext bundleContext = getBundleContext();
    Bundle bundle = bundleContext.getBundle();

    // test that the helper handlesecurity is called before the filter by setting an attribute on the request
    ServletContextHelper servletContextHelper = new ServletContextHelper(bundle) {

        @Override//from  w  w  w  .ja  va2s  . co  m
        public boolean handleSecurity(HttpServletRequest request, HttpServletResponse response)
                throws IOException {
            request.setAttribute(getName(), Boolean.TRUE);
            return super.handleSecurity(request, response);
        }

    };
    Filter f1 = new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            if (request.getAttribute(getName()) == Boolean.TRUE) {
                request.setAttribute(getName() + ".fromFilter", Boolean.TRUE);
            }
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
        }

    };
    Servlet s1 = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
            res.getWriter().print(req.getAttribute(getName() + ".fromFilter"));
        }

    };

    Collection<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
    try {
        Dictionary<String, String> contextProps = new Hashtable<String, String>();
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME, "a");
        contextProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_PATH, "/");
        registrations.add(
                bundleContext.registerService(ServletContextHelper.class, servletContextHelper, contextProps));

        Dictionary<String, String> filterProps = new Hashtable<String, String>();
        filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_FILTER_PATTERN, "/*");
        filterProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)");
        registrations.add(bundleContext.registerService(Filter.class, f1, filterProps));

        Dictionary<String, String> servletProps = new Hashtable<String, String>();
        servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S1");
        servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s1");
        servletProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HttpWhiteboardConstants.HTTP_WHITEBOARD_CONTEXT_NAME + "=a)");
        registrations.add(bundleContext.registerService(Servlet.class, s1, servletProps));

        String actual = requestAdvisor.request("s1");

        Assert.assertEquals(Boolean.TRUE.toString(), actual);
    } finally {
        for (ServiceRegistration<?> registration : registrations) {
            registration.unregister();
        }
    }
}

From source file:org.jenkinsci.plugins.reverse_proxy_auth.ReverseProxySecurityRealm.java

@Override
public Filter createFilter(FilterConfig filterConfig) {
    return new Filter() {
        public void init(FilterConfig filterConfig) throws ServletException {
        }//  ww w.  ja v  a  2  s .  c om

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

            String authorization = null;
            String userFromApiToken = null;
            if ((authorization = r.getHeader("Authorization")) != null
                    && authorization.toLowerCase().startsWith("basic ")) {
                String uidpassword = Scrambler.descramble(authorization.substring(6));
                int idx = uidpassword.indexOf(':');
                if (idx >= 0) {
                    String username = uidpassword.substring(0, idx);
                    String password = uidpassword.substring(idx + 1);

                    // attempt to authenticate as API token
                    User u = User.get(username, false);
                    if (u != null) {
                        ApiTokenProperty t = u.getProperty(ApiTokenProperty.class);
                        if (t != null && t.matchesPassword(password)) {
                            userFromApiToken = username;
                        }
                    }
                }
            }

            String userFromHeader = null;

            Authentication auth = Hudson.ANONYMOUS;
            if ((forwardedUser != null && (userFromHeader = r.getHeader(forwardedUser)) != null)
                    || userFromApiToken != null) {
                LOGGER.log(Level.FINE, "USER LOGGED IN: {0}", userFromHeader);
                if (userFromHeader == null && userFromApiToken != null) {
                    userFromHeader = userFromApiToken;
                }

                if (getLDAPURL() != null) {

                    GrantedAuthority[] storedGrants = authContext.get(userFromHeader);
                    if (storedGrants != null && storedGrants.length > 1) {
                        authorities = retrieveAuthoritiesIfNecessary(userFromHeader, storedGrants);
                    } else {
                        try {
                            LdapUserDetails userDetails = (LdapUserDetails) loadUserByUsername(userFromHeader);
                            authorities = userDetails.getAuthorities();

                            Set<GrantedAuthority> tempLocalAuthorities = new HashSet<GrantedAuthority>(
                                    Arrays.asList(authorities));
                            tempLocalAuthorities.add(AUTHENTICATED_AUTHORITY);
                            authorities = tempLocalAuthorities.toArray(new GrantedAuthority[0]);

                        } catch (UsernameNotFoundException e) {
                            LOGGER.log(Level.WARNING,
                                    "User not found in the LDAP directory: " + e.getMessage());

                            Set<GrantedAuthority> tempLocalAuthorities = new HashSet<GrantedAuthority>();
                            tempLocalAuthorities.add(AUTHENTICATED_AUTHORITY);
                            authorities = tempLocalAuthorities.toArray(new GrantedAuthority[0]);
                        }
                    }

                } else {
                    String groups = r.getHeader(headerGroups);

                    List<GrantedAuthority> localAuthorities = new ArrayList<GrantedAuthority>();
                    localAuthorities.add(AUTHENTICATED_AUTHORITY);

                    if (groups != null) {
                        StringTokenizer tokenizer = new StringTokenizer(groups, headerGroupsDelimiter);
                        while (tokenizer.hasMoreTokens()) {
                            final String token = tokenizer.nextToken().trim();
                            localAuthorities.add(new GrantedAuthorityImpl(token));
                        }
                    }

                    authorities = localAuthorities.toArray(new GrantedAuthority[0]);

                    SearchTemplate searchTemplate = new UserSearchTemplate(userFromHeader);

                    Set<String> foundAuthorities = proxyTemplate.searchForSingleAttributeValues(searchTemplate,
                            authorities);
                    Set<GrantedAuthority> tempLocalAuthorities = new HashSet<GrantedAuthority>();

                    String[] authString = foundAuthorities.toArray(new String[0]);
                    for (int i = 0; i < authString.length; i++) {
                        tempLocalAuthorities.add(new GrantedAuthorityImpl(authString[i]));
                    }

                    authorities = tempLocalAuthorities.toArray(new GrantedAuthority[0]);
                    authContext.put(userFromHeader, authorities);

                    auth = new UsernamePasswordAuthenticationToken(userFromHeader, "", authorities);
                }
                authContext.put(userFromHeader, authorities);
                auth = new UsernamePasswordAuthenticationToken(userFromHeader, "", authorities);
            }

            retrievedUser = userFromHeader;

            SecurityContextHolder.getContext().setAuthentication(auth);
            chain.doFilter(r, response);
        }

        public void destroy() {
        }
    };
}