Search in sources :

Example 1 with FilterRegistration

use of javax.servlet.FilterRegistration in project jersey by jersey.

the class FilterUrlMappingsProviderImpl method getFilterUrlMappings.

@Override
public List<String> getFilterUrlMappings(FilterConfig filterConfig) {
    FilterRegistration filterRegistration = filterConfig.getServletContext().getFilterRegistration(filterConfig.getFilterName());
    Collection<String> urlPatternMappings = filterRegistration.getUrlPatternMappings();
    List<String> result = new ArrayList<>();
    for (String pattern : urlPatternMappings) {
        result.add(pattern.endsWith("*") ? pattern.substring(0, pattern.length() - 1) : pattern);
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) FilterRegistration(javax.servlet.FilterRegistration)

Example 2 with FilterRegistration

use of javax.servlet.FilterRegistration in project ddf by codice.

the class FilterInjector method injectFilter.

/**
     * Injects the filter into the passed-in servlet context. This only works if
     * the servlet has not already been initialized.
     *
     * @param serviceReference Reference to the servlet context that the filter should be
     *                         injected into.
     */
public void injectFilter(ServiceReference<ServletContext> serviceReference) {
    Bundle refBundle = serviceReference.getBundle();
    LOGGER.debug("Adding Servlet Filter for {}", refBundle.getSymbolicName());
    BundleContext bundlectx = refBundle.getBundleContext();
    ServletContext context = bundlectx.getService(serviceReference);
    try {
        SessionCookieConfig sessionCookieConfig = context.getSessionCookieConfig();
        sessionCookieConfig.setPath("/");
        sessionCookieConfig.setSecure(true);
        sessionCookieConfig.setHttpOnly(true);
    } catch (Exception e) {
        LOGGER.trace("Failed trying to set the cookie config path to /. This can usually be ignored", e);
    }
    //Jetty will place non-programmatically added filters (filters added via web.xml) in front of programmatically
    //added filters. This is probably OK in most instances, however, this security filter must ALWAYS be first.
    //This reflection hack basically tricks Jetty into believing that this filter is a web.xml filter so that it always ends up first.
    //In order for this to work correctly, the delegating filter must always be added before any other programmatically added filters.
    Field field = null;
    try {
        //this grabs the enclosing instance class, which is actually a private class
        //this is the only way to do this in Java
        field = context.getClass().getDeclaredField("this$0");
        field.setAccessible(true);
    } catch (NoSuchFieldException e) {
        LOGGER.warn("Unable to find enclosing class of ServletContext for delegating filter. Security may not work correctly", e);
    }
    Field matchAfterField = null;
    Object matchAfterValue = null;
    ServletHandler handler = null;
    if (field != null) {
        //need to grab the servlet context handler so we can get down to the handler, which is what we really need
        ServletContextHandler httpServiceContext = null;
        try {
            httpServiceContext = (ServletContextHandler) field.get(context);
        } catch (IllegalAccessException e) {
            LOGGER.warn("Unable to get the ServletContextHandler for {}. The delegating filter may not work properly.", refBundle.getSymbolicName(), e);
        }
        if (httpServiceContext != null) {
            //now that we have the handler, we can muck with the filters and state variables
            handler = httpServiceContext.getServletHandler();
            SessionHandler sessionHandler = httpServiceContext.getSessionHandler();
            if (sessionHandler != null) {
                sessionHandler.addEventListener(new WrapperListener());
            }
            if (handler != null) {
                try {
                    matchAfterField = handler.getClass().getSuperclass().getDeclaredField("_matchAfterIndex");
                    matchAfterField.setAccessible(true);
                } catch (NoSuchFieldException e) {
                    LOGGER.warn("Unable to find the matchAfterIndex value for the ServletHandler. The delegating filter may not work properly.", e);
                }
                if (matchAfterField != null) {
                    try {
                        //this value is initialized to -1 and only changes after a programmatic filter has been added
                        //so basically we are grabbing this value (should be -1) and then setting the field back to that value
                        //after we add our delegating filter to the mix
                        matchAfterValue = matchAfterField.get(handler);
                    } catch (IllegalAccessException e) {
                        LOGGER.warn("Unable to get the value of the match after field. The delegating filter may not work properly.", e);
                    }
                }
            }
        }
    }
    try {
        //This causes the value of "_matchAfterIndex" to jump to 0 which means all web.xml filters will be added in front of it
        //this isn't what we want, so we need to reset it back to what it was before
        FilterRegistration filterReg = context.addFilter(DELEGATING_FILTER, delegatingServletFilter);
        if (filterReg == null) {
            filterReg = context.getFilterRegistration(DELEGATING_FILTER);
        } else {
            ((FilterRegistration.Dynamic) filterReg).setAsyncSupported(true);
        }
        filterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, ALL_URLS);
    } catch (IllegalStateException ise) {
        LOGGER.warn("Could not inject filter into {} because the servlet was already initialized.", refBundle.getSymbolicName(), ise);
    }
    if (matchAfterField != null && matchAfterValue != null) {
        try {
            //Reset the value back to what it was before we added our delegating filter, this should cause Jetty to behave as if
            //this was a filter added via web.xml
            matchAfterField.set(handler, matchAfterValue);
        } catch (IllegalAccessException e) {
            LOGGER.warn("Unable to set the match after field back to the original value. The delegating filter might be out of order", e);
        }
    } else {
        LOGGER.warn("Unable to set the match after field back to the original value. The delegating filter might be out of order.");
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServletHandler(org.eclipse.jetty.servlet.ServletHandler) Bundle(org.osgi.framework.Bundle) Field(java.lang.reflect.Field) ServletContext(javax.servlet.ServletContext) SessionCookieConfig(javax.servlet.SessionCookieConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) BundleContext(org.osgi.framework.BundleContext) FilterRegistration(javax.servlet.FilterRegistration)

Example 3 with FilterRegistration

use of javax.servlet.FilterRegistration in project Payara by payara.

the class EmbeddedAddServletAndFilterByClassNameTest method testEmbeddedAddServletDefaultVS.

@Test
public void testEmbeddedAddServletDefaultVS() throws Exception {
    VirtualServer vs = embedded.getVirtualServer("server");
    System.out.println("Default virtual server " + vs);
    Context context = (Context) embedded.createContext(root);
    ServletRegistration sr = context.addServlet("NewFilterServlet", "org.glassfish.tests.embedded.web.NewFilterServlet");
    sr.setInitParameter("servletInitName", "servletInitValue");
    sr.addMapping("/newFilterServlet");
    FilterRegistration fr = context.addFilter("NewFilter", "org.glassfish.tests.embedded.web.NewFilter");
    fr.setInitParameter("filterInitName", "filterInitValue");
    fr.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "NewFilterServlet");
    vs.addContext(context, contextRoot);
    URL servlet = new URL("http://localhost:8080/" + contextRoot + "/newFilterServlet");
    URLConnection yc = servlet.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
    }
    in.close();
    vs.removeContext(context);
}
Also used : ServletRegistration(javax.servlet.ServletRegistration) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) URL(java.net.URL) URLConnection(java.net.URLConnection) FilterRegistration(javax.servlet.FilterRegistration) Test(org.junit.Test)

Example 4 with FilterRegistration

use of javax.servlet.FilterRegistration in project Payara by payara.

the class EmbeddedAddServletAndFilterByClassTest method testEmbeddedAddServletDefaultVS.

@Test
public void testEmbeddedAddServletDefaultVS() throws Exception {
    VirtualServer vs = embedded.getVirtualServer("server");
    System.out.println("Default virtual server " + vs);
    Context context = (Context) embedded.createContext(root);
    ServletRegistration sr = context.addServlet("NewFilterServlet", (Class<? extends Servlet>) getClass().getClassLoader().loadClass("org.glassfish.tests.embedded.web.NewFilterServlet"));
    sr.setInitParameter("servletInitName", "servletInitValue");
    sr.addMapping("/newFilterServlet");
    FilterRegistration fr = context.addFilter("NewFilter", (Class<? extends Filter>) getClass().getClassLoader().loadClass("org.glassfish.tests.embedded.web.NewFilter"));
    fr.setInitParameter("filterInitName", "filterInitValue");
    fr.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "NewFilterServlet");
    vs.addContext(context, contextRoot);
    URL servlet = new URL("http://localhost:8080/" + contextRoot + "/newFilterServlet");
    URLConnection yc = servlet.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
    }
    in.close();
    vs.removeContext(context);
}
Also used : ServletRegistration(javax.servlet.ServletRegistration) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) URL(java.net.URL) URLConnection(java.net.URLConnection) FilterRegistration(javax.servlet.FilterRegistration) Test(org.junit.Test)

Example 5 with FilterRegistration

use of javax.servlet.FilterRegistration in project herd by FINRAOS.

the class WarInitializer method initRequestLoggingFilter.

/**
 * Initializes the request logging filter that logs all incoming REST requests.
 *
 * @param servletContext the servlet context.
 */
protected void initRequestLoggingFilter(ServletContext servletContext) {
    // Add a filter that logs incoming HTTP request and configure flags to enable more detailed logging.
    FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("requestLoggingFilter", new RequestLoggingFilter());
    filterRegistration.addMappingForUrlPatterns(null, true, "/rest/*");
}
Also used : RequestLoggingFilter(org.finra.herd.ui.RequestLoggingFilter) FilterRegistration(javax.servlet.FilterRegistration)

Aggregations

FilterRegistration (javax.servlet.FilterRegistration)16 Test (org.junit.Test)5 ServletRegistration (javax.servlet.ServletRegistration)4 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 URL (java.net.URL)3 URLConnection (java.net.URLConnection)3 SpringWebApplicationFactory (org.apache.wicket.spring.SpringWebApplicationFactory)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 HttpSessionEventPublisher (org.springframework.security.web.session.HttpSessionEventPublisher)2 RequestContextListener (org.springframework.web.context.request.RequestContextListener)2 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 HttpConstraintElement (javax.servlet.HttpConstraintElement)1 ServletContext (javax.servlet.ServletContext)1 ServletSecurityElement (javax.servlet.ServletSecurityElement)1 SessionCookieConfig (javax.servlet.SessionCookieConfig)1 SessionHandler (org.eclipse.jetty.server.session.SessionHandler)1 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)1 ServletHandler (org.eclipse.jetty.servlet.ServletHandler)1