Search in sources :

Example 1 with ServletContainerInitializer

use of javax.servlet.ServletContainerInitializer in project jetty.project by eclipse.

the class AnnotationConfiguration method getNonExcludedInitializers.

/**
     * Get SCIs that are not excluded from consideration
     * @param context the web app context 
     * @return the list of non-excluded servlet container initializers
     * @throws Exception if unable to get list 
     */
public List<ServletContainerInitializer> getNonExcludedInitializers(WebAppContext context) throws Exception {
    ArrayList<ServletContainerInitializer> nonExcludedInitializers = new ArrayList<ServletContainerInitializer>();
    //We use the ServiceLoader mechanism to find the ServletContainerInitializer classes to inspect
    long start = 0;
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        if (LOG.isDebugEnabled())
            start = System.nanoTime();
        Thread.currentThread().setContextClassLoader(context.getClassLoader());
        _loadedInitializers = ServiceLoader.load(ServletContainerInitializer.class);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
    if (LOG.isDebugEnabled())
        LOG.debug("Service loaders found in {}ms", (TimeUnit.MILLISECONDS.convert((System.nanoTime() - start), TimeUnit.NANOSECONDS)));
    Map<ServletContainerInitializer, Resource> sciResourceMap = new HashMap<ServletContainerInitializer, Resource>();
    ServletContainerInitializerOrdering initializerOrdering = getInitializerOrdering(context);
    //because containerInitializerOrdering omits it
    for (ServletContainerInitializer sci : _loadedInitializers) {
        if (matchesExclusionPattern(sci)) {
            if (LOG.isDebugEnabled())
                LOG.debug("{} excluded by pattern", sci);
            continue;
        }
        Resource sciResource = getJarFor(sci);
        if (isFromExcludedJar(context, sci, sciResource)) {
            if (LOG.isDebugEnabled())
                LOG.debug("{} is from excluded jar", sci);
            continue;
        }
        //check containerInitializerOrdering doesn't exclude it
        String name = sci.getClass().getName();
        if (initializerOrdering != null && (!initializerOrdering.hasWildcard() && initializerOrdering.getIndexOf(name) < 0)) {
            if (LOG.isDebugEnabled())
                LOG.debug("{} is excluded by ordering", sci);
            continue;
        }
        sciResourceMap.put(sci, sciResource);
    }
    //Order the SCIs that are included
    if (initializerOrdering != null && !initializerOrdering.isDefaultOrder()) {
        if (LOG.isDebugEnabled())
            LOG.debug("Ordering ServletContainerInitializers with " + initializerOrdering);
        //There is an ordering that is not just "*".
        //Arrange ServletContainerInitializers according to the ordering of classnames given, irrespective of coming from container or webapp classpaths
        nonExcludedInitializers.addAll(sciResourceMap.keySet());
        Collections.sort(nonExcludedInitializers, new ServletContainerInitializerComparator(initializerOrdering));
    } else {
        //no web.xml ordering defined, add SCIs in any order
        if (context.getMetaData().getOrdering() == null) {
            if (LOG.isDebugEnabled())
                LOG.debug("No web.xml ordering, ServletContainerInitializers in random order");
            nonExcludedInitializers.addAll(sciResourceMap.keySet());
        } else {
            if (LOG.isDebugEnabled())
                LOG.debug("Ordering ServletContainerInitializers with ordering {}", context.getMetaData().getOrdering());
            for (Map.Entry<ServletContainerInitializer, Resource> entry : sciResourceMap.entrySet()) {
                //add in SCIs from the container classpath
                if (entry.getKey().getClass().getClassLoader() == context.getClassLoader().getParent())
                    nonExcludedInitializers.add(entry.getKey());
                else if (//add in SCIs not in a jar, as they must be from WEB-INF/classes and can't be ordered
                entry.getValue() == null)
                    nonExcludedInitializers.add(entry.getKey());
            }
            //add SCIs according to the ordering of its containing jar
            for (Resource webInfJar : context.getMetaData().getOrderedWebInfJars()) {
                for (Map.Entry<ServletContainerInitializer, Resource> entry : sciResourceMap.entrySet()) {
                    if (webInfJar.equals(entry.getValue()))
                        nonExcludedInitializers.add(entry.getKey());
                }
            }
        }
    }
    if (LOG.isDebugEnabled()) {
        int i = 0;
        for (ServletContainerInitializer sci : nonExcludedInitializers) LOG.debug("ServletContainerInitializer: {} {} from {}", (++i), sci.getClass().getName(), sciResourceMap.get(sci));
    }
    return nonExcludedInitializers;
}
Also used : HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ArrayList(java.util.ArrayList) Resource(org.eclipse.jetty.util.resource.Resource) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 2 with ServletContainerInitializer

use of javax.servlet.ServletContainerInitializer in project jetty.project by eclipse.

the class AnnotationConfiguration method createServletContainerInitializerAnnotationHandlers.

public void createServletContainerInitializerAnnotationHandlers(WebAppContext context, List<ServletContainerInitializer> scis) throws Exception {
    if (scis == null || scis.isEmpty())
        // nothing to do
        return;
    List<ContainerInitializer> initializers = new ArrayList<ContainerInitializer>();
    context.setAttribute(CONTAINER_INITIALIZERS, initializers);
    for (ServletContainerInitializer service : scis) {
        HandlesTypes annotation = service.getClass().getAnnotation(HandlesTypes.class);
        ContainerInitializer initializer = null;
        if (annotation != null) {
            //There is a HandlesTypes annotation on the on the ServletContainerInitializer
            Class<?>[] classes = annotation.value();
            if (classes != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("HandlesTypes {} on initializer {}", Arrays.asList(classes), service.getClass());
                }
                initializer = new ContainerInitializer(service, classes);
                //process the whole class hierarchy to satisfy the ServletContainerInitializer
                if (context.getAttribute(CLASS_INHERITANCE_MAP) == null) {
                    //MultiMap<String> map = new MultiMap<>();
                    ConcurrentHashMap<String, ConcurrentHashSet<String>> map = new ClassInheritanceMap();
                    context.setAttribute(CLASS_INHERITANCE_MAP, map);
                    _classInheritanceHandler = new ClassInheritanceHandler(map);
                }
                for (Class<?> c : classes) {
                    //register a handler for it
                    if (c.isAnnotation()) {
                        if (LOG.isDebugEnabled())
                            LOG.debug("Registering annotation handler for " + c.getName());
                        _containerInitializerAnnotationHandlers.add(new ContainerInitializerAnnotationHandler(initializer, c));
                    }
                }
            } else {
                initializer = new ContainerInitializer(service, null);
                if (LOG.isDebugEnabled())
                    LOG.debug("No classes in HandlesTypes on initializer " + service.getClass());
            }
        } else {
            initializer = new ContainerInitializer(service, null);
            if (LOG.isDebugEnabled())
                LOG.debug("No HandlesTypes annotation on initializer " + service.getClass());
        }
        initializers.add(initializer);
    }
    //add a bean to the context which will call the servletcontainerinitializers when appropriate
    ServletContainerInitializersStarter starter = (ServletContainerInitializersStarter) context.getAttribute(CONTAINER_INITIALIZER_STARTER);
    if (starter != null)
        throw new IllegalStateException("ServletContainerInitializersStarter already exists");
    starter = new ServletContainerInitializersStarter(context);
    context.setAttribute(CONTAINER_INITIALIZER_STARTER, starter);
    context.addBean(starter, true);
}
Also used : ArrayList(java.util.ArrayList) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ConcurrentHashSet(org.eclipse.jetty.util.ConcurrentHashSet) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ContainerInitializer(org.eclipse.jetty.plus.annotation.ContainerInitializer) HandlesTypes(javax.servlet.annotation.HandlesTypes)

Example 3 with ServletContainerInitializer

use of javax.servlet.ServletContainerInitializer in project meecrowave by apache.

the class MeecrowaveContextConfig method processServletContainerInitializers.

@Override
protected void processServletContainerInitializers() {
    // use our finder
    if (!configuration.isTomcatScanning()) {
        return;
    }
    try {
        new WebappServiceLoader<ServletContainerInitializer>(context).load(ServletContainerInitializer.class).forEach(sci -> {
            final Set<Class<?>> classes = new HashSet<>();
            initializerClassMap.put(sci, classes);
            final HandlesTypes ht;
            try {
                ht = sci.getClass().getAnnotation(HandlesTypes.class);
            } catch (final Exception | NoClassDefFoundError e) {
                return;
            }
            if (ht == null) {
                return;
            }
            Stream.of(ht.value()).forEach(t -> {
                if (t.isAnnotation()) {
                    final Class<? extends Annotation> annotation = Class.class.cast(t);
                    finder.findAnnotatedClasses(annotation).forEach(classes::add);
                } else if (t.isInterface()) {
                    finder.findImplementations(t).forEach(classes::add);
                } else {
                    finder.findSubclasses(t).forEach(classes::add);
                }
            });
        });
    } catch (final IOException e) {
        ok = false;
    }
}
Also used : ServletContainerInitializer(javax.servlet.ServletContainerInitializer) IOException(java.io.IOException) HandlesTypes(javax.servlet.annotation.HandlesTypes) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 4 with ServletContainerInitializer

use of javax.servlet.ServletContainerInitializer in project tomcat70 by apache.

the class ContextConfig method checkHandlesTypes.

/**
 * For classes packaged with the web application, the class and each
 * super class needs to be checked for a match with {@link HandlesTypes} or
 * for an annotation that matches {@link HandlesTypes}.
 * @param javaClass
 */
protected void checkHandlesTypes(JavaClass javaClass) {
    // Skip this if we can
    if (typeInitializerMap.size() == 0)
        return;
    if ((javaClass.getAccessFlags() & org.apache.tomcat.util.bcel.Const.ACC_ANNOTATION) != 0) {
        // Skip annotations.
        return;
    }
    String className = javaClass.getClassName();
    Class<?> clazz = null;
    if (handlesTypesNonAnnotations) {
        // This *might* be match for a HandlesType.
        populateJavaClassCache(className, javaClass);
        JavaClassCacheEntry entry = javaClassCache.get(className);
        if (entry.getSciSet() == null) {
            try {
                populateSCIsForCacheEntry(entry);
            } catch (StackOverflowError soe) {
                throw new IllegalStateException(sm.getString("contextConfig.annotationsStackOverflow", context.getName(), classHierarchyToString(className, entry)));
            }
        }
        if (!entry.getSciSet().isEmpty()) {
            // Need to try and load the class
            clazz = Introspection.loadClass(context, className);
            if (clazz == null) {
                // Can't load the class so no point continuing
                return;
            }
            for (ServletContainerInitializer sci : entry.getSciSet()) {
                Set<Class<?>> classes = initializerClassMap.get(sci);
                if (classes == null) {
                    classes = new HashSet<Class<?>>();
                    initializerClassMap.put(sci, classes);
                }
                classes.add(clazz);
            }
        }
    }
    if (handlesTypesAnnotations) {
        for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry : typeInitializerMap.entrySet()) {
            if (entry.getKey().isAnnotation()) {
                AnnotationEntry[] annotationEntries = javaClass.getAnnotationEntries();
                if (annotationEntries != null) {
                    for (AnnotationEntry annotationEntry : annotationEntries) {
                        if (entry.getKey().getName().equals(getClassName(annotationEntry.getAnnotationType()))) {
                            if (clazz == null) {
                                clazz = Introspection.loadClass(context, className);
                                if (clazz == null) {
                                    // continuing
                                    return;
                                }
                            }
                            for (ServletContainerInitializer sci : entry.getValue()) {
                                initializerClassMap.get(sci).add(clazz);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }
}
Also used : Set(java.util.Set) RuleSet(org.apache.tomcat.util.digester.RuleSet) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) AnnotationEntry(org.apache.tomcat.util.bcel.classfile.AnnotationEntry) JavaClass(org.apache.tomcat.util.bcel.classfile.JavaClass) FilterMap(org.apache.catalina.deploy.FilterMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with ServletContainerInitializer

use of javax.servlet.ServletContainerInitializer in project tomcat70 by apache.

the class TestServletSecurityMappings method doTestSecurityAnnotationsAddServlet.

@Test
public void doTestSecurityAnnotationsAddServlet() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("/test", null);
    ctx.setMapperContextRootRedirectEnabled(redirectContextRoot);
    ServletContainerInitializer sci = new SCI(secureRoot, secureDefault, secureFoo);
    ctx.addServletContainerInitializer(sci, null);
    tomcat.start();
    ByteChunk bc = new ByteChunk();
    int rc;
    // Foo
    rc = getUrl("http://localhost:" + getPort() + "/test/foo", bc, false);
    if (secureFoo || secureDefault) {
        Assert.assertEquals(403, rc);
    } else {
        Assert.assertEquals(200, rc);
    }
    bc.recycle();
    // Default
    rc = getUrl("http://localhost:" + getPort() + "/test/something", bc, false);
    if (secureDefault) {
        Assert.assertEquals(403, rc);
    } else {
        Assert.assertEquals(200, rc);
    }
    bc.recycle();
    // Root
    rc = getUrl("http://localhost:" + getPort() + "/test", bc, false);
    if (redirectContextRoot) {
        Assert.assertEquals(302, rc);
    } else {
        if (secureRoot || secureDefault) {
            Assert.assertEquals(403, rc);
        } else {
            Assert.assertEquals(200, rc);
        }
    }
}
Also used : Context(org.apache.catalina.Context) ServletContext(javax.servlet.ServletContext) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

ServletContainerInitializer (javax.servlet.ServletContainerInitializer)25 IOException (java.io.IOException)10 HashMap (java.util.HashMap)9 HashSet (java.util.HashSet)9 ArrayList (java.util.ArrayList)8 Map (java.util.Map)8 Set (java.util.Set)8 File (java.io.File)7 MalformedURLException (java.net.MalformedURLException)6 HandlesTypes (javax.servlet.annotation.HandlesTypes)6 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 ServletContext (javax.servlet.ServletContext)5 LinkedHashMap (java.util.LinkedHashMap)4 LinkedHashSet (java.util.LinkedHashSet)4 List (java.util.List)4 Context (org.apache.catalina.Context)4 FilterMap (org.apache.catalina.deploy.FilterMap)4 Tomcat (org.apache.catalina.startup.Tomcat)4 InputStream (java.io.InputStream)3 TreeMap (java.util.TreeMap)3