下面列出了javax.servlet.Filter#init ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testMissingHostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertTrue(HostnameFilter.get().contains("???"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(HostnameFilter.get());
filter.destroy();
}
static Filter simplyInvokeInit(Class<?> clazz) throws Exception {
if (Filter.class.isAssignableFrom(clazz)) {
@SuppressWarnings("unchecked")
Class<? extends Filter> filterClass = (Class<? extends Filter>)clazz;
FilterConfig filterConfig = mock(FilterConfig.class);
ServletContext servletContext = new MockServletContext();
when(filterConfig.getServletContext()).thenReturn(servletContext);
Filter filter = filterClass.newInstance();
assertNotNull(filter);
SessionHelpers.resetForTests();
filter.init(filterConfig);
return filter;
} else {
fail("Not a Filter: " + clazz);
return null;
}
}
@Test
public void testMissingHostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn(null);
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertTrue(HostnameFilter.get().contains("???"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(HostnameFilter.get());
filter.destroy();
}
/**
* Initialize all the filters, calling each one's init method in turn in the order supplied.
* @see Filter#init(FilterConfig)
*/
@Override
public void init(FilterConfig config) throws ServletException {
for (Filter filter : this.filters) {
filter.init(config);
}
}
/**
* Initialize all the filters, calling each one's init method in turn in the order supplied.
* @see Filter#init(FilterConfig)
*/
@Override
public void init(FilterConfig config) throws ServletException {
for (Filter filter : this.filters) {
filter.init(config);
}
}
/**
* Initialize all the filters, calling each one's init method in turn in the order supplied.
* @see Filter#init(FilterConfig)
*/
@Override
public void init(FilterConfig config) throws ServletException {
for (Filter filter : this.filters) {
filter.init(config);
}
}
@Test
public void hostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
// Hostname was set to "localhost", but may get resolved automatically to
// "127.0.0.1" depending on OS.
assertTrue(HostnameFilter.get().contains("localhost") ||
HostnameFilter.get().contains("127.0.0.1"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(HostnameFilter.get());
filter.destroy();
}
/**
* Initialize all the filters, calling each one's init method in turn in the order supplied.
* @see Filter#init(FilterConfig)
*/
@Override
public void init(FilterConfig config) throws ServletException {
for (Filter filter : this.filters) {
filter.init(config);
}
}
@Test
public void hostname() throws Exception {
ServletRequest request = Mockito.mock(ServletRequest.class);
Mockito.when(request.getRemoteAddr()).thenReturn("localhost");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
// Hostname was set to "localhost", but may get resolved automatically to
// "127.0.0.1" depending on OS.
assertTrue(HostnameFilter.get().contains("localhost") ||
HostnameFilter.get().contains("127.0.0.1"));
invoked.set(true);
}
};
Filter filter = new HostnameFilter();
filter.init(null);
assertNull(HostnameFilter.get());
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(HostnameFilter.get());
filter.destroy();
}
@Override
public void init(Map<String, Object> pluginConfig) {
try {
final FilterConfig initConf = getInitFilterConfig(pluginConfig, true);
FilterConfig conf = new FilterConfig() {
@Override
public ServletContext getServletContext() {
return initConf.getServletContext();
}
@Override
public Enumeration<String> getInitParameterNames() {
return initConf.getInitParameterNames();
}
@Override
public String getInitParameter(String param) {
if (AuthenticationFilter.AUTH_TYPE.equals(param)) {
return HttpParamDelegationTokenAuthenticationHandler.class.getName();
}
return initConf.getInitParameter(param);
}
@Override
public String getFilterName() {
return "HttpParamFilter";
}
};
Filter kerberosFilter = new HttpParamToRequestFilter();
kerberosFilter.init(conf);
setKerberosFilter(kerberosFilter);
} catch (ServletException e) {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Error initializing kerberos authentication plugin: "+e);
}
}
public static synchronized void set(Filter filter) {
if (cachedConfig != null) {
try {
filter.init(cachedConfig);
}
catch (ServletException e) {
throw new IllegalStateException(e);
}
}
delegate = filter;
}
private Filter getInstance() throws ServletException {
if( instance == null ) {
try {
if( clazz == null ) {
clazz = getClazz();
}
Filter f = clazz.newInstance();
f.init(this);
instance = f;
} catch( Exception e ) {
throw new ServletException( e );
}
}
return instance;
}
private void addFilter(String name, String classname, Map<String, String> props) throws ServletException {
LOG.debug("Adding filter: " + name + "=" + classname);
Object filterObject = GlobalResourceLoader.getResourceLoader().getObject(new ObjectDefinition(classname));
if (filterObject == null) {
throw new ServletException("Filter '" + name + "' class not found: " + classname);
}
if (!(filterObject instanceof Filter)) {
LOG.error("Class '" + filterObject.getClass() + "' does not implement servlet javax.servlet.Filter");
return;
}
Filter filter = (Filter) filterObject;
BootstrapFilterConfig fc = new BootstrapFilterConfig(config.getServletContext(), name);
for (Map.Entry<String, String> entry : props.entrySet()) {
String key = entry.getKey().toString();
final String prefix = FILTER_PREFIX + name + ".";
if (!key.startsWith(prefix) || key.equals(FILTER_PREFIX + name + CLASS_SUFFIX)) {
continue;
}
String paramName = key.substring(prefix.length());
fc.addInitParameter(paramName, entry.getValue());
}
try {
filter.init(fc);
filters.put(name, filter);
} catch (ServletException se) {
LOG.error("Error initializing filter: " + name + " [" + classname + "]", se);
}
}
@Test
public void mdc() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getUserPrincipal()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("METHOD");
Mockito.when(request.getPathInfo()).thenReturn("/pathinfo");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), null);
assertEquals(MDC.get("user"), null);
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
MDC.clear();
Filter filter = new MDCFilter();
filter.init(null);
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(MDC.get("hostname"));
assertNull(MDC.get("user"));
assertNull(MDC.get("method"));
assertNull(MDC.get("path"));
Mockito.when(request.getUserPrincipal()).thenReturn(new Principal() {
@Override
public String getName() {
return "name";
}
});
invoked.set(false);
chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), null);
assertEquals(MDC.get("user"), "name");
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
HostnameFilter.HOSTNAME_TL.set("HOST");
invoked.set(false);
chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), "HOST");
assertEquals(MDC.get("user"), "name");
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
HostnameFilter.HOSTNAME_TL.remove();
filter.destroy();
}
@Test
public void mdc() throws Exception {
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getUserPrincipal()).thenReturn(null);
Mockito.when(request.getMethod()).thenReturn("METHOD");
Mockito.when(request.getPathInfo()).thenReturn("/pathinfo");
ServletResponse response = Mockito.mock(ServletResponse.class);
final AtomicBoolean invoked = new AtomicBoolean();
FilterChain chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), null);
assertEquals(MDC.get("user"), null);
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
MDC.clear();
Filter filter = new MDCFilter();
filter.init(null);
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
assertNull(MDC.get("hostname"));
assertNull(MDC.get("user"));
assertNull(MDC.get("method"));
assertNull(MDC.get("path"));
Mockito.when(request.getUserPrincipal()).thenReturn(new Principal() {
@Override
public String getName() {
return "name";
}
});
invoked.set(false);
chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), null);
assertEquals(MDC.get("user"), "name");
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
HostnameFilter.HOSTNAME_TL.set("HOST");
invoked.set(false);
chain = new FilterChain() {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse)
throws IOException, ServletException {
assertEquals(MDC.get("hostname"), "HOST");
assertEquals(MDC.get("user"), "name");
assertEquals(MDC.get("method"), "METHOD");
assertEquals(MDC.get("path"), "/pathinfo");
invoked.set(true);
}
};
filter.doFilter(request, response, chain);
assertTrue(invoked.get());
HostnameFilter.HOSTNAME_TL.remove();
filter.destroy();
}
public void init(final ServletContext servletContext, ObjectGraph objectGraph,
Set<Filter> initializedSoFar) throws ServletException {
// This absolutely must be a singleton, and so is only initialized once.
// TODO: There isn't a good way to make sure the class is a singleton. Classes with the @Singleton annotation
// can be identified, but classes that are singletons via an @Singleton annotated @Provides method won't
// be identified as singletons. Bad stuff may happen for non-singletons.
// if (!Scopes.isSingleton(filterClass)) {
// throw new ServletException("Filters must be bound as singletons. "
// + filterClass + " was not bound in singleton scope.");
// }
Filter filter;
if (filterInstance == null) {
filter = objectGraph.get(filterClass);
} else {
filter = filterInstance;
}
this.filter.set(filter);
// Only fire init() if this Singleton filter has not already appeared earlier
// in the filter chain.
if (initializedSoFar.contains(filter)) {
return;
}
// Initialize our filter with the configured context params and servlet context.
filter.init(new FilterConfig() {
@Override
public String getFilterName() {
return filterClass.getCanonicalName();
}
@Override
public ServletContext getServletContext() {
return servletContext;
}
@Override
public String getInitParameter(String s) {
return initParams.get(s);
}
@Override
public Enumeration<String> getInitParameterNames() {
return Iterators.asEnumeration(initParams.keySet().iterator());
}
});
initializedSoFar.add(filter);
}
/**
* Initialize the Filter delegate, defined as bean the given Spring
* application context.
* <p>The default implementation fetches the bean from the application context
* and calls the standard {@code Filter.init} method on it, passing
* in the FilterConfig of this Filter proxy.
* @param wac the root application context
* @return the initialized delegate Filter
* @throws ServletException if thrown by the Filter
* @see #getTargetBeanName()
* @see #isTargetFilterLifecycle()
* @see #getFilterConfig()
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
String targetBeanName = getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
Filter delegate = wac.getBean(targetBeanName, Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}
/**
* Initialize the Filter delegate, defined as bean the given Spring
* application context.
* <p>The default implementation fetches the bean from the application context
* and calls the standard {@code Filter.init} method on it, passing
* in the FilterConfig of this Filter proxy.
* @param wac the root application context
* @return the initialized delegate Filter
* @throws ServletException if thrown by the Filter
* @see #getTargetBeanName()
* @see #isTargetFilterLifecycle()
* @see #getFilterConfig()
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
String targetBeanName = getTargetBeanName();
Assert.state(targetBeanName != null, "No target bean name set");
Filter delegate = wac.getBean(targetBeanName, Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}
/**
* Initialize the Filter delegate, defined as bean the given Spring
* application context.
* <p>The default implementation fetches the bean from the application context
* and calls the standard {@code Filter.init} method on it, passing
* in the FilterConfig of this Filter proxy.
* @param wac the root application context
* @return the initialized delegate Filter
* @throws ServletException if thrown by the Filter
* @see #getTargetBeanName()
* @see #isTargetFilterLifecycle()
* @see #getFilterConfig()
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}
/**
* Initialize the Filter delegate, defined as bean the given Spring
* application context.
* <p>The default implementation fetches the bean from the application context
* and calls the standard {@code Filter.init} method on it, passing
* in the FilterConfig of this Filter proxy.
* @param wac the root application context
* @return the initialized delegate Filter
* @throws ServletException if thrown by the Filter
* @see #getTargetBeanName()
* @see #isTargetFilterLifecycle()
* @see #getFilterConfig()
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
Filter delegate = wac.getBean(getTargetBeanName(), Filter.class);
if (isTargetFilterLifecycle()) {
delegate.init(getFilterConfig());
}
return delegate;
}