Search in sources :

Example 1 with Resource

use of jakarta.annotation.Resource in project piranha by piranhacloud.

the class MicroInnerDeployer method start.

/**
 * Start the application.
 *
 * @param applicationArchive the application archive.
 * @param classLoader the classloader.
 * @param handlers the handlers.
 * @param config the configuration.
 * @return the map.
 */
public Map<String, Object> start(Archive<?> applicationArchive, ClassLoader classLoader, Map<String, Function<URL, URLConnection>> handlers, Map<String, Object> config) {
    try {
        WebApplication webApplication = getWebApplication(applicationArchive, classLoader);
        LOGGER.log(INFO, "Starting web application " + applicationArchive.getName() + " on Piranha Micro " + webApplication.getAttribute(MICRO_PIRANHA));
        // The global archive stream handler is set to resolve "shrinkwrap://" URLs (created from strings).
        // Such URLs come into being primarily when code takes resolves a class or resource from the class loader by URL
        // and then takes the string form of the URL representing the class or resource.
        GlobalArchiveStreamHandler streamHandler = new GlobalArchiveStreamHandler(webApplication);
        // Life map to the StaticURLStreamHandlerFactory used by the root class loader
        handlers.put("shrinkwrap", streamHandler::connect);
        // Source of annotations
        Index index = getIndex();
        // Target of annotations
        AnnotationManager annotationManager = new InternalAnnotationScanAnnotationManager();
        webApplication.getManager().setAnnotationManager(annotationManager);
        // Copy annotations from our "annotations" collection from source index to target manager
        forEachWebAnnotation(webAnnotation -> addAnnotationToIndex(index, webAnnotation, annotationManager));
        // Collect sub-classes/interfaces of our "instances" collection from source index to target manager
        forEachInstance(instanceClass -> addInstanceToIndex(index, instanceClass, annotationManager));
        // Collect any sub-classes/interfaces from any HandlesTypes annotation
        getAnnotations(index, HandlesTypes.class).map(this::getTarget).forEach(annotationTarget -> getAnnotationInstances(annotationTarget, HandlesTypes.class).map(HandlesTypes.class::cast).forEach(handlesTypesInstance -> stream(handlesTypesInstance.value()).forEach(e -> {
            if (e.isAnnotation()) {
                addAnnotationToIndex(index, e, annotationManager);
            } else {
                addInstanceToIndex(index, e, annotationManager);
            }
        })));
        // Setup the default identity store, which is used as the default "username and roles database" for
        // (Servlet) security.
        initIdentityStore(webApplication);
        setApplicationContextPath(webApplication, config, applicationArchive);
        DefaultWebApplicationExtensionContext extensionContext = new DefaultWebApplicationExtensionContext();
        for (WebApplicationExtension extension : ServiceLoader.load(WebApplicationExtension.class)) {
            extensionContext.add(extension);
        }
        extensionContext.configure(webApplication);
        webApplication.initialize();
        webApplication.start();
        if ((boolean) config.get("micro.http.start")) {
            HttpWebApplicationServer webApplicationServer = new HttpWebApplicationServer();
            webApplicationServer.addWebApplication(webApplication);
            ServiceLoader<HttpServer> httpServers = ServiceLoader.load(HttpServer.class);
            httpServer = httpServers.findFirst().orElseThrow();
            httpServer.setServerPort((Integer) config.get("micro.port"));
            httpServer.setSSL(Boolean.getBoolean("piranha.http.ssl"));
            httpServer.setHttpServerProcessor(webApplicationServer);
            httpServer.start();
        }
        return Map.of("deployedServlets", webApplication.getServletRegistrations().keySet(), "deployedApplication", new MicroInnerApplication(webApplication), "deployedContextRoot", webApplication.getContextPath());
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } catch (Exception e) {
        throw e;
    }
}
Also used : AnnotationManager(cloud.piranha.core.api.AnnotationManager) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) XPathExpressionException(javax.xml.xpath.XPathExpressionException) URL(java.net.URL) RunAs(jakarta.annotation.security.RunAs) PostConstruct(jakarta.annotation.PostConstruct) ClassInfo(org.jboss.jandex.ClassInfo) Node(org.jboss.shrinkwrap.api.Node) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) Resource(jakarta.annotation.Resource) ByteArrayInputStream(java.io.ByteArrayInputStream) DeclareRoles(jakarta.annotation.security.DeclareRoles) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) WebFilter(jakarta.servlet.annotation.WebFilter) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ShrinkWrapResource(cloud.piranha.resource.shrinkwrap.ShrinkWrapResource) HttpServer(cloud.piranha.http.api.HttpServer) ServiceLoader(java.util.ServiceLoader) PreDestroy(jakarta.annotation.PreDestroy) PermitAll(jakarta.annotation.security.PermitAll) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) Objects(java.util.Objects) Stream(java.util.stream.Stream) AnnotationInstance(org.jboss.jandex.AnnotationInstance) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) MultipartConfig(jakarta.servlet.annotation.MultipartConfig) CLASS(org.jboss.jandex.AnnotationTarget.Kind.CLASS) SAXException(org.xml.sax.SAXException) WebApplication(cloud.piranha.core.api.WebApplication) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TRUE(java.lang.Boolean.TRUE) Arrays.stream(java.util.Arrays.stream) Level(java.lang.System.Logger.Level) ArchiveAsset(org.jboss.shrinkwrap.api.asset.ArchiveAsset) ServletSecurity(jakarta.servlet.annotation.ServletSecurity) XPath(javax.xml.xpath.XPath) AnnotationManager(cloud.piranha.core.api.AnnotationManager) NODESET(javax.xml.xpath.XPathConstants.NODESET) Resources(jakarta.annotation.Resources) Function(java.util.function.Function) URLConnection(java.net.URLConnection) NamedNodeMap(org.w3c.dom.NamedNodeMap) Priority(jakarta.annotation.Priority) Index(org.jboss.jandex.Index) RolesAllowed(jakarta.annotation.security.RolesAllowed) HandlesTypes(jakarta.servlet.annotation.HandlesTypes) IndexReader(org.jboss.jandex.IndexReader) NodeList(org.w3c.dom.NodeList) DenyAll(jakarta.annotation.security.DenyAll) UTF_8(java.nio.charset.StandardCharsets.UTF_8) INFO(java.lang.System.Logger.Level.INFO) DotName.createSimple(org.jboss.jandex.DotName.createSimple) IOException(java.io.IOException) Archive(org.jboss.shrinkwrap.api.Archive) GlobalArchiveStreamHandler(cloud.piranha.resource.shrinkwrap.GlobalArchiveStreamHandler) Consumer(java.util.function.Consumer) WebListener(jakarta.servlet.annotation.WebListener) FIELD(org.jboss.jandex.AnnotationTarget.Kind.FIELD) XPathFactory(javax.xml.xpath.XPathFactory) METHOD(org.jboss.jandex.AnnotationTarget.Kind.METHOD) Logger(java.lang.System.Logger) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) WebInitParam(jakarta.servlet.annotation.WebInitParam) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) WebServlet(jakarta.servlet.annotation.WebServlet) InputStream(java.io.InputStream) DefaultWebApplicationExtensionContext(cloud.piranha.core.impl.DefaultWebApplicationExtensionContext) WebApplicationExtension(cloud.piranha.core.api.WebApplicationExtension) Index(org.jboss.jandex.Index) IOException(java.io.IOException) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SAXException(org.xml.sax.SAXException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HttpWebApplicationServer(cloud.piranha.http.webapp.HttpWebApplicationServer) GlobalArchiveStreamHandler(cloud.piranha.resource.shrinkwrap.GlobalArchiveStreamHandler) InternalAnnotationScanAnnotationManager(cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager) HttpServer(cloud.piranha.http.api.HttpServer) DefaultWebApplication(cloud.piranha.core.impl.DefaultWebApplication) WebApplication(cloud.piranha.core.api.WebApplication) HandlesTypes(jakarta.servlet.annotation.HandlesTypes)

Example 2 with Resource

use of jakarta.annotation.Resource in project tomcat by apache.

the class WebAnnotationSet method loadClassAnnotation.

/**
 * Process the annotations on a context for a given className.
 *
 * @param context The context which will have its annotations processed
 * @param clazz The class to examine for Servlet annotations
 */
protected static void loadClassAnnotation(Context context, Class<?> clazz) {
    /* Process Resource annotation.
         * Ref JSR 250
         */
    Resource resourceAnnotation = clazz.getAnnotation(Resource.class);
    if (resourceAnnotation != null) {
        addResource(context, resourceAnnotation);
    }
    /* Process Resources annotation.
         * Ref JSR 250
         */
    Resources resourcesAnnotation = clazz.getAnnotation(Resources.class);
    if (resourcesAnnotation != null && resourcesAnnotation.value() != null) {
        for (Resource resource : resourcesAnnotation.value()) {
            addResource(context, resource);
        }
    }
    /* Process EJB annotation.
         * Ref JSR 224, equivalent to the ejb-ref or ejb-local-ref
         * element in the deployment descriptor.
        {
            EJB annotation = clazz.getAnnotation(EJB.class);
            if (annotation != null) {

                if ((annotation.mappedName().length() == 0)
                        || annotation.mappedName().equals("Local")) {

                    ContextLocalEjb ejb = new ContextLocalEjb();

                    ejb.setName(annotation.name());
                    ejb.setType(annotation.beanInterface().getCanonicalName());
                    ejb.setDescription(annotation.description());

                    ejb.setHome(annotation.beanName());

                    context.getNamingResources().addLocalEjb(ejb);

                } else if (annotation.mappedName().equals("Remote")) {

                    ContextEjb ejb = new ContextEjb();

                    ejb.setName(annotation.name());
                    ejb.setType(annotation.beanInterface().getCanonicalName());
                    ejb.setDescription(annotation.description());

                    ejb.setHome(annotation.beanName());

                    context.getNamingResources().addEjb(ejb);

                }
            }
        }
        */
    /* Process WebServiceRef annotation.
         * Ref JSR 224, equivalent to the service-ref element in
         * the deployment descriptor.
         * The service-ref registration is not implemented
        {
            WebServiceRef annotation = clazz
                    .getAnnotation(WebServiceRef.class);
            if (annotation != null) {
                ContextService service = new ContextService();

                service.setName(annotation.name());
                service.setWsdlfile(annotation.wsdlLocation());

                service.setType(annotation.type().getCanonicalName());

                if (annotation.value() == null)
                    service.setServiceinterface(annotation.type()
                            .getCanonicalName());

                if (annotation.type().getCanonicalName().equals("Service"))
                    service.setServiceinterface(annotation.type()
                            .getCanonicalName());

                if (annotation.value().getCanonicalName().equals("Endpoint"))
                    service.setServiceendpoint(annotation.type()
                            .getCanonicalName());

                service.setPortlink(annotation.type().getCanonicalName());

                context.getNamingResources().addService(service);
            }
        }
        */
    /* Process DeclareRoles annotation.
         * Ref JSR 250, equivalent to the security-role element in
         * the deployment descriptor
         */
    DeclareRoles declareRolesAnnotation = clazz.getAnnotation(DeclareRoles.class);
    if (declareRolesAnnotation != null && declareRolesAnnotation.value() != null) {
        for (String role : declareRolesAnnotation.value()) {
            context.addSecurityRole(role);
        }
    }
}
Also used : ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) Resource(jakarta.annotation.Resource) DeclareRoles(jakarta.annotation.security.DeclareRoles) Resources(jakarta.annotation.Resources)

Example 3 with Resource

use of jakarta.annotation.Resource in project tomcat by apache.

the class WebAnnotationSet method loadMethodsAnnotation.

protected static void loadMethodsAnnotation(Context context, Class<?> clazz) {
    // Initialize the annotations
    Method[] methods = Introspection.getDeclaredMethods(clazz);
    if (methods != null && methods.length > 0) {
        for (Method method : methods) {
            Resource annotation = method.getAnnotation(Resource.class);
            if (annotation != null) {
                if (!Introspection.isValidSetter(method)) {
                    throw new IllegalArgumentException(sm.getString("webAnnotationSet.invalidInjection"));
                }
                String defaultName = clazz.getName() + SEPARATOR + Introspection.getPropertyName(method);
                Class<?> defaultType = (method.getParameterTypes()[0]);
                addResource(context, annotation, defaultName, defaultType);
            }
        }
    }
}
Also used : ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) Resource(jakarta.annotation.Resource) Method(java.lang.reflect.Method)

Example 4 with Resource

use of jakarta.annotation.Resource in project tomee by apache.

the class Assembler method validateCdiResourceProducers.

private void validateCdiResourceProducers(final AppContext appContext, final AppInfo info) {
    if (appContext.getWebBeansContext() == null) {
        return;
    }
    // validate @Produces @Resource/@PersistenceX/@EJB once all is bound to JNDI - best case - or with our model
    if (appContext.isStandaloneModule() && !appContext.getProperties().containsKey("openejb.cdi.skip-resource-validation")) {
        final Map<String, Object> bindings = appContext.getWebContexts().isEmpty() ? appContext.getBindings() : appContext.getWebContexts().iterator().next().getBindings();
        if (bindings != null && appContext.getWebBeansContext() != null && appContext.getWebBeansContext().getBeanManagerImpl().isInUse()) {
            for (final Bean<?> bean : appContext.getWebBeansContext().getBeanManagerImpl().getBeans()) {
                if (ResourceBean.class.isInstance(bean)) {
                    final ResourceReference reference = ResourceBean.class.cast(bean).getReference();
                    String jndi = reference.getJndiName().replace("java:", "");
                    if (reference.getJndiName().startsWith("java:/")) {
                        jndi = jndi.substring(1);
                    }
                    Object lookup = bindings.get(jndi);
                    if (lookup == null && reference.getAnnotation(EJB.class) != null) {
                        final CdiPlugin plugin = CdiPlugin.class.cast(appContext.getWebBeansContext().getPluginLoader().getEjbPlugin());
                        if (!plugin.isSessionBean(reference.getResourceType())) {
                            // local beans are here and access is O(1) instead of O(n)
                            boolean ok = false;
                            for (final BeanContext bc : appContext.getBeanContexts()) {
                                if (bc.getBusinessLocalInterfaces().contains(reference.getResourceType()) || bc.getBusinessRemoteInterfaces().contains(reference.getResourceType())) {
                                    ok = true;
                                    break;
                                }
                            }
                            if (!ok) {
                                throw new DefinitionException("EJB " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to " + reference.getResourceType());
                            }
                        }
                    }
                    if (Reference.class.isInstance(lookup)) {
                        try {
                            lookup = Reference.class.cast(lookup).getContent();
                        } catch (final Exception e) {
                            // surely too early, let's try some known locations
                            if (JndiUrlReference.class.isInstance(lookup)) {
                                checkBuiltInResourceTypes(reference, JndiUrlReference.class.cast(lookup).getJndiName());
                            }
                            continue;
                        }
                    } else if (lookup == null) {
                        // TODO: better validation with lookups in tomee, should be in TWAB surely but would split current code
                        final Resource r = Resource.class.cast(reference.getAnnotation(Resource.class));
                        if (r != null) {
                            if (!r.lookup().isEmpty()) {
                                checkBuiltInResourceTypes(reference, r.lookup());
                            } else if (!r.name().isEmpty()) {
                                final String name = "comp/env/" + r.name();
                                boolean done = false;
                                for (final WebAppInfo w : info.webApps) {
                                    for (final EnvEntryInfo e : w.jndiEnc.envEntries) {
                                        if (name.equals(e.referenceName)) {
                                            if (e.type != null && !reference.getResourceType().getName().equals(e.type)) {
                                                throw new DefinitionException("Env Entry " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast to " + reference.getResourceType());
                                            }
                                            done = true;
                                            break;
                                        }
                                    }
                                    if (done) {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (lookup != null && !reference.getResourceType().isInstance(lookup)) {
                        throw new DefinitionException("Resource " + reference.getJndiName() + " in " + reference.getOwnerClass() + " can't be cast, instance is " + lookup);
                    }
                }
            }
        }
    }
}
Also used : CdiPlugin(org.apache.openejb.cdi.CdiPlugin) ResourceBean(org.apache.webbeans.component.ResourceBean) Resource(jakarta.annotation.Resource) DestroyableResource(org.apache.openejb.api.resource.DestroyableResource) JndiUrlReference(org.apache.openejb.core.ivm.naming.JndiUrlReference) InvalidObjectException(java.io.InvalidObjectException) DefinitionException(jakarta.enterprise.inject.spi.DefinitionException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ObjectStreamException(java.io.ObjectStreamException) ResourceAdapterInternalException(jakarta.resource.spi.ResourceAdapterInternalException) URISyntaxException(java.net.URISyntaxException) ValidationException(jakarta.validation.ValidationException) UndeployException(org.apache.openejb.UndeployException) ConstructionException(org.apache.xbean.recipe.ConstructionException) MBeanRegistrationException(javax.management.MBeanRegistrationException) InstanceNotFoundException(javax.management.InstanceNotFoundException) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) MalformedObjectNameException(javax.management.MalformedObjectNameException) DuplicateDeploymentIdException(org.apache.openejb.DuplicateDeploymentIdException) TimeoutException(java.util.concurrent.TimeoutException) NamingException(javax.naming.NamingException) OpenEJBException(org.apache.openejb.OpenEJBException) NoSuchApplicationException(org.apache.openejb.NoSuchApplicationException) MalformedURLException(java.net.MalformedURLException) OpenEJBRuntimeException(org.apache.openejb.OpenEJBRuntimeException) BeanContext(org.apache.openejb.BeanContext) ResourceReference(org.apache.webbeans.spi.api.ResourceReference) DefinitionException(jakarta.enterprise.inject.spi.DefinitionException)

Example 5 with Resource

use of jakarta.annotation.Resource in project tomee by apache.

the class ResourceInjector method visitMethod.

public final void visitMethod(final Method method, final Annotation annotation) {
    assert annotation instanceof Resource : annotation;
    Resource res = (Resource) annotation;
    String resourceName = getResourceName(res, method);
    Class<?> clz = getResourceType(res, method);
    Object resource = resolveResource(resourceName, clz);
    if (resource == null && "".equals(res.name())) {
        resource = resolveResource(null, clz);
    }
    if (resource != null) {
        invokeSetter(method, resource);
    } else {
        LOG.log(Level.FINE, "RESOURCE_RESOLVE_FAILED", new Object[] { resourceName, clz });
    }
}
Also used : Resource(jakarta.annotation.Resource)

Aggregations

Resource (jakarta.annotation.Resource)15 Method (java.lang.reflect.Method)5 Field (java.lang.reflect.Field)4 EJB (jakarta.ejb.EJB)3 PersistenceContext (jakarta.persistence.PersistenceContext)3 PersistenceUnit (jakarta.persistence.PersistenceUnit)3 ContextResource (org.apache.tomcat.util.descriptor.web.ContextResource)3 Resources (jakarta.annotation.Resources)2 DeclareRoles (jakarta.annotation.security.DeclareRoles)2 WebServiceRef (jakarta.xml.ws.WebServiceRef)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 AnnotationManager (cloud.piranha.core.api.AnnotationManager)1 WebApplication (cloud.piranha.core.api.WebApplication)1 WebApplicationExtension (cloud.piranha.core.api.WebApplicationExtension)1 DefaultWebApplication (cloud.piranha.core.impl.DefaultWebApplication)1 DefaultWebApplicationExtensionContext (cloud.piranha.core.impl.DefaultWebApplicationExtensionContext)1 InternalAnnotationScanAnnotationManager (cloud.piranha.extension.annotationscan.internal.InternalAnnotationScanAnnotationManager)1 HttpServer (cloud.piranha.http.api.HttpServer)1 HttpWebApplicationServer (cloud.piranha.http.webapp.HttpWebApplicationServer)1