org.apache.tomcat.util.descriptor.web.FilterMap Java Examples

The following examples show how to use org.apache.tomcat.util.descriptor.web.FilterMap. 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: TomcatWebSocketTestServer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: TomcatWebSocketTestServer.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #3
Source File: TomcatWebSocketTestServer.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #4
Source File: ApplicationFilterFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return <code>true</code> if the context-relative request path
 * matches the requirements of the specified filter mapping;
 * otherwise, return <code>false</code>.
 *
 * @param filterMap Filter mapping being checked
 * @param requestPath Context-relative request path of this request
 */
private static boolean matchFiltersURL(FilterMap filterMap, String requestPath) {

    // Check the specific "*" special URL pattern, which also matches
    // named dispatches
    if (filterMap.getMatchAllUrlPatterns())
        return true;

    if (requestPath == null)
        return false;

    // Match on context relative request path
    String[] testPaths = filterMap.getURLPatterns();

    for (int i = 0; i < testPaths.length; i++) {
        if (matchFiltersURL(testPaths[i], requestPath)) {
            return true;
        }
    }

    // No match
    return false;

}
 
Example #5
Source File: ApplicationFilterFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return <code>true</code> if the specified servlet name matches
 * the requirements of the specified filter mapping; otherwise
 * return <code>false</code>.
 *
 * @param filterMap Filter mapping being checked
 * @param servletName Servlet name being checked
 */
private static boolean matchFiltersServlet(FilterMap filterMap,
                                    String servletName) {

    if (servletName == null) {
        return false;
    }
    // Check the specific "*" special servlet name
    else if (filterMap.getMatchAllServletNames()) {
        return true;
    } else {
        String[] servletNames = filterMap.getServletNames();
        for (int i = 0; i < servletNames.length; i++) {
            if (servletName.equals(servletNames[i])) {
                return true;
            }
        }
        return false;
    }

}
 
Example #6
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
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: TestRemoteIpFilter.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
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 #8
Source File: TestRequest.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
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 #9
Source File: TestAddCharSetFilter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doTest(String encoding, String expected, int mode, boolean useSetContentType)
        throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    // Add the Servlet
    CharsetServlet servlet = new CharsetServlet(mode, useSetContentType);
    Tomcat.addServlet(ctx, "servlet", servlet);
    ctx.addServletMappingDecoded("/", "servlet");

    // Add the Filter
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(AddDefaultCharsetFilter.class.getName());
    filterDef.setFilterName("filter");
    if (encoding != null) {
        filterDef.addInitParameter("encoding", encoding);
    }
    ctx.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("filter");
    filterMap.addServletName("servlet");
    ctx.addFilterMap(filterMap);

    tomcat.start();

    Map<String, List<String>> headers = new HashMap<>();
    getUrl("http://localhost:" + getPort() + "/", new ByteChunk(), headers);

    String ct = getSingleHeader("Content-Type", headers).toLowerCase(Locale.ENGLISH);
    Assert.assertEquals("text/plain;charset=" + expected.toLowerCase(Locale.ENGLISH), ct);
}
 
Example #10
Source File: ProgrammaticTomcat.java    From tutorials with MIT License 5 votes vote down vote up
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();
}
 
Example #11
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: MdwServletContainerFactory.java    From mdw with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: AbstractTomcatMetricsTest.java    From tomcat_exporter with Apache License 2.0 5 votes vote down vote up
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 #14
Source File: TomcatPolyfill.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 动态删除过滤器
 * @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 #15
Source File: TestRestCsrfPreventionFilter2.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
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 #16
Source File: ApplicationFilterRegistration.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public Collection<String> getServletNameMappings() {
    Collection<String> result = new HashSet<>();

    FilterMap[] filterMaps = context.findFilterMaps();

    for (FilterMap filterMap : filterMaps) {
        if (filterMap.getFilterName().equals(filterDef.getFilterName())) {
            for (String servletName : filterMap.getServletNames()) {
                result.add(servletName);
            }
        }
    }
    return result;
}
 
Example #17
Source File: ApplicationFilterRegistration.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void addMappingForUrlPatterns(
        EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter,
        String... urlPatterns) {

    FilterMap filterMap = new FilterMap();

    filterMap.setFilterName(filterDef.getFilterName());

    if (dispatcherTypes != null) {
        for (DispatcherType dispatcherType : dispatcherTypes) {
            filterMap.setDispatcher(dispatcherType.name());
        }
    }

    if (urlPatterns != null) {
        // % decoded (if necessary) using UTF-8
        for (String urlPattern : urlPatterns) {
            filterMap.addURLPattern(urlPattern);
        }

        if (isMatchAfter) {
            context.addFilterMap(filterMap);
        } else {
            context.addFilterMapBefore(filterMap);
        }
    }
    // else error?

}
 
Example #18
Source File: ApplicationFilterRegistration.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void addMappingForServletNames(
        EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter,
        String... servletNames) {

    FilterMap filterMap = new FilterMap();

    filterMap.setFilterName(filterDef.getFilterName());

    if (dispatcherTypes != null) {
        for (DispatcherType dispatcherType : dispatcherTypes) {
            filterMap.setDispatcher(dispatcherType.name());
        }
    }

    if (servletNames != null) {
        for (String servletName : servletNames) {
            filterMap.addServletName(servletName);
        }

        if (isMatchAfter) {
            context.addFilterMap(filterMap);
        } else {
            context.addFilterMapBefore(filterMap);
        }
    }
    // else error?
}
 
Example #19
Source File: ApplicationFilterFactory.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Convenience method which returns true if  the dispatcher type
 * matches the dispatcher types specified in the FilterMap
 */
private static boolean matchDispatcher(FilterMap filterMap, DispatcherType type) {
    switch (type) {
        case FORWARD :
            if ((filterMap.getDispatcherMapping() & FilterMap.FORWARD) != 0) {
                return true;
            }
            break;
        case INCLUDE :
            if ((filterMap.getDispatcherMapping() & FilterMap.INCLUDE) != 0) {
                return true;
            }
            break;
        case REQUEST :
            if ((filterMap.getDispatcherMapping() & FilterMap.REQUEST) != 0) {
                return true;
            }
            break;
        case ERROR :
            if ((filterMap.getDispatcherMapping() & FilterMap.ERROR) != 0) {
                return true;
            }
            break;
        case ASYNC :
            if ((filterMap.getDispatcherMapping() & FilterMap.ASYNC) != 0) {
                return true;
            }
            break;
    }
    return false;
}
 
Example #20
Source File: ContextMBean.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return the set of filter mappings for this Context.
 * @return a string array with a representation of all the filter mappings
 * @throws MBeanException propagated from the managed resource access
 */
public String[] findFilterMaps() throws MBeanException {

    Context context = doGetManagedResource();

    FilterMap[] maps = context.findFilterMaps();
    String[] stringMaps = new String[maps.length];
    for (int counter = 0; counter < maps.length; counter++) {
        stringMaps[counter] = maps[counter].toString();
    }

    return stringMaps;
}
 
Example #21
Source File: ApplicationFilterRegistration.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public Collection<String> getUrlPatternMappings() {
    Collection<String> result = new HashSet<>();

    FilterMap[] filterMaps = context.findFilterMaps();

    for (FilterMap filterMap : filterMaps) {
        if (filterMap.getFilterName().equals(filterDef.getFilterName())) {
            for (String urlPattern : filterMap.getURLPatterns()) {
                result.add(urlPattern);
            }
        }
    }
    return result;
}
 
Example #22
Source File: TesterContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void removeFilterMap(FilterMap filterMap) {
    // NO-OP
}
 
Example #23
Source File: FailedContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void addFilterMapBefore(FilterMap filterMap) { /* NO-OP */ }
 
Example #24
Source File: TomcatRsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public AddressInfo createRsHttpListener(final String appId, final String webContext, final HttpListener listener, final ClassLoader classLoader, final String completePath, final String virtualHost, final String auth, final String realm) {
    String path = webContext;
    if (path == null) {
        throw new NullPointerException("contextRoot is null");
    }
    if (listener == null) {
        throw new NullPointerException("listener is null");
    }

    // find the existing host (we do not auto-create hosts)
    Container host;
    Context context = null;
    if (virtualHost == null) {
        host = hosts.getDefault();
    } else {
        host = hosts.get(virtualHost);
    }

    if (host == null) {
        for (final Host h : hosts) {
            context = findContext(h, webContext);
            if (context != null) {
                host = h;
                if (classLoader != null && classLoader.equals(context.getLoader().getClassLoader())) {
                    break;
                } // else try next to find something better
            }
        }

        if (host == null) {
            throw new IllegalArgumentException("Invalid virtual host '" + virtualHost + "'.  Do you have a matching Host entry in the server.xml?");
        }
    } else {
        context = findContext(host, webContext);
    }

    if (context == null) {
        throw new IllegalStateException("Invalid context '" + webContext + "'.  Cannot find context in host " + host.getName());
    }

    final CxfRsHttpListener cxfRsHttpListener = findCxfRsHttpListener(listener);
    final String description = "tomee-jaxrs-" + listener;

    String mapping = completePath;
    if (!completePath.endsWith("/*")) { // respect servlet spec (!= from our embedded listeners)
        if (completePath.endsWith("*")) {
            mapping = completePath.substring(0, completePath.length() - 1);
        }
        mapping = mapping + "/*";
    }

    final String urlPattern = removeWebContext(webContext, mapping);
    cxfRsHttpListener.setUrlPattern(urlPattern.substring(0, urlPattern.length() - 1));

    final FilterDef filterDef = new FilterDef();
    filterDef.setAsyncSupported("true");
    filterDef.setDescription(description);
    filterDef.setFilterName(description);
    filterDef.setDisplayName(description);
    filterDef.setFilter(new CXFJAXRSFilter(cxfRsHttpListener, context.findWelcomeFiles()));
    filterDef.setFilterClass(CXFJAXRSFilter.class.getName());
    filterDef.addInitParameter("mapping", urlPattern.substring(0, urlPattern.length() - "/*".length())); // just keep base path
    context.addFilterDef(filterDef);

    final FilterMap filterMap = new FilterMap();
    filterMap.addURLPattern(urlPattern);
    for (final DispatcherType type : DispatcherType.values()) {
        filterMap.setDispatcher(type.name());
    }
    filterMap.setFilterName(filterDef.getFilterName());
    context.addFilterMap(filterMap);

    Registrations.addFilterConfig(context, filterDef);

    path = address(connectors, host.getName(), webContext);
    final String key = address(connectors, host.getName(), completePath);
    listeners.put(new Key(appId, key), listener);

    return new AddressInfo(path, key);
}
 
Example #25
Source File: FailedContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public FilterMap[] findFilterMaps() { return null; }
 
Example #26
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void beforeStart(final StandardContext standardContext) {
    if (standardContext.getResources() != null && LazyStopStandardRoot.class.isInstance(standardContext.getResources())) {
        // reset after reload
        Reflections.set(standardContext, "resources",  LazyStopStandardRoot.class.cast(standardContext.getResources()).getDelegate());
    }

    final ServletContext sc = standardContext.getServletContext();
    if (sc != null && !SystemInstance.get().getOptions().get(OPENEJB_JSESSION_ID_SUPPORT, true)) {
        final Set<SessionTrackingMode> defaultTrackingModes = sc.getEffectiveSessionTrackingModes();
        if (defaultTrackingModes.contains(SessionTrackingMode.URL)) {
            final Set<SessionTrackingMode> newModes = new HashSet<>();
            newModes.remove(SessionTrackingMode.URL);
            sc.setSessionTrackingModes(newModes);
        }
    }
    initContextLoader(standardContext);

    // used to add custom filters first - our arquillian integration uses it for instance
    // needs to be done now (= before start event) because of addFilterMapBefore() usage
    final String filters = SystemInstance.get().getProperty("org.apache.openejb.servlet.filters");
    if (filters != null) {
        final String[] names = filters.split(",");
        for (final String name : names) {
            final String[] clazzMapping = name.split("=");

            final FilterDef filterDef = new FilterDef();
            filterDef.setFilterClass(clazzMapping[0]);
            filterDef.setFilterName(clazzMapping[0]);
            standardContext.addFilterDef(filterDef);

            final FilterMap filterMap = new FilterMap();
            filterMap.setFilterName(clazzMapping[0]);
            filterMap.addURLPattern(clazzMapping[1]);
            standardContext.addFilterMapBefore(filterMap);
        }
    }

    // mainly to get back compatibility with tomcat <= 8.0
    final String cookieProcessor = SystemInstance.get().getProperty("tomee.tomcat.cookieProcessor");
    if (cookieProcessor != null) {
        // not that important for now if we use the container loader, we mainly want to be able to access
        // the legacy one
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            final Class<?> cookieProcessorClass = contextClassLoader.loadClass(cookieProcessor.trim());
            standardContext.setCookieProcessor(CookieProcessor.class.cast(cookieProcessorClass.newInstance()));
        } catch (final Exception e) {
            throw new IllegalArgumentException("Cannot set CookieProcessor: " + cookieProcessor);
        }
    }
}
 
Example #27
Source File: FailedContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void removeFilterMap(FilterMap filterMap) { /* NO-OP */ }
 
Example #28
Source File: TomcatFilterUtil.java    From aceql-http with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
    * Adds a predefined Filter definition and mapping to a Context Method
    * 
    * @param rootCtx
    *            the Context to add the predefined Filter to
    */
   public static void addFilterToContext(Context rootCtx) {

// See https://tomcat.apache.org/tomcat-8.5-doc/config/filter.html for
// filters

/*
 * <filter> <filter-name>CorsFilter</filter-name>
 * <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
 * <init-param> <param-name>cors.allowed.origins</param-name>
 * <param-value>*</param-value> </init-param> <init-param>
 * <param-name>cors.allowed.methods</param-name>
 * <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value> </init-param>
 * <init-param> <param-name>cors.allowed.headers</param-name>
 * <param-value>Content-Type,X-Requested-With,accept,Origin,Access-
 * Control-Request-Method,Access-Control-Request-Headers</param-value>
 * </init-param>
 * 
 * </filter> <filter-mapping> <filter-name>CorsFilter</filter-name>
 * <url-pattern>/*</url-pattern> </filter-mapping>
 */

String filterName = "CorsFilter";
String filterClass = "org.apache.catalina.filters.CorsFilter";

FilterDef filterDef = new FilterDef();

filterDef.setFilterName(filterName);
filterDef.setFilterClass(filterClass);

filterDef.addInitParameter("cors.allowed.origins", "*");
filterDef.addInitParameter("cors.allowed.methods",
	"GET,POST,HEAD,OPTIONS,PUT");
filterDef.addInitParameter("cors.allowed.headers",
	"Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers");

// Don't forget mapping
FilterMap filterMap = new FilterMap();
filterMap.setFilterName(filterName);
filterMap.addURLPattern("/*");

// Add both filter definition & mapping to context that will be used by
// a servlet:
rootCtx.addFilterDef(filterDef);
rootCtx.addFilterMap(filterMap);
   }
 
Example #29
Source File: TesterContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public FilterMap[] findFilterMaps() {
    return null;
}
 
Example #30
Source File: TesterContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void addFilterMapBefore(FilterMap filterMap) {
    // NO-OP
}