javax.servlet.annotation.WebFilter Java Examples

The following examples show how to use javax.servlet.annotation.WebFilter. 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: FilterHolder.java    From aws-serverless-java-container with Apache License 2.0 6 votes vote down vote up
public Registration(WebFilter annotation) {
    urlPatterns = new ArrayList<>();
    dispatcherTypes = new ArrayList<>();

    EnumSet<DispatcherType> dispatchers = EnumSet.noneOf(DispatcherType.class);
    dispatchers.addAll(Arrays.asList(annotation.dispatcherTypes()));

    if (annotation.value().length > 0) {
        addMappingForUrlPatterns(dispatchers, true, annotation.value());
    }

    if (annotation.urlPatterns().length > 0) {
        addMappingForUrlPatterns(dispatchers, true, annotation.urlPatterns());
    }

    asyncSupported = annotation.asyncSupported();
}
 
Example #2
Source File: ServerCmdlet.java    From HongsCORE with MIT License 6 votes vote down vote up
private void addFilter(ServletContextHandler context, Class clso, WebFilter anno) {
    DispatcherType[]  ds = anno.dispatcherTypes(  );
    List   <DispatcherType> ls = Arrays .asList(ds);
    EnumSet<DispatcherType> es = EnumSet.copyOf(ls);

    FilterHolder  hd = new FilterHolder (clso );
    hd.setName          (anno.filterName(    ));
    hd.setAsyncSupported(anno.asyncSupported());

    for(WebInitParam nv : anno.initParams ()) {
        hd.setInitParameter(nv.name( ), nv.value());
    }

    for(String       ur : anno.urlPatterns()) {
        context.addFilter (hd, ur, es);
    }
}
 
Example #3
Source File: WebFilterInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
private void configure(final ServletEnvironment environment, final Filter filter,
                       final String name, final WebFilter annotation) {
    final FilterRegistration.Dynamic mapping = environment.addFilter(name, filter);
    final EnumSet<DispatcherType> dispatcherTypes = EnumSet.copyOf(Arrays.asList(annotation.dispatcherTypes()));
    if (annotation.servletNames().length > 0) {
        mapping.addMappingForServletNames(dispatcherTypes, false, annotation.servletNames());
    } else {
        final String[] urlPatterns = annotation.urlPatterns().length > 0
                ? annotation.urlPatterns() : annotation.value();
        mapping.addMappingForUrlPatterns(dispatcherTypes, false, urlPatterns);
    }
    if (annotation.initParams().length > 0) {
        for (WebInitParam param : annotation.initParams()) {
            mapping.setInitParameter(param.name(), param.value());
        }
    }
    mapping.setAsyncSupported(annotation.asyncSupported());
}
 
Example #4
Source File: WebFilterInstaller.java    From dropwizard-guicey with MIT License 6 votes vote down vote up
@Override
public void install(final Environment environment, final Filter instance) {
    final Class<? extends Filter> extType = FeatureUtils.getInstanceClass(instance);
    final WebFilter annotation = FeatureUtils.getAnnotation(extType, WebFilter.class);
    final String[] servlets = annotation.servletNames();
    final String[] patterns = annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value();
    Preconditions.checkArgument(servlets.length > 0 || patterns.length > 0,
            "Filter %s not specified servlet or pattern for mapping", extType.getName());
    Preconditions.checkArgument(servlets.length == 0 || patterns.length == 0,
            "Filter %s specifies both servlets and patters, when only one allowed",
            extType.getName());
    final boolean servletMapping = servlets.length > 0;
    final AdminContext context = FeatureUtils.getAnnotation(extType, AdminContext.class);
    final String name = WebUtils.getFilterName(annotation, extType);
    reporter.line("%-25s %-8s %-4s %s   %s", Joiner.on(",").join(servletMapping ? servlets : patterns),
            WebUtils.getAsyncMarker(annotation), WebUtils.getContextMarkers(context),
            RenderUtils.renderClassLine(extType), name);

    if (WebUtils.isForMain(context)) {
        configure(environment.servlets(), instance, name, annotation);
    }
    if (WebUtils.isForAdmin(context)) {
        configure(environment.admin(), instance, name, annotation);
    }
}
 
Example #5
Source File: AbstractJoynrServletModule.java    From joynr with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up filters that are annotated with the {@link WebFilter} annotation.
 * Every class in the classpath is searched for the annotation.
 */
@SuppressWarnings("unchecked")
private void bindAnnotatedFilters() {

    String appsPackages = null;
    if (System.getProperties().containsKey(IO_JOYNR_APPS_PACKAGES)) {
        logger.info("Using property {} from system properties", IO_JOYNR_APPS_PACKAGES);
        appsPackages = System.getProperty(IO_JOYNR_APPS_PACKAGES);
    } else {
        Properties servletProperties = PropertyLoader.loadProperties("servlet.properties");
        if (servletProperties.containsKey(IO_JOYNR_APPS_PACKAGES)) {
            appsPackages = servletProperties.getProperty(IO_JOYNR_APPS_PACKAGES);
        }
    }

    if (appsPackages != null) {
        String[] packageNames = appsPackages.split(";");
        logger.info("Searching packages for @WebFilter annotation: {}", Arrays.toString(packageNames));

        PackageNamesScanner scanner = new PackageNamesScanner(packageNames);
        AnnotationScannerListener sl = new AnnotationScannerListener(WebFilter.class);
        scanner.scan(sl);

        for (Class<?> webFilterAnnotatedClass : sl.getAnnotatedClasses()) {

            if (Filter.class.isAssignableFrom(webFilterAnnotatedClass)) {
                bind(webFilterAnnotatedClass).in(Singleton.class);
                filter("/*").through((Class<? extends Filter>) webFilterAnnotatedClass);
                logger.info("Adding filter {} for '/*'", webFilterAnnotatedClass.getName());
            }

        }
    }
}
 
Example #6
Source File: AnnotationScanInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Is this a web annotation.
 *
 * @param annotation the annotation.
 * @return true if it is, false otherwise.
 */
private boolean isWebAnnotation(Annotation annotation) {
    return annotation instanceof WebServlet
            || annotation instanceof WebListener
            || annotation instanceof WebInitParam
            || annotation instanceof WebFilter
            || annotation instanceof ServletSecurity
            || annotation instanceof MultipartConfig;
}
 
Example #7
Source File: StartWebServer.java    From hammock with Apache License 2.0 5 votes vote down vote up
private void processFilters() {
    Consumer<Class<? extends Filter>> c = filter -> {
        WebFilter webFilter = ClassUtils.getAnnotation(filter, WebFilter.class);
        if(webFilter != null) {
            FilterDescriptor filterDescriptor = new FilterDescriptor(webFilter.filterName(),
                    webFilter.value(), mapUrls(webFilter.urlPatterns()), webFilter.dispatcherTypes(),
                    webFilter.initParams(), webFilter.asyncSupported(), webFilter.servletNames(),
                    filter);
            webServer.addFilter(filterDescriptor);
        }
    };
    extension.processFilters(c);
}
 
Example #8
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<FilterDefinition> detectFilters(Collection<Class<?>> filterClasses) {
    List<FilterDefinition> filterDefinitions = new ArrayList<>();
    for (Class<?> candidate : filterClasses) {
        if (Filter.class.isAssignableFrom(candidate)) {
            Class<? extends Filter> filterClass = (Class<? extends Filter>) candidate;
            WebFilter annotation = filterClass.getAnnotation(WebFilter.class);
            FilterDefinition filterDefinition = new FilterDefinition(
                    Strings.isNullOrEmpty(
                            annotation.filterName()) ? filterClass.getCanonicalName() : annotation.filterName(),
                    filterClass
            );
            filterDefinition.setAsyncSupported(annotation.asyncSupported());
            if (annotation.servletNames().length > 0) {
                filterDefinition.addServletMappings(
                        convert(annotation.dispatcherTypes(), false, annotation.servletNames()));
            }
            if (annotation.value().length > 0) {
                filterDefinition.addMappings(convert(annotation.dispatcherTypes(), false, annotation.value()));
            }
            if (annotation.urlPatterns().length > 0) {
                filterDefinition.addMappings(
                        convert(annotation.dispatcherTypes(), false, annotation.urlPatterns()));
            }
            filterDefinition.addInitParameters(convert(annotation.initParams()));
            filterDefinition.setPriority(priorityOf(filterClass));

            filterDefinitions.add(filterDefinition);
        }
    }

    return filterDefinitions;
}
 
Example #9
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public InitState initialize(InitContext initContext) {
    if (servletContext != null) {
        listenerDefinitions.addAll(
                detectListeners(initContext.scannedClassesByAnnotationClass().get(WebListener.class)));
        filterDefinitions.addAll(detectFilters(initContext.scannedClassesByAnnotationClass().get(WebFilter.class)));
        servletDefinitions.addAll(
                detectServlets(initContext.scannedClassesByAnnotationClass().get(WebServlet.class)));
    }

    return InitState.INITIALIZED;
}
 
Example #10
Source File: WebServletPlugin.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Collection<ClasspathScanRequest> classpathScanRequests() {
    return classpathScanRequestBuilder()
            .annotationType(WebFilter.class)
            .annotationType(WebServlet.class)
            .annotationType(WebListener.class)
            .build();
}
 
Example #11
Source File: ServerCmdlet.java    From HongsCORE with MIT License 5 votes vote down vote up
@Override
public void init(ServletContextHandler context) {
    String pkgx  = CoreConfig.getInstance("defines"   )
                             .getProperty("apply.serv");
    if  (  pkgx != null ) {
        String[]   pkgs = pkgx.split(";");
        for(String pkgn : pkgs) {
            pkgn = pkgn.trim  ( );
            if  (  pkgn.length( ) == 0  ) {
                continue;
            }

            Set<String> clss = getClss(pkgn);
            for(String  clsn : clss) {
                Class   clso = getClso(clsn);

                WebFilter   wf = (WebFilter  ) clso.getAnnotation(WebFilter.class  );
                if (null != wf) {
                    addFilter  (context, clso, wf);
                }

                WebServlet  wb = (WebServlet ) clso.getAnnotation(WebServlet.class );
                if (null != wb) {
                    addServlet (context, clso, wb);
                }

                WebListener wl = (WebListener) clso.getAnnotation(WebListener.class);
                if (null != wl) {
                    addListener(context, clso, wl);
                }
            }
        }
    }
}
 
Example #12
Source File: FilterHolder.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
private WebFilter getAnnotation() {
    if (isAnnotated()) {
        return filter.getClass().getAnnotation(WebFilter.class);
    } else {
        return null;
    }
}
 
Example #13
Source File: FilterHolder.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
private Map<String, String> readAnnotatedInitParams() {
    Map<String, String> initParams = new HashMap<>();
    if (isAnnotated()) {
        WebFilter regAnnotation = filter.getClass().getAnnotation(WebFilter.class);
        for (WebInitParam param : regAnnotation.initParams()) {
            initParams.put(param.name(), param.value());
        }
    }

    return initParams;
}
 
Example #14
Source File: FilterHolder.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
private String readAnnotatedFilterName() {
    if (isAnnotated()) {
        WebFilter regAnnotation = filter.getClass().getAnnotation(WebFilter.class);
        if (!"".equals(regAnnotation.filterName().trim())) {
            return regAnnotation.filterName();
        } else {
            return filter.getClass().getName();
        }
    } else {
        return null;
    }
}
 
Example #15
Source File: WebFilterInstaller.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
@Override
public boolean matches(final Class<?> type) {
    return FeatureUtils.is(type, Filter.class)
            && FeatureUtils.hasAnnotation(type, WebFilter.class);
}
 
Example #16
Source File: MeecrowaveContextConfig.java    From openwebbeans-meecrowave with Apache License 2.0 4 votes vote down vote up
@Override
protected void webConfig() {
    if (context.getServletContext().getAttribute("meecrowave.configuration") == null) { // redeploy
        context.getServletContext().setAttribute("meecrowave.configuration",
                Meecrowave.Builder.class.isInstance(configuration) ? configuration : new Meecrowave.Builder(configuration));
        context.addServletContainerInitializer(intializer, emptySet());
    }

    if (!configuration.isTomcatScanning()) {
        super.webConfig();
        return;
    }

    // eagerly start CDI to scan only once and not twice (tomcat+CDI)
    final ClassLoader loader = context.getLoader().getClassLoader(); // should already be started at that point
    final Thread thread = Thread.currentThread();
    final ClassLoader old = thread.getContextClassLoader();
    thread.setContextClassLoader(loader);
    try {
        final OWBTomcatWebScannerService scannerService = OWBTomcatWebScannerService.class.cast(WebBeansContext.getInstance().getScannerService());
        scannerService.setFilter(ofNullable(context.getJarScanner()).map(JarScanner::getJarScanFilter).orElse(null), context.getServletContext());
        scannerService.setDocBase(context.getDocBase());
        scannerService.setShared(configuration.getSharedLibraries());
        if (configuration.getWatcherBouncing() > 0) { // note that caching should be disabled with this config in most of the times
            watcher = new ReloadOnChangeController(context, configuration.getWatcherBouncing());
            scannerService.setFileVisitor(f -> watcher.register(f));
        }
        scannerService.scan();
        finder = scannerService.getFinder();
        finder.link();
        final CdiArchive archive = CdiArchive.class.cast(finder.getArchive());
        Stream.of(WebServlet.class, WebFilter.class, WebListener.class)
                .forEach(marker -> finder.findAnnotatedClasses(marker).stream()
                        .filter(c -> !Modifier.isAbstract(c.getModifiers()) && Modifier.isPublic(c.getModifiers()))
                        .forEach(webComponent -> webClasses.computeIfAbsent(
                                archive.classesByUrl().entrySet().stream()
                                        .filter(e -> e.getValue().getClassNames().contains(webComponent.getName()))
                                        .findFirst().get().getKey(), k -> new HashSet<>())
                                .add(webComponent)));
    } finally {
        thread.setContextClassLoader(old);
    }
    try {
        super.webConfig();
    } finally {
        webClasses.clear();
        finder = null;
    }
}
 
Example #17
Source File: WebServerExtension.java    From hammock with Apache License 2.0 4 votes vote down vote up
public void findFilters(@Observes @WithAnnotations({WebFilter.class})
                                  ProcessAnnotatedType<? extends Filter> pat) {
    filters.add(pat.getAnnotatedType().getJavaClass());
}
 
Example #18
Source File: FilterHolder.java    From aws-serverless-java-container with Apache License 2.0 4 votes vote down vote up
public boolean isAnnotated() {
    return filter.getClass().isAnnotationPresent(WebFilter.class);
}
 
Example #19
Source File: WebUtils.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * When filter name not set in annotation, name generates as: . (dot) at the beginning to indicate
 * generated name, followed by lower-cased class name. If class ends with "filter" then it will be cut off.
 * For example, for class "MyCoolFilter" generated name will be ".mycool".
 *
 * @param filter filter annotation
 * @param type   filter type
 * @return filter name or generated name if name not provided
 */
public static String getFilterName(final WebFilter filter, final Class<? extends Filter> type) {
    final String name = Strings.emptyToNull(filter.filterName());
    return name != null ? name : generateName(type, "filter");
}
 
Example #20
Source File: WebUtils.java    From dropwizard-guicey with MIT License 2 votes vote down vote up
/**
 * @param annotation filter registration annotation
 * @return "async" string if filter support async and empty string otherwise
 */
public static String getAsyncMarker(final WebFilter annotation) {
    return getAsyncMarker(annotation.asyncSupported());
}