Search in sources :

Example 31 with Filter

use of javax.servlet.Filter in project felix by apache.

the class HttpServiceTest method setupOldWhiteboardFilter.

public void setupOldWhiteboardFilter(final String pattern) throws Exception {
    Dictionary<String, Object> servletProps = new Hashtable<String, Object>();
    servletProps.put("pattern", pattern);
    final Filter f = new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            initLatch.countDown();
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            response.getWriter().print("FILTER-");
            response.flushBuffer();
            chain.doFilter(request, response);
        }

        @Override
        public void destroy() {
            destroyLatch.countDown();
        }
    };
    registrations.add(m_context.registerService(Filter.class.getName(), f, servletProps));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) Filter(javax.servlet.Filter) Hashtable(java.util.Hashtable) FilterChain(javax.servlet.FilterChain) FilterConfig(javax.servlet.FilterConfig)

Example 32 with Filter

use of javax.servlet.Filter in project felix by apache.

the class JettyServiceTest method testInitBundleContextDeployIT.

/**
 * Tests to ensure the osgi-bundlecontext is available for init methods.
 *
 * @throws MalformedURLException
 * @throws InterruptedException
 */
@Test
public void testInitBundleContextDeployIT() throws Exception {
    // Setup mocks
    Deployment mockDeployment = mock(Deployment.class);
    Bundle mockBundle = mock(Bundle.class);
    BundleContext mockBundleContext = mock(BundleContext.class);
    // Setup behaviors
    when(mockDeployment.getBundle()).thenReturn(mockBundle);
    final org.osgi.framework.Filter f = mock(org.osgi.framework.Filter.class);
    when(f.toString()).thenReturn("(prop=*)");
    when(mockBundleContext.createFilter(anyString())).thenReturn(f);
    when(mockBundle.getBundleContext()).thenReturn(mockBundleContext);
    when(mockBundle.getSymbolicName()).thenReturn("test");
    when(mockBundle.getVersion()).thenReturn(new Version("0.0.1"));
    Dictionary<String, String> headerProperties = new Hashtable<String, String>();
    headerProperties.put("Web-ContextPath", "test");
    when(mockBundle.getHeaders()).thenReturn(headerProperties);
    when(mockDeployment.getContextPath()).thenReturn("test");
    when(mockBundle.getEntry("/")).thenReturn(new URL("http://www.apache.com"));
    when(mockBundle.getState()).thenReturn(Bundle.ACTIVE);
    EnumSet<DispatcherType> dispatcherSet = EnumSet.allOf(DispatcherType.class);
    dispatcherSet.add(DispatcherType.REQUEST);
    WebAppBundleContext webAppBundleContext = new WebAppBundleContext("/", mockBundle, this.getClass().getClassLoader());
    final CountDownLatch testLatch = new CountDownLatch(2);
    // Add a Filter to test whether the osgi-bundlecontext is available at init
    webAppBundleContext.addServlet(new ServletHolder(new Servlet() {

        @Override
        public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
        // Do Nothing
        }

        @Override
        public void init(ServletConfig config) throws ServletException {
            ServletContext context = config.getServletContext();
            assertNotNull(context.getAttribute(OSGI_BUNDLECONTEXT));
            testLatch.countDown();
        }

        @Override
        public String getServletInfo() {
            return null;
        }

        @Override
        public ServletConfig getServletConfig() {
            return null;
        }

        @Override
        public void destroy() {
        // Do Nothing
        }
    }), "/test1");
    webAppBundleContext.addFilter(new FilterHolder(new Filter() {

        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            ServletContext context = filterConfig.getServletContext();
            assertNotNull(context.getAttribute(OSGI_BUNDLECONTEXT));
            testLatch.countDown();
        }

        @Override
        public void doFilter(ServletRequest arg0, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Do Nothing
        }

        @Override
        public void destroy() {
        // Do Nothing
        }
    }), "/test2", dispatcherSet);
    jettyService.deploy(mockDeployment, webAppBundleContext);
    // Fail if takes too long.
    if (!testLatch.await(10, TimeUnit.SECONDS)) {
        fail("Test Was not asserted");
    }
}
Also used : ServletRequest(javax.servlet.ServletRequest) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) FilterChain(javax.servlet.FilterChain) Deployment(org.apache.felix.http.jetty.internal.JettyService.Deployment) Matchers.anyString(org.mockito.Matchers.anyString) URL(java.net.URL) Version(org.osgi.framework.Version) Servlet(javax.servlet.Servlet) ServletContext(javax.servlet.ServletContext) FilterConfig(javax.servlet.FilterConfig) DispatcherType(javax.servlet.DispatcherType) ServletResponse(javax.servlet.ServletResponse) Bundle(org.osgi.framework.Bundle) Hashtable(java.util.Hashtable) ServletConfig(javax.servlet.ServletConfig) CountDownLatch(java.util.concurrent.CountDownLatch) Filter(javax.servlet.Filter) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 33 with Filter

use of javax.servlet.Filter in project nifi by apache.

the class JettyServer method configureConnectors.

private void configureConnectors(final Server server) throws ServerConfigurationException {
    // create the http configuration
    final HttpConfiguration httpConfiguration = new HttpConfiguration();
    final int headerSize = DataUnit.parseDataSize(props.getWebMaxHeaderSize(), DataUnit.B).intValue();
    httpConfiguration.setRequestHeaderSize(headerSize);
    httpConfiguration.setResponseHeaderSize(headerSize);
    if (props.getPort() != null) {
        final Integer port = props.getPort();
        if (port < 0 || (int) Math.pow(2, 16) <= port) {
            throw new ServerConfigurationException("Invalid HTTP port: " + port);
        }
        logger.info("Configuring Jetty for HTTP on port: " + port);
        final List<Connector> serverConnectors = Lists.newArrayList();
        final Map<String, String> httpNetworkInterfaces = props.getHttpNetworkInterfaces();
        if (httpNetworkInterfaces.isEmpty() || httpNetworkInterfaces.values().stream().filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) {
            // create the connector
            final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
            // set host and port
            if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTP_HOST))) {
                http.setHost(props.getProperty(NiFiProperties.WEB_HTTP_HOST));
            }
            http.setPort(port);
            serverConnectors.add(http);
        } else {
            // add connectors for all IPs from http network interfaces
            serverConnectors.addAll(Lists.newArrayList(httpNetworkInterfaces.values().stream().map(ifaceName -> {
                NetworkInterface iface = null;
                try {
                    iface = NetworkInterface.getByName(ifaceName);
                } catch (SocketException e) {
                    logger.error("Unable to get network interface by name {}", ifaceName, e);
                }
                if (iface == null) {
                    logger.warn("Unable to find network interface named {}", ifaceName);
                }
                return iface;
            }).filter(Objects::nonNull).flatMap(iface -> Collections.list(iface.getInetAddresses()).stream()).map(inetAddress -> {
                // create the connector
                final ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
                // set host and port
                http.setHost(inetAddress.getHostAddress());
                http.setPort(port);
                return http;
            }).collect(Collectors.toList())));
        }
        // add all connectors
        serverConnectors.forEach(server::addConnector);
    }
    if (props.getSslPort() != null) {
        final Integer port = props.getSslPort();
        if (port < 0 || (int) Math.pow(2, 16) <= port) {
            throw new ServerConfigurationException("Invalid HTTPs port: " + port);
        }
        logger.info("Configuring Jetty for HTTPs on port: " + port);
        final List<Connector> serverConnectors = Lists.newArrayList();
        final Map<String, String> httpsNetworkInterfaces = props.getHttpsNetworkInterfaces();
        if (httpsNetworkInterfaces.isEmpty() || httpsNetworkInterfaces.values().stream().filter(value -> !Strings.isNullOrEmpty(value)).collect(Collectors.toList()).isEmpty()) {
            final ServerConnector https = createUnconfiguredSslServerConnector(server, httpConfiguration);
            // set host and port
            if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.WEB_HTTPS_HOST))) {
                https.setHost(props.getProperty(NiFiProperties.WEB_HTTPS_HOST));
            }
            https.setPort(port);
            serverConnectors.add(https);
        } else {
            // add connectors for all IPs from https network interfaces
            serverConnectors.addAll(Lists.newArrayList(httpsNetworkInterfaces.values().stream().map(ifaceName -> {
                NetworkInterface iface = null;
                try {
                    iface = NetworkInterface.getByName(ifaceName);
                } catch (SocketException e) {
                    logger.error("Unable to get network interface by name {}", ifaceName, e);
                }
                if (iface == null) {
                    logger.warn("Unable to find network interface named {}", ifaceName);
                }
                return iface;
            }).filter(Objects::nonNull).flatMap(iface -> Collections.list(iface.getInetAddresses()).stream()).map(inetAddress -> {
                final ServerConnector https = createUnconfiguredSslServerConnector(server, httpConfiguration);
                // set host and port
                https.setHost(inetAddress.getHostAddress());
                https.setPort(port);
                return https;
            }).collect(Collectors.toList())));
        }
        // add all connectors
        serverConnectors.forEach(server::addConnector);
    }
}
Also used : Bundle(org.apache.nifi.bundle.Bundle) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) WebAppContext(org.eclipse.jetty.webapp.WebAppContext) Arrays(java.util.Arrays) FilterChain(javax.servlet.FilterChain) Enumeration(java.util.Enumeration) ServletException(javax.servlet.ServletException) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) UninheritableFlowException(org.apache.nifi.controller.UninheritableFlowException) LoggerFactory(org.slf4j.LoggerFactory) JarFile(java.util.jar.JarFile) FlowService(org.apache.nifi.services.FlowService) StringUtils(org.apache.commons.lang3.StringUtils) InetAddress(java.net.InetAddress) ContentAccess(org.apache.nifi.web.ContentAccess) Configuration(org.eclipse.jetty.webapp.Configuration) AnnotationConfiguration(org.eclipse.jetty.annotations.AnnotationConfiguration) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Map(java.util.Map) FlowSerializationException(org.apache.nifi.controller.serialization.FlowSerializationException) UiExtension(org.apache.nifi.ui.extension.UiExtension) UiExtensionType(org.apache.nifi.web.UiExtensionType) Filter(javax.servlet.Filter) Server(org.eclipse.jetty.server.Server) EnumSet(java.util.EnumSet) Collection(java.util.Collection) NetworkInterface(java.net.NetworkInterface) Set(java.util.Set) WebApplicationContext(org.springframework.web.context.WebApplicationContext) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) ServletResponse(javax.servlet.ServletResponse) UiExtensionMapping(org.apache.nifi.ui.extension.UiExtensionMapping) ExtensionManager(org.apache.nifi.nar.ExtensionManager) DataUnit(org.apache.nifi.processor.DataUnit) DocGenerator(org.apache.nifi.documentation.DocGenerator) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) KeyStoreUtils(org.apache.nifi.security.util.KeyStoreUtils) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashMap(java.util.HashMap) BundleDetails(org.apache.nifi.bundle.BundleDetails) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) JarEntry(java.util.jar.JarEntry) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) SocketException(java.net.SocketException) Lists(com.google.common.collect.Lists) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) GzipHandler(org.eclipse.jetty.server.handler.gzip.GzipHandler) FlowSynchronizationException(org.apache.nifi.controller.serialization.FlowSynchronizationException) LifeCycleStartException(org.apache.nifi.lifecycle.LifeCycleStartException) NiFiWebConfigurationContext(org.apache.nifi.web.NiFiWebConfigurationContext) ServletRequest(javax.servlet.ServletRequest) WebAppClassLoader(org.eclipse.jetty.webapp.WebAppClassLoader) Logger(org.slf4j.Logger) WebApplicationContextUtils(org.springframework.web.context.support.WebApplicationContextUtils) HandlerList(org.eclipse.jetty.server.handler.HandlerList) HttpServletResponse(javax.servlet.http.HttpServletResponse) ExtensionMapping(org.apache.nifi.nar.ExtensionMapping) IOException(java.io.IOException) BeansException(org.springframework.beans.BeansException) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) JettyWebXmlConfiguration(org.eclipse.jetty.webapp.JettyWebXmlConfiguration) InputStreamReader(java.io.InputStreamReader) ApplicationContext(org.springframework.context.ApplicationContext) File(java.io.File) NiFiServer(org.apache.nifi.NiFiServer) ServerConnector(org.eclipse.jetty.server.ServerConnector) FileFilter(java.io.FileFilter) NiFiProperties(org.apache.nifi.util.NiFiProperties) Paths(java.nio.file.Paths) Resource(org.eclipse.jetty.util.resource.Resource) FilterConfig(javax.servlet.FilterConfig) DispatcherType(javax.servlet.DispatcherType) ServletContext(javax.servlet.ServletContext) BufferedReader(java.io.BufferedReader) Connector(org.eclipse.jetty.server.Connector) ResourceCollection(org.eclipse.jetty.util.resource.ResourceCollection) Collections(java.util.Collections) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SocketException(java.net.SocketException) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) NetworkInterface(java.net.NetworkInterface) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) ServerConnector(org.eclipse.jetty.server.ServerConnector)

Example 34 with Filter

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

the class CasHandlerTest method createHandler.

private CasHandler createHandler() {
    CasHandler handler = new CasHandler();
    STSClientConfiguration clientConfiguration = mock(STSClientConfiguration.class);
    when(clientConfiguration.getAddress()).thenReturn(STS_ADDRESS);
    handler.setClientConfiguration(clientConfiguration);
    Filter testFilter = mock(Filter.class);
    handler.setProxyFilter(new ProxyFilter(Arrays.asList(testFilter)));
    return handler;
}
Also used : STSClientConfiguration(ddf.security.sts.client.configuration.STSClientConfiguration) ProxyFilter(org.codice.ddf.security.handler.cas.filter.ProxyFilter) AbstractCasFilter(org.jasig.cas.client.util.AbstractCasFilter) Filter(javax.servlet.Filter) ProxyFilter(org.codice.ddf.security.handler.cas.filter.ProxyFilter)

Example 35 with Filter

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

the class ProxyFilter method init.

/**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
public void init(FilterConfig filterConfig) throws ServletException {
    if (!initialized) {
        for (Filter filter : filters) {
            LOGGER.debug("Calling {}.init({})", filter.getClass().getName(), filterConfig);
            filter.init(filterConfig);
        }
        initialized = true;
    }
}
Also used : Filter(javax.servlet.Filter)

Aggregations

Filter (javax.servlet.Filter)185 FilterChain (javax.servlet.FilterChain)67 Test (org.junit.Test)57 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 ServletRequest (javax.servlet.ServletRequest)43 ServletResponse (javax.servlet.ServletResponse)43 ServletException (javax.servlet.ServletException)28 FilterConfig (javax.servlet.FilterConfig)25 IOException (java.io.IOException)23 ServletContext (javax.servlet.ServletContext)20 Injector (com.google.inject.Injector)17 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)16 OncePerRequestFilter (org.springframework.web.filter.OncePerRequestFilter)13 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12 Map (java.util.Map)9 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)9 ArrayList (java.util.ArrayList)8 Hashtable (java.util.Hashtable)8 DispatcherType (javax.servlet.DispatcherType)8