org.apache.tomcat.util.descriptor.web.FilterDef Java Examples
The following examples show how to use
org.apache.tomcat.util.descriptor.web.FilterDef.
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: TestContextConfigAnnotation.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Test public void testDuplicateFilterMapping() throws Exception { WebXml webxml = new WebXml(); Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>(); ContextConfig config = new ContextConfig(); File pFile = paramClassResource( "org/apache/catalina/startup/DuplicateMappingParamFilter"); Assert.assertTrue(pFile.exists()); try { config.processAnnotationsFile(pFile, webxml, false, javaClassCache); Assert.fail(); } catch (IllegalArgumentException ex) { // ignore } FilterDef filterDef = webxml.getFilters().get("paramD"); Assert.assertNull(filterDef); }
Example #2
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 6 votes |
private MockFilterChain testRemoteIpFilter(FilterDef filterDef, Request request) throws LifecycleException, IOException, ServletException { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); RemoteIpFilter remoteIpFilter = new RemoteIpFilter(); filterDef.setFilterClass(RemoteIpFilter.class.getName()); filterDef.setFilter(remoteIpFilter); filterDef.setFilterName(RemoteIpFilter.class.getName()); root.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(RemoteIpFilter.class.getName()); filterMap.addURLPatternDecoded("*"); root.addFilterMap(filterMap); getTomcatInstance().start(); MockFilterChain filterChain = new MockFilterChain(); // TEST TesterResponse response = new TesterResponse(); response.setRequest(request); remoteIpFilter.doFilter(request, response, filterChain); return filterChain; }
Example #3
Source File: TestRequest.java From Tomcat8-Source-Read with MIT License | 6 votes |
private synchronized void init() throws Exception { if (init) return; Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet()); root.addServletMappingDecoded("/test", "Bug37794"); if (createFilter) { FilterDef failedRequestFilter = new FilterDef(); failedRequestFilter.setFilterName("failedRequestFilter"); failedRequestFilter.setFilterClass( FailedRequestFilter.class.getName()); FilterMap failedRequestFilterMap = new FilterMap(); failedRequestFilterMap.setFilterName("failedRequestFilter"); failedRequestFilterMap.addURLPatternDecoded("/*"); root.addFilterDef(failedRequestFilter); root.addFilterMap(failedRequestFilterMap); } tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); init = true; }
Example #4
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Test public void testRequestForwarded() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for"); filterDef.addInitParameter("httpServerPort", "8080"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setHeader("x-my-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY Assert.assertEquals("org.apache.tomcat.request.forwarded", Boolean.TRUE, actualRequest.getAttribute(Globals.REQUEST_FORWARDED_ATTRIBUTE)); }
Example #5
Source File: TomcatWebSocketTestServer.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public void deployConfig(WebApplicationContext wac, Filter... filters) { Assert.state(this.port != -1, "setup() was never called."); this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir")); this.context.addApplicationListener(WsContextListener.class.getName()); Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true); this.context.addServletMapping("/", "dispatcherServlet"); for (Filter filter : filters) { FilterDef filterDef = new FilterDef(); filterDef.setFilterName(filter.getClass().getName()); filterDef.setFilter(filter); filterDef.setAsyncSupported("true"); this.context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(filter.getClass().getName()); filterMap.addURLPattern("/*"); filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC"); this.context.addFilterMap(filterMap); } }
Example #6
Source File: TestStandardContext.java From Tomcat8-Source-Read with MIT License | 6 votes |
private static void configureTest46243Context(Context context, boolean fail) { // Add a test filter that fails FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(Bug46243Filter.class.getName()); filterDef.setFilterName("Bug46243"); filterDef.addInitParameter("fail", Boolean.toString(fail)); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName("Bug46243"); filterMap.addURLPatternDecoded("*"); context.addFilterMap(filterMap); // Add a test servlet so there is something to generate a response if // it works (although it shouldn't) Tomcat.addServlet(context, "Bug46243", new HelloWorldServlet()); context.addServletMappingDecoded("/", "Bug46243"); }
Example #7
Source File: TomcatWebSocketTestServer.java From spring-analysis-note with MIT License | 6 votes |
@Override public void deployConfig(WebApplicationContext wac, Filter... filters) { Assert.state(this.port != -1, "setup() was never called."); this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir")); this.context.addApplicationListener(WsContextListener.class.getName()); Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true); this.context.addServletMappingDecoded("/", "dispatcherServlet"); for (Filter filter : filters) { FilterDef filterDef = new FilterDef(); filterDef.setFilterName(filter.getClass().getName()); filterDef.setFilter(filter); filterDef.setAsyncSupported("true"); this.context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(filter.getClass().getName()); filterMap.addURLPattern("/*"); filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC"); this.context.addFilterMap(filterMap); } }
Example #8
Source File: TomcatWebSocketTestServer.java From java-technology-stack with MIT License | 6 votes |
@Override public void deployConfig(WebApplicationContext wac, Filter... filters) { Assert.state(this.port != -1, "setup() was never called."); this.context = this.tomcatServer.addContext("", System.getProperty("java.io.tmpdir")); this.context.addApplicationListener(WsContextListener.class.getName()); Tomcat.addServlet(this.context, "dispatcherServlet", new DispatcherServlet(wac)).setAsyncSupported(true); this.context.addServletMappingDecoded("/", "dispatcherServlet"); for (Filter filter : filters) { FilterDef filterDef = new FilterDef(); filterDef.setFilterName(filter.getClass().getName()); filterDef.setFilter(filter); filterDef.setAsyncSupported("true"); this.context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(filter.getClass().getName()); filterMap.addURLPattern("/*"); filterMap.setDispatcher("REQUEST,FORWARD,INCLUDE,ASYNC"); this.context.addFilterMap(filterMap); } }
Example #9
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeUntrustedProxyInTheChain() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, untrusted-proxy, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertEquals("ip/host before untrusted-proxy must appear in x-forwarded-for", "140.211.11.130, proxy1", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertEquals("ip/host after untrusted-proxy must appear in x-forwarded-by", "proxy2", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "untrusted-proxy", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "untrusted-proxy", actualRemoteHost); }
Example #10
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeXforwardedHostAndPort() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("hostHeader", "x-forwarded-host"); filterDef.addInitParameter("portHeader", "x-forwarded-port"); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); MockHttpServletRequest request = new MockHttpServletRequest(); // client ip request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("192.168.0.10"); // protocol request.setSecure(false); request.setServerPort(8080); request.setScheme("http"); // host and port request.getCoyoteRequest().serverName().setString("10.0.0.1"); request.setHeader("x-forwarded-host", "example.com:8443"); request.setHeader("x-forwarded-proto", "https"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY // protocol String actualServerName = actualRequest.getServerName(); Assert.assertEquals("postInvoke serverName", "example.com", actualServerName); String actualScheme = actualRequest.getScheme(); Assert.assertEquals("postInvoke scheme", "https", actualScheme); int actualServerPort = actualRequest.getServerPort(); Assert.assertEquals("postInvoke serverPort", 443, actualServerPort); boolean actualSecure = actualRequest.isSecure(); Assert.assertTrue("postInvoke secure", actualSecure); }
Example #11
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeXforwardedHost() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("hostHeader", "x-forwarded-host"); filterDef.addInitParameter("portHeader", "x-forwarded-port"); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); MockHttpServletRequest request = new MockHttpServletRequest(); // client ip request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("192.168.0.10"); // protocol request.setSecure(false); request.setServerPort(8080); request.setScheme("http"); // host and port request.getCoyoteRequest().serverName().setString("10.0.0.1"); request.setHeader("x-forwarded-host", "example.com"); request.setHeader("x-forwarded-port", "8443"); request.setHeader("x-forwarded-proto", "https"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY // protocol String actualServerName = actualRequest.getServerName(); Assert.assertEquals("postInvoke serverName", "example.com", actualServerName); String actualScheme = actualRequest.getScheme(); Assert.assertEquals("postInvoke scheme", "https", actualScheme); int actualServerPort = actualRequest.getServerPort(); Assert.assertEquals("postInvoke serverPort", 8443, actualServerPort); boolean actualSecure = actualRequest.isSecure(); Assert.assertTrue("postInvoke secure", actualSecure); }
Example #12
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeAllProxiesAreTrustedEmptyInternal() throws Exception { // PREPARE RemoteIpFilter remoteIpFilter = new RemoteIpFilter(); FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", ""); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); filterDef.setFilter(remoteIpFilter); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("proxy3"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2, proxy3", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
Example #13
Source File: WebAnnotationSet.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Process the annotations for the filters. * * @param context The context which will have its annotations processed */ protected static void loadApplicationFilterAnnotations(Context context) { FilterDef[] filterDefs = context.findFilterDefs(); for (FilterDef filterDef : filterDefs) { Class<?> clazz = Introspection.loadClass(context, filterDef.getFilterClass()); if (clazz == null) { continue; } loadClassAnnotation(context, clazz); loadFieldsAnnotation(context, clazz); loadMethodsAnnotation(context, clazz); } }
Example #14
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeAllProxiesAreTrustedOrInternal() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2, 192.168.0.10, 192.168.0.11"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
Example #15
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeAllProxiesAreTrustedAndRemoteAddrMatchRegexp() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "127\\.0\\.0\\.1|192\\.168\\..*|another-internal-proxy"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.addHeader("x-forwarded-for", "140.211.11.130"); request.addHeader("x-forwarded-for", "proxy1"); request.addHeader("x-forwarded-for", "proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
Example #16
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeAllProxiesAreTrustedUnusedInternal() throws Exception { // PREPARE RemoteIpFilter remoteIpFilter = new RemoteIpFilter(); FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); filterDef.setFilter(remoteIpFilter); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("proxy3"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2, proxy3", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
Example #17
Source File: ContextMBean.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Return the set of defined filters for this Context. * @return a string array with a representation of all * the filter definitions * @throws MBeanException propagated from the managed resource access */ public String[] findFilterDefs() throws MBeanException { Context context = doGetManagedResource(); FilterDef[] filterDefs = context.findFilterDefs(); String[] stringFilters = new String[filterDefs.length]; for (int counter = 0; counter < filterDefs.length; counter++) { stringFilters[counter] = filterDefs[counter].toString(); } return stringFilters; }
Example #18
Source File: TestRestCsrfPreventionFilter2.java From Tomcat8-Source-Read with MIT License | 5 votes |
private void setUpApplication() throws Exception { context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir")); context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS); Tomcat.addServlet(context, SERVLET_NAME, new TesterServlet()); context.addServletMappingDecoded(URI_PROTECTED, SERVLET_NAME); FilterDef filterDef = new FilterDef(); filterDef.setFilterName(FILTER_NAME); filterDef.setFilterClass(RestCsrfPreventionFilter.class.getCanonicalName()); filterDef.addInitParameter(FILTER_INIT_PARAM, REMOVE_CUSTOMER + "," + ADD_CUSTOMER); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(FILTER_NAME); filterMap.addURLPatternDecoded(URI_CSRF_PROTECTED); context.addFilterMap(filterMap); SecurityCollection collection = new SecurityCollection(); collection.addPatternDecoded(URI_PROTECTED); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); context.addConstraint(sc); LoginConfig lc = new LoginConfig(); lc.setAuthMethod(METHOD); context.setLoginConfig(lc); AuthenticatorBase basicAuthenticator = new BasicAuthenticator(); context.getPipeline().addValve(basicAuthenticator); }
Example #19
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testInvokeNotAllowedRemoteAddr() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("not-allowed-internal-proxy"); request.setRemoteHost("not-allowed-internal-proxy-host"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); Assert.assertEquals("x-forwarded-for must be unchanged", "140.211.11.130, proxy1, proxy2", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); Assert.assertNull("x-forwarded-by must be null", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); Assert.assertEquals("remoteAddr", "not-allowed-internal-proxy", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); Assert.assertEquals("remoteHost", "not-allowed-internal-proxy-host", actualRemoteHost); }
Example #20
Source File: TestRemoteIpFilter.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testRequestAttributesForAccessLog() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for"); filterDef.addInitParameter("httpServerPort", "8080"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setHeader("x-my-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY Assert.assertEquals("org.apache.catalina.AccessLog.ServerPort", Integer.valueOf(8080), actualRequest.getAttribute(AccessLog.SERVER_PORT_ATTRIBUTE)); Assert.assertEquals("org.apache.catalina.AccessLog.RemoteAddr", "140.211.11.130", actualRequest.getAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE)); Assert.assertEquals("org.apache.catalina.AccessLog.RemoteHost", "140.211.11.130", actualRequest.getAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE)); }
Example #21
Source File: TestApplicationFilterConfig.java From Tomcat8-Source-Read with MIT License | 5 votes |
@Test public void testBug54170() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); Tomcat.addServlet(ctx, "HelloWorld", new HelloWorldServlet()); ctx.addServletMappingDecoded("/", "HelloWorld"); // Add a filter with a name that should be escaped if used in a JMX // object name FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(AddDefaultCharsetFilter.class.getName()); filterDef.setFilterName("bug54170*"); ctx.addFilterDef(filterDef); tomcat.start(); final MBeanServer mbeanServer = Registry.getRegistry(null, null).getMBeanServer(); // There should be one Servlet MBean registered Set<ObjectName> servlets = mbeanServer.queryNames( new ObjectName("Tomcat:j2eeType=Servlet,*"), null); Assert.assertEquals(1, servlets.size()); // There should be one Filter MBean registered Set<ObjectName> filters = mbeanServer.queryNames( new ObjectName("Tomcat:j2eeType=Filter,*"), null); Assert.assertEquals(1, filters.size()); }
Example #22
Source File: TomcatPolyfill.java From Milkomeda with MIT License | 5 votes |
/** * 动态删除过滤器 * @param name 过滤器名 * @param servletContext ServletContext * @return 删除是否成功 */ public static boolean removeDynamicFilter(String name, ServletContext servletContext) { Context standContext = ReflectUtil.invokeFieldPath(servletContext, "context.context"); if (standContext == null) { log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context' fail."); return false; } // ((ApplicationContextFacade) servletContext).context.context.filterMaps(在filterChain里根据映射的filterMaps转filterConfigs) FilterMap[] filterMaps = ReflectUtil.invokeMethod(standContext, "findFilterMaps", null); if (filterMaps == null) { log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context.findFilterMaps()' fail."); return false; } for (FilterMap filterMap : filterMaps) { if (filterMap.getFilterName().equals(name)) { ReflectUtil.invokeMethod(standContext, "removeFilterMap", new Class[]{FilterMap.class}, filterMap); break; } } // ((ApplicationContextFacade) servletContext).context.context.filterDefs(filterMaps和filterConfigs的数据源,并提供给外部接口访问) FilterDef filterDef = ReflectUtil.invokeMethod(standContext, "findFilterDef", new Class[]{String.class}, name); if (filterDef != null) { ReflectUtil.invokeMethod(standContext, "removeFilterDef", new Class[]{FilterDef.class}, filterDef); } // ((ApplicationContextFacade) servletContext).context.context.filterConfigs (FilterChain具体会读这个属性里的过滤器) Map<String, ApplicationFilterConfig> filterConfigs = ReflectUtil.invokeFieldPath(standContext, "filterConfigs"); if (filterConfigs == null) { log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context.filterConfigs' fail."); return false; } filterConfigs.remove(name); // boolean ((ApplicationContextFacade) servletContext).context.context.filterStart() (把filterDefs加载到filterConfigs) return (boolean) ReflectUtil.invokeMethod(standContext, "filterStart", null); }
Example #23
Source File: AbstractTomcatMetricsTest.java From tomcat_exporter with Apache License 2.0 | 5 votes |
public static void setUpTomcat(String dataSourceFactory) throws LifecycleException, ServletException { // create a tomcat instance tomcat = new Tomcat(); tomcat.setBaseDir("."); tomcat.setPort(0); tomcat.enableNaming(); // create a context with our test servlet Context ctx = tomcat.addContext(CONTEXT_PATH, new File(".").getAbsolutePath()); Tomcat.addServlet(ctx, SERVLET_NAME, new TestServlet()); ctx.addServletMappingDecoded("/*", SERVLET_NAME); // add our metrics filter FilterDef def = new FilterDef(); def.setFilterClass(TomcatServletMetricsFilter.class.getName()); def.setFilterName("metricsFilter"); def.addInitParameter("buckets",".01, .05, .1, .25, .5, 1, 2.5, 5, 10, 30"); ctx.addFilterDef(def); FilterMap map = new FilterMap(); map.setFilterName("metricsFilter"); map.addURLPattern("/*"); ctx.addFilterMap(map); // create a datasource ContextResource resource = new ContextResource(); resource.setName("jdbc/db"); resource.setAuth("Container"); resource.setType("javax.sql.DataSource"); resource.setScope("Sharable"); resource.setProperty("name", "foo"); resource.setProperty("factory", dataSourceFactory); resource.setProperty("driverClassName", "org.h2.Driver"); resource.setProperty("url", "jdbc:h2:mem:dummy"); resource.setProperty("jdbcInterceptors", "nl.nlighten.prometheus.tomcat.TomcatJdbcInterceptor(logFailed=true,logSlow=true,threshold=0,buckets=.01|.05|.1|1|10,slowQueryBuckets=1|10|30)"); ctx.getNamingResources().addResource(resource); // start instance tomcat.init(); tomcat.start(); }
Example #24
Source File: ContextFilter.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * SCIPIO: Reads the forwardRootControllerUris value from ContextFilter init-params from webXml, * trying to find the most appropriate setting. */ public static Boolean readForwardRootControllerUrisSetting(WebXml webXml, String logPrefix) { // HEURISTIC: we return the value of the highest-rated ContextFilter that // has forwardRootControllerUris present in its init-params (even if empty) int bestRating = 0; String aliasStr = null; String filterName = null; for(FilterDef filter : webXml.getFilters().values()) { int currentRating = rateContextFilterCandidate(filter); if (currentRating > 0) { Map<String, String> initParams = filter.getParameterMap(); if (initParams != null && initParams.containsKey("forwardRootControllerUris")) { if (currentRating > bestRating) { bestRating = currentRating; aliasStr = initParams.get("forwardRootControllerUris"); filterName = filter.getFilterName(); } } } } if (bestRating > 0) { Boolean alias = UtilMisc.booleanValueVersatile(aliasStr); if (alias != null) { if (logPrefix != null) Debug.logInfo(logPrefix+"Found web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris boolean value: " + alias, module); return alias; } else { if (UtilValidate.isNotEmpty(aliasStr)) { if (logPrefix != null) Debug.logError(logPrefix+"web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris has invalid boolean value: " + aliasStr, module); } else { if (logPrefix != null) Debug.logInfo(logPrefix+"Found web.xml ContextFilter (filter name '" + filterName + "') init-param forwardRootControllerUris, was empty; returning as unset", module); return null; } } } else { if (logPrefix != null) Debug.logInfo(logPrefix+"web.xml ContextFilter init-param forwardRootControllerUris setting not found", module); } return null; }
Example #25
Source File: ContextFilter.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * Heuristic for finding the most probable real ContextFilter. * NOTE: This is a problem because OFbiz frustratingly made a bunch of other classes * extend ContextFilter, and even scipio is forced to compound the problem as a result * of lack of good base classes. * @return a value between 0-5, 5 being best candidate */ public static int rateContextFilterCandidate(FilterDef filter) { String filterClass = filter.getFilterClass(); if (filterClass == null || filterClass.isEmpty()) return 0; // NOTE: this exact-class check is what stock code does for some other classes, so we have to follow suit if (ContextFilter.class.getName().equals(filterClass)) return 5; try { Class<?> filterCls = Thread.currentThread().getContextClassLoader().loadClass(filterClass); if (!ContextFilter.class.isAssignableFrom(filterCls)) return 0; } catch(Exception e) { Debug.logWarning("Could not load or test filter class (" + filterClass + "); may be invalid or a classloader issue: " + e.getMessage(), module); return 0; } String filterName = filter.getFilterName(); if (contextFilterClassName.equals(filterName)) return 4; if (filterName != null && filterName.contains(contextFilterClassName)) { if (filterClass.contains(contextFilterClassName)) return 3; } else { if (filterClass.contains(contextFilterClassName)) return 2; } // 1: at least is subclass, but lowest because stock Ofbiz overextended ContextFilter everywhere return 1; }
Example #26
Source File: ExtWebappInfo.java From scipio-erp with Apache License 2.0 | 5 votes |
private static String getUrlRewriteConfPathFromWebXml(WebXml webXml) { for (FilterDef filterDef : webXml.getFilters().values()) { String filterClassName = filterDef.getFilterClass(); // exact name is the original Ofbiz solution, return exact if found if (org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.class.getName().equals(filterClassName)) { String confPath = filterDef.getParameterMap().get("confPath"); if (UtilValidate.isNotEmpty(confPath)) { return confPath; } return DEFAULT_WEBAPP_URLREWRITE_FILE; } } return null; }
Example #27
Source File: MdwServletContainerFactory.java From mdw with Apache License 2.0 | 5 votes |
@Override public void customize(Context context) { context.addApplicationListener("org.apache.tomcat.websocket.server.WsContextListener"); context.addErrorPage(new ErrorPage() { @Override public int getErrorCode() { return 404; } @Override public String getLocation() { return "/404"; } }); context.addErrorPage(new ErrorPage() { @Override public int getErrorCode() { return 500; } @Override public String getLocation() { return "/error"; } }); // CORS access is wide open FilterDef corsFilter = new FilterDef(); corsFilter.setFilterName("CorsFilter"); corsFilter.setFilterClass("org.apache.catalina.filters.CorsFilter"); corsFilter.addInitParameter("cors.allowed.methods", "GET,POST,PUT,DELETE,HEAD,OPTIONS"); corsFilter.addInitParameter("cors.allowed.headers", "Authorization,Content-Type,X-Requested-With,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Accept-Encoding,Accept-Language,Cache-Control,Connection,Host,Pragma,Referer,User-Agent"); corsFilter.addInitParameter("cors.allowed.origins", "*"); context.addFilterDef(corsFilter); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(corsFilter.getFilterName()); filterMap.addURLPattern("/api/*"); filterMap.addURLPattern("/services/AppSummary"); context.addFilterMap(filterMap); }
Example #28
Source File: Registrations.java From tomee with Apache License 2.0 | 5 votes |
public static void addFilterConfig(final Context context, final FilterDef filterDef) { try { final Constructor<ApplicationFilterConfig> cons = ApplicationFilterConfig.class.getDeclaredConstructor(Context.class, FilterDef.class); if (!cons.isAccessible()) { cons.setAccessible(true); } final ApplicationFilterConfig config = cons.newInstance(context, filterDef); ((Map<String, ApplicationFilterConfig>) Reflections.get(context, "filterConfigs")).put(filterDef.getFilterName(), config); } catch (final Exception e) { throw new IllegalStateException(e); } }
Example #29
Source File: OpenEJBContextConfig.java From tomee with Apache License 2.0 | 5 votes |
@Override public void addFilterMapping(final FilterMap filterMap) { // we need to add this one before the mapping cause of tomcat validation (ie dont make deployment fail) if ("CDI Conversation Filter".equals(filterMap.getFilterName()) && !cdiConversation) { final FilterDef conversationFilter = new FilterDef(); conversationFilter.setAsyncSupported("true"); conversationFilter.setDescription("CDI Conversation Filter"); conversationFilter.setDisplayName("CDI Conversation Filter"); conversationFilter.setFilterName("CDI Conversation Filter"); conversationFilter.setFilterClass(WebConversationFilter.class.getName()); addFilter(conversationFilter); cdiConversation = true; } super.addFilterMapping(filterMap); }
Example #30
Source File: ProgrammaticTomcat.java From tutorials with MIT License | 5 votes |
public void startTomcat() throws LifecycleException { tomcat = new Tomcat(); tomcat.setPort(randomPort); tomcat.setHostname("localhost"); String appBase = "."; tomcat.getHost().setAppBase(appBase); File docBase = new File(System.getProperty("java.io.tmpdir")); Context context = tomcat.addContext("", docBase.getAbsolutePath()); // add a servlet Class servletClass = MyServlet.class; Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName()); context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName()); // add a filter and filterMapping Class filterClass = MyFilter.class; FilterDef myFilterDef = new FilterDef(); myFilterDef.setFilterClass(filterClass.getName()); myFilterDef.setFilterName(filterClass.getSimpleName()); context.addFilterDef(myFilterDef); FilterMap myFilterMap = new FilterMap(); myFilterMap.setFilterName(filterClass.getSimpleName()); myFilterMap.addURLPattern("/my-servlet/*"); context.addFilterMap(myFilterMap); tomcat.start(); // uncomment for live test // tomcat // .getServer() // .await(); }