Example usage for javax.servlet Filter init

List of usage examples for javax.servlet Filter init

Introduction

In this page you can find the example usage for javax.servlet Filter init.

Prototype

default public void init(FilterConfig filterConfig) throws ServletException 

Source Link

Document

Called by the web container to indicate to a filter that it is being placed into service.

The servlet container calls the init method exactly once after instantiating the filter.

Usage

From source file:org.openinfinity.sso.common.ss.sp.filters.MuleContextUsingDelegatingFilterProxy.java

private Filter initDelegate(ApplicationContext ac) throws ServletException {
    LOG.debug("Finding the delegate by bean name {}", getTargetBeanName());
    Filter delegate = ac.getBean(getTargetBeanName(), Filter.class);
    if (isTargetFilterLifecycle()) {
        LOG.debug("Initializing the delegate");
        delegate.init(getFilterConfig());
    }//from  w ww . j  ava 2  s  .  com
    return delegate;
}

From source file:de.micromata.genome.tpsb.httpmockup.MockServletContext.java

public MockServletContext addFilter(final String name, final Class<? extends Filter> filterClass,
        final Map<String, String> initParams) {

    try {/*from  www  .jav  a 2s .  c o  m*/
        final Filter filter = filterClass.newInstance();
        final MockFilterConfig fc = new MockFilterConfig();
        fc.setFilterName(name);
        fc.setServletContext(this);
        if (initParams != null) {
            fc.addAllInitParameters(initParams);
        }
        filter.init(fc);
        this.filtersConfig.addFilter(name, filter);
        return this;
    } catch (final Exception ex) {
        throw new RuntimeException("Exception in initializing filter: " + name + "; " + filterClass.getName()
                + "; " + ex.getMessage(), ex);
    }
}

From source file:org.apache.wiki.WikiSessionTest.java

/**
 * "Scaffolding" method that runs the session security filter on a mock request. We do this by creating a
 * complete mock servlet context and filter chain, and running the request through it. 
 * @param engine the wiki engine/*from w  w  w .ja v  a 2s  .  co  m*/
 * @param request the mock request to pass itnto the 
 * @throws ServletException
 * @throws IOException
 */
private static void runSecurityFilter(WikiEngine engine, HttpServletRequest request)
        throws ServletException, IOException {
    // Create a mock servlet context and stash the wiki engine in it
    ServletContext servletCtx = new MockServletContext("JSPWiki");
    servletCtx.setAttribute("org.apache.wiki.WikiEngine", engine);

    // Create a mock filter configuration and add the servlet context we just created
    MockFilterConfig filterConfig = new MockFilterConfig();
    filterConfig.setFilterName("WikiServletFilter");
    filterConfig.setServletContext(servletCtx);

    // Create the security filter and run the request  through it
    Filter filter = new WikiServletFilter();
    MockFilterChain chain = new MockFilterChain();
    chain.addFilter(filter);
    Servlet servlet = new MockServlet();
    chain.setServlet(servlet);
    filter.init(filterConfig);
    filter.doFilter(request, null, chain);
}

From source file:org.j2free.invoker.InvokerFilter.java

/**
 * Locks to prevent request processing while mapping is added.
 *
 * Finds all classes annotated with ServletConfig and maps the class to
 * the url specified in the annotation.  Wildcard mapping are allowed in
 * the form of *.extension or /some/path/*
 *
 * @param context an active ServletContext
 *///ww  w  .ja  v a  2 s  .  co m
public void load(final ServletContext context) {
    try {
        write.lock();

        LinkedList<URL> urlList = new LinkedList<URL>();
        urlList.addAll(Arrays.asList(ClasspathUrlFinder.findResourceBases(EMPTY)));
        urlList.addAll(Arrays.asList(WarUrlFinder.findWebInfLibClasspaths(context)));

        URL[] urls = new URL[urlList.size()];
        urls = urlList.toArray(urls);

        AnnotationDB annoDB = new AnnotationDB();
        annoDB.setScanClassAnnotations(true);
        annoDB.setScanFieldAnnotations(false);
        annoDB.setScanMethodAnnotations(false);
        annoDB.setScanParameterAnnotations(false);
        annoDB.scanArchives(urls);

        HashMap<String, Set<String>> annotationIndex = (HashMap<String, Set<String>>) annoDB
                .getAnnotationIndex();
        if (annotationIndex != null && !annotationIndex.isEmpty()) {
            //-----------------------------------------------------------
            // Look for any classes annotated with @ServletConfig
            Set<String> classNames = annotationIndex.get(ServletConfig.class.getName());

            if (classNames != null) {
                for (String c : classNames) {
                    try {
                        final Class<? extends HttpServlet> klass = (Class<? extends HttpServlet>) Class
                                .forName(c);

                        if (klass.isAnnotationPresent(ServletConfig.class)) {
                            final ServletConfig config = (ServletConfig) klass
                                    .getAnnotation(ServletConfig.class);

                            // If the config specifies String mapppings...
                            if (config.mappings() != null) {
                                for (String url : config.mappings()) {
                                    // Leave the asterisk, we'll add it when matching...
                                    //if (url.matches("(^\\*[^*]*?)|([^*]*?/\\*$)"))
                                    //    url = url.replace("*", EMPTY);

                                    url = url.toLowerCase(); // all comparisons are lower-case

                                    if (urlMap.putIfAbsent(url, klass) == null) {
                                        if (log.isDebugEnabled())
                                            log.debug("Mapping servlet " + klass.getName() + " to path " + url);
                                    } else
                                        log.error("Unable to map servlet  " + klass.getName() + " to path "
                                                + url + ", path already mapped to "
                                                + urlMap.get(url).getName());
                                }
                            }

                            // If the config specifies a regex mapping...
                            if (!empty(config.regex())) {
                                regexMap.putIfAbsent(config.regex(), klass);
                                if (log.isDebugEnabled())
                                    log.debug("Mapping servlet " + klass.getName() + " to regex path "
                                            + config.regex());
                            }

                            // Create an instance of the servlet and init it
                            HttpServlet servlet = klass.newInstance();
                            servlet.init(new ServletConfigImpl(klass.getName(), context));

                            // Store a reference
                            servletMap.put(klass, new ServletMapping(servlet, config));
                        }

                    } catch (Exception e) {
                        log.error("Error registering servlet [name=" + c + "]", e);
                    }
                }
            }

            //-----------------------------------------------------------
            // Look for any classes annotated with @FiltersConfig
            classNames = annotationIndex.get(FilterConfig.class.getName());
            if (classNames != null) {
                for (String c : classNames) {
                    try {
                        final Class<? extends Filter> klass = (Class<? extends Filter>) Class.forName(c);

                        if (klass.isAnnotationPresent(FilterConfig.class)) {
                            final FilterConfig config = (FilterConfig) klass.getAnnotation(FilterConfig.class);

                            // Create an instance of the servlet and init it
                            Filter filter = klass.newInstance();
                            filter.init(new FilterConfigImpl(klass.getName(), context));

                            if (log.isDebugEnabled())
                                log.debug("Mapping filter " + klass.getName() + " to path " + config.match());

                            // Store a reference
                            filters.add(new FilterMapping(filter, config));
                        }
                    } catch (Exception e) {
                        log.error("Error registering servlet [name=" + c + "]", e);
                    }
                }
            }
        }
    } catch (IOException e) {
        log.error("Error loading urlMappings", e);
    } finally {
        write.unlock(); // ALWAYS Release the configure lock
    }
}

From source file:org.jsecurity.web.config.IniWebConfiguration.java

/**
 * Initializes the filter by calling <code>filter.init( {@link #getFilterConfig() getFilterConfig()} );</code>.
 *
 * @param filter the filter to initialize with the <code>FilterConfig</code>.
 *//*from   w w  w .j  a  v a 2s.c o  m*/
protected void initFilter(Filter filter) {
    try {
        filter.init(getFilterConfig());
    } catch (ServletException e) {
        throw new ConfigurationException(e);
    }
}

From source file:org.openmrs.module.web.WebModuleUtil.java

/**
 * This method will initialize and store this module's filters
 *
 * @param module - The Module to load and register Filters
 * @param servletContext - The servletContext within which this method is called
 *///from  w w  w  .  j  av  a  2  s .c om
public static void loadFilters(Module module, ServletContext servletContext) {

    // Load Filters
    Map<String, Filter> filters = new HashMap<String, Filter>();
    try {
        for (ModuleFilterDefinition def : ModuleFilterDefinition.retrieveFilterDefinitions(module)) {
            if (moduleFiltersByName.containsKey(def.getFilterName())) {
                throw new ModuleException(
                        "A filter with name <" + def.getFilterName() + "> has already been registered.");
            }
            ModuleFilterConfig config = ModuleFilterConfig.getInstance(def, servletContext);
            Filter f = (Filter) ModuleFactory.getModuleClassLoader(module).loadClass(def.getFilterClass())
                    .newInstance();
            f.init(config);
            filters.put(def.getFilterName(), f);
        }
    } catch (ModuleException e) {
        throw e;
    } catch (Exception e) {
        throw new ModuleException("An error occurred initializing Filters for module: " + module.getModuleId(),
                e);
    }
    moduleFilters.put(module, filters.values());
    moduleFiltersByName.putAll(filters);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + filters.size() + " filters.");

    // Load Filter Mappings
    List<ModuleFilterMapping> modMappings = ModuleFilterMapping.retrieveFilterMappings(module);
    moduleFilterMappings.addAll(modMappings);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + modMappings.size()
            + " filter mappings.");
}

From source file:org.ops4j.pax.web.service.internal.FilterTest.java

@Test
public void filterIsCalledOnUrlPattern() throws NamespaceException, ServletException, IOException {
    Servlet servlet = createMock(Servlet.class);
    servlet.init((ServletConfig) notNull());
    servlet.destroy();/*w w  w .j  a  v  a  2  s . co m*/

    Filter filter = createMock(Filter.class);
    filter.init((FilterConfig) notNull());
    filter.doFilter((ServletRequest) notNull(), (ServletResponse) notNull(), (FilterChain) notNull());
    filter.destroy();

    replay(servlet, filter);

    HttpContext context = m_httpService.createDefaultHttpContext();
    m_httpService.registerServlet("/test", servlet, null, context);
    m_httpService.registerFilter(filter, new String[] { "/*" }, null, context);

    HttpMethod method = new GetMethod("http://localhost:8080/test");
    m_client.executeMethod(method);
    method.releaseConnection();

    m_httpService.unregister("/test");
    m_httpService.unregisterFilter(filter);

    verify(servlet, filter);
}

From source file:org.ops4j.pax.web.service.internal.FilterTest.java

@Test
public void filterIsCalledOnServlet() throws NamespaceException, ServletException, IOException {
    Servlet servlet = createMock(Servlet.class);
    servlet.init((ServletConfig) notNull());
    servlet.destroy();/* ww w .j a  v  a2 s .  c  om*/

    Filter filter = createMock(Filter.class);
    filter.init((FilterConfig) notNull());
    filter.doFilter((ServletRequest) notNull(), (ServletResponse) notNull(), (FilterChain) notNull());
    filter.destroy();

    replay(servlet, filter);

    HttpContext context = m_httpService.createDefaultHttpContext();
    m_httpService.registerServlet("/test", servlet, null, context);
    m_httpService.registerFilter(filter, null, new String[] { "/test" }, context);

    HttpMethod method = new GetMethod("http://localhost:8080/test");
    m_client.executeMethod(method);
    method.releaseConnection();

    m_httpService.unregister("/test");
    m_httpService.unregisterFilter(filter);

    verify(servlet, filter);
}