Example usage for javax.servlet FilterConfig FilterConfig

List of usage examples for javax.servlet FilterConfig FilterConfig

Introduction

In this page you can find the example usage for javax.servlet FilterConfig FilterConfig.

Prototype

FilterConfig

Source Link

Usage

From source file:com.nominanuda.solr.SpringMvcServerEmbed.java

public void init() throws ServletException {
    FilterConfig fc = new FilterConfig() {
        public String getInitParameter(String name) {
            return null;
        }//w w  w  .j  a  va 2  s.  c o  m

        public ServletContext getServletContext() {
            throw new UnsupportedOperationException();
        }

        @SuppressWarnings("rawtypes")
        public Enumeration getInitParameterNames() {
            throw new UnsupportedOperationException();
        }

        public String getFilterName() {
            throw new UnsupportedOperationException();
        }
    };
    solrDispatchFilter = new SolrDispatchFilter();
    solrDispatchFilter.init(fc);

    Check.illegalstate.assertFalse(SolrAware.getInstance().getCoreNames().isEmpty());
}

From source file:jetbrains.buildServer.server.rest.APIController.java

private FilterConfig createJerseyConfig() {
    return new FilterConfig() {
        Map<String, String> initParameters = new HashMap<String, String>();

        {//from   ww  w  . j  ava 2 s. c  o m
            //        initParameters.put("com.sun.jersey.config.property.WadlGeneratorConfig", "jetbrains.buildServer.server.rest.WadlGenerator");
            initParameters.put("com.sun.jersey.config.property.packages",
                    "jetbrains.buildServer.server.rest.request;" + getPackagesFromExtensions());
        }

        private String getPackagesFromExtensions() {
            return StringUtil.join(myServer.getExtensions(RESTControllerExtension.class),
                    new Function<RESTControllerExtension, String>() {
                        public String fun(final RESTControllerExtension restControllerExtension) {
                            return restControllerExtension.getPackage();
                        }
                    }, ";");
        }

        public String getFilterName() {
            return "jerseyFilter";
        }

        public ServletContext getServletContext() {
            //return APIController.this.getServletContext();
            // workaround for http://jetbrains.net/tracker/issue2/TW-7656
            for (ApplicationContext ctx = getApplicationContext(); ctx != null; ctx = ctx.getParent()) {
                if (ctx instanceof WebApplicationContext) {
                    return ((WebApplicationContext) ctx).getServletContext();
                }
            }
            throw new RuntimeException("WebApplication context was not found.");
        }

        public String getInitParameter(final String s) {
            return initParameters.get(s);
        }

        public Enumeration getInitParameterNames() {
            return new Vector<String>(initParameters.keySet()).elements();
        }
    };
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationFilter.java

/**
 * Initialize the filter.//from   w  ww  .  j ava 2s  .  c o  m
 *
 * @param filterConfig filter configuration.
 * @throws ServletException thrown if the filter could not be initialized.
 */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
    LOG.info("AtlasAuthenticationFilter initialization started");
    final FilterConfig globalConf = filterConfig;

    final Map<String, String> params = new HashMap<>();

    FilterConfig filterConfig1 = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            if (globalConf != null) {
                return globalConf.getServletContext();
            } else {
                return nullContext;
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "AtlasAuthenticationFilter";
        }
    };

    super.init(filterConfig1);

    optionsServlet = new HttpServlet() {
    };
    optionsServlet.init();

}

From source file:org.apache.ranger.security.web.filter.RangerKRBAuthenticationFilter.java

@Override
public void init(FilterConfig conf) throws ServletException {
    final FilterConfig globalConf = conf;
    final Map<String, String> params = new HashMap<String, String>();
    params.put(AUTH_TYPE, PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple"));
    params.put(NAME_RULES_PARAM, PropertiesUtil.getProperty(NAME_RULES, "DEFAULT"));
    params.put(TOKEN_VALID_PARAM, PropertiesUtil.getProperty(TOKEN_VALID, "30"));
    params.put(COOKIE_DOMAIN_PARAM,/*from   www.ja v a2s.  c om*/
            PropertiesUtil.getProperty(COOKIE_DOMAIN, PropertiesUtil.getProperty(HOST_NAME, "localhost")));
    params.put(COOKIE_PATH_PARAM, PropertiesUtil.getProperty(COOKIE_PATH, "/"));
    try {
        params.put(PRINCIPAL_PARAM, SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(PRINCIPAL, ""),
                PropertiesUtil.getProperty(HOST_NAME)));
    } catch (IOException ignored) {
        // do nothing
    }
    params.put(KEYTAB_PARAM, PropertiesUtil.getProperty(KEYTAB, ""));

    FilterConfig myConf = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            if (globalConf != null) {
                return globalConf.getServletContext();
            } else {
                return noContext;
            }
        }

        @SuppressWarnings("unchecked")
        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "KerberosFilter";
        }
    };
    super.init(myConf);
}

From source file:org.apache.solr.security.GenericHadoopAuthPlugin.java

@SuppressWarnings("unchecked")
protected FilterConfig getInitFilterConfig(Map<String, Object> pluginConfig) {
    Map<String, String> params = new HashMap<>();

    String type = (String) Objects.requireNonNull(pluginConfig.get(HADOOP_AUTH_TYPE));
    params.put(HADOOP_AUTH_TYPE, type);/*from  w  ww  .ja v  a  2s. c  o  m*/

    String sysPropPrefix = (String) pluginConfig.getOrDefault(SYSPROP_PREFIX_PROPERTY, "solr.");
    Collection<String> authConfigNames = (Collection<String>) pluginConfig
            .getOrDefault(AUTH_CONFIG_NAMES_PROPERTY, Collections.emptyList());
    Map<String, String> authConfigDefaults = (Map<String, String>) pluginConfig
            .getOrDefault(DEFAULT_AUTH_CONFIGS_PROPERTY, Collections.emptyMap());
    Map<String, String> proxyUserConfigs = (Map<String, String>) pluginConfig.getOrDefault(PROXY_USER_CONFIGS,
            Collections.emptyMap());

    for (String configName : authConfigNames) {
        String systemProperty = sysPropPrefix + configName;
        String defaultConfigVal = authConfigDefaults.get(configName);
        String configVal = System.getProperty(systemProperty, defaultConfigVal);
        if (configVal != null) {
            params.put(configName, configVal);
        }
    }

    // Configure proxy user settings.
    params.putAll(proxyUserConfigs);

    final ServletContext servletContext = new AttributeOnlyServletContext();
    log.info("Params: " + params);

    ZkController controller = coreContainer.getZkController();
    if (controller != null) {
        servletContext.setAttribute(DELEGATION_TOKEN_ZK_CLIENT, controller.getZkClient());
    }

    FilterConfig conf = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "HadoopAuthFilter";
        }
    };

    return conf;
}

From source file:org.apache.solr.security.KerberosPlugin.java

@VisibleForTesting
protected FilterConfig getInitFilterConfig(Map<String, Object> pluginConfig, boolean skipKerberosChecking) {
    Map<String, String> params = new HashMap();
    params.put("type", "kerberos");
    putParam(params, "kerberos.name.rules", NAME_RULES_PARAM, "DEFAULT");
    putParam(params, "token.valid", TOKEN_VALID_PARAM, "30");
    putParam(params, "cookie.path", COOKIE_PATH_PARAM, "/");
    if (!skipKerberosChecking) {
        putParam(params, "kerberos.principal", PRINCIPAL_PARAM, null);
        putParam(params, "kerberos.keytab", KEYTAB_PARAM, null);
    } else {//from  w  w w .ja  v a 2s  . com
        putParamOptional(params, "kerberos.principal", PRINCIPAL_PARAM);
        putParamOptional(params, "kerberos.keytab", KEYTAB_PARAM);
    }

    String delegationTokenStr = System.getProperty(DELEGATION_TOKEN_ENABLED, null);
    boolean delegationTokenEnabled = (delegationTokenStr == null) ? false
            : Boolean.parseBoolean(delegationTokenStr);
    ZkController controller = coreContainer.getZkController();

    if (delegationTokenEnabled) {
        putParam(params, "delegation-token.token-kind", DELEGATION_TOKEN_KIND, DELEGATION_TOKEN_TYPE_DEFAULT);
        if (coreContainer.isZooKeeperAware()) {
            putParam(params, "signer.secret.provider", DELEGATION_TOKEN_SECRET_PROVIDER, "zookeeper");
            if ("zookeeper".equals(params.get("signer.secret.provider"))) {
                String zkHost = controller.getZkServerAddress();
                putParam(params, "token.validity", DELEGATION_TOKEN_VALIDITY, "36000");
                params.put("zk-dt-secret-manager.enable", "true");

                String chrootPath = zkHost.contains("/") ? zkHost.substring(zkHost.indexOf("/")) : "";
                String znodeWorkingPath = chrootPath + SecurityAwareZkACLProvider.SECURITY_ZNODE_PATH
                        + "/zkdtsm";
                // Note - Curator complains if the znodeWorkingPath starts with /
                znodeWorkingPath = znodeWorkingPath.startsWith("/") ? znodeWorkingPath.substring(1)
                        : znodeWorkingPath;
                putParam(params, "zk-dt-secret-manager.znodeWorkingPath",
                        DELEGATION_TOKEN_SECRET_MANAGER_ZNODE_WORKING_PATH, znodeWorkingPath);
                putParam(params, "signer.secret.provider.zookeeper.path",
                        DELEGATION_TOKEN_SECRET_PROVIDER_ZK_PATH, "/token");
                // ensure krb5 is setup properly before running curator
                getHttpClientBuilder(SolrHttpClientBuilder.create());
            }
        } else {
            log.info("CoreContainer is not ZooKeeperAware, not setting ZK-related delegation token properties");
        }
    }

    // Special handling for the "cookie.domain" based on whether port should be
    // appended to the domain. Useful for situations where multiple solr nodes are
    // on the same host.
    String usePortStr = System.getProperty(COOKIE_PORT_AWARE_PARAM, null);
    boolean needPortAwareCookies = (usePortStr == null) ? false : Boolean.parseBoolean(usePortStr);

    if (!needPortAwareCookies || !coreContainer.isZooKeeperAware()) {
        putParam(params, "cookie.domain", COOKIE_DOMAIN_PARAM, null);
    } else { // we need port aware cookies and we are in SolrCloud mode.
        String host = System.getProperty(COOKIE_DOMAIN_PARAM, null);
        if (host == null) {
            throw new SolrException(ErrorCode.SERVER_ERROR,
                    "Missing required parameter '" + COOKIE_DOMAIN_PARAM + "'.");
        }
        int port = controller.getHostPort();
        params.put("cookie.domain", host + ":" + port);
    }

    // check impersonator config
    for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) {
        String key = e.nextElement().toString();
        if (key.startsWith(IMPERSONATOR_PREFIX)) {
            if (!delegationTokenEnabled) {
                throw new SolrException(ErrorCode.SERVER_ERROR,
                        "Impersonator configuration requires delegation tokens to be enabled: " + key);
            }
            params.put(key, System.getProperty(key));
        }
    }
    final ServletContext servletContext = new AttributeOnlyServletContext();
    if (controller != null) {
        servletContext.setAttribute(DELEGATION_TOKEN_ZK_CLIENT, controller.getZkClient());
    }
    if (delegationTokenEnabled) {
        kerberosFilter = new DelegationTokenKerberosFilter();
        // pass an attribute-enabled context in order to pass the zkClient
        // and because the filter may pass a curator instance.
    } else {
        kerberosFilter = new KerberosFilter();
    }
    log.info("Params: " + params);

    FilterConfig conf = new FilterConfig() {
        @Override
        public ServletContext getServletContext() {
            return servletContext;
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return new IteratorEnumeration(params.keySet().iterator());
        }

        @Override
        public String getInitParameter(String param) {
            return params.get(param);
        }

        @Override
        public String getFilterName() {
            return "KerberosFilter";
        }
    };

    return conf;
}

From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.service.NuxeoCorsFilterDescriptor.java

public FilterConfig buildFilterConfig() {
    final Dictionary<String, String> parameters = buildDictionary();

    return new FilterConfig() {
        @Override//  www  .  j  a  v a2s.  c om
        public String getFilterName() {
            return "NuxeoCorsFilterDescriptor";
        }

        @Override
        public ServletContext getServletContext() {
            // Not used with @see CORSFilter
            return null;
        }

        @Override
        public String getInitParameter(String name) {
            return parameters.get(name);
        }

        @Override
        public Enumeration getInitParameterNames() {
            return parameters.keys();
        }
    };
}

From source file:org.ovirt.engine.api.common.security.CORSSupportFilter.java

private void lazyInit() throws ServletException {
    // Check if the CORS support is enabled:
    final Boolean enabled = (Boolean) getBackendParameter(ConfigurationValues.CORSSupport);
    if (enabled == null || !enabled) {
        log.info("CORS support is disabled.");
        return;//from  ww w  . j a  v  a  2s.c  om
    }

    // Get the allowed origins from the backend configuration:
    final String allowedOrigins = (String) getBackendParameter(ConfigurationValues.CORSAllowedOrigins);
    if (StringUtils.isEmpty(allowedOrigins)) {
        log.warn(
                "The CORS support has been enabled, but the list of allowed origins is empty. This means that CORS "
                        + "support will actually be disabled.");
        return;
    }
    log.info("CORS support is enabled for origins \"{}\".", allowedOrigins);

    // Populate the parameters for the delegate:
    final Map<String, String> parameters = new HashMap<>();
    parameters.put(CORSFilter.PARAM_CORS_ALLOWED_METHODS, "GET,POST,PUT,DELETE");
    parameters.put(CORSFilter.PARAM_CORS_ALLOWED_HEADERS, "Accept,Authorization,Content-Type");
    parameters.put(CORSFilter.PARAM_CORS_ALLOWED_ORIGINS, allowedOrigins);

    // Add all the parameters of this filter to those passed to the delegate, so that the user can override the
    // configuration modifying the web.xml file:
    final Enumeration<String> names = config.getInitParameterNames();
    while (names.hasMoreElements()) {
        final String name = names.nextElement();
        final String value = config.getInitParameter(name);
        parameters.put(name, value);
    }

    // Create the delegate and initialize with the prepared parameters:
    delegate = new CORSFilter();
    delegate.init(new FilterConfig() {
        @Override
        public String getFilterName() {
            return config.getFilterName();
        }

        @Override
        public ServletContext getServletContext() {
            return config.getServletContext();
        }

        @Override
        public String getInitParameter(String name) {
            return parameters.get(name);
        }

        @Override
        public Enumeration<String> getInitParameterNames() {
            return Collections.enumeration(parameters.keySet());
        }
    });
}

From source file:org.seasar.cubby.plugins.guice.CubbyModuleTest.java

@Test
public void configure() throws Exception {
    final HttpServletRequest request = createNiceMock(HttpServletRequest.class);
    final HttpServletResponse response = createNiceMock(HttpServletResponse.class);
    final ServletContext servletContext = createNiceMock(ServletContext.class);
    expect(servletContext.getInitParameter("cubby.guice.module")).andStubReturn(TestModule.class.getName());
    final Hashtable<String, Object> attributes = new Hashtable<String, Object>();
    expect(servletContext.getAttribute((String) anyObject())).andStubAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(getCurrentArguments()[0]);
        }/*w  w  w . j  a v  a 2  s. c o m*/

    });
    servletContext.setAttribute((String) anyObject(), anyObject());
    expectLastCall().andAnswer(new IAnswer<Void>() {

        public Void answer() throws Throwable {
            attributes.put((String) getCurrentArguments()[0], getCurrentArguments()[1]);
            return null;
        }

    });
    replay(servletContext);

    final CubbyGuiceServletContextListener cubbyGuiceServletContextListener = new CubbyGuiceServletContextListener();
    cubbyGuiceServletContextListener.contextInitialized(new ServletContextEvent(servletContext));

    final GuiceFilter guiceFilter = new GuiceFilter();
    guiceFilter.init(new FilterConfig() {

        public String getFilterName() {
            return "guice";
        }

        public String getInitParameter(final String name) {
            return null;
        }

        @SuppressWarnings("unchecked")
        public Enumeration getInitParameterNames() {
            return new Vector<String>().elements();
        }

        public ServletContext getServletContext() {
            return servletContext;
        }

    });

    final FilterChain chain = new FilterChain() {

        public void doFilter(final ServletRequest request, final ServletResponse response)
                throws IOException, ServletException {
            final PluginRegistry pluginRegistry = PluginRegistry.getInstance();
            final GuicePlugin guicePlugin = new GuicePlugin();
            try {
                guicePlugin.initialize(servletContext);
                guicePlugin.ready();
                pluginRegistry.register(guicePlugin);
            } catch (final Exception e) {
                throw new ServletException(e);
            }

            final Injector injector = guicePlugin.getInjector();
            System.out.println(injector);

            final PathResolverProvider pathResolverProvider = ProviderFactory.get(PathResolverProvider.class);
            final PathResolver pathResolver = pathResolverProvider.getPathResolver();
            System.out.println(pathResolver);

            final PathTemplateParser pathTemplateParser = injector.getInstance(PathTemplateParser.class);
            System.out.println(pathTemplateParser);
            assertTrue(pathTemplateParser instanceof MyPathTemplateParser);

            final ContainerProvider containerProvider = ProviderFactory.get(ContainerProvider.class);
            final Container container = containerProvider.getContainer();
            final Foo foo = container.lookup(Foo.class);
            System.out.println(foo);
            System.out.println(foo.pathResolver);

            assertSame(pathResolver, foo.pathResolver);

            try {
                final Baz baz = injector.getInstance(Baz.class);
                System.out.println(baz);
                fail();
            } catch (final ConfigurationException e) {
                // ok
            }

            final ConverterProvider converterProvider = ProviderFactory.get(ConverterProvider.class);
            System.out.println(converterProvider);
            System.out.println(converterProvider.getConverter(BigDecimalConverter.class));

            final FileUpload fileUpload1 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload1);
            System.out.println(fileUpload1.getFileItemFactory());

            final FileUpload fileUpload2 = injector.getInstance(FileUpload.class);
            System.out.println(fileUpload2);
            System.out.println(fileUpload2.getFileItemFactory());

            assertNotSame(fileUpload1, fileUpload2);
            assertNotSame(fileUpload1.getFileItemFactory(), fileUpload2.getFileItemFactory());
        }

    };
    guiceFilter.doFilter(request, response, chain);
    cubbyGuiceServletContextListener.contextDestroyed(new ServletContextEvent(servletContext));
    ThreadContext.remove();
}

From source file:wicket.protocol.http.MockWebApplication.java

/**
 * Create the mock http application that can be used for testing.
 * /*from  w  w  w  . j av a 2  s .  c  o m*/
 * @param path
 *            The absolute path on disk to the web application contents
 *            (e.g. war root) - may be null
 * @see wicket.protocol.http.MockServletContext
 */
public MockWebApplication(final String path) {
    final MockServletContext context = new MockServletContext(this, null);
    WicketFilter filter = new WicketFilter() {
        @Override
        protected IWebApplicationFactory getApplicationFactory() {
            return new IWebApplicationFactory() {
                public WebApplication createApplication(WicketFilter filter) {
                    return MockWebApplication.this;
                };
            };
        }
    };
    try {
        filter.init(new FilterConfig() {

            public ServletContext getServletContext() {
                return context;
            }

            public Enumeration getInitParameterNames() {
                return null;
            }

            public String getInitParameter(String name) {
                if (name.equals(WicketFilter.FILTER_PATH_PARAM)) {
                    return getName();
                }
                return null;
            }

            public String getFilterName() {
                return "WicketMockServlet";
            }
        });
    } catch (ServletException e) {
        throw new RuntimeException(e);
    }
    Application.set(this);
}