Java Code Examples for javax.servlet.Filter

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project org.ops4j.pax.wicket, under directory /service/src/main/java/org/ops4j/pax/wicket/internal/.

Source file: FilterDelegator.java

  19 
vote

public void doFilter(ServletRequest request,ServletResponse response) throws IOException, ServletException {
  if (filterIndex < filters.size()) {
    Filter filter=filters.get(filterIndex);
    LOGGER.debug("call filter {} of type {} ",filterIndex,filter.getClass().getName());
    filterIndex++;
    filter.doFilter(request,response,this);
  }
 else {
    servlet.service(request,response);
  }
}
 

Example 2

From project ajah, under directory /ajah-spring-mvc/src/main/java/com/ajah/spring/mvc/util/.

Source file: FilterUtils.java

  18 
vote

/** 
 * Convenience method for adding a filter that is available as a Spring bean/service to all requests.
 * @see ServletContext#addFilter(String,Class)
 * @param filterClass The class of Filter to instantiate.
 * @param appContext The application context to find the bean in.
 * @param servletContext
 * @return The Dynamic Mapping created by this method.
 */
public static Dynamic add(final Class<? extends Filter> filterClass,final ApplicationContext appContext,final ServletContext servletContext){
  final Filter filter=appContext.getBean(filterClass);
  final FilterRegistration.Dynamic reg=servletContext.addFilter(filterClass.getName(),filter);
  reg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*");
  return reg;
}
 

Example 3

From project crowd2-plugin, under directory /src/main/java/de/theit/jenkins/crowd/.

Source file: CrowdSecurityRealm.java

  18 
vote

/** 
 * {@inheritDoc}
 * @see hudson.security.SecurityRealm#createFilter(javax.servlet.FilterConfig)
 */
@Override public Filter createFilter(FilterConfig filterConfig){
  if (null == this.configuration) {
    initializeConfiguration();
  }
  Filter defaultFilter=super.createFilter(filterConfig);
  return new CrowdServletFilter(this,this.configuration,defaultFilter);
}
 

Example 4

From project crowd2-plugin_1, under directory /src/main/java/de/theit/hudson/crowd/.

Source file: CrowdSecurityRealm.java

  18 
vote

/** 
 * {@inheritDoc}
 * @see hudson.security.SecurityRealm#createFilter(javax.servlet.FilterConfig)
 */
@Override public Filter createFilter(FilterConfig filterConfig){
  if (null == this.configuration) {
    initializeConfiguration();
  }
  Filter defaultFilter=super.createFilter(filterConfig);
  return new CrowdServletFilter(this,this.configuration,defaultFilter);
}
 

Example 5

From project cxf-dosgi, under directory /dsw/cxf-dsw/src/main/java/org/apache/cxf/dosgi/dsw/handlers/.

Source file: SecurityDelegatingHttpContext.java

  18 
vote

public void doFilter(ServletRequest request,ServletResponse response) throws IOException, ServletException {
  if (current < filters.length && !response.isCommitted()) {
    Filter filter=filters[current++];
    LOG.info("doFilter() on " + filter);
    filter.doFilter(request,response,this);
  }
}
 

Example 6

From project guice-jit-providers, under directory /extensions/servlet/src/com/google/inject/servlet/.

Source file: FilterChainInvocation.java

  18 
vote

/** 
 * Iterates over the remaining filter definitions. Returns the first applicable filter, or null if none apply.
 */
private Filter findNextFilter(HttpServletRequest request){
  while (++index < filterDefinitions.length) {
    Filter filter=filterDefinitions[index].getFilterIfMatching(request);
    if (filter != null) {
      return filter;
    }
  }
  return null;
}
 

Example 7

From project Ivory, under directory /webapp/src/test/java/org/apache/ivory/security/.

Source file: BasicAuthFilterTest.java

  18 
vote

@Test public void testAnonymous() throws Exception {
  Filter filter=new BasicAuthFilter();
synchronized (StartupProperties.get()) {
    StartupProperties.get().setProperty("security.enabled","true");
    filter.init(mockConfig);
  }
  CurrentUser.authenticate("nouser");
  Assert.assertEquals(CurrentUser.getUser(),"nouser");
  when(mockRequest.getHeader("Remote-User")).thenReturn("testuser");
  filter.doFilter(mockRequest,mockResponse,mockChain);
  Assert.assertEquals(CurrentUser.getUser(),"testuser");
}
 

Example 8

From project jsf-test, under directory /jetty/src/main/java/org/jboss/test/faces/jetty/.

Source file: JettyServer.java

  18 
vote

@Override public void addFilter(FilterHolder filerHolder){
  Map<String,String> initParameters=filerHolder.getInitParameters();
  String mapping=filerHolder.getMapping();
  String name=filerHolder.getName();
  Filter filter=filerHolder.getFilter();
  org.mortbay.jetty.servlet.FilterHolder jettyFilterHolder=new org.mortbay.jetty.servlet.FilterHolder(filter);
  jettyFilterHolder.setName(name);
  jettyFilterHolder.setInitParameters(initParameters);
  webAppContext.addFilter(jettyFilterHolder,mapping,Handler.ALL);
}
 

Example 9

From project nuxeo-filesystem-connectors, under directory /nuxeo-generic-wss-handler/src/test/java/org/nuxeo/wss/fprpc/tests/fakews/.

Source file: TestFakeLists.java

  18 
vote

@Test public void testHandling() throws Exception {
  Filter filter=new WSSFilter();
  filter.init(null);
  FakeRequest request=FakeRequestBuilder.buildFromResource("WebUrlFromPageUrl.dump");
  FakeResponse response=new FakeResponse();
  filter.doFilter(request,response,null);
  String result=response.getOutput();
  String[] lines=result.split("\n");
  assertEquals("<WebUrlFromPageUrlResult>http://localhost/</WebUrlFromPageUrlResult>",lines[4].trim());
}
 

Example 10

From project nuxeo-webengine, under directory /nuxeo-webengine-jaxrs/src/main/java/org/nuxeo/ecm/webengine/jaxrs/servlet/.

Source file: RequestChain.java

  18 
vote

@Override public void doFilter(ServletRequest request,ServletResponse response) throws IOException, ServletException {
  if (filterIndex < filters.length) {
    Filter filter=filters[filterIndex++];
    filter.doFilter(request,response,this);
  }
 else {
    servlet.service(request,response);
  }
}
 

Example 11

From project openengsb-framework, under directory /ui/common/src/test/java/org/openengsb/ui/common/util/.

Source file: DelegatingSecurityFilterTest.java

  18 
vote

@Test public void testDoFilter_shouldDelegateToSecurityFilterChain() throws Exception {
  ServletRequest req=mock(ServletRequest.class);
  ServletResponse resp=mock(ServletResponse.class);
  FilterChain chain=mock(FilterChain.class);
  Filter filter=filterFactory.createFilter(mock(ConfigurableFilterConfig.class));
  filter.doFilter(req,resp,chain);
  verify(delegateFilter).doFilter(req,resp,chain);
}
 

Example 12

From project org.ops4j.pax.web, under directory /pax-web-extender-war/src/main/java/org/ops4j/pax/web/extender/war/internal/.

Source file: UnregisterWebAppVisitorWC.java

  18 
vote

/** 
 * Unregisters filter from web container.
 * @throws NullArgumentException if filter is null
 * @see WebAppVisitor#visit(WebAppFilter)
 */
public void visit(final WebAppFilter webAppFilter){
  NullArgumentException.validateNotNull(webAppFilter,"Web app filter");
  final Filter filter=webAppFilter.getFilter();
  if (filter != null) {
    try {
      m_webContainer.unregisterFilter(filter);
    }
 catch (    Exception ignore) {
      LOG.error("Unregistration exception. Skipping.",ignore);
    }
  }
}
 

Example 13

From project qi4j-libraries, under directory /http/src/main/java/org/qi4j/library/http/.

Source file: JettyMixin.java

  18 
vote

private void addFilters(Context root,Iterable<ServiceReference<Filter>> filters){
  for (  ServiceReference<Filter> filter : filters) {
    FilterInfo filterInfo=filter.metaInfo(FilterInfo.class);
    String filterPath=filterInfo.getPath();
    Filter filterInstance=filter.get();
    FilterHolder holder=new FilterHolder(filterInstance);
    holder.setInitParameters(filterInfo.initParameters());
    root.addFilter(holder,filterPath,toInt(filterInfo.dispatchers()));
  }
}
 

Example 14

From project repose, under directory /project-set/core/core-lib/src/test/java/com/rackspace/papi/filter/.

Source file: FilterClassFactoryTest.java

  18 
vote

@Test public void shouldCreateNewInstance() throws ClassNotFoundException {
  ClassLoader mockedClassLoader=mock(ClassLoader.class);
  FilterType mockedFilterType=mock(FilterType.class);
  FullyQualifiedClassType mockedClassType=mock(FullyQualifiedClassType.class);
  when(mockedClassLoader.loadClass(any(String.class))).thenReturn((Class)FakeFilterClass.class);
  when(mockedFilterType.getFilterClass()).thenReturn(mockedClassType);
  when(mockedClassType.getValue()).thenReturn("Fake class name");
  FilterClassFactory filterClassFactory=new FilterClassFactory(mockedFilterType,mockedClassLoader);
  Filter newFilter=filterClassFactory.newInstance(mock(ApplicationContext.class));
  assertNotNull(newFilter);
}
 

Example 15

From project shiro, under directory /support/spring/src/main/java/org/apache/shiro/spring/web/.

Source file: ShiroFilterFactoryBean.java

  18 
vote

/** 
 * Inspects a bean, and if it implements the  {@link Filter} interface, automatically adds that filterinstance to the internal  {@link #setFilters(java.util.Map) filters map} that will be referencedlater during filter chain construction.
 */
public Object postProcessBeforeInitialization(Object bean,String beanName) throws BeansException {
  if (bean instanceof Filter) {
    log.debug("Found filter chain candidate filter '{}'",beanName);
    Filter filter=(Filter)bean;
    applyGlobalPropertiesIfNecessary(filter);
    getFilters().put(beanName,filter);
  }
 else {
    log.trace("Ignoring non-Filter bean '{}'",beanName);
  }
  return bean;
}
 

Example 16

From project sisu-guice, under directory /extensions/servlet/src/com/google/inject/servlet/.

Source file: FilterChainInvocation.java

  18 
vote

/** 
 * Iterates over the remaining filter definitions. Returns the first applicable filter, or null if none apply.
 */
private Filter findNextFilter(HttpServletRequest request){
  while (++index < filterDefinitions.length) {
    Filter filter=filterDefinitions[index].getFilterIfMatching(request);
    if (filter != null) {
      return filter;
    }
  }
  return null;
}
 

Example 17

From project spring-security, under directory /config/src/main/java/org/springframework/security/config/http/.

Source file: DefaultFilterChainValidator.java

  18 
vote

private void checkForDuplicates(Class<? extends Filter> clazz,List<Filter> filters){
  for (int i=0; i < filters.size(); i++) {
    Filter f1=filters.get(i);
    if (clazz.isAssignableFrom(f1.getClass())) {
      for (int j=i + 1; j < filters.size(); j++) {
        Filter f2=filters.get(j);
        if (clazz.isAssignableFrom(f2.getClass())) {
          logger.warn("Possible error: Filters at position " + i + " and "+ j+ " are both "+ "instances of "+ clazz.getName());
          return;
        }
      }
    }
  }
}
 

Example 18

From project virgo.snaps, under directory /org.eclipse.virgo.snaps.core/src/main/java/org/eclipse/virgo/snaps/core/internal/webapp/container/.

Source file: FilterManager.java

  18 
vote

private void processFilterMappings(WebXml webXml,Map<String,FilterHolder> filters) throws SnapException {
  for (  UrlPatternFilterMappingDefinition definition : webXml.getUrlPatternFilterMappingDefinitions()) {
    Filter filter=filters.get(definition.getFilterName()).getInstance();
    this.urlPatternFilterMappings.add(new UrlPatternFilterMapping(filter,ManagerUtils.expandMapping(definition.getUrlPattern(),this.snapServletContext),definition.getFilterDispatcherTypes()));
  }
  for (  ServletNameFilterMappingDefinition definition : webXml.getServletNameFilterMappingDefinitions()) {
    Filter filter=filters.get(definition.getFilterName()).getInstance();
    this.servletNameFilterMappings.add(new ServletNameFilterMapping(filter,definition.getServletName(),definition.getFilterDispatcherTypes()));
  }
}
 

Example 19

From project hoop, under directory /hoop-server/src/test/java/com/cloudera/lib/servlet/.

Source file: TestHostnameFilter.java

  17 
vote

@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 {
      Assert.assertEquals(HostnameFilter.get(),"localhost");
      invoked.set(true);
    }
  }
;
  Filter filter=new HostnameFilter();
  filter.init(null);
  Assert.assertNull(HostnameFilter.get());
  filter.doFilter(request,response,chain);
  Assert.assertTrue(invoked.get());
  Assert.assertNull(HostnameFilter.get());
  filter.destroy();
}
 

Example 20

From project java-cas-client, under directory /cas-client-core/src/main/java/org/jasig/cas/client/util/.

Source file: DelegatingFilter.java

  17 
vote

public void doFilter(final ServletRequest request,final ServletResponse response,final FilterChain filterChain) throws IOException, ServletException {
  final String parameter=CommonUtils.safeGetParameter((HttpServletRequest)request,this.requestParameterName);
  if (CommonUtils.isNotEmpty(parameter)) {
    for (    final String key : this.delegators.keySet()) {
      if ((parameter.equals(key) && this.exactMatch) || (parameter.matches(key) && !this.exactMatch)) {
        final Filter filter=this.delegators.get(key);
        if (log.isDebugEnabled()) {
          log.debug("Match found for parameter [" + this.requestParameterName + "] with value ["+ parameter+ "]. Delegating to filter ["+ filter.getClass().getName()+ "]");
        }
        filter.doFilter(request,response,filterChain);
        return;
      }
    }
  }
  log.debug("No match found for parameter [" + this.requestParameterName + "] with value ["+ parameter+ "]");
  if (this.defaultFilter != null) {
    this.defaultFilter.doFilter(request,response,filterChain);
  }
 else {
    filterChain.doFilter(request,response);
  }
}
 

Example 21

From project nuxeo-chemistry, under directory /nuxeo-opencmis-tests/src/test/java/org/nuxeo/ecm/core/opencmis/impl/.

Source file: NuxeoSessionClientServerTestCase.java

  17 
vote

protected void setUpTomcat() throws Exception {
  Tomcat tomcat=new Tomcat();
  tomcat.setBaseDir(".");
  tomcat.setHostname(HOST);
  tomcat.setPort(PORT);
  ProtocolHandler p=tomcat.getConnector().getProtocolHandler();
  JIoEndpoint endpoint=(JIoEndpoint)getFieldValue(p,"endpoint");
  endpoint.setMaxKeepAliveRequests(1);
  URL url=getResource(BASE_RESOURCE);
  File docBase=new File(url.getPath());
  org.apache.catalina.Context context=tomcat.addContext("/",docBase.getAbsolutePath());
  String SERVLET_NAME="testServlet";
  Wrapper servlet=tomcat.addServlet("/",SERVLET_NAME,getServlet());
  servlet.addInitParameter(CmisAtomPubServlet.PARAM_CALL_CONTEXT_HANDLER,BasicAuthCallContextHandler.class.getName());
  context.addServletMapping("/*",SERVLET_NAME);
  context.setApplicationLifecycleListeners(getEventListeners());
  Filter filter=getFilter();
  if (filter != null) {
    String FILTER_NAME="NuxeoAuthenticationFilter";
    FilterDef filterDef=new FilterDef();
    filterDef.setFilterName(FILTER_NAME);
    filterDef.setFilterClass(filter.getClass().getName());
    context.addFilterDef(filterDef);
    FilterMap filterMap=new FilterMap();
    filterMap.setFilterName(FILTER_NAME);
    filterMap.addServletName(SERVLET_NAME);
    context.addFilterMap(filterMap);
  }
  serverURI=new URI("http://" + HOST + ':'+ PORT+ '/');
  tomcat.start();
  this.tomcat=tomcat;
}
 

Example 22

From project spring-test-mvc, under directory /src/main/java/org/springframework/test/web/server/.

Source file: MockFilterChain.java

  17 
vote

/** 
 * Invoke registered  {@link Filter}s and/or  {@link Servlet} also saving therequest and response.
 */
public void doFilter(ServletRequest request,ServletResponse response) throws IOException, ServletException {
  Assert.notNull(request,"Request must not be null");
  Assert.notNull(response,"Response must not be null");
  if (this.request != null) {
    throw new IllegalStateException("This FilterChain has already been called!");
  }
  if (this.iterator == null) {
    this.iterator=this.filters.iterator();
  }
  if (this.iterator.hasNext()) {
    Filter nextFilter=this.iterator.next();
    nextFilter.doFilter(request,response,this);
  }
  this.request=request;
  this.response=response;
}
 

Example 23

From project tempo, under directory /liferay-ticket-filter/src/main/java/org/intalio/tempo/web/.

Source file: CASFilter520.java

  17 
vote

protected void processFilter(HttpServletRequest request,HttpServletResponse response,FilterChain filterChain){
  try {
    long companyId=PortalUtil.getCompanyId(request);
    if (PrefsPropsUtil.getBoolean(companyId,PropsKeys.CAS_AUTH_ENABLED,PropsValues.CAS_AUTH_ENABLED)) {
      String pathInfo=request.getPathInfo();
      if (pathInfo.indexOf("/portal/logout") != -1) {
        HttpSession session=request.getSession();
        session.invalidate();
        String logoutUrl=PrefsPropsUtil.getString(companyId,PropsKeys.CAS_LOGOUT_URL,PropsValues.CAS_LOGOUT_URL);
        response.sendRedirect(logoutUrl);
      }
 else {
        Filter casFilter=getCASFilter(companyId);
        casFilter.doFilter(request,response,filterChain);
      }
    }
 else {
      processFilter(CASFilter.class,request,response,filterChain);
    }
  }
 catch (  Exception e) {
    _log.error(e,e);
  }
}
 

Example 24

From project webframe, under directory /wf-web/src/main/java/org/webframe/web/filter/.

Source file: WFFilterChain.java

  17 
vote

public void doFilter(final ServletRequest request,final ServletResponse response) throws IOException, ServletException {
  if (currentPosition == additionalFilters.size()) {
    if (webframeFilterProxy != null) {
      FilterChain lastChain=webframeFilterProxy.afterSecurityFilterChain(request,response,originalChain);
      if (webframeFilterProxy.hasSecurity) {
        webframeFilterProxy.superDoFilter(request,response,lastChain);
      }
 else {
        lastChain.doFilter(request,response);
      }
    }
 else {
      originalChain.doFilter(request,response);
    }
  }
 else {
    currentPosition++;
    Filter nextFilter=additionalFilters.get(currentPosition - 1);
    if (log.isDebugEnabled()) {
      log.debug("At position " + currentPosition + " of "+ additionalFilters.size()+ " in additional filter chain; firing Filter: '"+ nextFilter.getClass().getSimpleName()+ "'");
    }
    nextFilter.doFilter(request,response,this);
  }
}
 

Example 25

From project agile, under directory /agile-framework/src/main/java/org/headsupdev/agile/framework/.

Source file: HeadsUpActivator.java

  15 
vote

/** 
 * Called whenever the OSGi framework starts our bundle
 */
public void start(BundleContext bc) throws Exception {
  String defaultTimeZoneId=System.getProperty("agile.runtime.timezone");
  if (defaultTimeZoneId != null) {
    Manager.getLogger(getClass().getName()).info("Detected system timezone " + defaultTimeZoneId);
    TimeZone defaultTimeZone=TimeZone.getTimeZone(defaultTimeZoneId);
    Manager.getStorageInstance().getGlobalConfiguration().setDefaultTimeZone(defaultTimeZone);
  }
  Manager.getLogger(getClass().getName()).info("Default timezone set to " + Manager.getStorageInstance().getGlobalConfiguration().getDefaultTimeZone().getID());
  Dictionary props=new Hashtable();
  props.put("alias","/");
  props.put("servlet-name","Wicket Servlet");
  bc.registerService(Servlet.class.getName(),new HeadsUpServlet(),props);
  props=new Hashtable();
  String[] urls={"/*"};
  props.put("filter-name","Wicket Filter");
  props.put("urlPatterns",urls);
  bc.registerService(Filter.class.getName(),new HeadsUpFilter(),props);
  props=new Hashtable();
  props.put("alias","/repository/*");
  bc.registerService(Servlet.class.getName(),new RepositoryServlet(),props);
  props=new Hashtable();
  props.put("alias","/favicon.ico");
  bc.registerService(Servlet.class.getName(),new FaviconServlet(),props);
  HomeApplication homeApp=new HomeApplication();
  homeApp.setContext(bc);
  props=new Properties();
  bc.registerService(Application.class.getName(),homeApp,props);
  DefaultErrorPageMapping error=new DefaultErrorPageMapping();
  error.setError("404");
  error.setLocation("/filenotfound");
  bc.registerService(ErrorPageMapping.class.getName(),error,null);
  System.out.println("Started version " + Manager.getStorageInstance().getGlobalConfiguration().getBuildVersion() + " at "+ Manager.getStorageInstance().getGlobalConfiguration().getBaseUrl());
  webTracker=new WebTracker(bc);
  webTracker.open();
  appTracker=new AppTracker(bc);
  appTracker.open();
}
 

Example 26

From project airlift, under directory /http-server/src/main/java/io/airlift/http/server/.

Source file: HttpServer.java

  15 
vote

private static ServletContextHandler createServletContext(Servlet theServlet,Map<String,String> parameters,Set<Filter> filters,TraceTokenManager tokenManager,LoginService loginService,String... connectorNames){
  ServletContextHandler context=new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  context.addFilter(new FilterHolder(new TimingFilter()),"/*",null);
  if (tokenManager != null) {
    context.addFilter(new FilterHolder(new TraceTokenFilter(tokenManager)),"/*",null);
  }
  context.addFilter(GzipFilter.class,"/*",null);
  context.addFilter(GZipRequestFilter.class,"/*",null);
  if (loginService != null) {
    SecurityHandler securityHandler=createSecurityHandler(loginService);
    context.setSecurityHandler(securityHandler);
  }
  for (  Filter filter : filters) {
    context.addFilter(new FilterHolder(filter),"/*",null);
  }
  ServletHolder servletHolder=new ServletHolder(theServlet);
  servletHolder.setInitParameters(ImmutableMap.copyOf(parameters));
  context.addServlet(servletHolder,"/*");
  context.setConnectorNames(connectorNames);
  return context;
}
 

Example 27

From project core_4, under directory /impl/src/main/java/org/richfaces/webapp/.

Source file: GenericServletContainerInitializer.java

  15 
vote

/** 
 * Detects if given  {@link Filter} class has been already registered.
 * @param filterClass {@link Filter} implementation class
 * @param context to search for registration
 * @return true if given {@link Filter} class has been already registered.
 */
protected boolean hasFilterMapping(Class<? extends Filter> filterClass,ServletContext context){
  Collection<? extends FilterRegistration> filterRegistrations=context.getFilterRegistrations().values();
  for (  FilterRegistration filterRegistration : filterRegistrations) {
    if (filterClass.getName().equals(filterRegistration.getClassName())) {
      return true;
    }
  }
  return false;
}
 

Example 28

From project guice-automatic-injection, under directory /integrations/enterprise/src/main/java/de/devsurf/injection/guice/enterprise/features/.

Source file: WebFilterBindingFeature.java

  15 
vote

@Override public void process(final Class<Object> annotatedClass,final Map<String,Annotation> annotations){
  final WebFilter annotation=(WebFilter)annotations.get(WebFilter.class.getName());
  String[] patterns=annotation.value();
  final String value;
  final String[] values;
  if (patterns.length > 0) {
    value=resolver.resolve(patterns[0]);
    if (patterns.length > 1) {
      values=new String[patterns.length - 1];
      for (int i=1; i < patterns.length; i++) {
        values[i - 1]=resolver.resolve(patterns[i]);
      }
    }
 else {
      values=new String[0];
    }
  }
 else {
    LOGGER.info("Ignoring Filter \"" + annotatedClass + "\", because no Values for URLs were specified.");
    return;
  }
  _binder.install(new ServletModule(){
    @Override protected void configureServlets(){
      filter(value,values).through(annotatedClass.asSubclass(Filter.class));
    }
  }
);
}
 

Example 29

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/utils/.

Source file: CommonServletFilter.java

  15 
vote

@Override public void init(final FilterConfig arg0) throws ServletException {
  try {
    final Class<?> filterClass=Class.forName(Config.getString("databinding","secure.filter"));
    this.servletFiler=(Filter)filterClass.newInstance();
    this.servletFiler.init(arg0);
    PhLogger.getLogger().info("Security Filter successfully loaded");
  }
 catch (  final ClassNotFoundException e) {
    PhLogger.getLogger().info("No Security Filter available");
  }
catch (  final Exception e) {
    PhLogger.getLogger().error("Could not create Servlet Filter: " + e.getMessage(),e);
  }
}
 

Example 30

From project jira-hudson-integration, under directory /hudson-apiv2-plugin/src/main/java/com/marvelution/hudson/plugins/apiv2/.

Source file: APIv2Plugin.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public void start() throws Exception {
  super.start();
  plugin=this;
  load();
  LOGGER.info("Adding the APIv2 Filters");
  filters.add(new HudsonAPIV2ServletFilter());
  for (  Filter filter : filters) {
    PluginServletFilter.addFilter(filter);
  }
  LOGGER.info("Loading the Activity Cache");
  File activityCacheFile=getFile(ACTIVITIES_CACHE_FILE);
  if (activityCacheFile.exists()) {
    try {
      activitiesCache=(ActivitiesCache)XSTREAM.fromXML(new FileInputStream(activityCacheFile));
    }
 catch (    Exception e) {
      activitiesCache=new ActivitiesCache();
      LOGGER.severe("Failed to load the " + ACTIVITIES_CACHE_FILE + " and will thus not be available for the REST APIs");
    }
  }
  LOGGER.info("Loading the Issues Cache");
  File issuesCacheFile=getFile(ISSUES_CACHE_FILE);
  if (issuesCacheFile.exists()) {
    try {
      issuesCache=(IssuesCache)XSTREAM.fromXML(new FileInputStream(issuesCacheFile));
    }
 catch (    Exception e) {
      issuesCache=new IssuesCache();
      LOGGER.severe("Failed to load the " + ISSUES_CACHE_FILE + " and will thus not be available for the REST APIs");
    }
  }
  if (StringUtils.isBlank(issuesCache.getIssueKeyRegex())) {
    issuesCache.setIssueKeyRegex(JiraKeyUtils.DEFAULT_JIRA_ISSUE_KEY_PATTERN.pattern());
  }
}
 

Example 31

From project jsecurity, under directory /web/src/main/java/org/apache/ki/web/config/.

Source file: IniWebConfiguration.java

  15 
vote

/** 
 * Returns the <code>FilterChain</code> to use for the specified application path, or <code>null</code> if the original <code>FilterChain</code> should be used. <p/> The default implementation simply calls <code>this.chains.get(chainUrl)</code> to acquire the configured <code>List&lt;Filter&gt;</code> filter chain.  If that configured chain is non-null and not empty, it is returned, otherwise <code>null</code> is returned to indicate that the <code>originalChain</code> should be used instead.
 * @param chainUrl      the configured filter chain url
 * @param originalChain the original FilterChain given by the Servlet container.
 * @return the <code>FilterChain</code> to use for the specified application path, or <code>null</code> if theoriginal <code>FilterChain</code> should be used.
 */
protected FilterChain getChain(String chainUrl,FilterChain originalChain){
  List<Filter> pathFilters=this.chains.get(chainUrl);
  if (pathFilters != null && !pathFilters.isEmpty()) {
    return createChain(pathFilters,originalChain);
  }
  return null;
}
 

Example 32

From project maven-wagon, under directory /wagon-tcks/wagon-tck-http/src/main/java/org/apache/maven/wagon/tck/http/fixture/.

Source file: ServerFixture.java

  15 
vote

public void addFilter(final String pathSpec,final Filter filter){
  String name="filter" + filterCount++;
  FilterMapping fm=new FilterMapping();
  fm.setPathSpec(pathSpec);
  fm.setFilterName(name);
  FilterHolder fh=new FilterHolder(filter);
  fh.setName(name);
  webappContext.getServletHandler().addFilter(fh,fm);
}
 

Example 33

From project ning-service-skeleton, under directory /base/src/main/java/com/ning/jetty/base/modules/.

Source file: BaseServerModule.java

  15 
vote

public BaseServerModule(final Map<Class,Object> bindings,final ConfigSource configSource,final List<Class> configs,final List<Class<? extends HealthCheck>> healthchecks,final List<Class> beans,final String areciboProfile,final boolean trackRequests,final boolean log4jEnabled,final String jaxRSUriPattern,final List<String> jaxRSResources,final List<Module> modules,final Map<String,ArrayList<Map.Entry<Class<? extends Filter>,Map<String,String>>>> filters,final Map<String,ArrayList<Map.Entry<Class<? extends Filter>,Map<String,String>>>> filtersRegex,final Map<String,Class<? extends HttpServlet>> jaxRSServlets,final Map<String,Class<? extends HttpServlet>> jaxRSServletsRegex,final Map<String,Class<? extends HttpServlet>> servlets,final Map<String,Class<? extends HttpServlet>> servletsRegex){
  this.bindings.putAll(bindings);
  this.configSource=configSource;
  this.configs.addAll(configs);
  this.healthchecks.addAll(healthchecks);
  this.beans.addAll(beans);
  this.areciboProfile=areciboProfile;
  this.log4jEnabled=log4jEnabled;
  this.trackRequests=trackRequests;
  this.jaxRSUriPattern=jaxRSUriPattern;
  this.jaxRSResources.addAll(jaxRSResources);
  this.modules.addAll(modules);
  this.filters=filters;
  this.filtersRegex=filtersRegex;
  this.jaxRSServlets=jaxRSServlets;
  this.jaxRSServletsRegex=jaxRSServletsRegex;
  this.servlets=servlets;
  this.servletsRegex=servletsRegex;
  this.configs.add(DaoConfig.class);
  this.configs.add(TrackerConfig.class);
}
 

Example 34

From project openwebbeans, under directory /webbeans-tomcat6/src/main/java/org/apache/webbeans/web/tomcat/.

Source file: TomcatWebPlugin.java

  15 
vote

/** 
 * {@inheritDoc}
 */
@Override public boolean supportsJavaEeComponentInjections(Class<?> clazz){
  if (Servlet.class.isAssignableFrom(clazz) || Filter.class.isAssignableFrom(clazz) || ServletContextListener.class.isAssignableFrom(clazz)|| ServletContextAttributeListener.class.isAssignableFrom(clazz)|| HttpSessionActivationListener.class.isAssignableFrom(clazz)|| HttpSessionAttributeListener.class.isAssignableFrom(clazz)|| HttpSessionBindingListener.class.isAssignableFrom(clazz)|| HttpSessionListener.class.isAssignableFrom(clazz)|| ServletRequestListener.class.isAssignableFrom(clazz)|| ServletRequestAttributeListener.class.isAssignableFrom(clazz)|| clazz.isAnnotationPresent(WebService.class)) {
    return true;
  }
  return false;
}
 

Example 35

From project osgi-utils, under directory /com.c4biz.osgiutils.vaadin.equinox.shiro/src/com/c4biz/osgiutils/vaadin/equinox/shiro/.

Source file: ApplicationRegister.java

  15 
vote

private Filter getSecurityFilter(){
  if (filter == null) {
    filter=new IniShiroFilter();
  }
  return filter;
}
 

Example 36

From project platform_3, under directory /http-server/src/main/java/com/proofpoint/http/server/.

Source file: HttpServer.java

  15 
vote

private static ServletContextHandler createServletContext(Servlet theServlet,Map<String,String> parameters,Set<Filter> filters,TraceTokenManager tokenManager,LoginService loginService,String... connectorNames){
  ServletContextHandler context=new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  context.addFilter(new FilterHolder(new TimingFilter()),"/*",null);
  if (tokenManager != null) {
    context.addFilter(new FilterHolder(new TraceTokenFilter(tokenManager)),"/*",null);
  }
  context.addFilter(GzipFilter.class,"/*",null);
  context.addFilter(GZipRequestFilter.class,"/*",null);
  if (loginService != null) {
    SecurityHandler securityHandler=createSecurityHandler(loginService);
    context.setSecurityHandler(securityHandler);
  }
  for (  Filter filter : filters) {
    context.addFilter(new FilterHolder(filter),"/*",null);
  }
  ServletHolder servletHolder=new ServletHolder(theServlet);
  servletHolder.setInitParameters(ImmutableMap.copyOf(parameters));
  context.addServlet(servletHolder,"/*");
  context.setConnectorNames(connectorNames);
  return context;
}
 

Example 37

From project security_1, under directory /security-web/src/main/java/org/sonatype/security/web/guice/.

Source file: SecurityWebModule.java

  15 
vote

public FilterChainManager get(){
  FilterChainManager filterChainManager=new DefaultFilterChainManager(filterConfig);
  for (  Entry<String,Filter> entry : filterMap.entrySet()) {
    filterChainManager.addFilter(entry.getKey(),entry.getValue(),true);
  }
  return filterChainManager;
}
 

Example 38

From project spring-flex, under directory /spring-flex-core/src/main/java/org/springframework/flex/security3/.

Source file: SecurityConfigurationPostProcessor.java

  15 
vote

public void afterPropertiesSet() throws Exception {
  if (this.sessionAuthenticationStrategy != null) {
    this.sessionAuthenticationStrategy=new FlexSessionAwareSessionAuthenticationStrategy(this.sessionAuthenticationStrategy);
    Set<Filter> allFilters=new HashSet<Filter>(BeanFactoryUtils.beansOfTypeIncludingAncestors(context,Filter.class,false,false).values());
    if (this.filterChainProxy != null) {
      allFilters.addAll(new FilterChainAccessor(this.filterChainProxy).getFilters());
    }
    for (    Filter filter : allFilters) {
      BeanWrapper bw=PropertyAccessorFactory.forBeanPropertyAccess(filter);
      for (      PropertyDescriptor pd : bw.getPropertyDescriptors()) {
        if (ClassUtils.isAssignableValue(pd.getPropertyType(),this.sessionAuthenticationStrategy) && bw.isWritableProperty(pd.getName())) {
          bw.setPropertyValue(pd.getName(),this.sessionAuthenticationStrategy);
        }
      }
    }
  }
  Map<String,ExceptionTranslator> exceptionTranslators=BeanFactoryUtils.beansOfTypeIncludingAncestors(context,ExceptionTranslator.class);
  if (!CollectionUtils.isEmpty(exceptionTranslators)) {
    Map<String,FlexAuthenticationEntryPoint> entryPoints=BeanFactoryUtils.beansOfTypeIncludingAncestors(context,FlexAuthenticationEntryPoint.class);
    for (    FlexAuthenticationEntryPoint entryPoint : entryPoints.values()) {
      if (CollectionUtils.isEmpty(entryPoint.getExceptionTranslators())) {
        entryPoint.setExceptionTranslators(new HashSet<ExceptionTranslator>(exceptionTranslators.values()));
      }
    }
  }
}
 

Example 39

From project undertow, under directory /servlet/src/main/java/io/undertow/servlet/api/.

Source file: FilterInfo.java

  15 
vote

public FilterInfo(final String name,final Class<? extends Filter> filterClass){
  if (name == null) {
    throw UndertowServletMessages.MESSAGES.paramCannotBeNull("name");
  }
  if (filterClass == null) {
    throw UndertowServletMessages.MESSAGES.paramCannotBeNull("filterClass","Filter",name);
  }
  if (!Filter.class.isAssignableFrom(filterClass)) {
    throw UndertowServletMessages.MESSAGES.filterMustImplementFilter(name,filterClass);
  }
  try {
    final Constructor<Filter> ctor=(Constructor<Filter>)filterClass.getDeclaredConstructor();
    ctor.setAccessible(true);
    this.instanceFactory=new ConstructorInstanceFactory<Filter>(ctor);
    this.name=name;
    this.filterClass=filterClass;
  }
 catch (  NoSuchMethodException e) {
    throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("Filter",filterClass);
  }
}
 

Example 40

From project winstone, under directory /src/java/winstone/.

Source file: FilterConfiguration.java

  15 
vote

/** 
 * Implements the first-time-init of an instance, and wraps it in a dispatcher.
 */
public Filter getFilter() throws ServletException {
synchronized (this.filterSemaphore) {
    if (isUnavailable())     throw new WinstoneException(Launcher.RESOURCES.getString("FilterConfiguration.FilterUnavailable"));
 else     if (this.instance == null)     try {
      ClassLoader cl=Thread.currentThread().getContextClassLoader();
      Thread.currentThread().setContextClassLoader(this.loader);
      Class filterClass=Class.forName(classFile,true,this.loader);
      this.instance=(Filter)filterClass.newInstance();
      Logger.log(Logger.DEBUG,Launcher.RESOURCES,"FilterConfiguration.init",this.filterName);
      this.instance.init(this);
      Thread.currentThread().setContextClassLoader(cl);
    }
 catch (    ClassNotFoundException err) {
      Logger.log(Logger.ERROR,Launcher.RESOURCES,"FilterConfiguration.ClassLoadError",this.classFile,err);
    }
catch (    IllegalAccessException err) {
      Logger.log(Logger.ERROR,Launcher.RESOURCES,"FilterConfiguration.ClassLoadError",this.classFile,err);
    }
catch (    InstantiationException err) {
      Logger.log(Logger.ERROR,Launcher.RESOURCES,"FilterConfiguration.ClassLoadError",this.classFile,err);
    }
catch (    ServletException err) {
      this.instance=null;
      if (err instanceof UnavailableException)       setUnavailable();
      throw err;
    }
  }
  return this.instance;
}