javax.servlet.Filter#init ( )源码实例Demo

下面列出了javax.servlet.Filter#init ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: hadoop   文件: TestHostnameFilter.java
@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();
}
 
源代码2 项目: HttpSessionReplacer   文件: ITFilters.java
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;
  }
}
 
源代码3 项目: big-c   文件: TestHostnameFilter.java
@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();
}
 
源代码4 项目: spring-analysis-note   文件: CompositeFilter.java
/**
 * 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);
	}
}
 
源代码5 项目: java-technology-stack   文件: CompositeFilter.java
/**
 * 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);
	}
}
 
源代码6 项目: lams   文件: CompositeFilter.java
/**
 * 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);
	}
}
 
源代码7 项目: hadoop   文件: TestHostnameFilter.java
@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();
}
 
源代码8 项目: spring4-understanding   文件: CompositeFilter.java
/**
 * 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);
	}
}
 
源代码9 项目: big-c   文件: TestHostnameFilter.java
@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);
  }
}
 
源代码11 项目: nexus-public   文件: DelegatingFilter.java
public static synchronized void set(Filter filter) {
  if (cachedConfig != null) {
    try {
      filter.init(cachedConfig);
    }
    catch (ServletException e) {
      throw new IllegalStateException(e);
    }
  }
  delegate = filter;
}
 
源代码12 项目: knox   文件: GatewayFilter.java
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;
}
 
源代码13 项目: rice   文件: BootstrapFilter.java
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);
	}
}
 
源代码14 项目: hadoop   文件: TestMDCFilter.java
@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();
}
 
源代码15 项目: big-c   文件: TestMDCFilter.java
@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();
}
 
源代码16 项目: dagger-servlet   文件: FilterDefinition.java
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;
}
 
源代码19 项目: lams   文件: DelegatingFilterProxy.java
/**
 * 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;
}
 
 方法所在类