Java Code Examples for javax.servlet.Filter#init()

The following examples show how to use javax.servlet.Filter#init() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestHostnameFilter.java    From big-c with Apache License 2.0 7 votes vote down vote up
@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();
}
 
Example 2
Source File: TestHostnameFilter.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 3
Source File: ITFilters.java    From HttpSessionReplacer with MIT License 6 votes vote down vote up
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;
  }
}
 
Example 4
Source File: CompositeFilter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 5
Source File: BootstrapFilter.java    From rice with Educational Community License v2.0 5 votes vote down vote up
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);
	}
}
 
Example 6
Source File: GatewayFilter.java    From knox with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: DelegatingFilter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public static synchronized void set(Filter filter) {
  if (cachedConfig != null) {
    try {
      filter.init(cachedConfig);
    }
    catch (ServletException e) {
      throw new IllegalStateException(e);
    }
  }
  delegate = filter;
}
 
Example 8
Source File: HttpParamDelegationTokenPlugin.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 9
Source File: TestHostnameFilter.java    From big-c with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: CompositeFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 11
Source File: TestHostnameFilter.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: CompositeFilter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 13
Source File: CompositeFilter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 14
Source File: TestMDCFilter.java    From big-c with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example 15
Source File: TestMDCFilter.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@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();
}
 
Example 16
Source File: FilterDefinition.java    From dagger-servlet with Apache License 2.0 4 votes vote down vote up
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);
    }
 
Example 17
Source File: DelegatingFilterProxy.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 18
Source File: DelegatingFilterProxy.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: DelegatingFilterProxy.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: DelegatingFilterProxy.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * 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;
}