javax.servlet.Filter Java Examples
The following examples show how to use
javax.servlet.Filter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestHostnameFilter.java From big-c with Apache License 2.0 | 7 votes |
@Test public void testMissingHostname() throws Exception { ServletRequest request = Mockito.mock(ServletRequest.class); Mockito.when(request.getRemoteAddr()).thenReturn(null); ServletResponse response = Mockito.mock(ServletResponse.class); final AtomicBoolean invoked = new AtomicBoolean(); FilterChain chain = new FilterChain() { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { assertTrue(HostnameFilter.get().contains("???")); invoked.set(true); } }; Filter filter = new HostnameFilter(); filter.init(null); assertNull(HostnameFilter.get()); filter.doFilter(request, response, chain); assertTrue(invoked.get()); assertNull(HostnameFilter.get()); filter.destroy(); }
Example #2
Source File: ShiroConfiguration.java From White-Jotter with MIT License | 7 votes |
@Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setLoginUrl("/nowhere"); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); Map<String, Filter> customizedFilter = new HashMap<>(); // 自定义过滤器设置 1 customizedFilter.put("url", getURLPathMatchingFilter()); // 自定义过滤器设置 2,命名,需在设置过滤路径前 filterChainDefinitionMap.put("/api/authentication", "authc"); // 防鸡贼登录 filterChainDefinitionMap.put("/api/menu", "authc"); filterChainDefinitionMap.put("/api/admin/**", "authc"); filterChainDefinitionMap.put("/api/admin/**", "url"); // 自定义过滤器设置 3,设置过滤路径 shiroFilterFactoryBean.setFilters(customizedFilter); // 自定义过滤器设置 4,启用 shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; }
Example #3
Source File: TestServer.java From nomulus with Apache License 2.0 | 6 votes |
private Context createHandler( Map<String, Path> runfiles, ImmutableList<Route> routes, ImmutableList<Class<? extends Filter>> filters) { Context context = new Context(server, CONTEXT_PATH, Context.SESSIONS); context.addServlet(new ServletHolder(HealthzServlet.class), "/healthz"); for (Map.Entry<String, Path> runfile : runfiles.entrySet()) { context.addServlet( StaticResourceServlet.create(runfile.getKey(), runfile.getValue()), runfile.getKey()); } for (Route route : routes) { context.addServlet( new ServletHolder(wrapServlet(route.servletClass(), filters)), route.path()); } ServletHolder holder = new ServletHolder(DefaultServlet.class); holder.setInitParameter("aliases", "1"); context.addServlet(holder, "/*"); return context; }
Example #4
Source File: LocalDataflowResource.java From spring-cloud-dashboard with Apache License 2.0 | 6 votes |
@Override protected void before() throws Throwable { originalConfigLocation = System.getProperty("spring.config.location"); if (!StringUtils.isEmpty(configurationLocation)) { System.setProperty("spring.config.location", configurationLocation); } app = new SpringApplication(LocalTestDataFlowServer.class); configurableApplicationContext = (WebApplicationContext) app.run(new String[]{"--server.port=0"}); Collection<Filter> filters = configurableApplicationContext.getBeansOfType(Filter.class).values(); mockMvc = MockMvcBuilders.webAppContextSetup(configurableApplicationContext) .addFilters(filters.toArray(new Filter[filters.size()])) .build(); dataflowPort = configurableApplicationContext.getEnvironment().resolvePlaceholders("${server.port}"); }
Example #5
Source File: NanoPiranha.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Service. * * @param servletRequest the request. * @param servletResponse the response. * @throws IOException when an I/O error occurs. * @throws ServletException when a Servlet error occurs. */ public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { Iterator<Filter> iterator = filters.descendingIterator(); NanoFilterChain chain = new NanoFilterChain(servlet); while (iterator.hasNext()) { Filter filter = iterator.next(); NanoFilterChain previousChain = chain; chain = new NanoFilterChain(filter, previousChain); } if (servletRequest.getServletContext() == null && servletRequest instanceof NanoRequest) { NanoRequest nanoRequest = (NanoRequest) servletRequest; nanoRequest.setWebApplication(webApplication); } if (servletResponse instanceof NanoResponse) { NanoResponse nanoResponse = (NanoResponse) servletResponse; nanoResponse.setWebApplication(webApplication); } chain.doFilter(servletRequest, servletResponse); servletResponse.flushBuffer(); }
Example #6
Source File: AbstractMockMvcBuilder.java From java-technology-stack with MIT License | 6 votes |
/** * Build a {@link org.springframework.test.web.servlet.MockMvc} instance. */ @Override @SuppressWarnings("rawtypes") public final MockMvc build() { WebApplicationContext wac = initWebAppContext(); ServletContext servletContext = wac.getServletContext(); MockServletConfig mockServletConfig = new MockServletConfig(servletContext); for (MockMvcConfigurer configurer : this.configurers) { RequestPostProcessor processor = configurer.beforeMockMvcCreated(this, wac); if (processor != null) { if (this.defaultRequestBuilder == null) { this.defaultRequestBuilder = MockMvcRequestBuilders.get("/"); } if (this.defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder) { ((ConfigurableSmartRequestBuilder) this.defaultRequestBuilder).with(processor); } } } Filter[] filterArray = this.filters.toArray(new Filter[0]); return super.createMockMvc(filterArray, mockServletConfig, wac, this.defaultRequestBuilder, this.globalResultMatchers, this.globalResultHandlers, this.dispatcherServletCustomizers); }
Example #7
Source File: ShiroBundle.java From dropwizard-shiro with Apache License 2.0 | 6 votes |
/** * Create the Shiro filter. Overriding this method allows for complete customization of how Shiro is initialized. */ protected Filter createFilter(final T configuration) { ShiroConfiguration shiroConfig = narrow(configuration); final IniWebEnvironment shiroEnv = new IniWebEnvironment(); shiroEnv.setConfigLocations(shiroConfig.iniConfigs()); shiroEnv.init(); AbstractShiroFilter shiroFilter = new AbstractShiroFilter() { @Override public void init() throws Exception { Collection<Realm> realms = createRealms(configuration); WebSecurityManager securityManager = realms.isEmpty() ? shiroEnv.getWebSecurityManager() : new DefaultWebSecurityManager(realms); setSecurityManager(securityManager); setFilterChainResolver(shiroEnv.getFilterChainResolver()); } }; return shiroFilter; }
Example #8
Source File: StreamlineApplication.java From streamline with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private void addServletFilters(StreamlineConfiguration configuration, Environment environment) { List<ServletFilterConfiguration> servletFilterConfigurations = configuration.getServletFilters(); if (servletFilterConfigurations != null && !servletFilterConfigurations.isEmpty()) { for (ServletFilterConfiguration servletFilterConfiguration: servletFilterConfigurations) { try { addServletFilter(environment, servletFilterConfiguration.getClassName(), (Class<? extends Filter>) Class.forName(servletFilterConfiguration.getClassName()), servletFilterConfiguration.getParams()); } catch (Exception e) { LOG.error("Error occurred while adding servlet filter {}", servletFilterConfiguration); throw new RuntimeException(e); } } } else { LOG.info("No servlet filters configured"); } }
Example #9
Source File: Init.java From openwebbeans-meecrowave with Apache License 2.0 | 6 votes |
@Override public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException { ctx.addFilter("sci", new Filter() { @Override public void init(final FilterConfig filterConfig) throws ServletException { // no-op } @Override public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { response.getWriter().write("sci:" + c.stream().map(Class::getName).sorted().collect(joining())); } @Override public void destroy() { // no-op } }).addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/sci"); }
Example #10
Source File: ShiroConfiguration.java From watchdog-framework with MIT License | 6 votes |
@Bean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager){ log.info("Shiro Configuration initialized"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); //设置SecurityManager shiroFilterFactoryBean.setSecurityManager(securityManager); //拦截器 //<!-- 过滤链定义,从上向下顺序执行,一般将 /**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了; //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问--> Map<String,String> filterChainDefinitionMap = shiroService.getFilterChainDefinitionMap(); //过滤器 Map<String,Filter> filters = new HashMap<>(); filters.put("perms",new JwtFilter()); shiroFilterFactoryBean.setFilters(filters); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; }
Example #11
Source File: InstanceEvent.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
/** * Construct a new InstanceEvent with the specified parameters. This * constructor is used for filter processing events. * * @param wrapper Wrapper managing this servlet instance * @param filter Filter instance for which this event occurred * @param type Event type (required) * @param request Servlet request we are processing * @param response Servlet response we are processing * @param exception Exception that occurred */ public InstanceEvent(Wrapper wrapper, Filter filter, String type, ServletRequest request, ServletResponse response, Throwable exception) { super(wrapper); this.filter = filter; this.servlet = null; this.type = type; this.request = request; this.response = response; this.exception = exception; }
Example #12
Source File: UserAgentMetricFilterTest.java From data-highway with Apache License 2.0 | 5 votes |
@Test public void testName() throws Exception { when(request.getRequestURI()).thenReturn("/onramp/v1/roads/road1/messages"); when(request.getHeader("User-Agent")).thenReturn("product1/1.0 product2/2.0 product3/3.0"); Set<String> products = new HashSet<>(Arrays.asList("product1", "product2", "product4")); Filter underTest = new UserAgentMetricFilter(registry, products); underTest.doFilter(request, response, chain); assertThat(counter1.count(), is(1.0)); assertThat(counter2.count(), is(1.0)); assertThat(counter3.count(), is(0.0)); assertThat(counter4.count(), is(0.0)); verify(chain).doFilter(request, response); }
Example #13
Source File: XssConfig.java From runscore with Apache License 2.0 | 5 votes |
@Bean public FilterRegistrationBean<Filter> xssFilterRegistrationBean() { FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>(new XssFilter()); filterRegistrationBean.setOrder(1); filterRegistrationBean.setEnabled(true); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; }
Example #14
Source File: ShiroAutoConfiguration.java From spring-boot-shiro with Apache License 2.0 | 5 votes |
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) { Map<String, Filter> filterMap = null; if (filters != null) { filterMap = new LinkedHashMap<String, Filter>(); for (String name : filters.keySet()) { Class<? extends Filter> clazz = filters.get(name); Filter f = BeanUtils.instantiate(clazz); filterMap.put(name, f); } } return filterMap; }
Example #15
Source File: DelegatingFilterProxy.java From java-technology-stack with MIT License | 5 votes |
@Override public void destroy() { Filter delegateToUse = this.delegate; if (delegateToUse != null) { destroyDelegate(delegateToUse); } }
Example #16
Source File: FilterDataTest.java From micro-server with Apache License 2.0 | 5 votes |
@Test public void testFilterData() { Filter filter = mock(Filter.class); FilterData data = new FilterData("mapping", "filterName", filter); assertThat(data.getMapping(), is("mapping")); assertThat(data.getFilterName(), is("filterName")); assertThat(data.getFilter(), is(filter)); }
Example #17
Source File: AbstractMockMvcBuilder.java From java-technology-stack with MIT License | 5 votes |
public final <T extends B> T addFilters(Filter... filters) { Assert.notNull(filters, "filters cannot be null"); for (Filter f : filters) { Assert.notNull(f, "filters cannot contain null values"); this.filters.add(f); } return self(); }
Example #18
Source File: WebSecurityModule.java From seed with Mozilla Public License 2.0 | 5 votes |
private Key<? extends Filter> findKey(String filterName) { Key<? extends Filter> currentKey = null; if (DEFAULT_FILTERS.containsKey(filterName)) { currentKey = DEFAULT_FILTERS.get(filterName); } else { for (Class<? extends Filter> filterClass : customFilters) { String name = filterClass.getAnnotation(SecurityFilter.class).value(); if (filterName.equals(name)) { currentKey = Key.get(filterClass); } } } return currentKey; }
Example #19
Source File: WebInitializer.java From Spring with Apache License 2.0 | 5 votes |
@Override protected Filter[] getServletFilters() { CharacterEncodingFilter cef = new CharacterEncodingFilter(); cef.setEncoding("UTF-8"); cef.setForceEncoding(true); return new Filter[]{new HiddenHttpMethodFilter(), cef}; }
Example #20
Source File: StreamlineApplication.java From streamline with Apache License 2.0 | 5 votes |
private void addSecurityHeaders(Environment environment) { Map<String, String> params = new HashMap<>(); params.put("X-Frame-Options", "SAMEORIGIN"); params.put("X-XSS-Protection", "1; mode=block"); params.put("X-Content-Type-Options", "nosniff"); params.put("Content-Security-Policy", "script-src 'self'; object-src 'self'"); params.put("Strict-Transport-Security", "max-age=31536000; includeSubDomains"); Class<? extends Filter> filter = StreamlineResponseHeaderFilter.class; addServletFilter(environment, filter.getName() + ".internal", filter, params); }
Example #21
Source File: DefaultFilterEnvironment.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Initialize the filter. * * @throws ServletException when a servlet error occurs. */ public void initialize() throws ServletException { if (filter == null) { try { Class<? extends Filter> clazz = webApplication.getClassLoader().loadClass(className).asSubclass(Filter.class); filter = webApplication.createFilter(clazz); } catch (Throwable throwable) { throw new ServletException("Unable to initialize the filter", throwable); } } }
Example #22
Source File: WebSecurityModule.java From seed with Mozilla Public License 2.0 | 5 votes |
WebSecurityModule(ServletContext servletContext, WebSecurityConfig securityConfig, Collection<Class<? extends Filter>> customFilters, String applicationName, SecurityGuiceConfigurer securityGuiceConfigurer) { super(servletContext); this.securityConfig = securityConfig; this.customFilters = customFilters; this.applicationName = applicationName; this.securityGuiceConfigurer = securityGuiceConfigurer; }
Example #23
Source File: InstanceSupport.java From Tomcat7.0.67 with Apache License 2.0 | 5 votes |
/** * Notify all lifecycle event listeners that a particular event has * occurred for this Container. The default implementation performs * this notification synchronously using the calling thread. * * @param type Event type * @param filter The relevant Filter for this event * @param exception Exception that occurred */ public void fireInstanceEvent(String type, Filter filter, Throwable exception) { if (listeners.length == 0) return; InstanceEvent event = new InstanceEvent(wrapper, filter, type, exception); InstanceListener interested[] = listeners; for (int i = 0; i < interested.length; i++) interested[i].instanceEvent(event); }
Example #24
Source File: IamFilterChainManager.java From super-cloudops with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override protected NamedFilterList ensureChain(String chainName) { NamedFilterList chain = getChain(chainName); if (chain == null) { /* * Cloning is required here, or multiple calls to the new * SimpleNamedFilterList will result in additional premiseFilter * duplication. */ chain = new SimpleNamedFilterList(chainName, (List<Filter>) premiseFilters.clone()); getFilterChains().put(chainName, chain); } return chain; }
Example #25
Source File: ShiroAutoConfiguration.java From utils with Apache License 2.0 | 5 votes |
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) { Map<String, Filter> filterMap = null; if (filters != null) { filterMap = new LinkedHashMap<String, Filter>(); for (String name : filters.keySet()) { Class<? extends Filter> clazz = filters.get(name); Filter f = BeanUtils.instantiate(clazz); filterMap.put(name, f); } } return filterMap; }
Example #26
Source File: MVCConfiguration.java From spring-oauth-server with GNU General Public License v2.0 | 5 votes |
/** * sitemesh filter */ @Bean public FilterRegistrationBean sitemesh() { FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); registrationBean.setFilter(new SOSSiteMeshFilter()); registrationBean.addUrlPatterns("/*"); //注意: 在 spring security filter之后 registrationBean.setOrder(8899); return registrationBean; }
Example #27
Source File: ShiroConfiguration.java From faster-framework-project with Apache License 2.0 | 5 votes |
/** * 过滤器 * * @param securityManager 权限管理器 * @param shiroProperties shiro配置 * @return 过滤器 */ @Bean @ConditionalOnMissingBean public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager, ShiroProperties shiroProperties) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroProperties.getFilterChainDefinitionMap()); Map<String, Filter> filters = new LinkedHashMap<>(); filters.put("jwt", new ShiroFilter()); shiroFilterFactoryBean.setFilters(filters); return shiroFilterFactoryBean; }
Example #28
Source File: AnnotationConfigDispatcherServletInitializerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void noFilters() throws ServletException { initializer = new MyAnnotationConfigDispatcherServletInitializer() { @Override protected Filter[] getServletFilters() { return null; } }; initializer.onStartup(servletContext); assertEquals(0, filterRegistrations.size()); }
Example #29
Source File: AnnotationConfigDispatcherServletInitializerTests.java From spring-analysis-note with MIT License | 5 votes |
@Override public Dynamic addFilter(String filterName, Filter filter) { if (filters.containsKey(filterName)) { return null; } filters.put(filterName, filter); MockFilterRegistration registration = new MockFilterRegistration(); filterRegistrations.put(filterName, registration); return registration; }
Example #30
Source File: ZuulApplication.java From blog-microservices with Apache License 2.0 | 5 votes |
@Bean public Filter logFilter() { // TODO: Extract bean-def to Util-component! CommonsRequestLoggingFilter filter = new CommonsRequestLoggingFilter(); filter.setIncludeQueryString(true); filter.setIncludePayload(true); filter.setMaxPayloadLength(5120); return filter; }