Search in sources :

Example 6 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 7 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes in project tomcat70 by apache.

the class ContextConfig method processServletContainerInitializers.

/**
 * Scan JARs for ServletContainerInitializer implementations.
 */
protected void processServletContainerInitializers() {
    List<ServletContainerInitializer> detectedScis;
    try {
        WebappServiceLoader<ServletContainerInitializer> loader = new WebappServiceLoader<ServletContainerInitializer>(context);
        detectedScis = loader.load(ServletContainerInitializer.class);
    } catch (IOException e) {
        log.error(sm.getString("contextConfig.servletContainerInitializerFail", context.getName()), e);
        ok = false;
        return;
    }
    for (ServletContainerInitializer sci : detectedScis) {
        initializerClassMap.put(sci, new HashSet<Class<?>>());
        HandlesTypes ht;
        try {
            ht = sci.getClass().getAnnotation(HandlesTypes.class);
        } catch (Exception e) {
            if (log.isDebugEnabled()) {
                log.info(sm.getString("contextConfig.sci.debug", sci.getClass().getName()), e);
            } else {
                log.info(sm.getString("contextConfig.sci.info", sci.getClass().getName()));
            }
            continue;
        }
        if (ht == null) {
            continue;
        }
        Class<?>[] types = ht.value();
        if (types == null) {
            continue;
        }
        for (Class<?> type : types) {
            if (type.isAnnotation()) {
                handlesTypesAnnotations = true;
            } else {
                handlesTypesNonAnnotations = true;
            }
            Set<ServletContainerInitializer> scis = typeInitializerMap.get(type);
            if (scis == null) {
                scis = new HashSet<ServletContainerInitializer>();
                typeInitializerMap.put(type, scis);
            }
            scis.add(sci);
        }
    }
}
Also used : IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) NamingException(javax.naming.NamingException) FileNotFoundException(java.io.FileNotFoundException) NameNotFoundException(javax.naming.NameNotFoundException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) ClassFormatException(org.apache.tomcat.util.bcel.classfile.ClassFormatException) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) JavaClass(org.apache.tomcat.util.bcel.classfile.JavaClass) HandlesTypes(javax.servlet.annotation.HandlesTypes)

Example 8 with HandlesTypes

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

the class ServletContainerInitializerRegistrationBean method customize.

@Override
public void customize(ConfigurableServletWebServerFactory factory) {
    factory.addInitializers(servletContext -> {
        HandlesTypes handlesTypes = AnnotationUtils.findAnnotation(getServletContainerInitializerClass(), HandlesTypes.class);
        Set<Class<?>> classes = null;
        if (handlesTypes != null) {
            classes = getClasses(handlesTypes);
        }
        BeanUtils.instantiateClass(getServletContainerInitializerClass()).onStartup(classes, servletContext);
    });
}
Also used : HandlesTypes(javax.servlet.annotation.HandlesTypes)

Example 9 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes in project Payara by payara.

the class ServletContainerInitializerUtil method getInterestList.

/**
 * Builds a mapping of classes to the list of ServletContainerInitializers
 * interested in them
 *
 * @param initializers an Iterable over all ServletContainerInitializers
 * that need to be considered
 *
 * @return Mapping of classes to list of ServletContainerInitializers
 * interested in them
 */
public static Map<Class<?>, List<Class<? extends ServletContainerInitializer>>> getInterestList(Iterable<ServletContainerInitializer> initializers) {
    if (null == initializers) {
        return null;
    }
    Map<Class<?>, List<Class<? extends ServletContainerInitializer>>> interestList = null;
    // initializers are interested
    for (ServletContainerInitializer sc : initializers) {
        if (interestList == null) {
            interestList = new HashMap<Class<?>, List<Class<? extends ServletContainerInitializer>>>();
        }
        Class<? extends ServletContainerInitializer> sciClass = sc.getClass();
        HandlesTypes ann = (HandlesTypes) sciClass.getAnnotation(HandlesTypes.class);
        if (ann == null) {
            // This initializer does not contain @HandlesTypes
            // This means it should always be called for all web apps
            // So map it with a special token
            List<Class<? extends ServletContainerInitializer>> currentInitializerList = interestList.get(ServletContainerInitializerUtil.class);
            if (currentInitializerList == null) {
                List<Class<? extends ServletContainerInitializer>> arr = new ArrayList<Class<? extends ServletContainerInitializer>>();
                arr.add(sciClass);
                interestList.put(ServletContainerInitializerUtil.class, arr);
            } else {
                currentInitializerList.add(sciClass);
            }
        } else {
            Class[] interestedClasses = ann.value();
            if ((interestedClasses != null) && (interestedClasses.length != 0)) {
                for (Class c : interestedClasses) {
                    List<Class<? extends ServletContainerInitializer>> currentInitializerList = interestList.get(c);
                    if (currentInitializerList == null) {
                        List<Class<? extends ServletContainerInitializer>> arr = new ArrayList<Class<? extends ServletContainerInitializer>>();
                        arr.add(sciClass);
                        interestList.put(c, arr);
                    } else {
                        currentInitializerList.add(sciClass);
                    }
                }
            }
        }
    }
    return interestList;
}
Also used : ServletContainerInitializer(javax.servlet.ServletContainerInitializer) HandlesTypes(javax.servlet.annotation.HandlesTypes)

Example 10 with HandlesTypes

use of javax.servlet.annotation.HandlesTypes in project flow by vaadin.

the class VaadinAppShellInitializer method init.

/**
 * Initializes the {@link AppShellRegistry} for the application.
 *
 * @param classes
 *            a set of classes that matches the {@link HandlesTypes} set in
 *            this class.
 * @param context
 *            the {@link VaadinContext}.
 */
@SuppressWarnings("unchecked")
public static void init(Set<Class<?>> classes, VaadinContext context) {
    ApplicationConfiguration config = ApplicationConfiguration.get(context);
    if (config.useV14Bootstrap()) {
        return;
    }
    boolean disregardOffendingAnnotations = config.getBooleanProperty(Constants.ALLOW_APPSHELL_ANNOTATIONS, false);
    AppShellRegistry registry = AppShellRegistry.getInstance(context);
    registry.reset();
    if (classes == null || classes.isEmpty()) {
        return;
    }
    List<String> offendingAnnotations = new ArrayList<>();
    classes.stream().sorted((a, b) -> registry.isShell(a) ? -1 : registry.isShell(b) ? 1 : 0).forEach(clz -> {
        if (registry.isShell(clz)) {
            registry.setShell((Class<? extends AppShellConfigurator>) clz);
            getLogger().debug("Using {} class for configuring `index.html` response", clz.getName());
        } else {
            String error = registry.validateClass(clz);
            if (error != null) {
                offendingAnnotations.add(error);
            }
        }
    });
    if (!offendingAnnotations.isEmpty()) {
        if (disregardOffendingAnnotations) {
            boolean hasPwa = offendingAnnotations.stream().anyMatch(err -> err.matches(".*@PWA.*"));
            String message = String.format(hasPwa ? ERROR_HEADER_OFFENDING_PWA : ERROR_HEADER_NO_SHELL, String.join("\n  ", offendingAnnotations));
            getLogger().error(message);
        } else {
            String message = String.format(ERROR_HEADER_NO_SHELL, String.join("\n  ", offendingAnnotations));
            throw new InvalidApplicationConfigurationException(message);
        }
    }
    List<String> classesImplementingPageConfigurator = classes.stream().filter(clz -> PageConfigurator.class.isAssignableFrom(clz)).map(Class::getName).collect(Collectors.toList());
    if (!classesImplementingPageConfigurator.isEmpty()) {
        String message = String.join("\n - ", classesImplementingPageConfigurator);
        if (registry.getShell() != null) {
            message = String.format(ERROR_HEADER_OFFENDING_CONFIGURATOR, registry.getShell().getName(), message);
            throw new InvalidApplicationConfigurationException(message);
        } else {
            message = String.format(ERROR_HEADER_NO_APP_CONFIGURATOR, message);
            getLogger().error(message);
        }
    }
}
Also used : VaadinServletContext(com.vaadin.flow.server.VaadinServletContext) Arrays(java.util.Arrays) Inline(com.vaadin.flow.component.page.Inline) HandlesTypes(javax.servlet.annotation.HandlesTypes) LoggerFactory(org.slf4j.LoggerFactory) PageConfigurator(com.vaadin.flow.server.PageConfigurator) PageTitle(com.vaadin.flow.router.PageTitle) ArrayList(java.util.ArrayList) NoTheme(com.vaadin.flow.theme.NoTheme) Theme(com.vaadin.flow.theme.Theme) ERROR_HEADER_NO_APP_CONFIGURATOR(com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_NO_APP_CONFIGURATOR) ERROR_HEADER_OFFENDING_CONFIGURATOR(com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_OFFENDING_CONFIGURATOR) Constants(com.vaadin.flow.server.Constants) AppShellConfigurator(com.vaadin.flow.component.page.AppShellConfigurator) ServletContextListener(javax.servlet.ServletContextListener) ERROR_HEADER_OFFENDING_PWA(com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_OFFENDING_PWA) Logger(org.slf4j.Logger) PWA(com.vaadin.flow.server.PWA) Meta(com.vaadin.flow.component.page.Meta) Set(java.util.Set) Collectors(java.util.stream.Collectors) WebListener(javax.servlet.annotation.WebListener) Serializable(java.io.Serializable) List(java.util.List) VaadinContext(com.vaadin.flow.server.VaadinContext) ServletContextEvent(javax.servlet.ServletContextEvent) InvalidApplicationConfigurationException(com.vaadin.flow.server.InvalidApplicationConfigurationException) Annotation(java.lang.annotation.Annotation) BodySize(com.vaadin.flow.component.page.BodySize) ERROR_HEADER_NO_SHELL(com.vaadin.flow.server.AppShellRegistry.ERROR_HEADER_NO_SHELL) AppShellRegistry(com.vaadin.flow.server.AppShellRegistry) ServletContext(javax.servlet.ServletContext) Viewport(com.vaadin.flow.component.page.Viewport) Push(com.vaadin.flow.component.page.Push) InvalidApplicationConfigurationException(com.vaadin.flow.server.InvalidApplicationConfigurationException) ArrayList(java.util.ArrayList) AppShellRegistry(com.vaadin.flow.server.AppShellRegistry) PageConfigurator(com.vaadin.flow.server.PageConfigurator)

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