Example usage for javax.servlet Filter getClass

List of usage examples for javax.servlet Filter getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:shiver.me.timbers.spring.security.modification.SecurityFilterChainModifier.java

@Override
@SuppressWarnings("unchecked")
public <F extends Filter> void modifyLink(SecurityFilterChain filterChain, Class<F> filterType,
        Modifier<F> modifier) {
    for (Filter filter : filterChain.getFilters()) {
        if (filterType.isAssignableFrom(filter.getClass())) {
            modifier.modify((F) filter);
        }/*w  w  w  .j ava  2  s .  c o m*/
    }
}

From source file:grails.plugin.springsecurity.web.filter.DebugFilter.java

protected String formatFilters(List<Filter> filters) {
    StringBuilder sb = new StringBuilder("Security filter chain: ");
    if (filters == null) {
        sb.append("no match");
    } else if (filters.isEmpty()) {
        sb.append("[] empty (bypassed by security='none') ");
    } else {/* w w w  . ja va  2  s  .c om*/
        sb.append("[\n");
        for (Filter f : filters) {
            sb.append("  ").append(f.getClass().getSimpleName()).append("\n");
        }
        sb.append("]");
    }

    return sb.toString();
}

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

@Override
public void doFilter(final ServletRequest req, final ServletResponse resp)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) req;
    String uri = hreq.getRequestURI();
    String localUri = uri;//from w ww .  j  av  a  2  s.  c om
    if (StringUtils.isNotBlank(hreq.getServletPath()) && StringUtils.isNotBlank(hreq.getPathInfo()) == true) {
        localUri = hreq.getServletPath() + hreq.getPathInfo();
    }
    final MockFiltersConfig fc = this.mockupServletContext.getFiltersConfig();

    this.filterIndex = fc.getNextFilterMapDef(localUri, this.filterIndex, this.dispatcherFlag);
    if (this.filterIndex == -1) {
        this.mockupServletContext.serveServlet((HttpServletRequest) req, (HttpServletResponse) resp);
        return;
    }
    final Filter f = fc.getFilterMapping().get(this.filterIndex).getFilterDef().getFilter();
    ++this.filterIndex;
    if (log.isDebugEnabled() == true) {
        log.debug("Filter filter: " + f.getClass().getName());
    }
    f.doFilter(req, resp, this);

}

From source file:io.nebo.container.NettyEmbeddedContext.java

@Override
public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
    return addFilter(filterName, filter.getClass().getName(), filter);
}

From source file:com.jsmartframework.web.manager.ContextControl.java

@Override
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent event) {
    try {/*  www .  j  ava  2 s .co  m*/
        ServletContext servletContext = event.getServletContext();

        CONFIG.init(servletContext);
        if (CONFIG.getContent() == null) {
            throw new RuntimeException("Configuration file " + Constants.WEB_CONFIG_XML
                    + " was not found in WEB-INF resources folder!");
        }

        String contextConfigLocation = "com.jsmartframework.web.manager";
        if (CONFIG.getContent().getPackageScan() != null) {
            contextConfigLocation += "," + CONFIG.getContent().getPackageScan();
        }

        // Configure necessary parameters in the ServletContext to set Spring configuration without needing an XML file
        AnnotationConfigWebApplicationContext configWebAppContext = new AnnotationConfigWebApplicationContext();
        configWebAppContext.setConfigLocation(contextConfigLocation);

        CONTEXT_LOADER = new ContextLoader(configWebAppContext);
        CONTEXT_LOADER.initWebApplicationContext(servletContext);

        TagEncrypter.init();
        TEXTS.init();
        IMAGES.init(servletContext);
        HANDLER.init(servletContext);

        // ServletControl -> @MultipartConfig @WebServlet(name = "ServletControl", displayName = "ServletControl", loadOnStartup = 1)
        Servlet servletControl = servletContext.createServlet(
                (Class<? extends Servlet>) Class.forName("com.jsmartframework.web.manager.ServletControl"));
        ServletRegistration.Dynamic servletControlReg = (ServletRegistration.Dynamic) servletContext
                .addServlet("ServletControl", servletControl);
        servletControlReg.setAsyncSupported(true);
        servletControlReg.setLoadOnStartup(1);

        // ServletControl Initial Parameters
        InitParam[] initParams = CONFIG.getContent().getInitParams();
        if (initParams != null) {
            for (InitParam initParam : initParams) {
                servletControlReg.setInitParameter(initParam.getName(), initParam.getValue());
            }
        }

        // MultiPart to allow file upload on ServletControl
        MultipartConfigElement multipartElement = getServletMultipartElement();
        if (multipartElement != null) {
            servletControlReg.setMultipartConfig(multipartElement);
        }

        // Security constraint to ServletControl
        ServletSecurityElement servletSecurityElement = getServletSecurityElement(servletContext);
        if (servletSecurityElement != null) {
            servletControlReg.setServletSecurity(servletSecurityElement);
        }

        // TODO: Fix problem related to authentication by container to use SSL dynamically (Maybe create more than one servlet for secure and non-secure patterns)
        // Check also the use of request.login(user, pswd)
        // Check the HttpServletRequest.BASIC_AUTH, CLIENT_CERT_AUTH, FORM_AUTH, DIGEST_AUTH
        // servletReg.setRunAsRole("admin");
        // servletContext.declareRoles("admin");

        // ServletControl URL mapping
        String[] servletMapping = getServletMapping();
        servletControlReg.addMapping(servletMapping);

        // ErrorFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter errorFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.ErrorFilter"));
        FilterRegistration.Dynamic errorFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("ErrorFilter", errorFilter);

        errorFilterReg.setAsyncSupported(true);
        errorFilterReg.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR), true, "/*");

        // EncodeFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter encodeFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.EncodeFilter"));
        FilterRegistration.Dynamic encodeFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("EncodeFilter", encodeFilter);

        encodeFilterReg.setAsyncSupported(true);
        encodeFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // CacheFilter -> @WebFilter(urlPatterns = {"/*"})
        Filter cacheFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.filter.CacheFilter"));
        FilterRegistration.Dynamic cacheFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("CacheFilter", cacheFilter);

        cacheFilterReg.setAsyncSupported(true);
        cacheFilterReg.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR), true,
                "/*");

        // Add custom filters defined by client
        for (String filterName : sortCustomFilters()) {
            Filter customFilter = servletContext
                    .createFilter((Class<? extends Filter>) HANDLER.webFilters.get(filterName));
            HANDLER.executeInjection(customFilter);

            WebFilter webFilter = customFilter.getClass().getAnnotation(WebFilter.class);
            FilterRegistration.Dynamic customFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter(filterName, customFilter);

            if (webFilter.initParams() != null) {
                for (WebInitParam initParam : webFilter.initParams()) {
                    customFilterReg.setInitParameter(initParam.name(), initParam.value());
                }
            }
            customFilterReg.setAsyncSupported(webFilter.asyncSupported());
            customFilterReg.addMappingForUrlPatterns(EnumSet.copyOf(Arrays.asList(webFilter.dispatcherTypes())),
                    true, webFilter.urlPatterns());
        }

        // FilterControl -> @WebFilter(servletNames = {"ServletControl"})
        Filter filterControl = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.FilterControl"));
        FilterRegistration.Dynamic filterControlReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("FilterControl", filterControl);

        filterControlReg.setAsyncSupported(true);
        filterControlReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // OutputFilter -> @WebFilter(servletNames = {"ServletControl"})
        Filter outputFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.OutputFilter"));
        FilterRegistration.Dynamic outputFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("OutputFilter", outputFilter);

        outputFilterReg.setAsyncSupported(true);
        outputFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD,
                DispatcherType.ERROR, DispatcherType.INCLUDE), true, "ServletControl");

        // AsyncFilter -> @WebFilter(servletNames = {"ServletControl"})
        // Filter used case AsyncContext is dispatched internally by AsyncBean implementation
        Filter asyncFilter = servletContext.createFilter(
                (Class<? extends Filter>) Class.forName("com.jsmartframework.web.manager.AsyncFilter"));
        FilterRegistration.Dynamic asyncFilterReg = (FilterRegistration.Dynamic) servletContext
                .addFilter("AsyncFilter", asyncFilter);

        asyncFilterReg.setAsyncSupported(true);
        asyncFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.ASYNC), true, "ServletControl");

        // SessionControl -> @WebListener
        EventListener sessionListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.SessionControl"));
        servletContext.addListener(sessionListener);

        // RequestControl -> @WebListener
        EventListener requestListener = servletContext.createListener((Class<? extends EventListener>) Class
                .forName("com.jsmartframework.web.manager.RequestControl"));
        servletContext.addListener(requestListener);

        // Custom WebServlet -> Custom Servlets created by application
        for (String servletName : HANDLER.webServlets.keySet()) {
            Servlet customServlet = servletContext
                    .createServlet((Class<? extends Servlet>) HANDLER.webServlets.get(servletName));
            HANDLER.executeInjection(customServlet);

            WebServlet webServlet = customServlet.getClass().getAnnotation(WebServlet.class);
            ServletRegistration.Dynamic customReg = (ServletRegistration.Dynamic) servletContext
                    .addServlet(servletName, customServlet);

            customReg.setLoadOnStartup(webServlet.loadOnStartup());
            customReg.setAsyncSupported(webServlet.asyncSupported());

            WebInitParam[] customInitParams = webServlet.initParams();
            if (customInitParams != null) {
                for (WebInitParam customInitParam : customInitParams) {
                    customReg.setInitParameter(customInitParam.name(), customInitParam.value());
                }
            }

            // Add mapping url for custom servlet
            customReg.addMapping(webServlet.urlPatterns());

            if (customServlet.getClass().isAnnotationPresent(MultipartConfig.class)) {
                customReg.setMultipartConfig(new MultipartConfigElement(
                        customServlet.getClass().getAnnotation(MultipartConfig.class)));
            }
        }

        // Controller Dispatcher for Spring MVC
        Set<String> requestPaths = HANDLER.requestPaths.keySet();
        if (!requestPaths.isEmpty()) {
            ServletRegistration.Dynamic mvcDispatcherReg = servletContext.addServlet("DispatcherServlet",
                    new DispatcherServlet(configWebAppContext));
            mvcDispatcherReg.setLoadOnStartup(1);
            mvcDispatcherReg.addMapping(requestPaths.toArray(new String[requestPaths.size()]));

            // RequestPathFilter -> @WebFilter(servletNames = {"DispatcherServlet"})
            Filter requestPathFilter = servletContext.createFilter((Class<? extends Filter>) Class
                    .forName("com.jsmartframework.web.manager.RequestPathFilter"));
            FilterRegistration.Dynamic reqPathFilterReg = (FilterRegistration.Dynamic) servletContext
                    .addFilter("RequestPathFilter", requestPathFilter);

            reqPathFilterReg.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST,
                    DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.INCLUDE, DispatcherType.ASYNC),
                    true, "DispatcherServlet");
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.ireland.jnetty.webapp.WebApp.java

@Override
public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) {
    Class cl = filter.getClass();

    return addFilter(filterName, cl.getName(), cl, filter);
}

From source file:org.apache.camel.component.jetty.JettyHttpComponent.java

private void enableMultipartFilter(HttpEndpoint endpoint, Server server, String connectorKey) throws Exception {
    ServletContextHandler context = (ServletContextHandler) server
            .getChildHandlerByClass(ServletContextHandler.class);
    CamelContext camelContext = this.getCamelContext();
    FilterHolder filterHolder = new FilterHolder();
    filterHolder.setInitParameter("deleteFiles", "true");
    if (ObjectHelper.isNotEmpty(camelContext.getProperties().get(TMP_DIR))) {
        File file = new File(camelContext.getProperties().get(TMP_DIR));
        if (!file.isDirectory()) {
            throw new RuntimeCamelException(
                    "The temp file directory of camel-jetty is not exists, please recheck it with directory name :"
                            + camelContext.getProperties().get(TMP_DIR));
        }/*  w w  w .  jav a 2  s.c  o m*/
        context.setAttribute("javax.servlet.context.tempdir", file);
    }
    // if a filter ref was provided, use it.
    Filter filter = ((JettyHttpEndpoint) endpoint).getMultipartFilter();
    if (filter == null) {
        // if no filter ref was provided, use the default filter
        filter = new MultiPartFilter();
    }
    filterHolder.setFilter(new CamelMultipartFilter(filter));
    String pathSpec = endpoint.getPath();
    if (pathSpec == null || "".equals(pathSpec)) {
        pathSpec = "/";
    }
    if (endpoint.isMatchOnUriPrefix()) {
        pathSpec = pathSpec.endsWith("/") ? pathSpec + "*" : pathSpec + "/*";
    }
    context.addFilter(filterHolder, pathSpec, 0);
    LOG.debug("using multipart filter implementation " + filter.getClass().getName() + " for path " + pathSpec);
}

From source file:org.codice.ddf.security.filter.delegate.DelegateServletFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

    if (contextPolicyManager != null) {
        String contextPath = !StringUtils.isBlank(httpRequest.getContextPath()) ? httpRequest.getContextPath()
                : httpRequest.getServletPath() + httpRequest.getPathInfo();
        if (contextPolicyManager.isWhiteListed(contextPath)) {
            LOGGER.debug(/*from  ww  w  .ja  va 2 s .  com*/
                    "Current Context path {} has been white listed by the local policy, no authentication or authorization filters will be applied.",
                    contextPath);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
    }

    LinkedList<ServiceReference<Filter>> serviceRefs = new LinkedList<ServiceReference<Filter>>();
    try {
        serviceRefs.addAll(ctx.getServiceReferences(Filter.class, null));
    } catch (InvalidSyntaxException e) {
        LOGGER.warn("Could not lookup service references.", e);
    }

    if (!serviceRefs.isEmpty()) {
        LOGGER.debug("Found {} filter, now filtering...", serviceRefs.size());

        ProxyFilterChain chain = new ProxyFilterChain(filterChain);

        Iterator<ServiceReference<Filter>> reverseIterator = serviceRefs.descendingIterator();
        while (reverseIterator.hasNext()) {
            ServiceReference<Filter> curReference = reverseIterator.next();
            Filter curFilter = ctx.getService(curReference);
            if (!curFilter.getClass().toString().equals(this.getClass().toString())) {
                chain.addFilter(curFilter);
            }
            reverseIterator.remove();
        }

        chain.doFilter(servletRequest, servletResponse);
    } else {
        LOGGER.debug("Did not find any filters");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

From source file:org.forgerock.openidm.servletregistration.impl.ServletRegistrationSingleton.java

/**
 * Registers a servlet filter configuration
 * @param config the filter configuration
 * @return the registered Filter//from   ww  w. ja  v  a  2s .  co  m
 * @throws Exception
 */
private Filter registerFilterWithWebContainer(JsonValue config) throws Exception {
    // Get required info from config
    String filterClass = config.get(SERVLET_FILTER_CLASS).required().asString();
    logger.info("Using filter class: {}", filterClass);
    List<URL> urls = config.get(SERVLET_FILTER_CLASS_PATH_URLS)
            .asList(new Function<JsonValue, URL, JsonValueException>() {
                @Override
                public URL apply(JsonValue jsonValue) throws JsonValueException {
                    return jsonValue.asURL();
                }
            });
    logger.info("Added URLs { {} })) to filter classpath", StringUtils.join(urls, ", "));

    Map<String, Object> preInvokeReqAttributes = config.get(SERVLET_FILTER_PRE_INVOKE_ATTRIBUTES).asMap();

    // Servlet names this filter should apply to, e.g. one could also add "OpenIDM Web"
    List<String> servletNames = config.get(SERVLET_FILTER_SERVLET_NAMES)
            .defaultTo(Arrays.asList(DEFAULT_SERVLET_NAME)).asList(String.class);

    // URL patterns to apply the filter to, e.g. one could also add "/openidmui/*");
    List<String> urlPatterns = config.get(SERVLET_FILTER_URL_PATTERNS)
            .defaultTo(Arrays.asList(DEFAULT_SERVLET_URL_PATTERNS)).asList(String.class);

    // Filter init params, a string to string map
    JsonValue rawInitParams = config.get("initParams");
    Map<String, String> initParams = new HashMap<>();
    for (String initParamKey : rawInitParams.keys()) {
        initParams.put(initParamKey, rawInitParams.get(initParamKey).asString());
    }

    // Create a classloader and dynamically create the requested filter
    Filter filter = null;
    ClassLoader filterCL = null;
    ClassLoader origCL = Thread.currentThread().getContextClassLoader();
    try {
        filterCL = new URLClassLoader(urls.toArray(new URL[0]), this.getClass().getClassLoader());
        Thread.currentThread().setContextClassLoader(filterCL);
        filter = (Filter) (Class.forName(filterClass, true, filterCL).newInstance());
    } catch (Exception ex) {
        logger.warn("Configured class {} failed to load from configured class path URLs {}",
                new Object[] { filterClass, urls, ex });
        throw ex;
    } finally {
        Thread.currentThread().setContextClassLoader(origCL);
    }

    // Create filter
    Filter proxiedFilter = (Filter) Proxy.newProxyInstance(filter.getClass().getClassLoader(),
            new Class[] { Filter.class }, new FilterProxy(filter, filterCL, preInvokeReqAttributes));

    // Register filter
    webContainer.registerFilter(proxiedFilter, urlPatterns.toArray(new String[urlPatterns.size()]),
            servletNames.toArray(new String[servletNames.size()]), new Hashtable<String, Object>(initParams),
            webContainer.getDefaultSharedHttpContext());
    return proxiedFilter;
}

From source file:org.jasig.cas.client.util.DelegatingFilter.java

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 Iterator iter = this.delegators.keySet().iterator(); iter.hasNext();) {
            final String key = (String) iter.next();

            if ((parameter.equals(key) && this.exactMatch) || (parameter.matches(key) && !this.exactMatch)) {
                final Filter 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() + "]");
                }// w  ww .j  ava  2s. c om
                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);
    }
}