下面列出了怎么用javax.servlet.FilterConfig的API类实例代码及写法,或者点击链接到github查看源代码。
public static FilterConfig getFilterConfigSpecificOriginNullAllowed() {
final String allowedHttpHeaders =
CorsFilter.DEFAULT_ALLOWED_HTTP_HEADERS;
final String allowedHttpMethods =
CorsFilter.DEFAULT_ALLOWED_HTTP_METHODS;
final String allowedOrigins = HTTP_TOMCAT_APACHE_ORG + ",null";
final String exposedHeaders = CorsFilter.DEFAULT_EXPOSED_HEADERS;
final String supportCredentials =
CorsFilter.DEFAULT_SUPPORTS_CREDENTIALS;
final String preflightMaxAge =
CorsFilter.DEFAULT_PREFLIGHT_MAXAGE;
final String decorateRequest = CorsFilter.DEFAULT_DECORATE_REQUEST;
return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods,
allowedOrigins, exposedHeaders, supportCredentials,
preflightMaxAge, decorateRequest);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
// Build HSTS header value
StringBuilder hstsValue = new StringBuilder("max-age=");
hstsValue.append(hstsMaxAgeSeconds);
if (hstsIncludeSubDomains) {
hstsValue.append(";includeSubDomains");
}
hstsHeaderValue = hstsValue.toString();
// Anti click-jacking
StringBuilder cjValue = new StringBuilder(antiClickJackingOption.headerValue);
if (antiClickJackingOption == XFrameOption.ALLOW_FROM) {
cjValue.append(':');
cjValue.append(antiClickJackingUri);
}
antiClickJackingHeaderValue = cjValue.toString();
}
public static FilterConfig getSecureFilterConfig() {
final String allowedHttpHeaders =
CorsFilter.DEFAULT_ALLOWED_HTTP_HEADERS;
final String allowedHttpMethods =
CorsFilter.DEFAULT_ALLOWED_HTTP_METHODS + ",PUT";
final String allowedOrigins = HTTPS_WWW_APACHE_ORG;
final String exposedHeaders = CorsFilter.DEFAULT_EXPOSED_HEADERS;
final String supportCredentials = "true";
final String preflightMaxAge =
CorsFilter.DEFAULT_PREFLIGHT_MAXAGE;
final String decorateRequest = CorsFilter.DEFAULT_DECORATE_REQUEST;
return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods,
allowedOrigins, exposedHeaders, supportCredentials,
preflightMaxAge, decorateRequest);
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
this.servletContext = filterConfig.getServletContext();
LOGGER.debug("Log4jServletFilter initialized.");
this.initializer = WebLoggerContextUtils.getWebLifeCycle(this.servletContext);
this.initializer.clearLoggerContext(); // the application is mostly finished starting up now
filterConfig.getServletContext().setAttribute("log4j.requestExecutor",
(BiConsumer<ServletRequest, Runnable>) (request, command) -> {
try {
Log4jServletFilter.this.initializer.setLoggerContext();
CURRENT_REQUEST.set(request);
command.run();
} finally {
Log4jServletFilter.this.initializer.clearLoggerContext();
CURRENT_REQUEST.remove();
}
});
}
@Test
public void testGetConfiguration() throws ServletException {
AuthFilter filter = new AuthFilter();
Map<String, String> m = new HashMap<String,String>();
m.put(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_PRINCIPAL_KEY,
"xyz/[email protected]");
m.put(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY,
"thekeytab");
FilterConfig config = new DummyFilterConfig(m);
Properties p = filter.getConfiguration("random", config);
Assert.assertEquals("xyz/[email protected]",
p.getProperty("kerberos.principal"));
Assert.assertEquals("thekeytab", p.getProperty("kerberos.keytab"));
Assert.assertEquals("true",
p.getProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED));
}
@Override
protected void loadFilterRules(FilterConfig filterConfig) throws ServletException {
String configFileName = filterConfig.getInitParameter("configFile");
Resource resource = resourceLoader.getResource("classpath:" +webappProperty.getWebjarClasspath() + configFileName);
InputStream configFileResource;
try {
configFileResource = resource.getInputStream();
} catch (IOException e1) {
throw new ServletException("Could not read security filter config file '" + configFileName + "': no such resource in servlet context.");
}
try {
filterRules = FilterRules.load(configFileResource);
} catch (Exception e) {
throw new RuntimeException("Exception while parsing '" + configFileName + "'", e);
} finally {
IoUtil.closeSilently(configFileResource);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
try {
input = filterConfig.getInitParameter( "input" );
if( input == null ) {
input = "";
}
output = filterConfig.getInitParameter( "output" );
if( output == null ) {
output = "";
}
dict = loadDictionary( filterConfig.getInitParameter( "lookup" ) );
boolean useOriginalOnLookupFailure = Boolean.parseBoolean(filterConfig.getInitParameter("use.original.on.lookup.failure"));
template = new RegexTemplate( input, output, dict, useOriginalOnLookupFailure);
} catch ( PrincipalMappingException e ) {
throw new ServletException( e );
}
}
@Before
public void setUp() throws Exception {
preRenderSEOFilter = new PreRenderSEOFilter() {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
setPrerenderSeoService(new PrerenderSeoService(toMap(filterConfig)) {
@Override
protected CloseableHttpClient getHttpClient() {
return httpClient;
}
@Override
protected HttpGet getHttpGet(String apiUrl) {
return httpGet;
}
});
}
};
}
@Test
public void doFilter() throws Exception {
HttpServletRequest req = mock(HttpServletRequest.class);
final String path = "/foo/bar/baz/bang/zilch/zip/nada";
when(req.getRequestURI()).thenReturn(path);
when(req.getMethod()).thenReturn(HttpMethods.GET);
HttpServletResponse res = mock(HttpServletResponse.class);
FilterChain c = mock(FilterChain.class);
String name = "foo";
FilterConfig cfg = mock(FilterConfig.class);
when(cfg.getInitParameter(MetricsFilter.METRIC_NAME_PARAM)).thenReturn(name);
when(cfg.getInitParameter(MetricsFilter.PATH_COMPONENT_PARAM)).thenReturn("0");
f.init(cfg);
f.doFilter(req, res, c);
verify(c).doFilter(req, res);
final Double sampleValue = CollectorRegistry.defaultRegistry.getSampleValue(name + "_count", new String[]{"path", "method"}, new String[]{path, HttpMethods.GET});
assertNotNull(sampleValue);
assertEquals(1, sampleValue, 0.0001);
}
/**
* Returns the value of the initParam.
* @param filterConfig a FilterConfig instance
* @param initParam the name of the init parameter
* @param variable the variable to use if the init param was not defined
* @return a String
*/
private String getValue(FilterConfig filterConfig, String initParam, String variable) {
final String value = filterConfig.getInitParameter(initParam);
if (StringUtils.isNotBlank(value)) {
return value;
} else {
return variable;
}
}
public void init(final FilterConfig filterConfig, final Class<? extends Filter> filterClazz) {
this.simpleFilterName = filterClazz.getSimpleName();
final String fileLocationFromFilterConfig = filterConfig.getInitParameter(CONFIGURATION_FILE_LOCATION);
final boolean filterConfigFileLoad = loadPropertiesFromFile(fileLocationFromFilterConfig);
if (!filterConfigFileLoad) {
final String fileLocationFromServletConfig = filterConfig.getServletContext().getInitParameter(CONFIGURATION_FILE_LOCATION);
final boolean servletContextFileLoad = loadPropertiesFromFile(fileLocationFromServletConfig);
if (!servletContextFileLoad) {
final boolean defaultConfigFileLoaded = loadPropertiesFromFile(DEFAULT_CONFIGURATION_FILE_LOCATION);
Assert.isTrue(defaultConfigFileLoaded, "unable to load properties to configure CAS client");
}
}
}
public static FilterConfig getEmptyFilterConfig() {
final String allowedHttpHeaders = "";
final String allowedHttpMethods = "";
final String allowedOrigins = "";
final String exposedHeaders = "";
final String supportCredentials = "";
final String preflightMaxAge = "";
final String decorateRequest = "";
return generateFilterConfig(allowedHttpHeaders, allowedHttpMethods,
allowedOrigins, exposedHeaders, supportCredentials,
preflightMaxAge, decorateRequest);
}
/**
* @param filterConfig The {@link FilterConfig} for initializing this Servlet filter.
* @return The {@link HttpTagAndSpanNamingStrategy} that should be used by this instance. Delegates to
* {@link #getTagStrategyFromName(String)}, and uses {@link #getDefaultTagStrategy()} as a last resort if
* {@link #getTagStrategyFromName(String)} throws an exception.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> initializeTagAndNamingStrategy(
FilterConfig filterConfig
) {
String tagStrategyString = filterConfig.getInitParameter(TAG_AND_SPAN_NAMING_STRATEGY_INIT_PARAM_NAME);
try {
return getTagStrategyFromName(tagStrategyString);
} catch(Throwable t) {
logger.warn("Unable to match tagging strategy " + tagStrategyString + ". Using default Zipkin strategy", t);
return getDefaultTagStrategy();
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
if (context == null) {
throw new ServletException("init failed");
}
this.qFileFactory = (QFileFactory) context.getBean("v2Factory");
}
public void init(FilterConfig cfg) throws ServletException {
iSaver = new Saver();
iSaver.start();
String exclude = cfg.getInitParameter("exclude");
if (exclude != null) {
for (String x: exclude.split(","))
iExclude.add(x);
}
iGson = new GsonBuilder().create();
}
@Override
public void init(FilterConfig fc)
throws ServletException {
String fn;
fn = fc.getInitParameter("request-attr");
if (fn != null) SSRA = fn;
fn = fc.getInitParameter("request-name");
if (fn != null) SSRN = fn;
fn = fc.getInitParameter( "cookie-name");
if (fn != null) SSCN = fn;
fn = fc.getInitParameter( "cookie-path");
if (fn != null) SSCP = fn;
fn = fc.getInitParameter( "cookie-max-age");
if (fn != null) SSCX = Integer.parseInt(fn);
fn = fc.getInitParameter( "record-max-age");
if (fn != null) SSRX = Integer.parseInt(fn);
if (! SSCP.startsWith("/")) {
SSCP = Core.BASE_HREF + "/" + SSCP;
}
inside = SessFilter.class.getName()+":"+fc.getFilterName()+":INSIDE";
ignore = new PasserHelper(
fc.getInitParameter("ignore-urls"),
fc.getInitParameter("attend-urls")
);
}
@Override public void init(FilterConfig filterConfig) {
String rangeProp = "request.range";
String defaultRange = "10000";
range = Long.valueOf(env.getProperty(rangeProp, defaultRange));
String countProp = "request.count";
String defaultCount = "3";
count = Integer.valueOf(env.getProperty(countProp, defaultCount));
String typeProp = "request.type";
String defaultType = "MAP";
type = CacheType.valueOf(env.getProperty(typeProp, defaultType));
LogUtils.trackInfo(logger, "Initiating LimitFilter with: " + type.name());
}
@Test
public void testUnknownUser() throws ServletException {
final FilterConfig config = EasyMock.createNiceMock(FilterConfig.class);
EasyMock.expect(config.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
ServletContext context = EasyMock.createNiceMock(ServletContext.class);
EasyMock.expect(config.getServletContext() ).andReturn( context ).anyTimes();
EasyMock.expect(context.getInitParameter("principal.mapping") ).andReturn( "" ).anyTimes();
EasyMock.replay( config );
EasyMock.replay( context );
final HadoopGroupProviderFilter filter = new HadoopGroupProviderFilter();
final Subject subject = new Subject();
subject.getPrincipals().add(new PrimaryPrincipal(failUsername));
filter.init(config);
final String principal = filter.mapUserPrincipal(
((Principal) subject.getPrincipals(PrimaryPrincipal.class).toArray()[0])
.getName());
final String[] groups = filter.mapGroupPrincipals(principal, subject);
assertThat(principal, is(failUsername));
assertThat(
"Somehow groups were found for this user, how is it possible ! check 'bash -c groups' command ",
groups.length == 0);
}
@Override
public void init(FilterConfig config) throws ServletException {
super.init(config);
debug = Boolean.TRUE.equals(UtilMisc.booleanValueVersatile(config.getInitParameter("debug")));
seoUrlEnabled = !Boolean.FALSE.equals(UtilMisc.booleanValueVersatile(config.getInitParameter("seoUrlEnabled")));
if (seoUrlEnabled) {
WebsiteSeoConfig.registerWebsiteForSeo(WebsiteSeoConfig.makeConfig(config.getServletContext(), true));
urlWorker = SeoCatalogUrlWorker.getInstance(null, config.getServletContext().getInitParameter("webSiteId"));
}
rewriteOutboundUrls = Boolean.TRUE.equals(UtilMisc.booleanValueVersatile(config.getInitParameter("rewriteOutboundUrls")));
}
private static GatewayFilter createFilter( FilterConfig filterConfig ) throws ServletException {
GatewayFilter filter;
InputStream stream;
String location = filterConfig.getInitParameter( GATEWAY_DESCRIPTOR_LOCATION_PARAM );
if( location != null ) {
stream = filterConfig.getServletContext().getResourceAsStream( location );
if( stream == null ) {
stream = filterConfig.getServletContext().getResourceAsStream( "/WEB-INF/" + location );
}
} else {
stream = filterConfig.getServletContext().getResourceAsStream( GATEWAY_DESCRIPTOR_LOCATION_DEFAULT );
}
filter = createFilter( stream, filterConfig.getServletContext());
return filter;
}
private void initializeAllowedOrigins(FilterConfig filterConfig) {
String allowedOriginsConfig =
filterConfig.getInitParameter(ALLOWED_ORIGINS);
if (allowedOriginsConfig == null) {
allowedOriginsConfig = ALLOWED_ORIGINS_DEFAULT;
}
allowedOrigins.addAll(
Arrays.asList(allowedOriginsConfig.trim().split("\\s*,\\s*")));
allowAllOrigins = allowedOrigins.contains("*");
LOG.info("Allowed Origins: " + StringUtils.join(allowedOrigins, ','));
LOG.info("Allow All Origins: " + allowAllOrigins);
}
private void initFilterPath(FilterConfig filterConfig) {
initFilterPathFromConfig(filterConfig);
if (filterPath == null) {
initFilterPathFromWebXml(filterConfig);
}
if (filterPath == null) {
StringBuilder message = new StringBuilder();
message.append("Unable to determine filter path from filter init-param, web.xml.");
message.append("Assuming user will set filter path manually by calling setFilterPath(String)");
log.warn(message.toString());
}
}
protected Configuration getProxyuserConfiguration(FilterConfig filterConfig) {
Map<String, String> proxyuserConf = KMSWebApp.getConfiguration().
getValByRegex("hadoop\\.kms\\.proxyuser\\.");
Configuration conf = new Configuration(false);
for (Map.Entry<String, String> entry : proxyuserConf.entrySet()) {
conf.set(entry.getKey().substring("hadoop.kms.".length()),
entry.getValue());
}
return conf;
}
@Test
public void testCreateHttpClientSSLContextDefaults() throws Exception {
KeystoreService keystoreService = createMock(KeystoreService.class);
expect(keystoreService.getTruststoreForHttpClient()).andReturn(null).once();
GatewayConfig gatewayConfig = createMock(GatewayConfig.class);
expect(gatewayConfig.isMetricsEnabled()).andReturn(false).once();
expect(gatewayConfig.getHttpClientMaxConnections()).andReturn(32).once();
expect(gatewayConfig.getHttpClientConnectionTimeout()).andReturn(20000).once();
expect(gatewayConfig.getHttpClientSocketTimeout()).andReturn(20000).once();
GatewayServices gatewayServices = createMock(GatewayServices.class);
expect(gatewayServices.getService(ServiceType.KEYSTORE_SERVICE)).andReturn(keystoreService).once();
ServletContext servletContext = createMock(ServletContext.class);
expect(servletContext.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig).atLeastOnce();
expect(servletContext.getAttribute(GatewayServices.GATEWAY_SERVICES_ATTRIBUTE)).andReturn(gatewayServices).atLeastOnce();
FilterConfig filterConfig = createMock(FilterConfig.class);
expect(filterConfig.getServletContext()).andReturn(servletContext).atLeastOnce();
expect(filterConfig.getInitParameter("useTwoWaySsl")).andReturn("false").once();
expect(filterConfig.getInitParameter("httpclient.maxConnections")).andReturn(null).once();
expect(filterConfig.getInitParameter("httpclient.connectionTimeout")).andReturn(null).once();
expect(filterConfig.getInitParameter("httpclient.socketTimeout")).andReturn(null).once();
expect(filterConfig.getInitParameter("serviceRole")).andReturn(null).once();
replay(keystoreService, gatewayConfig, gatewayServices, servletContext, filterConfig);
DefaultHttpClientFactory factory = new DefaultHttpClientFactory();
HttpClient client = factory.createHttpClient(filterConfig);
assertNotNull(client);
verify(keystoreService, gatewayConfig, gatewayServices, servletContext, filterConfig);
}
public final void init(final FilterConfig filterConfig, final Class<? extends Filter> clazz) {
this.simpleFilterName = clazz.getSimpleName();
try {
this.context = new InitialContext();
} catch (final NamingException e) {
logger.error("Unable to create InitialContext. No properties can be loaded via JNDI.", e);
}
}
public void init(FilterConfig config) throws ServletException {
servletContext = config.getServletContext();
// check for possible robot pattern
String robotPatternStr = config.getInitParameter("referrer.robotCheck.userAgentPattern");
if (!UtilValidate.isEmpty(robotPatternStr)) {
// Parse the pattern, and store the compiled form.
try {
robotPattern = Pattern.compile(robotPatternStr);
config.getServletContext().setAttribute(SpamFilterTooFreq.BOTNAME, robotPattern);
} catch (Exception e) {
// Most likely a PatternSyntaxException; log and continue as if
// it is not set.
log.error("Error parsing referrer.robotCheck.userAgentPattern value '" + robotPatternStr + "'. Robots will not be filtered. ", e);
}
}
Runnable startFiltertask = new Runnable() {
public void run() {
isFilter = true;
}
};
// per one hour start check
ScheduledExecutorUtil.scheduExecStatic.scheduleAtFixedRate(startFiltertask, 60, 60 * 60, TimeUnit.SECONDS);
Runnable stopFiltertask = new Runnable() {
public void run() {
isFilter = false;
if (customizedThrottle != null) {
// when stop .clear the check cache.
customizedThrottle.clearCache();
}
}
};
// after 5 Mintues stop it.
ScheduledExecutorUtil.scheduExecStatic.scheduleAtFixedRate(stopFiltertask, 60 * 10, 60 * 65, TimeUnit.SECONDS);
}
static void setTLs(HttpServletRequest req, HttpServletResponse resp, FilterConfig conf, AppContext context,
RequestVo requestVo, String format) {
setHttpRequest(req);
setHttpResponse(resp);
setFilterConfig(conf);
setAppContext(context);
setRequestVo(requestVo);
setFormat(format);
exceptionHappened.set(false);
}
@Test
public void testGetToken() throws Exception {
AuthenticationFilter filter = new AuthenticationFilter();
try {
FilterConfig config = Mockito.mock(FilterConfig.class);
Mockito.when(config.getInitParameter("management.operation.return")).
thenReturn("true");
Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn(
DummyAuthenticationHandler.class.getName());
Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret");
Mockito.when(config.getInitParameterNames()).thenReturn(
new Vector<String>(
Arrays.asList(AuthenticationFilter.AUTH_TYPE,
AuthenticationFilter.SIGNATURE_SECRET,
"management.operation.return")).elements());
SignerSecretProvider secretProvider =
getMockedServletContextWithStringSigner(config);
filter.init(config);
AuthenticationToken token = new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE);
token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC);
Signer signer = new Signer(secretProvider);
String tokenSigned = signer.sign(token.toString());
Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned);
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie});
AuthenticationToken newToken = filter.getToken(request);
Assert.assertEquals(token.toString(), newToken.toString());
} finally {
filter.destroy();
}
}
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
// Initialize defaults
parseAndStore(DEFAULT_ALLOWED_ORIGINS, DEFAULT_ALLOWED_HTTP_METHODS,
DEFAULT_ALLOWED_HTTP_HEADERS, DEFAULT_EXPOSED_HEADERS,
DEFAULT_SUPPORTS_CREDENTIALS, DEFAULT_PREFLIGHT_MAXAGE,
DEFAULT_DECORATE_REQUEST);
if (filterConfig != null) {
String configAllowedOrigins = filterConfig
.getInitParameter(PARAM_CORS_ALLOWED_ORIGINS);
String configAllowedHttpMethods = filterConfig
.getInitParameter(PARAM_CORS_ALLOWED_METHODS);
String configAllowedHttpHeaders = filterConfig
.getInitParameter(PARAM_CORS_ALLOWED_HEADERS);
String configExposedHeaders = filterConfig
.getInitParameter(PARAM_CORS_EXPOSED_HEADERS);
String configSupportsCredentials = filterConfig
.getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS);
String configPreflightMaxAge = filterConfig
.getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE);
String configDecorateRequest = filterConfig
.getInitParameter(PARAM_CORS_REQUEST_DECORATE);
parseAndStore(configAllowedOrigins, configAllowedHttpMethods,
configAllowedHttpHeaders, configExposedHeaders,
configSupportsCredentials, configPreflightMaxAge,
configDecorateRequest);
}
}
@Override
public void init( FilterConfig config ) throws ServletException {
servletContext = config.getServletContext();
servletName = config.getInitParameter( DISPATCH_SERVLET_PARAM_NAME );
}