Search in sources :

Example 51 with FilterConfig

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

the class AuthorizationFilterTest method testUnAuthorizedSubject.

@Test
public void testUnAuthorizedSubject() {
    FilterConfig filterConfig = mock(FilterConfig.class);
    ContextPolicyManager contextPolicyManager = new TestPolicyManager();
    contextPolicyManager.setContextPolicy(PATH, getMockContextPolicy());
    AuthorizationFilter loginFilter = new AuthorizationFilter(contextPolicyManager);
    try {
        loginFilter.init(filterConfig);
    } catch (ServletException e) {
        fail(e.getMessage());
    }
    Subject subject = mock(Subject.class);
    when(subject.isPermitted(any(CollectionPermission.class))).thenReturn(false);
    ThreadContext.bind(subject);
    HttpServletRequest servletRequest = getMockServletRequest();
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = (request, response) -> fail("Should not have called doFilter without a valid Subject");
    try {
        loginFilter.doFilter(servletRequest, servletResponse, filterChain);
    } catch (IOException | ServletException e) {
        fail(e.getMessage());
    }
    ThreadContext.unbindSubject();
}
Also used : FilterChain(javax.servlet.FilterChain) ServletException(javax.servlet.ServletException) ContextPolicy(org.codice.ddf.security.policy.context.ContextPolicy) CollectionPermission(ddf.security.permission.CollectionPermission) Collection(java.util.Collection) KeyValuePermission(ddf.security.permission.KeyValuePermission) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HashMap(java.util.HashMap) Test(org.junit.Test) Subject(ddf.security.Subject) Mockito.when(org.mockito.Mockito.when) Matchers.anyString(org.mockito.Matchers.anyString) Matchers.any(org.mockito.Matchers.any) HttpServletRequest(javax.servlet.http.HttpServletRequest) ThreadContext(org.apache.shiro.util.ThreadContext) Map(java.util.Map) FilterConfig(javax.servlet.FilterConfig) SecurityConstants(ddf.security.SecurityConstants) Assert.fail(org.junit.Assert.fail) Collections(java.util.Collections) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) Mockito.mock(org.mockito.Mockito.mock) Before(org.junit.Before) FilterChain(javax.servlet.FilterChain) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Subject(ddf.security.Subject) ContextPolicyManager(org.codice.ddf.security.policy.context.ContextPolicyManager) ServletException(javax.servlet.ServletException) HttpServletRequest(javax.servlet.http.HttpServletRequest) FilterConfig(javax.servlet.FilterConfig) CollectionPermission(ddf.security.permission.CollectionPermission) Test(org.junit.Test)

Example 52 with FilterConfig

use of javax.servlet.FilterConfig in project dhis2-core by dhis2.

the class ExcludableShallowEtagHeaderFilter method initFilterBean.

@Override
protected void initFilterBean() throws ServletException {
    FilterConfig filterConfig = getFilterConfig();
    String excludeRegex = filterConfig != null ? filterConfig.getInitParameter(EXCLUDE_URI_REGEX_VAR_NAME) : null;
    Assert.notNull(excludeRegex, String.format(excludeRegex, "Parameter '%s' must be specified for ExcludableShallowEtagHeaderFilter", EXCLUDE_URI_REGEX_VAR_NAME));
    pattern = Pattern.compile(excludeRegex);
    log.debug(String.format("ExcludableShallowEtagHeaderFilter initialized with %s: '%s'", EXCLUDE_URI_REGEX_VAR_NAME, excludeRegex));
}
Also used : FilterConfig(javax.servlet.FilterConfig)

Example 53 with FilterConfig

use of javax.servlet.FilterConfig in project tomee by apache.

the class LightweightWebAppBuilder method deployWebApps.

@Override
public void deployWebApps(final AppInfo appInfo, final ClassLoader appClassLoader) throws Exception {
    final CoreContainerSystem cs = (CoreContainerSystem) SystemInstance.get().getComponent(ContainerSystem.class);
    final AppContext appContext = cs.getAppContext(appInfo.appId);
    if (appContext == null) {
        throw new OpenEJBRuntimeException("Can't find app context for " + appInfo.appId);
    }
    for (final WebAppInfo webAppInfo : appInfo.webApps) {
        ClassLoader classLoader = loaderByWebContext.get(webAppInfo.moduleId);
        if (classLoader == null) {
            classLoader = appClassLoader;
        }
        final Set<Injection> injections = new HashSet<Injection>(appContext.getInjections());
        injections.addAll(new InjectionBuilder(classLoader).buildInjections(webAppInfo.jndiEnc));
        final List<BeanContext> beanContexts;
        if (!appInfo.webAppAlone) {
            // add module bindings in app
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            beanContexts = assembler.initEjbs(classLoader, appInfo, appContext, injections, new ArrayList<BeanContext>(), webAppInfo.moduleId);
            appContext.getBeanContexts().addAll(beanContexts);
        } else {
            beanContexts = null;
        }
        final Map<String, Object> bindings = new HashMap<>();
        bindings.putAll(appContext.getBindings());
        bindings.putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        final WebContext webContext = new WebContext(appContext);
        webContext.setBindings(bindings);
        webContext.getBindings().putAll(new JndiEncBuilder(webAppInfo.jndiEnc, injections, webAppInfo.moduleId, "Bean", null, webAppInfo.uniqueId, classLoader, appInfo.properties).buildBindings(JndiEncBuilder.JndiScope.comp));
        webContext.setJndiEnc(WebInitialContext.create(bindings, appContext.getGlobalJndiContext()));
        webContext.setClassLoader(classLoader);
        webContext.setId(webAppInfo.moduleId);
        webContext.setContextRoot(webAppInfo.contextRoot);
        webContext.setHost(webAppInfo.host);
        webContext.getInjections().addAll(injections);
        webContext.setInitialContext(new EmbeddedInitialContext(webContext.getJndiEnc(), webContext.getBindings()));
        final ServletContext component = SystemInstance.get().getComponent(ServletContext.class);
        final ServletContextEvent sce = component == null ? new MockServletContextEvent() : new ServletContextEvent(new LightServletContext(component, webContext.getClassLoader()));
        servletContextEvents.put(webAppInfo, sce);
        webContext.setServletContext(sce.getServletContext());
        SystemInstance.get().fireEvent(new EmbeddedServletContextCreated(sce.getServletContext()));
        appContext.getWebContexts().add(webContext);
        cs.addWebContext(webContext);
        if (!appInfo.webAppAlone && hasCdi(appInfo)) {
            final Assembler assembler = SystemInstance.get().getComponent(Assembler.class);
            new CdiBuilder().build(appInfo, appContext, beanContexts, webContext);
            assembler.startEjbs(true, beanContexts);
        }
        // listeners
        for (final ListenerInfo listener : webAppInfo.listeners) {
            final Class<?> clazz = webContext.getClassLoader().loadClass(listener.classname);
            final Object instance = webContext.newInstance(clazz);
            if (ServletContextListener.class.isInstance(instance)) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        ((ServletContextListener) instance).contextInitialized(sce);
                    }
                });
            }
            List<Object> list = listeners.get(webAppInfo);
            if (list == null) {
                list = new ArrayList<Object>();
                listeners.put(webAppInfo, list);
            }
            list.add(instance);
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebListener annotation = clazz.getAnnotation(WebListener.class);
                if (annotation != null) {
                    final Object instance = webContext.newInstance(clazz);
                    if (ServletContextListener.class.isInstance(instance)) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                ((ServletContextListener) instance).contextInitialized(sce);
                            }
                        });
                    }
                    List<Object> list = listeners.get(webAppInfo);
                    if (list == null) {
                        list = new ArrayList<Object>();
                        listeners.put(webAppInfo, list);
                    }
                    list.add(instance);
                }
            }
        }
        final DeployedWebObjects deployedWebObjects = new DeployedWebObjects();
        deployedWebObjects.webContext = webContext;
        servletDeploymentInfo.put(webAppInfo, deployedWebObjects);
        if (webContext.getWebBeansContext() != null && webContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
            final Thread thread = Thread.currentThread();
            final ClassLoader old = thread.getContextClassLoader();
            thread.setContextClassLoader(webContext.getClassLoader());
            try {
                OpenEJBLifecycle.class.cast(webContext.getWebBeansContext().getService(ContainerLifecycle.class)).startServletContext(sce.getServletContext());
            } finally {
                thread.setContextClassLoader(old);
            }
        }
        if (addServletMethod == null) {
            // can't manage filter/servlets
            continue;
        }
        // register filters
        for (final FilterInfo info : webAppInfo.filters) {
            switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                @Override
                public void run() {
                    for (final String mapping : info.mappings) {
                        final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, info.initParams);
                        try {
                            addFilterMethod.invoke(null, info.classname, webContext, mapping, config);
                            deployedWebObjects.filterMappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                }
            });
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String filterPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, filterPath);
                final WebFilter annotation = clazz.getAnnotation(WebFilter.class);
                if (annotation != null) {
                    final Properties initParams = new Properties();
                    for (final WebInitParam param : annotation.initParams()) {
                        initParams.put(param.name(), param.value());
                    }
                    final FilterConfig config = new SimpleFilterConfig(sce.getServletContext(), info.name, initParams);
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addFilterMethod.invoke(null, clazz.getName(), webContext, mapping, config);
                                        deployedWebObjects.filterMappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        final Map<String, PortInfo> ports = new TreeMap<String, PortInfo>();
        for (final PortInfo port : webAppInfo.portInfos) {
            ports.put(port.serviceLink, port);
        }
        // register servlets
        for (final ServletInfo info : webAppInfo.servlets) {
            if ("true".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxrs.on", "true"))) {
                // skip jaxrs servlets
                boolean skip = false;
                for (final ParamValueInfo pvi : info.initParams) {
                    if ("javax.ws.rs.Application".equals(pvi.name) || Application.class.getName().equals(pvi.name)) {
                        skip = true;
                    }
                }
                if (skip) {
                    continue;
                }
                if (info.servletClass == null) {
                    try {
                        if (Application.class.isAssignableFrom(classLoader.loadClass(info.servletName))) {
                            continue;
                        }
                    } catch (final Exception e) {
                    // no-op
                    }
                }
            }
            // If POJO web services, it will be overriden with WsServlet
            if (ports.containsKey(info.servletName) || ports.containsKey(info.servletClass)) {
                continue;
            }
            // deploy
            for (final String mapping : info.mappings) {
                switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                    @Override
                    public void run() {
                        try {
                            addServletMethod.invoke(null, info.servletClass, webContext, mapping);
                            deployedWebObjects.mappings.add(mapping);
                        } catch (final Exception e) {
                            LOGGER.warning(e.getMessage(), e);
                        }
                    }
                });
            }
        }
        for (final ClassListInfo info : webAppInfo.webAnnotatedClasses) {
            final String url = info.name;
            for (final String servletPath : info.list) {
                final Class<?> clazz = loadFromUrls(webContext.getClassLoader(), url, servletPath);
                final WebServlet annotation = clazz.getAnnotation(WebServlet.class);
                if (annotation != null) {
                    for (final String[] mappings : asList(annotation.urlPatterns(), annotation.value())) {
                        switchServletContextIfNeeded(sce.getServletContext(), new Runnable() {

                            @Override
                            public void run() {
                                for (final String mapping : mappings) {
                                    try {
                                        addServletMethod.invoke(null, clazz.getName(), webContext, mapping);
                                        deployedWebObjects.mappings.add(mapping);
                                    } catch (final Exception e) {
                                        LOGGER.warning(e.getMessage(), e);
                                    }
                                }
                            }
                        });
                    }
                }
            }
        }
        if (addDefaults != null && tryJsp()) {
            addDefaults.invoke(null, webContext);
            deployedWebObjects.mappings.add("*\\.jsp");
        }
    }
}
Also used : CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) ContainerSystem(org.apache.openejb.spi.ContainerSystem) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ServletInfo(org.apache.openejb.assembler.classic.ServletInfo) WebAppInfo(org.apache.openejb.assembler.classic.WebAppInfo) ParamValueInfo(org.apache.openejb.assembler.classic.ParamValueInfo) FilterConfig(javax.servlet.FilterConfig) HashSet(java.util.HashSet) InjectionBuilder(org.apache.openejb.assembler.classic.InjectionBuilder) CoreContainerSystem(org.apache.openejb.core.CoreContainerSystem) Injection(org.apache.openejb.Injection) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) ListenerInfo(org.apache.openejb.assembler.classic.ListenerInfo) CdiBuilder(org.apache.openejb.cdi.CdiBuilder) Assembler(org.apache.openejb.assembler.classic.Assembler) OpenEJBLifecycle(org.apache.openejb.cdi.OpenEJBLifecycle) WebContext(org.apache.openejb.core.WebContext) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent) Properties(java.util.Properties) ClassListInfo(org.apache.openejb.assembler.classic.ClassListInfo) PortInfo(org.apache.openejb.assembler.classic.PortInfo) WebServlet(javax.servlet.annotation.WebServlet) MockServletContext(org.apache.webbeans.web.lifecycle.test.MockServletContext) ServletContext(javax.servlet.ServletContext) FilterInfo(org.apache.openejb.assembler.classic.FilterInfo) WebFilter(javax.servlet.annotation.WebFilter) AppContext(org.apache.openejb.AppContext) TreeMap(java.util.TreeMap) NamingException(javax.naming.NamingException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) WebListener(javax.servlet.annotation.WebListener) JndiEncBuilder(org.apache.openejb.assembler.classic.JndiEncBuilder) WebInitParam(javax.servlet.annotation.WebInitParam) ServletContextEvent(javax.servlet.ServletContextEvent) MockServletContextEvent(org.apache.webbeans.web.lifecycle.test.MockServletContextEvent)

Example 54 with FilterConfig

use of javax.servlet.FilterConfig in project Openfire by igniterealtime.

the class HttpBindManager method createBoshHandler.

private void createBoshHandler(ContextHandlerCollection contexts, String boshPath) {
    ServletContextHandler context = new ServletContextHandler(contexts, boshPath, ServletContextHandler.SESSIONS);
    // Ensure the JSP engine is initialized correctly (in order to be able to cope with Tomcat/Jasper precompiled JSPs).
    final List<ContainerInitializer> initializers = new ArrayList<>();
    initializers.add(new ContainerInitializer(new JasperInitializer(), null));
    context.setAttribute("org.eclipse.jetty.containerInitializers", initializers);
    context.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
    context.setAllowNullPathInfo(true);
    context.addServlet(new ServletHolder(new HttpBindServlet()), "/*");
    if (isHttpCompressionEnabled()) {
        Filter gzipFilter = new AsyncGzipFilter() {

            @Override
            public void init(FilterConfig config) throws ServletException {
                super.init(config);
                _methods.add(HttpMethod.POST.asString());
                Log.info("Installed response compression filter");
            }
        };
        FilterHolder filterHolder = new FilterHolder();
        filterHolder.setFilter(gzipFilter);
        context.addFilter(filterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
    }
}
Also used : FilterHolder(org.eclipse.jetty.servlet.FilterHolder) AsyncGzipFilter(org.eclipse.jetty.servlets.AsyncGzipFilter) SimpleInstanceManager(org.apache.tomcat.SimpleInstanceManager) InstanceManager(org.apache.tomcat.InstanceManager) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) SimpleInstanceManager(org.apache.tomcat.SimpleInstanceManager) Filter(javax.servlet.Filter) AsyncGzipFilter(org.eclipse.jetty.servlets.AsyncGzipFilter) ContainerInitializer(org.eclipse.jetty.plus.annotation.ContainerInitializer) FilterConfig(javax.servlet.FilterConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) JasperInitializer(org.apache.jasper.servlet.JasperInitializer)

Example 55 with FilterConfig

use of javax.servlet.FilterConfig in project jetty.project by eclipse.

the class FilterHolderTest method testInitialize.

@Test
public void testInitialize() throws Exception {
    ServletHandler handler = new ServletHandler();
    final AtomicInteger counter = new AtomicInteger(0);
    Filter filter = new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            counter.incrementAndGet();
        }

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

        @Override
        public void destroy() {
        }
    };
    FilterHolder fh = new FilterHolder();
    fh.setServletHandler(handler);
    fh.setName("xx");
    fh.setFilter(filter);
    try (StacklessLogging stackless = new StacklessLogging(FilterHolder.class)) {
        fh.initialize();
        fail("Not started");
    } catch (Exception e) {
    //expected
    }
    fh.start();
    fh.initialize();
    assertEquals(1, counter.get());
    fh.initialize();
    assertEquals(1, counter.get());
    fh.stop();
    assertEquals(1, counter.get());
    fh.start();
    assertEquals(1, counter.get());
    fh.initialize();
    assertEquals(2, counter.get());
}
Also used : ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Filter(javax.servlet.Filter) FilterChain(javax.servlet.FilterChain) FilterConfig(javax.servlet.FilterConfig) StacklessLogging(org.eclipse.jetty.util.log.StacklessLogging) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

FilterConfig (javax.servlet.FilterConfig)118 Test (org.junit.Test)70 HttpServletRequest (javax.servlet.http.HttpServletRequest)64 FilterChain (javax.servlet.FilterChain)63 HttpServletResponse (javax.servlet.http.HttpServletResponse)50 ServletContext (javax.servlet.ServletContext)28 HashMap (java.util.HashMap)21 ServletException (javax.servlet.ServletException)21 Vector (java.util.Vector)17 Properties (java.util.Properties)15 Filter (javax.servlet.Filter)14 ServletResponse (javax.servlet.ServletResponse)14 ServletRequest (javax.servlet.ServletRequest)12 IOException (java.io.IOException)10 SignerSecretProvider (org.apache.hadoop.security.authentication.util.SignerSecretProvider)10 HttpCookie (java.net.HttpCookie)9 Cookie (javax.servlet.http.Cookie)9 Signer (org.apache.hadoop.security.authentication.util.Signer)9 Enumeration (java.util.Enumeration)8 CrossOriginFilter (org.apache.hadoop.security.http.CrossOriginFilter)8