Search in sources :

Example 1 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes 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 2 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes 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 3 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes in project adeptj-runtime by AdeptJ.

the class ContainerInitializer method onStartup.

/**
 * {@inheritDoc}
 */
@Override
public void onStartup(Set<Class<?>> startupAwareClasses, ServletContext context) {
    Logger logger = LoggerFactory.getLogger(ContainerInitializer.class);
    if (startupAwareClasses == null || startupAwareClasses.isEmpty()) {
        // We can't go ahead if StartupAware implementations are not passed by container.
        logger.error("No @HandlesTypes(StartupAware) on classpath!!");
        throw new IllegalStateException("No @HandlesTypes(StartupAware) on classpath!!");
    } else {
        ServletContextHolder.INSTANCE.setServletContext(context);
        startupAwareClasses.stream().sorted(new StartupAwareComparator()).peek(startupAwareClass -> logger.info("@HandlesTypes: [{}]", startupAwareClass)).forEach(startupAwareClass -> {
            try {
                startupAwareClass.asSubclass(StartupAware.class).getDeclaredConstructor().newInstance().onStartup(context);
            } catch (Exception ex) {
                // NOSONAR
                logger.error("Exception while executing StartupAware#onStartup!!", ex);
                throw new InitializationException("Exception while executing StartupAware#onStartup!!", ex);
            }
        });
        // If we are here means startup went well above, register FrameworkShutdownHandler now.
        context.addListener(FrameworkShutdownHandler.class);
    }
}
Also used : ServletContainerInitializer(javax.servlet.ServletContainerInitializer) Logger(org.slf4j.Logger) ServletContextHolder(com.adeptj.runtime.common.ServletContextHolder) LoggerFactory(org.slf4j.LoggerFactory) HandlesTypes(javax.servlet.annotation.HandlesTypes) FrameworkShutdownHandler(com.adeptj.runtime.osgi.FrameworkShutdownHandler) Set(java.util.Set) InitializationException(com.adeptj.runtime.exception.InitializationException) ServletContext(javax.servlet.ServletContext) Logger(org.slf4j.Logger) InitializationException(com.adeptj.runtime.exception.InitializationException) InitializationException(com.adeptj.runtime.exception.InitializationException)

Example 4 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes in project wildfly by wildfly.

the class ServletContainerInitializerDeploymentProcessor method deploy.

/**
 * Process SCIs.
 */
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final ModuleSpecification moduleSpecification = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    final ServiceModuleLoader loader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
        // Skip non web deployments
        return;
    }
    WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    assert warMetaData != null;
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
        throw UndertowLogger.ROOT_LOGGER.failedToResolveModule(deploymentUnit);
    }
    final ClassLoader classLoader = module.getClassLoader();
    ScisMetaData scisMetaData = deploymentUnit.getAttachment(ScisMetaData.ATTACHMENT_KEY);
    if (scisMetaData == null) {
        scisMetaData = new ScisMetaData();
        deploymentUnit.putAttachment(ScisMetaData.ATTACHMENT_KEY, scisMetaData);
    }
    Set<ServletContainerInitializer> scis = scisMetaData.getScis();
    Set<Class<? extends ServletContainerInitializer>> sciClasses = new HashSet<>();
    if (scis == null) {
        scis = new LinkedHashSet<>();
        scisMetaData.setScis(scis);
    }
    Map<ServletContainerInitializer, Set<Class<?>>> handlesTypes = scisMetaData.getHandlesTypes();
    if (handlesTypes == null) {
        handlesTypes = new HashMap<ServletContainerInitializer, Set<Class<?>>>();
        scisMetaData.setHandlesTypes(handlesTypes);
    }
    // Find the SCIs from shared modules
    for (ModuleDependency dependency : moduleSpecification.getAllDependencies()) {
        // Should not include SCI if services is not included
        if (!dependency.isImportServices()) {
            continue;
        }
        try {
            Module depModule = loader.loadModule(dependency.getIdentifier());
            ServiceLoader<ServletContainerInitializer> serviceLoader = depModule.loadService(ServletContainerInitializer.class);
            for (ServletContainerInitializer service : serviceLoader) {
                if (sciClasses.add(service.getClass())) {
                    scis.add(service);
                }
            }
        } catch (ModuleLoadException e) {
            if (!dependency.isOptional()) {
                throw UndertowLogger.ROOT_LOGGER.errorLoadingSCIFromModule(dependency.getIdentifier().toString(), e);
            }
        }
    }
    // Find local ServletContainerInitializer services
    List<String> order = warMetaData.getOrder();
    Map<String, VirtualFile> localScis = warMetaData.getScis();
    if (order != null && localScis != null) {
        for (String jar : order) {
            VirtualFile sci = localScis.get(jar);
            if (sci != null) {
                scis.addAll(loadSci(classLoader, sci, jar, true, sciClasses));
            }
        }
    }
    // SCI's deployed in the war itself
    if (localScis != null) {
        VirtualFile warDeployedScis = localScis.get("classes");
        if (warDeployedScis != null) {
            scis.addAll(loadSci(classLoader, warDeployedScis, deploymentUnit.getName(), true, sciClasses));
        }
    }
    // Process HandlesTypes for ServletContainerInitializer
    Map<Class<?>, Set<ServletContainerInitializer>> typesMap = new HashMap<Class<?>, Set<ServletContainerInitializer>>();
    for (ServletContainerInitializer service : scis) {
        try {
            if (service.getClass().isAnnotationPresent(HandlesTypes.class)) {
                HandlesTypes handlesTypesAnnotation = service.getClass().getAnnotation(HandlesTypes.class);
                Class<?>[] typesArray = handlesTypesAnnotation.value();
                if (typesArray != null) {
                    for (Class<?> type : typesArray) {
                        Set<ServletContainerInitializer> servicesSet = typesMap.get(type);
                        if (servicesSet == null) {
                            servicesSet = new HashSet<ServletContainerInitializer>();
                            typesMap.put(type, servicesSet);
                        }
                        servicesSet.add(service);
                        handlesTypes.put(service, new HashSet<Class<?>>());
                    }
                }
            }
        } catch (ArrayStoreException e) {
            // Class.findAnnotation() has a bug under JDK < 11 which throws ArrayStoreException
            throw UndertowLogger.ROOT_LOGGER.missingClassInAnnotation(HandlesTypes.class.getSimpleName(), service.getClass().getName());
        }
    }
    Class<?>[] typesArray = typesMap.keySet().toArray(new Class<?>[0]);
    final CompositeIndex index = deploymentUnit.getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
    if (index == null) {
        throw UndertowLogger.ROOT_LOGGER.unableToResolveAnnotationIndex(deploymentUnit);
    }
    final CompositeIndex parent;
    if (deploymentUnit.getParent() != null) {
        parent = deploymentUnit.getParent().getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
    } else {
        parent = null;
    }
    // WFLY-4205, look in the parent as well as the war
    CompositeIndex parentIndex = deploymentUnit.getParent() == null ? null : deploymentUnit.getParent().getAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
    // Find classes which extend, implement, or are annotated by HandlesTypes
    for (Class<?> type : typesArray) {
        DotName className = DotName.createSimple(type.getName());
        Set<ClassInfo> classInfos = new HashSet<>();
        classInfos.addAll(processHandlesType(className, type, index, parent));
        if (parentIndex != null) {
            classInfos.addAll(processHandlesType(className, type, parentIndex, parent));
        }
        Set<Class<?>> classes = loadClassInfoSet(classInfos, classLoader);
        Set<ServletContainerInitializer> sciSet = typesMap.get(type);
        for (ServletContainerInitializer sci : sciSet) {
            handlesTypes.get(sci).addAll(classes);
        }
    }
}
Also used : ModuleLoadException(org.jboss.modules.ModuleLoadException) VirtualFile(org.jboss.vfs.VirtualFile) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) ModuleDependency(org.jboss.as.server.deployment.module.ModuleDependency) HashMap(java.util.HashMap) WarMetaData(org.jboss.as.web.common.WarMetaData) CompositeIndex(org.jboss.as.server.deployment.annotation.CompositeIndex) DotName(org.jboss.jandex.DotName) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) HandlesTypes(javax.servlet.annotation.HandlesTypes) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) ServiceModuleLoader(org.jboss.as.server.moduleservice.ServiceModuleLoader) ModuleSpecification(org.jboss.as.server.deployment.module.ModuleSpecification) Module(org.jboss.modules.Module) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) ClassInfo(org.jboss.jandex.ClassInfo)

Example 5 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes 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);
                    classes.addAll(finder.findAnnotatedClasses(annotation));
                } else if (t.isInterface()) {
                    classes.addAll(finder.findImplementations(t));
                } else {
                    classes.addAll(finder.findSubclasses(t));
                }
            });
        });
    } catch (final IOException e) {
        ok = false;
    }
}
Also used : ServletContainerInitializer(javax.servlet.ServletContainerInitializer) WebappServiceLoader(org.apache.catalina.startup.WebappServiceLoader) IOException(java.io.IOException) HandlesTypes(javax.servlet.annotation.HandlesTypes) IOException(java.io.IOException) HashSet(java.util.HashSet)

Aggregations

HandlesTypes (javax.servlet.annotation.HandlesTypes)10 ServletContainerInitializer (javax.servlet.ServletContainerInitializer)7 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 Set (java.util.Set)3 ArrayList (java.util.ArrayList)2 ServletContext (javax.servlet.ServletContext)2 ServletContextHolder (com.adeptj.runtime.common.ServletContextHolder)1 InitializationException (com.adeptj.runtime.exception.InitializationException)1 FrameworkShutdownHandler (com.adeptj.runtime.osgi.FrameworkShutdownHandler)1 AppShellConfigurator (com.vaadin.flow.component.page.AppShellConfigurator)1 BodySize (com.vaadin.flow.component.page.BodySize)1 Inline (com.vaadin.flow.component.page.Inline)1 Meta (com.vaadin.flow.component.page.Meta)1 Push (com.vaadin.flow.component.page.Push)1 Viewport (com.vaadin.flow.component.page.Viewport)1 PageTitle (com.vaadin.flow.router.PageTitle)1 AppShellRegistry (com.vaadin.flow.server.AppShellRegistry)1 ERROR_HEADER_NO_APP_CONFIGURATOR (com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_NO_APP_CONFIGURATOR)1 ERROR_HEADER_NO_SHELL (com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_NO_SHELL)1